Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(hotkeys): show the current view's shortcuts with ? (#8230)

teo04e0354ed22c
diff --git a/apps/web/src/components/app/GlobalHotkeys.tsx b/apps/web/src/components/app/GlobalHotkeys.tsx
index 712cd68444..c2a63b7332 100644
--- a/apps/web/src/components/app/GlobalHotkeys.tsx
+++ b/apps/web/src/components/app/GlobalHotkeys.tsx
@@ -23,8 +23,9 @@ import {
type SettingsTab,
useSettingsState,
} from '@core/constant/SettingsState';
+import { getShortcutSheet, type ShortcutSheet } from '@core/hotkey/getCommands';
import { registerHotkey } from '@core/hotkey/hotkeys';
-import { setActiveScope } from '@core/hotkey/state';
+import { activeScope, setActiveScope } from '@core/hotkey/state';
import { TOKENS } from '@core/hotkey/tokens';
import type { ValidHotkey } from '@core/hotkey/types';
import { fireAndForget } from '@core/util/fireAndForget';
@@ -61,6 +62,7 @@ import {
resolveActiveThemeId,
scheduleThemePreviewEnd,
} from '@theme/utils/themeUtils';
+import { ResultAsync } from 'neverthrow';
import { type Component, onCleanup, Show } from 'solid-js';
import { useSplitLayout } from './split-layout/layout';
@@ -127,6 +129,29 @@ function useHotkeyAnalytics(): void {
});
}
+/** The sheet loads on demand; it is not part of the startup bundle. */
+async function toggleKeyboardShortcuts(sheet: ShortcutSheet) {
+ const span = Telemetry.span('hotkeys.shortcut_sheet.toggle');
+ try {
+ span.setAttr('shortcut_sheet.view_count', sheet.view.length);
+ span.setAttr('shortcut_sheet.app_count', sheet.app.length);
+ const loaded = await ResultAsync.fromPromise(
+ import('./KeyboardShortcutsDialog'),
+ (error) => error
+ );
+ if (loaded.isErr()) {
+ span.setAttr('shortcut_sheet.outcome', 'load_failed');
+ span.error(loaded.error);
+ toast.failure('Unable to show keyboard shortcuts');
+ return;
+ }
+ loaded.value.toggleKeyboardShortcuts(sheet);
+ span.setAttr('shortcut_sheet.outcome', 'toggled');
+ } finally {
+ span.end();
+ }
+}
+
export default function GlobalShortcuts() {
const canFit = () => globalSplitManager()?.canAppendSplit() ?? true;
@@ -572,6 +597,29 @@ export default function GlobalShortcuts() {
},
});
+ registerHotkey({
+ hotkeyToken: TOKENS.global.keyboardShortcuts,
+ // '?' arrives as shift+/ and prints back as '?'.
+ hotkey: 'shift+/',
+ scopeId: 'global',
+ description: 'Show keyboard shortcuts',
+ keywords: ['hotkeys', 'keys', 'help', 'cheat sheet'],
+ // Only the key: run from the command menu, the sheet would describe the
+ // menu rather than the view it was opened from.
+ hide: true,
+ keyDownHandler: (e) => {
+ // German and French layouts type `/` with Shift, which also reads as
+ // shift+/; only an actual `?` opens the sheet.
+ if (e && e.key !== '?') return false;
+ // Read before the sheet takes focus and changes the active scope.
+ fireAndForget(
+ toggleKeyboardShortcuts(getShortcutSheet(activeScope())),
+ 'global-hotkeys'
+ );
+ return true;
+ },
+ });
+
registerHotkey({
hotkeyToken: TOKENS.global.undo,
hotkey: 'cmd+z',
diff --git a/apps/web/src/components/app/KeyboardShortcutsDialog.tsx b/apps/web/src/components/app/KeyboardShortcutsDialog.tsx
new file mode 100644
index 0000000000..6ed1ed8f45
--- /dev/null
+++ b/apps/web/src/components/app/KeyboardShortcutsDialog.tsx
@@ -0,0 +1,118 @@
+import type {
+ ShortcutSheet,
+ ShortcutSheetEntry,
+} from '@core/hotkey/getCommands';
+import { prettyPrintHotkeyString } from '@core/hotkey/utils';
+import {
+ ActionDialogShell,
+ Dialog,
+ type DialogHandle,
+ Hotkey,
+ type ManagedDialogProps,
+ openDialog,
+} from '@ui';
+import { For, Index, Show } from 'solid-js';
+
+function ShortcutRow(props: { entry: ShortcutSheetEntry }) {
+ return (
+ <li class="flex min-h-8 items-center justify-between gap-4 text-sm">
+ <span class="min-w-0 truncate text-ink">{props.entry.description}</span>
+ {/* Screen readers get the keys as words; the glyphs are visual. */}
+ <span class="sr-only">
+ {props.entry.bindings
+ .map((binding) => binding.join(' then '))
+ .join(' or ')}
+ </span>
+ <span
+ aria-hidden="true"
+ class="flex shrink-0 flex-wrap items-center justify-end gap-1 text-xs text-ink-extra-muted"
+ >
+ <Index each={props.entry.bindings}>
+ {(binding, bindingIndex) => (
+ <>
+ <Show when={bindingIndex > 0}>
+ <span>or</span>
+ </Show>
+ <Index each={binding()}>
+ {(key, keyIndex) => (
+ <>
+ <Show when={keyIndex > 0}>
+ <span>then</span>
+ </Show>
+ <Hotkey
+ shortcut={prettyPrintHotkeyString(key())}
+ theme="muted"
+ />
+ </>
+ )}
+ </Index>
+ </>
+ )}
+ </Index>
+ </span>
+ </li>
+ );
+}
+
+function ShortcutSection(props: {
+ title: string;
+ entries: ShortcutSheetEntry[];
+}) {
+ return (
+ <Show when={props.entries.length > 0}>
+ <section aria-label={props.title} class="min-w-0">
+ <h3 class="mb-2 text-xs font-medium text-ink-muted">{props.title}</h3>
+ <ul class="flex flex-col">
+ <For each={props.entries}>
+ {(entry) => <ShortcutRow entry={entry} />}
+ </For>
+ </ul>
+ </section>
+ </Show>
+ );
+}
+
+function KeyboardShortcutsDialog(
+ props: ManagedDialogProps & { sheet: ShortcutSheet }
+) {
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ position="center"
+ animate
+ class="w-full max-w-[min(52rem,calc(100vw-16px))]"
+ >
+ <ActionDialogShell>
+ <div class="shrink-0 border-b border-edge-divider px-5 py-4">
+ <ActionDialogShell.Title>Keyboard shortcuts</ActionDialogShell.Title>
+ </div>
+ {/* Focusable so the keyboard can scroll a long sheet. */}
+ <div
+ tabIndex={0}
+ aria-label="Shortcuts"
+ class="grid min-h-0 gap-x-8 gap-y-6 overflow-y-auto p-5 outline-none focus-visible:ring focus-visible:ring-inset focus-visible:ring-accent sm:grid-cols-2"
+ >
+ <ShortcutSection title="This view" entries={props.sheet.view} />
+ <ShortcutSection title="Everywhere" entries={props.sheet.app} />
+ </div>
+ </ActionDialogShell>
+ </Dialog>
+ );
+}
+
+let open: DialogHandle | undefined;
+
+/** Shows the shortcuts that were available when the sheet was read, or
+ * closes the sheet when it is already showing. */
+export function toggleKeyboardShortcuts(sheet: ShortcutSheet) {
+ if (open?.isOpen()) {
+ open.close();
+ return;
+ }
+ open = openDialog(
+ KeyboardShortcutsDialog,
+ { sheet },
+ { key: 'keyboard-shortcuts' }
+ );
+}
diff --git a/apps/web/src/features/settings/Shortcuts.tsx b/apps/web/src/features/settings/Shortcuts.tsx
index 57808c57e5..bc9497baa6 100644
--- a/apps/web/src/features/settings/Shortcuts.tsx
+++ b/apps/web/src/features/settings/Shortcuts.tsx
@@ -904,6 +904,11 @@ const shortcutSections: ShortcutSection[] = [
description: 'Focus AI chat',
},
{ keys: ['g'], codes: ['KeyG'], description: 'Go to a view' },
+ {
+ keys: ['?'],
+ codes: ['ShiftLeft', 'Slash'],
+ description: 'Show shortcuts for the current view',
+ },
],
},
{
diff --git a/apps/web/src/lib/core/hotkey/getCommands.ts b/apps/web/src/lib/core/hotkey/getCommands.ts
index 5aa574d8f5..3065115ae8 100644
--- a/apps/web/src/lib/core/hotkey/getCommands.ts
+++ b/apps/web/src/lib/core/hotkey/getCommands.ts
@@ -16,6 +16,8 @@ type sortAndFilterOptions = {
limitToCurrentScope?: boolean;
// skips the runWithInputFocused filter — use for the command menu where all commands should be shown regardless of input focus
ignoreInputFocused?: boolean;
+ // keeps commands registered with `hide` — the shortcut sheet lists hidden navigation keys
+ includeHidden?: boolean;
};
// This is reactive on active scope (if scope not specified), activeElement, and commmand conditions.
@@ -99,7 +101,100 @@ const filterCommands = (displayOptions: sortAndFilterOptions) => {
(displayOptions.ignoreInputFocused ||
!isEditableInput(activeElement() as HTMLElement) ||
command.runWithInputFocused) &&
- hideValue !== true
+ (displayOptions.includeHidden || hideValue !== true)
);
};
};
+
+/** One action in the shortcut sheet. Each binding is a key sequence. */
+export type ShortcutSheetEntry = {
+ description: string;
+ bindings: ValidHotkey[][];
+};
+
+export type ShortcutSheet = {
+ /** Shortcuts of the focused view and its parents, nearest first. */
+ view: ShortcutSheetEntry[];
+ /** Shortcuts that work anywhere in the app. */
+ app: ShortcutSheetEntry[];
+};
+
+/**
+ * Every shortcut reachable from a scope, for the shortcut sheet. Unlike the
+ * command menu it includes hidden navigation keys (j/k, Enter, Escape) and
+ * expands leader keys into sequences (g then e). Conditions are evaluated
+ * now, so read it before the sheet takes focus from the view.
+ */
+export function getShortcutSheet(scopeId: string): ShortcutSheet {
+ const sections = {
+ view: new Map<string, ShortcutSheetEntry>(),
+ app: new Map<string, ShortcutSheetEntry>(),
+ };
+ const seenBindings = new Set<string>();
+ const add = (
+ section: keyof typeof sections,
+ command: HotkeyCommand,
+ binding: ValidHotkey[]
+ ) => {
+ const bindingKey = binding.join(' ');
+ if (seenBindings.has(bindingKey)) return;
+ seenBindings.add(bindingKey);
+ const description =
+ typeof command.description === 'function'
+ ? command.description()
+ : command.description;
+ const entry = sections[section].get(description);
+ if (entry) entry.bindings.push(binding);
+ else
+ sections[section].set(description, { description, bindings: [binding] });
+ };
+
+ const commands = getActiveCommandsFromScope(scopeId, {
+ sortByScopeLevel: true,
+ hideCommandsWithoutHotkeys: true,
+ ignoreInputFocused: true,
+ includeHidden: true,
+ });
+ // Each key runs the nearest scope's command, and within a scope the one
+ // with the highest handler priority. Shadowing is per key, so a command
+ // keeps its other keys when only one of them is claimed nearer.
+ const keyOwners = new Map<ValidHotkey, HotkeyCommand>();
+ for (const command of [...commands].sort(
+ (a, b) =>
+ a.scopeLevel - b.scopeLevel ||
+ (b.handlerPriority ?? 0) - (a.handlerPriority ?? 0)
+ )) {
+ for (const hotkey of command.hotkeys ?? []) {
+ if (!keyOwners.has(hotkey)) keyOwners.set(hotkey, command);
+ }
+ }
+ for (const command of commands) {
+ const section = command.scopeId === 'global' ? 'app' : 'view';
+ const leaderScope = command.activateCommandScopeId;
+ const hidden =
+ typeof command.hide === 'function' ? command.hide() : command.hide;
+ if (!leaderScope || hidden !== true) {
+ for (const hotkey of command.hotkeys ?? []) {
+ if (keyOwners.get(hotkey) === command) add(section, command, [hotkey]);
+ }
+ }
+ if (!leaderScope) continue;
+ // In dispatch order, so a letter a view claims shadows the app's.
+ const followers = getActiveCommandsFromScope(leaderScope, {
+ limitToCurrentScope: true,
+ hideCommandsWithoutHotkeys: true,
+ ignoreInputFocused: true,
+ }).sort((a, b) => (b.handlerPriority ?? 0) - (a.handlerPriority ?? 0));
+ for (const leader of command.hotkeys ?? []) {
+ for (const follower of followers) {
+ for (const hotkey of follower.hotkeys ?? []) {
+ add(follower.sheetSection ?? section, follower, [leader, hotkey]);
+ }
+ }
+ }
+ }
+ return {
+ view: [...sections.view.values()],
+ app: [...sections.app.values()],
+ };
+}
diff --git a/apps/web/src/lib/core/hotkey/hotkeys.ts b/apps/web/src/lib/core/hotkey/hotkeys.ts
index efffe11dce..85be54f486 100644
--- a/apps/web/src/lib/core/hotkey/hotkeys.ts
+++ b/apps/web/src/lib/core/hotkey/hotkeys.ts
@@ -137,6 +137,7 @@ export function registerHotkey(
onHighlightEnd,
tags,
keywords,
+ sheetSection,
surfaceNestedCommands,
shouldReturnFocusOnClose,
proxiedHotkey,
@@ -247,6 +248,7 @@ export function registerHotkey(
onHighlightEnd,
tags,
keywords,
+ sheetSection,
surfaceNestedCommands,
shouldReturnFocusOnClose,
proxiedHotkey,
diff --git a/apps/web/src/lib/core/hotkey/shortcut-sheet.test.ts b/apps/web/src/lib/core/hotkey/shortcut-sheet.test.ts
new file mode 100644
index 0000000000..c9e9447dcd
--- /dev/null
+++ b/apps/web/src/lib/core/hotkey/shortcut-sheet.test.ts
@@ -0,0 +1,168 @@
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, expect, test } from 'vitest';
+import { getShortcutSheet } from './getCommands';
+import { registerHotkey } from './hotkeys';
+import { hotkeyScopeTree } from './state';
+import { registerScope, removeScope } from './utils';
+
+const disposers: (() => void)[] = [];
+const scopes: string[] = [];
+
+afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+ for (const scope of scopes.splice(0)) {
+ if (hotkeyScopeTree.has(scope)) removeScope(scope);
+ }
+});
+
+function domScope(scopeId: string) {
+ registerScope({ scopeId, parentScopeId: 'global', type: 'dom' });
+ scopes.push(scopeId);
+ return scopeId;
+}
+
+function leaderScope(scopeId: string) {
+ registerScope({
+ scopeId,
+ parentScopeId: 'global',
+ type: 'command',
+ activationKeys: ['g'],
+ });
+ scopes.push(scopeId);
+ return scopeId;
+}
+
+test('lists hidden navigation keys, leader sequences and the nearest binding of a key', () => {
+ const view = domScope('sheet-view');
+ const goTo = leaderScope('sheet-go-to');
+ const [archived, setArchived] = createSignal(false);
+ createRoot((dispose) => {
+ disposers.push(dispose);
+ const handler = () => true;
+ registerHotkey({
+ scopeId: view,
+ hotkey: ['j', 'arrowdown'],
+ description: 'Move down',
+ keyDownHandler: handler,
+ hide: true,
+ });
+ registerHotkey({
+ scopeId: view,
+ hotkey: 'e',
+ description: 'Mark done',
+ keyDownHandler: handler,
+ condition: () => !archived(),
+ });
+ // Shadowed by the view's `e`, so it must not be documented for this view.
+ registerHotkey({
+ scopeId: 'global',
+ hotkey: 'e',
+ description: 'Global e',
+ keyDownHandler: handler,
+ });
+ registerHotkey({
+ scopeId: 'global',
+ hotkey: 'g',
+ description: 'Go to',
+ keyDownHandler: handler,
+ activateCommandScopeId: goTo,
+ hide: true,
+ registrationType: 'add',
+ });
+ registerHotkey({
+ scopeId: goTo,
+ hotkey: 'i',
+ description: 'Go to Home',
+ keyDownHandler: handler,
+ registrationType: 'add',
+ });
+ // A view claiming the same letter runs first, so it is what g i does.
+ registerHotkey({
+ scopeId: goTo,
+ hotkey: 'i',
+ description: 'Go to Signal',
+ keyDownHandler: handler,
+ registrationType: 'add',
+ handlerPriority: 3,
+ sheetSection: 'view',
+ });
+ });
+
+ const sheet = getShortcutSheet(view);
+ // The view's letter is listed with the view's keys, not under Everywhere.
+ expect(sheet.view).toEqual([
+ { description: 'Move down', bindings: [['j'], ['arrowdown']] },
+ { description: 'Mark done', bindings: [['e']] },
+ { description: 'Go to Signal', bindings: [['g', 'i']] },
+ ]);
+ expect(sheet.app.map((entry) => entry.description)).not.toContain(
+ 'Go to Signal'
+ );
+ expect(sheet.app.map((entry) => entry.description)).not.toContain('Global e');
+ expect(sheet.app.map((entry) => entry.description)).not.toContain('Go to');
+ expect(sheet.app.map((entry) => entry.description)).not.toContain(
+ 'Go to Home'
+ );
+
+ // Conditions describe what works right now.
+ setArchived(true);
+ expect(
+ getShortcutSheet(view).view.map((entry) => entry.description)
+ ).not.toContain('Mark done');
+});
+
+test('keeps the keys of a partly shadowed command and follows handler priority', () => {
+ const view = domScope('sheet-partial-view');
+ createRoot((dispose) => {
+ disposers.push(dispose);
+ const handler = () => true;
+ // The view claims `e`; the global command still answers to `x`.
+ registerHotkey({
+ scopeId: view,
+ hotkey: 'e',
+ description: 'Mark done',
+ keyDownHandler: handler,
+ });
+ registerHotkey({
+ scopeId: 'global',
+ hotkey: ['e', 'x'],
+ description: 'Select',
+ keyDownHandler: handler,
+ });
+ // Two handlers on one key in one scope: the higher handler priority runs,
+ // whatever their display priority.
+ registerHotkey({
+ scopeId: view,
+ hotkey: 'o',
+ description: 'Open later',
+ keyDownHandler: handler,
+ registrationType: 'add',
+ displayPriority: 10,
+ });
+ registerHotkey({
+ scopeId: view,
+ hotkey: 'o',
+ description: 'Open now',
+ keyDownHandler: handler,
+ registrationType: 'add',
+ handlerPriority: 3,
+ });
+ });
+
+ const sheet = getShortcutSheet(view);
+ expect(sheet.view).toContainEqual({
+ description: 'Mark done',
+ bindings: [['e']],
+ });
+ expect(sheet.view).toContainEqual({
+ description: 'Open now',
+ bindings: [['o']],
+ });
+ expect(sheet.view.map((entry) => entry.description)).not.toContain(
+ 'Open later'
+ );
+ expect(sheet.app).toContainEqual({
+ description: 'Select',
+ bindings: [['x']],
+ });
+});
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index b28824c69e..8fbe3425bc 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -111,6 +111,7 @@ export const TOKENS = {
inviteTeam: 'global.inviteTeam',
undo: 'global.undo',
redo: 'global.redo',
+ keyboardShortcuts: 'global.keyboardShortcuts',
zoomIn: 'global.zoomIn',
zoomOut: 'global.zoomOut',
zoomReset: 'global.zoomReset',
diff --git a/apps/web/src/lib/core/hotkey/types.ts b/apps/web/src/lib/core/hotkey/types.ts
index 9418dd8cb4..952a3e3ff7 100644
--- a/apps/web/src/lib/core/hotkey/types.ts
+++ b/apps/web/src/lib/core/hotkey/types.ts
@@ -62,6 +62,9 @@ export interface HotkeyCommand {
tags?: string[];
// Optional related search terms for the command palette.
keywords?: string[];
+ // The shortcut sheet section, when the scope does not say: a key a view
+ // registers in an app-wide leader scope (g then a letter) is the view's.
+ sheetSection?: 'view';
// If true, command palette search also includes one level of nested commands.
surfaceNestedCommands?: boolean;
/**
@@ -204,6 +207,11 @@ export interface HotkeyRegistrationOptions {
* Optional related search terms for the command palette.
*/
keywords?: string[];
+ /**
+ * List this key under the current view in the shortcut sheet, for a view's
+ * key registered in an app-wide leader scope.
+ */
+ sheetSection?: 'view';
/**
* If true, command palette search also includes one level of nested commands.
*/
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 05f6312723..590f925fac 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -944,6 +944,10 @@ restart rules still apply.
## Keyboard model (from the in-app guide; verified partially)
- `Ctrl/Cmd+K` — jump to anything by name.
+- `?` — the focused view's shortcuts, read from its registered keys (hidden
+ navigation keys and `g` sequences included); `?` again closes it. Only the
+ key opens it: the command menu does not list it, since run from there it
+ would describe the menu. A view's `g` letters are listed under that view.
- `c` then `d`/`t`/`e`/`m`/`a` — create doc / task / email / channel / AI chat.
Single-letter shortcuts only work when no editor has focus; press `Escape` first.
- `/` — search everything. `j`/`k` — move in lists. `e` — mark done.