142 lines
6.3 KiB
JavaScript
142 lines
6.3 KiB
JavaScript
// Context menus on the footer microphone/headphones buttons: pick the input or output device.
|
|
// Uses the same discovery and selection path as Settings → Звук (voice.deviceChoices / choose*Device).
|
|
// Opening never toggles mute or deafen; left click on the buttons keeps its own behaviour.
|
|
import { $, h, icon } from './dom.js';
|
|
import { S } from './state.js';
|
|
import * as voice from './voice.js';
|
|
|
|
let open = null; // { menu, anchor, cleanup }
|
|
let hooks = { openAudioSettings: () => {} };
|
|
|
|
export function initDeviceMenus(h0) {
|
|
hooks = { ...hooks, ...h0 };
|
|
bind($('#btn-mute'), 'input');
|
|
bind($('#btn-deafen'), 'output');
|
|
}
|
|
|
|
function bind(button, kind) {
|
|
button.setAttribute('aria-haspopup', 'menu');
|
|
button.addEventListener('contextmenu', (e) => {
|
|
e.preventDefault();
|
|
show(button, kind, { x: e.clientX, y: e.clientY });
|
|
});
|
|
button.addEventListener('keydown', (e) => {
|
|
if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
|
|
e.preventDefault();
|
|
show(button, kind, null);
|
|
}
|
|
});
|
|
}
|
|
|
|
function close({ restoreFocus = true } = {}) {
|
|
if (!open) return;
|
|
const { menu, anchor, cleanup } = open;
|
|
open = null;
|
|
cleanup();
|
|
menu.remove();
|
|
anchor.setAttribute('aria-expanded', 'false');
|
|
if (restoreFocus) anchor.focus();
|
|
}
|
|
|
|
let generation = 0;
|
|
|
|
/**
|
|
* The menu element exists from the first moment (with a loading line), so every close path — Escape,
|
|
* outside click, window blur, another menu — applies while device enumeration is still pending. The
|
|
* enumeration result only fills the menu that is still open for this request; a stale result is dropped.
|
|
*/
|
|
function show(anchor, kind, point) {
|
|
close({ restoreFocus: false });
|
|
const gen = ++generation;
|
|
const title = kind === 'input' ? 'Микрофон' : 'Устройство вывода';
|
|
const body = h('div', { class: 'menu-body' }, h('p', { class: 'menu-note', text: 'Получаем список устройств…' }));
|
|
const menu = h('div', { class: 'device-menu', role: 'menu', 'aria-label': title, 'aria-busy': 'true', tabindex: '-1' },
|
|
h('div', { class: 'menu-title', text: title }),
|
|
body);
|
|
document.body.appendChild(menu);
|
|
anchor.setAttribute('aria-expanded', 'true');
|
|
position(menu, anchor, point);
|
|
|
|
let focusables = [];
|
|
const focusAt = (i) => focusables.length && focusables[(i + focusables.length) % focusables.length].focus();
|
|
const onKey = (e) => {
|
|
const i = focusables.indexOf(document.activeElement);
|
|
if (e.key === 'ArrowDown') { e.preventDefault(); focusAt(i + 1); }
|
|
else if (e.key === 'ArrowUp') { e.preventDefault(); focusAt(i - 1); }
|
|
else if (e.key === 'Home') { e.preventDefault(); focusAt(0); }
|
|
else if (e.key === 'End') { e.preventDefault(); focusAt(focusables.length - 1); }
|
|
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
|
|
else if (e.key === 'Tab') { close({ restoreFocus: false }); }
|
|
};
|
|
const onPointer = (e) => {
|
|
if (!menu.contains(e.target) && e.target !== anchor) close({ restoreFocus: false });
|
|
};
|
|
const onDismiss = () => close({ restoreFocus: false });
|
|
menu.addEventListener('keydown', onKey);
|
|
document.addEventListener('pointerdown', onPointer, true);
|
|
window.addEventListener('resize', onDismiss);
|
|
window.addEventListener('blur', onDismiss);
|
|
open = {
|
|
gen,
|
|
menu,
|
|
anchor,
|
|
cleanup: () => {
|
|
document.removeEventListener('pointerdown', onPointer, true);
|
|
window.removeEventListener('resize', onDismiss);
|
|
window.removeEventListener('blur', onDismiss);
|
|
},
|
|
};
|
|
menu.focus();
|
|
|
|
voice.deviceChoices().then((choices) => {
|
|
if (!open || open.gen !== gen || !choices) return; // closed or replaced meanwhile
|
|
const data = kind === 'input' ? choices.input : choices.output;
|
|
const selected = (kind === 'input' ? S.prefs.inputDeviceId : S.prefs.outputDeviceId) || '';
|
|
const items = data.options.map((o) => {
|
|
const item = h('button', {
|
|
class: 'menu-item',
|
|
type: 'button',
|
|
role: 'menuitemradio',
|
|
'aria-checked': String(o.value === selected),
|
|
tabindex: '-1',
|
|
}, h('span', { class: 'menu-check', 'aria-hidden': 'true' }, o.value === selected ? icon('check') : null), h('span', { class: 'menu-label', text: o.label }));
|
|
item.addEventListener('click', async () => {
|
|
close();
|
|
if (o.value === selected) return;
|
|
if (kind === 'input') await voice.chooseInputDevice(o.value);
|
|
else await voice.chooseOutputDevice(o.value);
|
|
});
|
|
return item;
|
|
});
|
|
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: 'Настройки звука…' }));
|
|
settingsItem.addEventListener('click', () => {
|
|
close({ restoreFocus: false });
|
|
hooks.openAudioSettings();
|
|
});
|
|
const note = data.redacted || data.physical === 0
|
|
? h('p', { class: 'menu-note', text: data.redacted ? 'Движок скрыл список устройств: доступно только системное устройство.' : kind === 'input' ? 'Микрофоны не найдены.' : 'Устройства вывода не найдены.' })
|
|
: null;
|
|
body.replaceChildren(...items, ...(note ? [note] : []), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
|
|
menu.removeAttribute('aria-busy');
|
|
position(menu, anchor, point);
|
|
focusables = [...items, settingsItem];
|
|
// Move focus into the list only if it is still inside the menu (the user may have clicked elsewhere).
|
|
if (menu.contains(document.activeElement)) focusAt(Math.max(0, items.findIndex((i) => i.getAttribute('aria-checked') === 'true')));
|
|
});
|
|
}
|
|
|
|
/** Above the button (the footer sits at the bottom), clamped inside the viewport. */
|
|
function position(menu, anchor, point) {
|
|
const rect = anchor.getBoundingClientRect();
|
|
const mw = menu.offsetWidth;
|
|
const mh = menu.offsetHeight;
|
|
const margin = 8;
|
|
let left = point ? point.x : rect.left;
|
|
let top = (point ? point.y : rect.top) - mh - 6;
|
|
if (top < margin) top = Math.min(rect.bottom + 6, window.innerHeight - mh - margin);
|
|
left = Math.max(margin, Math.min(left, window.innerWidth - mw - margin));
|
|
top = Math.max(margin, top);
|
|
menu.style.left = `${Math.round(left)}px`;
|
|
menu.style.top = `${Math.round(top)}px`;
|
|
}
|