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.

fix(hotkeys): stop the g leader's timeout from stealing focus (#9733)

Wolf Mermelsteind11143f31885
diff --git a/apps/web/src/components/app/app-sidebar/go-to-leader.test.tsx b/apps/web/src/components/app/app-sidebar/go-to-leader.test.tsx
new file mode 100644
index 0000000000..e3392ad6d2
--- /dev/null
+++ b/apps/web/src/components/app/app-sidebar/go-to-leader.test.tsx
@@ -0,0 +1,98 @@
+import { GO_TO_COMMAND_SCOPE } from '@app/constants/hotkeys';
+import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
+import {
+ attachGlobalDOMScope,
+ registerHotkey,
+ useHotKeyRoot,
+ useHotkeyDOMScope,
+} from '@core/hotkey/hotkeys';
+import { activeScope, setActiveScope } from '@core/hotkey/state';
+import { render } from '@solidjs/testing-library';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { isGoToLeaderActive, useGoToLeader } from './go-to-leader';
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ vi.useRealTimers();
+ setActiveScope('global');
+});
+
+function press(key: string) {
+ document.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }));
+ document.dispatchEvent(new KeyboardEvent('keyup', { key, bubbles: true }));
+}
+
+function setup() {
+ function Harness() {
+ setHotkeyRoot(useHotKeyRoot());
+ const [attachSplit] = useHotkeyDOMScope('split');
+ const goToLeader = useGoToLeader();
+ // g a: the destination's composer mounts and takes focus a moment later,
+ // as Agents does.
+ registerHotkey({
+ hotkey: 'a',
+ scopeId: GO_TO_COMMAND_SCOPE,
+ description: 'Go to Agents',
+ keyDownHandler: () => {
+ goToLeader.leave();
+ setTimeout(() =>
+ document
+ .querySelector<HTMLElement>('[data-testid="composer"]')
+ ?.focus()
+ );
+ return true;
+ },
+ });
+ return (
+ <div ref={(element) => attachGlobalDOMScope(element)}>
+ <div ref={attachSplit} tabIndex={0} data-testid="split">
+ <div contentEditable tabIndex={0} data-testid="composer" />
+ </div>
+ </div>
+ );
+ }
+ return render(() => <Harness />);
+}
+
+it('keeps focus on a destination reached before the hints show', () => {
+ const view = setup();
+ view.getByTestId('split').focus();
+
+ press('g');
+ press('a');
+ vi.advanceTimersByTime(0);
+ expect(document.activeElement).toBe(view.getByTestId('composer'));
+
+ vi.advanceTimersByTime(3000);
+ expect(document.activeElement).toBe(view.getByTestId('composer'));
+ expect(isGoToLeaderActive()).toBe(false);
+});
+
+it('keeps focus on a destination reached after the hints show', () => {
+ const view = setup();
+ view.getByTestId('split').focus();
+
+ press('g');
+ vi.advanceTimersByTime(300);
+ expect(isGoToLeaderActive()).toBe(true);
+ press('a');
+ vi.advanceTimersByTime(0);
+ expect(document.activeElement).toBe(view.getByTestId('composer'));
+
+ vi.advanceTimersByTime(3000);
+ expect(document.activeElement).toBe(view.getByTestId('composer'));
+ expect(isGoToLeaderActive()).toBe(false);
+});
+
+it('leaves the GoTo scope when no destination follows', () => {
+ const view = setup();
+ view.getByTestId('split').focus();
+
+ press('g');
+ vi.advanceTimersByTime(300);
+ expect(activeScope()).toBe(GO_TO_COMMAND_SCOPE);
+
+ vi.advanceTimersByTime(2000);
+ expect(activeScope()).not.toBe(GO_TO_COMMAND_SCOPE);
+ expect(isGoToLeaderActive()).toBe(false);
+});
diff --git a/apps/web/src/components/app/app-sidebar/go-to-leader.ts b/apps/web/src/components/app/app-sidebar/go-to-leader.ts
new file mode 100644
index 0000000000..3d8eb3d25f
--- /dev/null
+++ b/apps/web/src/components/app/app-sidebar/go-to-leader.ts
@@ -0,0 +1,109 @@
+import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
+import { t } from '@app/lib/i18n';
+import { useHotkeyInterceptor } from '@app/signal/hotkeyRoot';
+import { getRunnableHotkeys } from '@core/hotkey/getCommands';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { activeScope, clearPressedKeys } from '@core/hotkey/state';
+import { TOKENS } from '@core/hotkey/tokens';
+import { activateClosestDOMScope } from '@core/hotkey/utils';
+import { debounce } from '@solid-primitives/scheduled';
+import { createSignal, onCleanup } from 'solid-js';
+
+/** Whether the "g" leader key is currently awaiting a destination key. */
+const [goToHotkeyVisible, setGoToHotkeyVisible] = createSignal(false);
+
+/**
+ * True while the "g" leader awaits a destination, so nav buttons can show
+ * their destination key. Any key in the GoTo scope leaves it, including a
+ * view's own GoTo command (Email's g s), so the hints clear with it.
+ */
+export const isGoToLeaderActive = () =>
+ goToHotkeyVisible() && activeScope() === GO_TO_COMMAND_SCOPE;
+
+const resetGoToHotkeysState = () => {
+ setGoToHotkeyVisible(false);
+ // To prevent the next key from triggering the hotkey handler,
+ // we reset the pressed keys state and exit the command scope
+ clearPressedKeys();
+ activateClosestDOMScope();
+};
+
+/**
+ * Registers "g" as the leader that activates the global GoTo command scope.
+ * Returns `leave`, which a destination calls once it fires.
+ */
+export function useGoToLeader() {
+ // Any key already left the GoTo scope, and the destination it reached may
+ // have focused an input since. Exiting again would refocus the split.
+ const debounceResetHotkeysState = debounce(() => {
+ if (activeScope() === GO_TO_COMMAND_SCOPE) resetGoToHotkeysState();
+ else setGoToHotkeyVisible(false);
+ }, 2000);
+ const debounceSetHotkeyVisible = debounce(
+ () => setGoToHotkeyVisible(true),
+ 200
+ );
+
+ const leaderHotkey = registerHotkey({
+ hotkey: GO_TO_LEADER_KEY,
+ scopeId: 'global',
+ hotkeyToken: TOKENS.sidebar.goToLeader,
+ description: () => t('nav.goToPage'),
+ keyDownHandler: () => {
+ // We debounce the time till the hot keys are visible to allow other commands
+ // like g+g to fire
+ debounceSetHotkeyVisible();
+ debounceResetHotkeysState();
+ return true;
+ },
+ activateCommandScopeId: GO_TO_COMMAND_SCOPE,
+ hide: true,
+ registrationType: 'add',
+ });
+
+ // The leader registers in the 'global' scope, which outlives its component,
+ // so dispose it on unmount. Otherwise a remount (e.g. crossing the mobile
+ // breakpoint) stacks duplicate 'add' handlers.
+ onCleanup(() => {
+ leaderHotkey.dispose();
+ debounceResetHotkeysState.clear();
+ debounceSetHotkeyVisible.clear();
+ });
+
+ // When the go to command scope is active, we want to prevent
+ // other default hotkeys from running. So doing "g" + some key
+ // not part of the sidebar hotkeys, won't fire the command
+ // for the key
+ useHotkeyInterceptor((context) => {
+ // If a hotkey is going to be fired, but the hotkeys are not
+ // visible, then it's not a sidebar nav hotkey and we can
+ // ignore it and reset our visible state
+ if (!goToHotkeyVisible()) {
+ debounceSetHotkeyVisible.clear();
+ return false;
+ }
+
+ if (context.eventType !== 'keydown') return false;
+
+ if (
+ context.activeScopeId !== GO_TO_COMMAND_SCOPE ||
+ // The sidebar's letters and those a focused view adds (Email's g s).
+ getRunnableHotkeys(GO_TO_COMMAND_SCOPE).has(context.pressedKeysString)
+ ) {
+ return false;
+ }
+
+ resetGoToHotkeysState();
+ debounceResetHotkeysState.clear();
+
+ return true;
+ });
+
+ const leave = () => {
+ debounceSetHotkeyVisible.clear();
+ debounceResetHotkeysState.clear();
+ if (goToHotkeyVisible()) resetGoToHotkeysState();
+ };
+
+ return { leave };
+}
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index de53854642..11d315731c 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -1,4 +1,4 @@
-import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
+import { GO_TO_COMMAND_SCOPE } from '@app/constants/hotkeys';
import {
EXTERNAL_VIEW_PATH,
LIST_VIEW_PATHS,
@@ -18,8 +18,8 @@ import {
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { t } from '@app/lib/i18n';
-import { useHotkeyInterceptor } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { useGoToLeader } from '@components/app/app-sidebar/go-to-leader';
import { useSplitLayout } from '@components/app/split-layout/layout';
import type {
ReferredFrom,
@@ -35,12 +35,9 @@ import {
enableTasksReviews,
enableWhatsappLinked,
} from '@core/constant/featureFlags';
-import { getRunnableHotkeys } from '@core/hotkey/getCommands';
import { registerHotkey } from '@core/hotkey/hotkeys';
-import { activeScope, clearPressedKeys } from '@core/hotkey/state';
import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';
import type { ValidHotkey } from '@core/hotkey/types';
-import { activateClosestDOMScope } from '@core/hotkey/utils';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import BellIcon from '@icon/system/regular/bell.svg';
import HomeIcon from '@icon/system/regular/house.svg';
@@ -48,13 +45,11 @@ import SearchIcon from '@icon/system/regular/magnifying-glass.svg';
import PlugIcon from '@icon/system/regular/plug.svg';
import ActivityIcon from '@icon/system/regular/pulse.svg';
import { ContextMenu } from '@kobalte/core/context-menu';
-import { debounce } from '@solid-primitives/scheduled';
import { cn } from '@ui';
import {
type Component,
createEffect,
createMemo,
- createSignal,
type JSX,
onCleanup,
Show,
@@ -216,25 +211,6 @@ export function navigateToSidebarView(args: {
}).split;
}
-/** Whether the "g" leader key is currently awaiting a destination key. */
-const [goToHotkeyVisible, setGoToHotkeyVisible] = createSignal(false);
-
-/**
- * True while the "g" leader awaits a destination, so nav buttons can show
- * their destination key. Any key in the GoTo scope leaves it, including a
- * view's own GoTo command (Email's g s), so the hints clear with it.
- */
-export const isGoToLeaderActive = () =>
- goToHotkeyVisible() && activeScope() === GO_TO_COMMAND_SCOPE;
-
-const resetGoToHotkeysState = () => {
- setGoToHotkeyVisible(false);
- // To prevent the next key from triggering the hotkey handler,
- // we reset the pressed keys state and exit the command scope
- clearPressedKeys();
- activateClosestDOMScope();
-};
-
/**
* Hosts the always-on global shortcuts that must keep working even on
* full-cover routes like solo settings: the "g" leader key with its per-link
@@ -275,68 +251,12 @@ export const GoToHotkeys = () => {
)
);
- const debounceResetHotkeysState = debounce(resetGoToHotkeysState, 2000);
- const debounceSetHotkeyVisible = debounce(
- () => setGoToHotkeyVisible(true),
- 200
- );
+ const goToLeader = useGoToLeader();
- // Register 'g' as a leader key that activates the global GO_TO command scope
- const leaderHotkey = registerHotkey({
- hotkey: GO_TO_LEADER_KEY,
- scopeId: 'global',
- hotkeyToken: TOKENS.sidebar.goToLeader,
- description: () => t('nav.goToPage'),
- keyDownHandler: () => {
- // We debounce the time till the hot keys are visible to allow other commands
- // like g+g to fire
- debounceSetHotkeyVisible();
- debounceResetHotkeysState();
- return true;
- },
- activateCommandScopeId: GO_TO_COMMAND_SCOPE,
- hide: true,
- registrationType: 'add',
- });
-
- // These two register in the 'global' scope, which outlives this component, so
- // dispose them on unmount. Otherwise a remount (e.g. crossing the mobile
- // breakpoint) leaks: the 'add' leader stacks duplicate handlers and the
- // token-only invite command accumulates in the registry. The per-link nav
- // hotkeys below are disposed by their own effect cleanup.
- onCleanup(() => {
- inviteHotkey.dispose();
- leaderHotkey.dispose();
- });
-
- // When the go to command scope is active, we want to prevent
- // other default hotkeys from running. So doing "g" + some key
- // not part of the sidebar hotkeys, won't fire the command
- // for the key
- useHotkeyInterceptor((context) => {
- // If a hotkey is going to be fired, but the hotkeys are not
- // visible, then it's not a sidebar nav hotkey and we can
- // ignore it and reset our visible state
- if (!goToHotkeyVisible()) {
- debounceSetHotkeyVisible.clear();
- return false;
- }
-
- if (context.eventType !== 'keydown') return false;
-
- if (
- context.activeScopeId !== GO_TO_COMMAND_SCOPE ||
- // The sidebar's letters and those a focused view adds (Email's g s).
- getRunnableHotkeys(GO_TO_COMMAND_SCOPE).has(context.pressedKeysString)
- ) {
- return false;
- }
-
- resetGoToHotkeysState();
- debounceResetHotkeysState.clear();
-
- return true;
- });
+ // Send Invites registers in the 'global' scope, which outlives this
+ // component, so dispose it on unmount. The per-link nav hotkeys below are
+ // disposed by their own effect cleanup.
+ onCleanup(() => inviteHotkey.dispose());
// Register navigation shortcuts in the global GO_TO command scope.
// This must be reactive because prod feature flags can add links after the
@@ -345,10 +265,7 @@ export const GoToHotkeys = () => {
const disposers = links().map((link) => {
const openSidebarView = (e?: KeyboardEvent) => {
e?.preventDefault();
- if (goToHotkeyVisible()) {
- resetGoToHotkeysState();
- debounceResetHotkeysState.clear();
- }
+ goToLeader.leave();
if (link.id === 'search' && !e?.shiftKey) {
const activeSplit = globalSplitManager()?.activeSplit();
diff --git a/apps/web/src/components/app/sidebar-next/list-nav.test.tsx b/apps/web/src/components/app/sidebar-next/list-nav.test.tsx
index 2327f06725..1bd12263ba 100644
--- a/apps/web/src/components/app/sidebar-next/list-nav.test.tsx
+++ b/apps/web/src/components/app/sidebar-next/list-nav.test.tsx
@@ -40,8 +40,10 @@ vi.mock('@app/signal/splitLayout', () => ({
returnFocus: vi.fn(),
}),
}));
-vi.mock('@components/app/app-sidebar/sidebar', () => ({
+vi.mock('@components/app/app-sidebar/go-to-leader', () => ({
isGoToLeaderActive: () => mocks.goToLeaderActive(),
+}));
+vi.mock('@components/app/app-sidebar/sidebar', () => ({
navigateToSidebarView: mocks.navigate,
sidebarContent: (id: string) => ({ type: 'component', id }),
SidebarOpenInSplitMenu: (props: ParentProps) => props.children,
diff --git a/apps/web/src/components/app/sidebar-next/list-nav.tsx b/apps/web/src/components/app/sidebar-next/list-nav.tsx
index d93d0f7475..8a4dd07485 100644
--- a/apps/web/src/components/app/sidebar-next/list-nav.tsx
+++ b/apps/web/src/components/app/sidebar-next/list-nav.tsx
@@ -4,8 +4,8 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { t } from '@app/lib/i18n';
import { useSplitRouter } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { isGoToLeaderActive } from '@components/app/app-sidebar/go-to-leader';
import {
- isGoToLeaderActive,
navigateToSidebarView,
SidebarOpenInSplitMenu,
sidebarContent,