waybetter/packages/shell/src/frame/AppMenu.tsx

616 lines
37 KiB
TypeScript

// The app menu: the titlebar's "Settings and more" button, at the far end of the titlebar cluster
// (before the caption buttons on Windows and Linux; macOS has none there). It opens on click, on
// Alt+F and F10 (Shell.tsx; a focused tab forwards the keys), from the command palette, from the
// last row of the account menu, and from the app's logo at the start of the titlebar (the same
// menu, hung under the logo on its side of the window). Its rows are the app's (`ShellSite.menu`, menuModel.ts): built-in
// ones by name, each shown only when the app serves what it needs, and the app's own.
//
// Like every shell menu it is an overlay: while open the shell is raised above the tab webviews
// (`setOverlay`), panes stay visible and nothing is dimmed. Keyboard: arrows, Home/End, type-ahead,
// the arrow pointing along the reading direction opens a submenu and the other one closes it,
// Enter or Space chooses, Esc closes one level. Submenus fly out beside the menu and stay inside
// the window (in a narrow one they lie over it). Words: menuMessages.en.json (`menuText`).
import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts';
import { invoke, listen } from './bridge.ts';
import { describe, diag } from './diag.ts';
import { decks } from './deckStore.ts';
import { refreshDev } from './devHost.ts';
import { useDev, usePaneTick, useT } from './hooks.ts';
import { formatNumber } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import {
DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow,
type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuModeStatus, type MenuRow,
} from './menuModel.ts';
import { ReportDialog } from './ReportDialog.tsx';
import { safe, setSafeMode } from './safeStore.ts';
import { hasFeature, site } from './site.ts';
import { isWeb, setOverlay, shell, type TabParams } from './state.ts';
import { openWorkspaceSave } from './TitlebarExtras.tsx';
import { os, startDrag, systemMenu } from './windowBinding.ts';
import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
import { readZoom, stepZoom, zoomOf, zoomTarget } from './zoomStore.ts';
import './appMenu.css';
/** How the menu is asked to open: under the logo instead of its button, at a submenu, with the first row focused (keyboard), or closing if it is open. */
export type AppMenuRequest = { anchor?: 'button' | 'logo'; submenu?: string; keyboard?: boolean; toggle?: boolean };
/** Opens the app menu (Alt+F / F10, the palette, the account menu's last row). */
export const openAppMenu = (request: AppMenuRequest = {}) => window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: request }));
const mac = os === 'macos';
/** The keys that open the menu, as the button's tooltip and the account menu write them. */
export const APP_MENU_KEYS = mac ? 'F10' : 'Alt+F';
const getError = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^Error: /, '');
const percent = (factor: number) => formatNumber(factor, { style: 'percent', maximumFractionDigits: 0 });
type Focus = { level: number; id?: string; edge?: 'first' | 'last' | 'menu' };
/** Where the menu hangs: under its button (from the window's end edge) or under the logo (from its start edge). */
type Anchor = { at: 'button' | 'logo'; top: number; left?: number; right?: number };
/** Which trigger the open menu hangs from (null: closed), for the triggers' `aria-expanded`. */
let openAt: Anchor['at'] | null = null;
function noteOpen(at: Anchor['at'] | null) {
if (openAt === at) return;
openAt = at;
window.dispatchEvent(new CustomEvent('bt-app-menu-state'));
}
/** The rows of one level a key can stop on: enabled items; the zoom row counts once. */
function stopsOf(menu: HTMLElement): HTMLElement[] {
const all = Array.from(menu.querySelectorAll<HTMLElement>('[data-item]:not(:disabled)'));
const active = document.activeElement;
const zoom = all.filter(el => 'zoom' in el.dataset);
const keep = zoom.find(el => el === active) ?? zoom.find(el => el.getAttribute('aria-disabled') !== 'true') ?? zoom[0];
return all.filter(el => !('zoom' in el.dataset) || el === keep);
}
export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
const t = useT();
usePaneTick();
const dev = useDev();
const config = site();
const menu = config.menu ?? {};
const [open, setOpen] = useState(false);
const [path, setPath] = useState<string[]>([]);
const [anchor, setAnchor] = useState<Anchor>({ at: 'button', top: 50, right: 8 });
const [mode, setMode] = useState<string | null>(null);
const [modeStatus, setModeStatus] = useState<MenuModeStatus | null>(null);
const [asking, setAsking] = useState<{ to: string; changes: number; reapply?: boolean } | null>(null);
const [version, setVersion] = useState('');
const [update, setUpdate] = useState<UpdateStatus>({ state: 'idle' });
const [askedUpdate, setAskedUpdate] = useState(false);
const [reporting, setReporting] = useState(false);
const [error, setError] = useState('');
const [, tick] = useReducer((n: number) => n + 1, 0);
const button = useRef<HTMLButtonElement>(null);
const layers = useRef<HTMLDivElement>(null);
const focusNext = useRef<Focus | null>(null);
const before = useRef<HTMLElement | null>(null);
const hover = useRef<{ el: Element | null; timer?: ReturnType<typeof setTimeout> }>({ el: null });
const typed = useRef({ text: '', at: 0 });
const live = useRef({ open, path });
live.current = { open, path };
// Whatever a row shows may change while the menu is open (a language or theme picked in it).
useEffect(() => {
const events = ['bt-zoom', 'bt-workspaces', 'bt-decks', 'bt-site', 'bt-safe'];
for (const event of events) window.addEventListener(event, tick);
const off = [config.themes?.subscribe(tick), menu.languages?.subscribe(tick)];
return () => {
for (const event of events) window.removeEventListener(event, tick);
for (const dispose of off) dispose?.();
};
}, []);
/** Where a request without an anchor opens: the button when this app shows one, else the logo. */
const home = (): Anchor['at'] => (trigger ? 'button' : 'logo');
function show(request: AppMenuRequest = {}) {
const at = request.anchor ?? home();
diag(`menu open: anchor=${at} keyboard=${!!request.keyboard} hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
const logo = at === 'logo' ? document.querySelector('.bt-titlebar-logo') : null;
const rect = (logo ?? button.current)?.getBoundingClientRect();
if (rect) {
const top = Math.round(rect.bottom + 6);
setAnchor(logo ? { at: 'logo', top, left: Math.max(8, Math.round(rect.left - 3)) } : { at: 'button', top, right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
}
const active = document.activeElement as HTMLElement | null;
before.current = active && active !== document.body && document.hasFocus() ? active : null;
// Keys pressed in a tab open the menu: the shell takes the keyboard. A click on the shell already
// gave it the keyboard, so nothing native is asked for then.
if (!document.hasFocus()) invoke('shell_focus').catch(() => {});
setAsking(null); setError('');
setPath(request.submenu ? [request.submenu] : []);
focusNext.current = request.submenu ? { level: 1, edge: 'first' } : { level: 0, edge: request.keyboard ? 'first' : 'menu' };
setOpen(true);
// What the rows show, read fresh.
void readZoom(zoomTarget());
if (hasFeature('developer')) void refreshDev();
if (hasFeature('workspaces') && !workspaces.loaded) void loadWorkspaces().catch(() => {});
void config.themes?.loadThemes();
menu.modes?.current().then(setMode, () => {});
menu.modes?.status?.().then(setModeStatus, () => {});
if (!version) menu.version?.().then(setVersion, () => {});
setAskedUpdate(false);
if (hasFeature('updates')) invoke('update_status').then(value => setUpdate(parseUpdateStatus(value)), () => {});
}
/** `escape`: back to what had focus before. `action` and `away`: nothing focused, so typing returns to the active pane. */
function close(how: 'escape' | 'action' | 'away' = 'away', why = '') {
diag(`menu close: ${how}${why ? ` (${why})` : ''} hasFocus=${document.hasFocus()}`);
clearTimeout(hover.current.timer);
hover.current = { el: null };
focusNext.current = null;
setOpen(false); setPath([]); setAsking(null); setError('');
if (how === 'escape' && before.current?.isConnected) before.current.focus();
before.current = null;
}
// The updater's steps (checking, downloading, ready) as they happen.
useEffect(() => {
if (!hasFeature('updates')) return;
let disposed = false;
let unlisten: (() => void) | undefined;
listen('update-status', event => setUpdate(parseUpdateStatus(event.payload)))
.then(dispose => { if (disposed) dispose(); else unlisten = dispose; })
.catch(() => {});
return () => { disposed = true; unlisten?.(); };
}, []);
useEffect(() => {
const onRequest = (event: Event) => {
const request = (event as CustomEvent<AppMenuRequest | undefined>).detail ?? {};
// Asked again from the other trigger, the open menu moves there instead of closing.
if (live.current.open && request.toggle && (request.anchor ?? home()) === (openAt ?? home())) close('escape'); else show(request);
};
window.addEventListener('bt-app-menu', onRequest);
return () => window.removeEventListener('bt-app-menu', onRequest);
}, [version]);
useEffect(() => {
if (!open) return;
// Native tab webviews would cover the menu.
setOverlay(1);
noteOpen(anchor.at);
// The window lost the keyboard: the menu closes, unless the focus is back a moment later (taking the
// keyboard from a tab for Alt+F / F10 can pass through a blur on its way to the shell).
let leaving: ReturnType<typeof setTimeout> | undefined;
const away = () => {
diag(`menu: window blur hasFocus=${document.hasFocus()}`);
clearTimeout(leaving);
leaving = setTimeout(() => { if (!document.hasFocus()) close('away', 'blur'); else diag('menu: blur passed, focus is back'); }, 160);
};
const resized = () => close();
// Keys while nothing in the menu has focus (a click on its padding): Esc closes, arrows enter it.
const onKey = (event: KeyboardEvent) => {
if (layers.current?.contains(event.target as Node)) return;
if (event.key === 'Escape') { event.preventDefault(); close('escape'); return; }
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
focusNext.current = { level: live.current.path.length, edge: event.key === 'ArrowDown' ? 'first' : 'last' };
tick();
}
};
window.addEventListener('blur', away);
window.addEventListener('resize', resized);
window.addEventListener('keydown', onKey);
return () => { clearTimeout(leaving); setOverlay(-1); noteOpen(null); window.removeEventListener('blur', away); window.removeEventListener('resize', resized); window.removeEventListener('keydown', onKey); };
}, [open, anchor.at]);
const layer = (level: number) => layers.current?.querySelector<HTMLElement>(`[data-level="${level}"]`) ?? null;
// After every render: submenus sit beside their row, inside the window; then the focus that was asked for.
useLayoutEffect(() => {
if (!open) return;
for (let level = 1; level <= path.length; level += 1) {
const el = layer(level);
const parent = layer(level - 1);
const row = parent?.querySelector<HTMLElement>(`[data-item="${CSS.escape(path[level - 1]!)}"]`);
if (!el || !parent) continue;
const edge = 8;
const box = parent.getBoundingClientRect();
el.style.maxHeight = `${window.innerHeight - edge * 2}px`;
const { width, height } = el.getBoundingClientRect();
const left = submenuLeft(box, width, window.innerWidth, edge);
// It slides in from the side it hangs on.
el.style.setProperty('--bt-app-sub-from', left < box.left ? '6px' : '-6px');
const top = Math.max(edge, Math.min((row?.getBoundingClientRect().top ?? box.top) - 6, window.innerHeight - height - edge));
el.style.left = `${Math.round(left)}px`;
el.style.top = `${Math.round(top)}px`;
}
const want = focusNext.current;
const el = want ? layer(want.level) : null;
if (!want || !el) return;
focusNext.current = null;
const stops = stopsOf(el);
const target = want.id ? el.querySelector<HTMLElement>(`[data-item="${CSS.escape(want.id)}"]:not(:disabled)`)
: want.edge === 'menu' ? el : want.edge === 'last' ? stops[stops.length - 1] : stops[0];
(target ?? el).focus();
});
const openSub = (level: number, id: string, focus = false) => {
setPath(current => [...current.slice(0, level), id]);
setAsking(null); setError('');
if (focus) focusNext.current = { level: level + 1, edge: 'first' };
};
/** Closes the submenu at `level`; its row gets the focus back. */
const closeSub = (level: number) => {
focusNext.current = { level: level - 1, id: path[level - 1] };
setPath(current => current.slice(0, level - 1));
setAsking(null); setError('');
};
async function activate(row: MenuItemRow, level: number) {
if (row.disabled) return;
if (row.submenu) {
if (path[level] === row.id) { focusNext.current = { level: level + 1, edge: 'first' }; tick(); } else openSub(level, row.id, true);
return;
}
setError('');
if (!row.keepOpen) close('action');
try { await row.run?.(); }
catch (failure) { if (row.keepOpen) setError(getError(failure)); else console.error('[shell] menu', failure); }
}
// -------------------------------------------------------------------------------------------
// Rows
const item = (id: string, label: string, icon: IconName | undefined, rest: Partial<MenuItemRow> = {}): MenuItemRow => ({ kind: 'item', id, label, icon, ...rest });
/** "Plugins…": a row that opens a section of the app's panel. */
const section = (name: string) => menuText('section', { section: name });
const active = shell.api?.activePanel;
const activeParams = active?.params as TabParams | undefined;
const canSplit = !!active && (isWeb(active) || active.group.panels.length > 1);
const languageName = (code: string | undefined) => menu.languages?.list.find(language => language.code === code)?.name;
const themeState = config.themes?.current();
const themeId = config.themes && themeState ? config.themes.adapter.preset(themeState.choice) : '';
const modeList = menu.modes?.list() ?? [];
/** Settings → Language: the panel's Settings, scrolled to that group once it is there. */
function openSettingsAt(anchor: string) {
shell.openPanelSection('settings');
let tries = 0;
const find = () => {
const heading = document.getElementById(`${anchor}-h`);
if (heading) heading.scrollIntoView({ block: 'start' });
else if ((tries += 1) < 40) setTimeout(find, 50);
};
find();
}
function builtin(id: BuiltinMenuItem): MenuRow {
switch (id) {
case 'new-tab': return item(id, t('wb.shell.tab.new'), 'plus', { shortcut: 'Ctrl+T', run: () => shell.shortcut('new-tab') });
case 'split-right': return item(id, t('wb.shell.menu.splitRight'), 'split', { shortcut: 'Ctrl+\\', disabled: !canSplit, run: () => shell.shortcut('split-right') });
case 'split-down': return item(id, t('wb.shell.menu.splitDown'), 'splitDown', { shortcut: 'Ctrl+Shift+\\', disabled: !canSplit, run: () => shell.shortcut('split-down') });
case 'new-column': return item(id, menuText('newColumn'), 'columns', {
run: () => {
// The deck in front, else the first one; with none yet, the deck tab itself (it starts one).
const target = activeParams?.kind === 'deck' ? activeParams.deckId : decks.list[0]?.id;
shell.run(target ? { type: 'deck-add', deckId: target } : { type: 'deck' });
},
});
case 'language': return item(id, t('wb.settings.language.title'), 'globe', { submenu: true, hint: languageName(menu.languages?.state().locale) });
case 'theme': return item(id, menuText('theme'), 'palette', { submenu: true, hint: themeId ? config.themes!.themeName(themeId) : undefined });
case 'mode': {
const label = modeList.find(entry => entry.id === mode)?.label;
return item(id, t('wb.modes.section'), 'layers', { submenu: true, hint: label && modeStatus?.custom ? t('wb.modes.custom', { mode: label }) : label });
}
case 'zoom': return { kind: 'zoom', id: 'zoom' };
case 'plugins': return item(id, section(t('wb.panel.section.plugins')), 'plug', { run: () => shell.openPanelSection('plugins') });
case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') });
case 'strings': return item(id, section(menuText('strings')), 'globe', { run: () => shell.openPanelSection('languages') });
case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name });
case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !active || !isWeb(active), run: () => shell.shortcut('find') });
case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) });
case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') });
case 'developer': return item(id, menuText('developer'), 'code', { submenu: true });
case 'updates': {
// A real check: the row asks the updater now and says what came of it (the titlebar chip stays the loud part).
const row = updateRow(update, askedUpdate, version);
return item(id, row.label, 'reload', {
hint: row.hint, title: row.title, keepOpen: row.action === 'check' || row.action === 'wait',
run: async () => {
if (row.action === 'open') { shell.openPanelSection('updates'); return; }
if (row.action === 'restart') { await invoke('apply_update'); return; }
if (row.action !== 'check') return;
setAskedUpdate(true);
setUpdate({ state: 'checking' });
// One request, no retry: whatever the updater answers is what the row says.
try { setUpdate(parseUpdateStatus(await invoke('update_check'))); } catch { setUpdate({ state: 'error', message: '' }); }
},
});
}
// Off: a submenu that says what it does before anything reloads. On: one row that leaves it.
case 'safe-mode': return safe.active
? item(id, menuText('safeLeave'), 'shield', { run: () => setSafeMode(false) })
: item(id, menuText('safeRestart'), 'shield', { submenu: true });
case 'report': return item(id, menuText('report'), 'flag', { run: () => setReporting(true) });
case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') });
case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') });
}
}
function submenuRows(id: string): MenuRow[] {
switch (id) {
case 'language': {
const languages = menu.languages;
if (!languages) return [];
const rows = languageRows(languages.list, languages.state(), { site: t('wb.settings.language.followSite'), system: t('wb.settings.language.followSystem'), more: menuText('moreLanguages') });
return rows.map(row => {
if (row.kind !== 'item') return row;
const choice = languageChoice(row.id);
// Switching is live and the menu stays: what was picked can be read (or undone) on the spot.
return choice ? { ...row, keepOpen: true, run: () => languages.set(choice) } : { ...row, run: () => openSettingsAt('language') };
});
}
case 'theme': {
const themes = config.themes;
if (!themes || !themeState) return [];
const list: MenuRow[] = themes.allThemes(themeState.choice).map(theme => item(`theme:${theme.id}`, theme.name, undefined, {
check: 'radio', checked: theme.id === themeId, keepOpen: true, swatch: themes.adapter.dots(theme),
// As Appearance does: a theme starts without the customizations made on another one.
run: () => themes.setChoice(themes.adapter.choiceForId(themeState.choice, theme.id)),
}));
return joinGroups([list, [
item('theme:builder', section(t('wb.panel.section.builder')), 'edit', { run: () => shell.openPanelSection('builder') }),
item('theme:more', menuText('moreAppearance'), 'palette', { run: () => shell.openPanelSection('themes') }),
]]);
}
case 'mode': {
const modes = menu.modes;
if (!modes) return [];
const name = (modeId: string) => modeList.find(entry => entry.id === modeId)?.label ?? modeId;
const apply = async (to: string, keep: boolean) => { await modes.apply(to, keep); setMode(to); close('action'); };
const at = path.indexOf('mode') + 1;
if (asking?.reapply && modeStatus) {
// What applying the mode again turns on and off, said before it happens.
return [
{ kind: 'note', id: 'mode:reapply-hint', title: t('wb.modes.reapply', { mode: name(asking.to) }), text: t('wb.modes.reapplyHint', { mode: name(asking.to) }) },
...(modeStatus.on.length ? [{ kind: 'note' as const, id: 'mode:reapply-on', title: '', text: t('wb.modes.turnsOn', { list: modeStatus.on.join(', ') }) }] : []),
...(modeStatus.off.length ? [{ kind: 'note' as const, id: 'mode:reapply-off', title: '', text: t('wb.modes.turnsOff', { list: modeStatus.off.join(', ') }) }] : []),
item('mode:reapply-yes', t('wb.modes.reapply', { mode: name(asking.to) }), 'reload', { keepOpen: true, run: async () => { await modes.reapply?.(); close('action'); } }),
item('mode:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => { focusNext.current = { level: at, id: 'mode:reapply' }; setAsking(null); } }),
];
}
if (asking) {
// The question Settings asks: what was changed by hand stays, or the mode is taken as it is.
return [
{ kind: 'note', id: 'mode:question', title: t('wb.modes.keepQuestion'), text: t('wb.modes.keepHint', { count: asking.changes }) },
item('mode:keep', t('wb.modes.keep'), 'check', { keepOpen: true, run: () => apply(asking.to, true) }),
item('mode:reset', t('wb.modes.reset', { mode: name(asking.to) }), 'reload', { keepOpen: true, run: () => apply(asking.to, false) }),
item('mode:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => { focusNext.current = { level: at, id: `mode:${asking.to}` }; setAsking(null); } }),
];
}
const list = modeList.map(entry => item(`mode:${entry.id}`, entry.label, undefined, {
check: 'radio', checked: entry.id === mode, keepOpen: true,
run: async () => {
if (entry.id === mode) { close('action'); return; }
const changes = await modes.changes(entry.id);
if (changes > 0) { focusNext.current = { level: at, edge: 'first' }; setAsking({ to: entry.id, changes }); } else await apply(entry.id, false);
},
}));
if (!mode || !modeStatus?.custom || !modes.reapply) return list;
// The mode is a starting point: the features moved on, and nothing applies it again unasked.
const grew: MenuRow[] = modeStatus.added > 0 ? [{ kind: 'note', id: 'mode:grew', title: '', text: t('wb.modes.grew', { mode: name(mode), count: modeStatus.added }) }] : [];
return joinGroups([list, [
{ kind: 'note', id: 'mode:custom', title: t('wb.modes.custom', { mode: name(mode) }) },
...grew,
item('mode:reapply', t('wb.modes.reapply', { mode: name(mode) }), 'reload', {
keepOpen: true,
run: () => {
focusNext.current = { level: at, edge: 'first' };
setAsking({ to: mode, changes: 0, reapply: true });
if (modeStatus.added > 0) void modes.seen?.().then(() => setModeStatus({ ...modeStatus, added: 0 }), () => {});
},
}),
]]);
}
case 'workspaces': {
const list = workspaceList();
const rows: MenuRow[] = list.length
? list.map(entry => item(`ws:${entry.id}`, entry.name, undefined, { check: 'radio', checked: entry.id === workspaces.active, hint: t('wb.ws.tabs', { count: entry.tabs }), run: () => restoreWorkspace(entry.id) }))
: [{ kind: 'note', id: 'ws:none', title: '', text: menuText('noWorkspaces') }];
return joinGroups([rows, [item('ws:save', menuText('saveLayout'), 'plus', { run: openWorkspaceSave })]]);
}
case 'safe-mode': return [
{ kind: 'note', id: 'safe:question', title: menuText('safeQuestion'), text: menuText('safeExplain') },
item('safe:confirm', menuText('safeConfirm'), 'shield', { run: () => setSafeMode(true) }),
item('safe:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => closeSub(path.indexOf('safe-mode') + 1) }),
];
case 'developer': return [
item('dev:mode', t('wb.dev.mode'), undefined, { check: 'checkbox', checked: dev.enabled, keepOpen: true, run: async () => { await invoke('dev_set', { enabled: !dev.enabled }); await refreshDev(); } }),
item('dev:folder', menuText('pluginsFolder'), 'folder', { run: () => invoke('plugins_open_folder') }),
];
default: return specRows(findSpec(groups, id)?.submenu?.() ?? []);
}
}
const groups = menu.groups ?? DEFAULT_MENU;
const env: MenuEnv = {
decks: !!config.deck, languages: !!menu.languages, themes: !!config.themes, modes: modeList.length > 0,
zoom: hasFeature('zoom'), find: hasFeature('find'), safeMode: hasFeature('safeMode'), store: hasFeature('store'), strings: config.features?.strings === true, workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'),
};
const rootRows = () => joinGroups(planMenu(groups, env).map(group => group.flatMap(entry => (typeof entry === 'string' ? [builtin(entry)] : specRows([entry])))));
const labelOf = (id: string, rows: MenuRow[]) => rows.find((row): row is MenuItemRow => row.kind === 'item' && row.id === id)?.label ?? '';
// -------------------------------------------------------------------------------------------
// Keyboard and pointer
function onKey(event: ReactKeyboardEvent<HTMLDivElement>) {
const target = event.target as HTMLElement;
const menuEl = target.closest<HTMLElement>('[data-level]');
if (!menuEl) return;
const level = Number(menuEl.dataset.level);
const { key } = event;
// The keyboard leads now: the row under a resting pointer takes the focus back only when the pointer moves on.
clearTimeout(hover.current.timer);
hover.current = { el: null };
const keys = submenuKeys(getComputedStyle(menuEl).direction === 'rtl');
const done = () => { event.preventDefault(); event.stopPropagation(); };
if (key === 'Escape') { done(); if (level > 0) closeSub(level); else close('escape'); return; }
if (key === 'Tab') { done(); close('escape'); return; }
// The zoom row is one stop: left and right move through − + and reset (laid out left to right).
if ('zoom' in target.dataset && (key === 'ArrowLeft' || key === 'ArrowRight')) {
done();
const controls = Array.from(menuEl.querySelectorAll<HTMLElement>('[data-zoom]'));
controls[Math.max(0, Math.min(controls.length - 1, controls.indexOf(target) + (key === 'ArrowRight' ? 1 : -1)))]?.focus();
return;
}
if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End') {
done();
const stops = stopsOf(menuEl);
stops[moveStop(stops.indexOf(target), key, stops.length)]?.focus();
return;
}
if (key === keys.open) {
if (target.getAttribute('aria-haspopup') === 'menu' && target.dataset.item) { done(); openSub(level, target.dataset.item, true); }
return;
}
if (key === keys.close) { if (level > 0) { done(); closeSub(level); } return; }
const now = Date.now();
const typing = !!typed.current.text && now - typed.current.at <= 700;
// Enter, and Space outside a typed word: the row's own click chooses it; on the menu itself nothing is chosen.
if (key === 'Enter' || (key === ' ' && !typing)) {
if (target === menuEl) done();
typed.current.text = '';
return;
}
if (key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey) return;
// Type-ahead: the next row whose label starts with what was typed.
done();
typed.current = { text: typing ? typed.current.text + key : key, at: now };
const stops = stopsOf(menuEl);
const found = typeahead(stops.map(el => el.dataset.label ?? ''), stops.indexOf(target), typed.current.text);
if (found >= 0) stops[found]!.focus();
}
/** The pointer moves the focus, like the arrows do: one highlight. A row with a submenu opens it after a beat. */
function onHover(row: MenuItemRow | null, level: number, el: HTMLElement) {
if (hover.current.el === el) return;
clearTimeout(hover.current.timer);
hover.current = { el };
if (document.activeElement !== el) el.focus({ preventScroll: true });
if (row?.submenu) {
if (path[level] !== row.id) hover.current.timer = setTimeout(() => openSub(level, row.id), 170);
} else if (path.length > level) {
hover.current.timer = setTimeout(() => { setPath(current => current.slice(0, level)); setAsking(null); }, 280);
}
}
// -------------------------------------------------------------------------------------------
function renderRow(row: MenuRow, level: number, index: number) {
if (row.kind === 'separator') return <hr key={`sep${index}`} role="separator"/>;
if (row.kind === 'note') {
return <div key={row.id} className={`bt-app-note${row.tone === 'error' ? ' is-error' : ''}`} role={row.tone === 'error' ? 'alert' : 'presentation'}>
{row.title && <strong>{row.title}</strong>}{row.text && <span>{row.text}</span>}
</div>;
}
if (row.kind === 'zoom') {
const tab = zoomTarget();
const factor = zoomOf(tab);
const control = (id: string, label: string, icon: IconName, direction: 1 | -1 | 0, off: boolean, className = '') =>
<button type="button" role="menuitem" tabIndex={-1} className={className} data-item={`zoom:${id}`} data-zoom="" data-label={menuText('zoom')}
aria-label={label} title={tab ? label : menuText('zoomNone')} aria-disabled={off}
onPointerMove={event => onHover(null, level, event.currentTarget)} onClick={() => { if (!off) void stepZoom(direction, tab); }}>
<Icon name={icon}/>
</button>;
return <div key="zoom" className={`bt-app-zoom${tab ? '' : ' is-off'}`} role="group" aria-label={menuText('zoom')} title={tab ? undefined : menuText('zoomNone')}>
<Icon name="zoom"/>
<span className="bt-menu-label">{menuText('zoom')}</span>
<span className="bt-app-zoom-step">
{control('out', menuText('zoomOut'), 'minus', -1, !tab || factor <= ZOOM_MIN)}
<output className="bt-app-zoom-value" aria-live="polite">{percent(factor)}</output>
{control('in', menuText('zoomIn'), 'plus', 1, !tab || factor >= ZOOM_MAX)}
</span>
{control('reset', menuText('zoomReset'), 'reload', 0, !tab || factor === 1, 'bt-app-zoom-reset')}
</div>;
}
const expanded = row.submenu ? path[level] === row.id : undefined;
return <button key={row.id} type="button" tabIndex={-1} disabled={row.disabled} data-item={row.id} data-label={row.label} title={row.title}
role={row.check === 'radio' ? 'menuitemradio' : row.check ? 'menuitemcheckbox' : 'menuitem'} aria-checked={row.check ? !!row.checked : undefined}
aria-haspopup={row.submenu ? 'menu' : undefined} aria-expanded={expanded}
onPointerMove={event => onHover(row, level, event.currentTarget)} onClick={() => void activate(row, level)}>
{row.check ? <span className="bt-app-check">{row.checked && <Icon name="check"/>}</span> : row.icon ? <Icon name={row.icon}/> : <span className="bt-app-check"/>}
{/* A language's own name keeps its own direction (<bdi>) but starts where every other label does. */}
<span className="bt-menu-label">{row.lang ? <bdi lang={row.lang} dir={row.dir}>{row.label}</bdi> : row.label}</span>
{row.swatch && <span className="wb-dots" aria-hidden="true" style={{ background: row.swatch.page }}>
<i style={{ background: row.swatch.bg, boxShadow: `inset 0 0 0 1px ${row.swatch.border}` }}/><i style={{ background: row.swatch.text }}/><i style={{ background: row.swatch.accent }}/>
</span>}
{row.hint && <span className="bt-app-hint">{row.hint}</span>}
{row.shortcut && <span className="bt-menu-keys">{shortcutText(row.shortcut, mac)}</span>}
{row.submenu && <Icon name="chevronRight" className="bt-app-chevron"/>}
</button>;
}
function renderMenus() {
const root = rootRows();
const levels: Array<{ rows: MenuRow[]; label: string }> = [{ rows: root, label: menuText('label') }];
path.forEach((id, index) => levels.push({ rows: submenuRows(id), label: labelOf(id, levels[index]!.rows) }));
// An error belongs to the level it happened on: the deepest one open.
if (error) levels[levels.length - 1]!.rows = [...levels[levels.length - 1]!.rows, { kind: 'note', id: 'error', title: '', text: error, tone: 'error' }];
return levels.map(({ rows, label }, level) => <div key={level === 0 ? 'root' : `${level}:${path[level - 1]}`} role="menu" aria-label={label} tabIndex={-1} data-level={level}
className={level === 0 ? `bt-menu bt-app-menu bt-pop${anchor.at === 'logo' ? '' : ' bt-pop--right'}` : 'bt-menu bt-app-menu bt-app-sub'}
style={level === 0 ? { top: anchor.top, left: anchor.left, right: anchor.right, maxHeight: `calc(100vh - ${anchor.top + 8}px)` } : undefined}>
{rows.map((row, index) => renderRow(row, level, index))}
</div>);
}
const label = menuText('label');
return <>
{trigger && <button ref={button} type="button" className="bt-app-button" aria-haspopup="menu" aria-expanded={open && anchor.at === 'button'} aria-label={label} title={`${label} (${APP_MENU_KEYS})`}
onClick={event => (open && anchor.at === 'button' ? close('escape') : show({ keyboard: event.detail === 0 }))}>
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="5.75" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="18.25" r="1.6"/></svg>
</button>}
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={layers} className="bt-app-layers" onMouseDown={event => event.stopPropagation()} onContextMenu={event => { event.preventDefault(); event.stopPropagation(); }} onKeyDown={onKey}>
{renderMenus()}
</div>
</div>, document.body)}
{reporting && <ReportDialog onClose={() => setReporting(false)}/>}
</>;
}
/**
* The app's logo at the start of the titlebar: a second trigger of the same menu, hung under the
* logo. A click opens it; a press that turns into a drag moves the window, as the titlebar around
* it does; a right-click shows the window's system menu, where a titlebar icon has always had it.
*/
export function AppMenuLogo() {
useT();
const [expanded, setExpanded] = useState(openAt === 'logo');
const press = useRef<{ x: number; y: number; dragged: boolean } | null>(null);
useEffect(() => {
const update = () => setExpanded(openAt === 'logo');
window.addEventListener('bt-app-menu-state', update);
return () => window.removeEventListener('bt-app-menu-state', update);
}, []);
const { product, logo } = site();
const label = menuText('label');
return <button type="button" className="bt-titlebar-logo" aria-haspopup="menu" aria-expanded={expanded} aria-label={`${product}: ${label}`} title={`${product} · ${label}`}
onPointerDown={event => { if (event.button === 0) press.current = { x: event.clientX, y: event.clientY, dragged: false }; }}
onPointerMove={event => {
const start = press.current;
if (!start || start.dragged || !(event.buttons & 1)) return;
// The press became a drag: the window moves, and no menu opens when the button is released.
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) { start.dragged = true; startDrag(); }
}}
onClick={event => {
const dragged = press.current?.dragged;
press.current = null;
if (!dragged) openAppMenu({ anchor: 'logo', toggle: true, keyboard: event.detail === 0 });
}}
onContextMenu={event => {
event.preventDefault(); event.stopPropagation();
const scale = window.devicePixelRatio || 1;
systemMenu(Math.round(event.screenX * scale), Math.round(event.screenY * scale));
}}>
<img src={logo} alt="" draggable={false}/>
</button>;
}