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.

21.1 KB
Raw Blame
import {
  COMMAND_MENU_CATEGORY_LEADER_KEY,
  COMMAND_MENU_CATEGORY_SCOPE,
  CREATE_MENU_COMMAND_SCOPE,
} from '@app/constants/hotkeys';
import { type CategoryFilter, CommandState } from '@app/features/command';
import {
  createMenuOpen,
  setCreateMenuOpen,
  useCreateCommands,
} from '@app/features/command/Launcher';
import { openMacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { inEnglish, t } from '@app/lib/i18n';
import { beginInteraction } from '@app/observability/flow';
import { useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
import { useHandleFileUpload } from '@app/util/handleFileUpload';
import { useLogout } from '@core/auth/logout';
import { toast } from '@core/component/Toast/Toast';
import { enableSnippets, LOCAL_ONLY } from '@core/constant/featureFlags';
import {
  type SettingsTab,
  useSettingsState,
} from '@core/constant/SettingsState';
import { getShortcutSheet, type ShortcutSheet } from '@core/hotkey/getCommands';
import { registerHotkey } from '@core/hotkey/hotkeys';
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';
import {
  handleFolderSelect,
  openFilePicker,
  openFolderPicker,
} from '@core/util/upload';
import IconGear from '@icon/system/regular/gear.svg';
import Plus from '@icon/system/regular/plus.svg';
import LogoutIcon from '@icon/system/regular/sign-out.svg';
import Upload from '@icon/system/regular/upload.svg';
import UserIcon from '@icon/system/regular/user.svg';
import { Telemetry } from '@macro-inc/observability';
import { useMutationUndoContext } from '@queries/undo';
import { debounce } from '@solid-primitives/scheduled';
import { ThemeChips } from '@theme/components/ThemeChips';
import {
  darkModeTheme,
  lightModeTheme,
  setDarkModeTheme,
  setLightModeTheme,
  setThemeMode,
  systemMode,
  themeMode,
  themes,
} from '@theme/signals/themeSignals';
import type { ThemeV3 } from '@theme/types/themeTypes';
import {
  applySystemTheme,
  applyTheme,
  previewTheme,
  resolveActiveThemeId,
  scheduleThemePreviewEnd,
} from '@theme/utils/themeUtils';
import { ResultAsync } from 'neverthrow';
import { type Component, onCleanup, Show } from 'solid-js';
import { useSplitLayout } from './split-layout/layout';

// `keyword` is the English name, kept as a search term in every language;
// `label` is the displayed (translated) name.
const COMMAND_MENU_CATEGORY_HOTKEYS: Array<{
  category: CategoryFilter;
  hotkey: ValidHotkey;
  keyword: string;
  label: string;
}> = [
  {
    category: 'all',
    hotkey: 'l',
    keyword: 'All',
    get label() {
      return t('commandMenu.categoryAll');
    },
  },
  {
    category: 'commands',
    hotkey: 'm',
    keyword: 'Command',
    get label() {
      return t('commandMenu.categoryCommands');
    },
  },
  {
    category: 'chats',
    hotkey: 'a',
    keyword: 'Agents',
    get label() {
      return t('commandMenu.categoryAgents');
    },
  },
  {
    category: 'documents',
    hotkey: 'f',
    keyword: 'Files',
    get label() {
      return t('commandMenu.categoryFiles');
    },
  },
  {
    category: 'tasks',
    hotkey: 't',
    keyword: 'Tasks',
    get label() {
      return t('commandMenu.categoryTasks');
    },
  },
  {
    category: 'channels',
    hotkey: 'c',
    keyword: 'Channels',
    get label() {
      return t('commandMenu.categoryChannels');
    },
  },
  {
    category: 'dms',
    hotkey: 'p',
    keyword: 'People',
    get label() {
      return t('commandMenu.categoryPeople');
    },
  },
];

function useHotkeyAnalytics(): void {
  const analytics = useAnalytics();

  const track = (
    description: string,
    token: string | undefined,
    key: string
  ) => {
    analytics.track('hotkey_use', {
      action: description,
      token,
      key,
    });
  };

  const debouncedTrack = debounce(track, 250);

  let lastFired: string | undefined;
  useSubscribeToKeypress((context) => {
    // Only track when a command was actually executed
    if (!context.commandCaptured) return;

    const command = context.commandCaptured;
    // Analytics groups actions by their English description in every language.
    const description = inEnglish(() =>
      typeof command.description === 'function'
        ? command.description()
        : command.description
    );

    const pressedKeysString = context.pressedKeysString;

    // If we keep firing the same key, we can debounce the track call to avoid
    // sending many of the same event (like for tab, j, k, etc.). Otherwise, we
    // can just track normally for unique events
    let trackFn = lastFired === pressedKeysString ? debouncedTrack : track;

    if (lastFired !== pressedKeysString) {
      debouncedTrack.clear();
    }

    trackFn(description, command.hotkeyToken, pressedKeysString);

    lastFired = pressedKeysString;
  });

  onCleanup(() => {
    debouncedTrack.clear();
  });
}

/** 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;
  /** Room to split the active split toward `side`; with none active, room at the end. */
  const canSplitActive = (side: 'right' | 'below') => {
    const manager = globalSplitManager();
    const active = manager?.activeSplitId();
    if (!manager || !active) return canFit();

    return manager.canSplit(active, side);
  };

  const analytics = useAnalytics();
  const undoCtx = useMutationUndoContext();

  useHotkeyAnalytics();

  const { openSettings, settingsOpen, selectTab, toggleSettings } =
    useSettingsState();
  const logout = useLogout();

  const handleFileUpload = useHandleFileUpload();
  const snippetsFlag = useFeatureFlag(enableSnippets);

  const handleCommandMenu = (event?: KeyboardEvent) => {
    const willOpen = !CommandState.isOpen();

    if (willOpen) {
      analytics.track('command_menu_open', { from: 'global_hotkey' });
    }

    const interaction = willOpen
      ? beginInteraction('quick_access.open', { event })
      : undefined;
    try {
      CommandState.toggle();
    } finally {
      interaction?.end();
    }
  };

  registerHotkey({
    hotkeyToken: TOKENS.global.createCommand,
    hotkey: 'c',
    scopeId: 'global',
    description: () => t('commands.create'),
    keyDownHandler: () => {
      const willOpen = !createMenuOpen();

      if (willOpen) {
        analytics.track('create_menu_open', { from: 'global_hotkey' });
      }

      setCreateMenuOpen((prev) => !prev);
      return true;
    },
    displayPriority: 10,
    activateCommandScopeId: CREATE_MENU_COMMAND_SCOPE,
    surfaceNestedCommands: true,
    keywords: ['new', 'make', 'add'],
    icon: Plus,
  });

  const createCommands = useCreateCommands();
  createCommands.forEach((item) => {
    registerHotkey({
      hotkeyToken: item.hotkeyToken,
      hotkey: item.hotkey,
      scopeId: CREATE_MENU_COMMAND_SCOPE,
      description: item.description,
      condition: () =>
        (item.condition?.() ?? true) &&
        (item.enabled?.() ?? true) &&
        (item.blockName !== 'snippet' || snippetsFlag().enabled),
      // Entries that deliberately share a key (the flagged agent pair) opt
      // into 'add' so both survive registration and the dispatcher picks the
      // one whose condition passes, rather than the later silently winning.
      registrationType: item.registrationType,
      keyDownHandler: item.keyDownHandler,
      icon: Plus,
      tags: item.tags,
      keywords: item.keywords,
      hide: () =>
        !(item.enabled?.() ?? true) ||
        (item.blockName === 'snippet' && !snippetsFlag().enabled),
      runWithInputFocused: item.runWithInputFocused ?? true,
    });
  });

  registerHotkey({
    hotkey: 'escape',
    scopeId: CREATE_MENU_COMMAND_SCOPE,
    description: () => t('commands.closeCreate'),
    condition: createMenuOpen,
    keyDownHandler: () => {
      setCreateMenuOpen(false);
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    hotkey: 'c',
    scopeId: CREATE_MENU_COMMAND_SCOPE,
    description: () => t('commands.closeCreate'),
    condition: () =>
      createMenuOpen() &&
      !createCommands.some(
        (item) => item.hotkey === 'c' && (item.enabled?.() ?? true)
      ),
    registrationType: 'add',
    keyDownHandler: () => {
      setCreateMenuOpen(false);
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    hotkeyToken: TOKENS.global.commandMenu,
    hotkey: 'cmd+k',
    scopeId: 'global',
    description: () =>
      CommandState.isOpen()
        ? t('commands.closeCommandMenu')
        : t('commands.openCommandMenu'),
    keyDownHandler: (event) => {
      console.log('## CMD K - global');
      handleCommandMenu(event);
      return true;
    },
    displayPriority: 10,
    hide: CommandState.isOpen,
    runWithInputFocused: true,
  });

  registerHotkey({
    hotkey: COMMAND_MENU_CATEGORY_LEADER_KEY,
    scopeId: 'global',
    description: () => t('commands.openCategory'),
    keyDownHandler: () => true,
    activateCommandScopeId: COMMAND_MENU_CATEGORY_SCOPE,
    surfaceNestedCommands: true,
    keywords: ['command menu', 'palette', 'category'],
  });

  for (const item of COMMAND_MENU_CATEGORY_HOTKEYS) {
    registerHotkey({
      hotkey: item.hotkey,
      scopeId: COMMAND_MENU_CATEGORY_SCOPE,
      description: () =>
        t('commands.openCategoryNamed', { category: item.label }),
      keyDownHandler: () => {
        setActiveScope('global');
        CommandState.setCategoryFilter(item.category);
        CommandState.setQuery('');
        CommandState.setSelectedIndex(0);
        CommandState.open();
        return true;
      },
      keywords: ['command menu', 'palette', 'category', item.keyword],
      runWithInputFocused: true,
    });
  }

  const { openWithSplit } = useSplitLayout();

  /** Opens Home splitting the active split toward `side`. */
  const splitActive = (side: 'right' | 'below') => {
    const active = globalSplitManager()?.activeSplitId();
    analytics.track('split_created', { from: 'global_hotkey', side });
    openWithSplit(
      { type: 'component', id: 'home' },
      {
        referredFrom: 'hotkey',
        allowDuplicate: true,
        preferNewSplit: true,
        beside: active && { split: active, side },
      }
    );
    return true;
  };
  const createNewSplit = () => splitActive('right');
  const createNewSplitBelow = () => splitActive('below');

  registerHotkey({
    hotkey: 'cmd+\\',
    scopeId: 'global',
    description: () => t('commands.createNewSplit'),
    condition: () => canSplitActive('right'),
    keyDownHandler: createNewSplit,
    runWithInputFocused: true,
  });

  registerHotkey({
    hotkeyToken: TOKENS.global.createNewSplit,
    hotkey: '\\',
    scopeId: 'global',
    description: () => t('commands.createNewSplit'),
    condition: () => canSplitActive('right'),
    keyDownHandler: createNewSplit,
  });

  registerHotkey({
    hotkey: 'shift+cmd+\\',
    scopeId: 'global',
    description: () => t('commands.createNewSplitBelow'),
    condition: () => canSplitActive('below'),
    keyDownHandler: createNewSplitBelow,
    runWithInputFocused: true,
  });

  registerHotkey({
    hotkeyToken: TOKENS.global.createNewSplitBelow,
    hotkey: 'shift+\\',
    scopeId: 'global',
    description: () => t('commands.createNewSplitBelow'),
    condition: () => canSplitActive('below'),
    keyDownHandler: createNewSplitBelow,
  });

  // Open settings to a specific tab, switching the page in place if settings
  // are already open.
  const openSettingsAt = (tab?: SettingsTab) => {
    if (settingsOpen()) {
      if (tab) selectTab(tab);
      return;
    }
    openSettings(tab);
  };

  registerHotkey({
    hotkeyToken: TOKENS.global.toggleSettings,
    hotkey: 'cmd+;',
    scopeId: 'global',
    description: () => t('commands.toggleSettings'),
    keyDownHandler: () => {
      toggleSettings();
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    scopeId: 'global',
    description: () => t('commands.account'),
    icon: UserIcon,
    keyDownHandler: () => {
      openSettingsAt('Account');
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    scopeId: 'global',
    description: () => t('commands.logout'),
    icon: LogoutIcon,
    keyDownHandler: () => {
      logout().catch((error) => {
        Telemetry.error(error, { surface: 'logout' });
        toast.failure(t('commands.failedToSignOut'));
      });
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    scopeId: 'global',
    description: () => t('commands.mcpSetup'),
    keyDownHandler: () => {
      openMacroMcpSetupModal();
      return true;
    },
    icon: IconGear,
    runWithInputFocused: true,
    displayPriority: 9,
    tags: ['mcp', 'model context protocol', 'setup', 'connect macro'],
  });

  const setThemeScope = registerHotkey({
    scopeId: 'global',
    description: () => t('commands.changeTheme'),
    keyDownHandler: () => {
      return true;
    },
    activateCommandScope: true,
    runWithInputFocused: true,
    displayPriority: 10,
  });

  const ThemeDisplay: Component<{ theme: ThemeV3 }> = (props) => (
    <div class="flex items-center gap-2">
      {props.theme.name}
      <ThemeChips theme={props.theme} size="sm" />
    </div>
  );

  // The per-mode theme the OS scheme currently resolves to — shown as the
  // "System preference" option's swatch and previewed on highlight.
  const systemResolvedTheme = (): ThemeV3 | undefined =>
    themes().find(
      (theme) =>
        theme.id ===
        (systemMode() === 'dark' ? darkModeTheme() : lightModeTheme())
    );

  const setVisibleTheme = (themeId: string) => {
    const resolvedMode = themeMode() === 'system' ? systemMode() : themeMode();
    if (resolvedMode === 'dark') {
      setDarkModeTheme(themeId);
    } else {
      setLightModeTheme(themeId);
    }
  };

  // "System preference" mirrors the Active-theme dropdown's first option: follow
  // the OS scheme rather than pinning a fixed theme.
  registerHotkey({
    scopeId: setThemeScope.commandScopeId,
    description: () => t('commands.systemPreference'),
    keyDownHandler: () => {
      applySystemTheme();
      analytics.track('theme_changed', { themeId: 'system' });
      return true;
    },
    runWithInputFocused: true,
    displayComponent: () => (
      <div class="flex items-center gap-2">
        {t('commands.systemPreference')}
        <Show when={systemResolvedTheme()}>
          {(theme) => <ThemeChips theme={theme()} size="sm" />}
        </Show>
      </div>
    ),
    onHighlight: () => {
      const theme = systemResolvedTheme();
      if (theme) previewTheme(theme.id);
    },
    onHighlightEnd: scheduleThemePreviewEnd,
  });

  themes().forEach((theme) => {
    registerHotkey({
      scopeId: setThemeScope.commandScopeId,
      description: `${theme.name}`,
      keyDownHandler: () => {
        // Change the theme currently being viewed without switching between
        // static and system-driven theme modes.
        setVisibleTheme(theme.id);
        applyTheme(resolveActiveThemeId());
        analytics.track('theme_changed', { themeId: theme.id });
        return true;
      },
      runWithInputFocused: true,
      displayComponent: () => <ThemeDisplay theme={theme} />,
      onHighlight: () => previewTheme(theme.id),
      onHighlightEnd: scheduleThemePreviewEnd,
    });
  });

  const setPreferredLightScope = registerHotkey({
    scopeId: 'global',
    description: () => t('commands.setDefaultLightTheme'),
    keyDownHandler: () => {
      return true;
    },
    activateCommandScope: true,
    runWithInputFocused: true,
  });

  themes().forEach((theme) => {
    registerHotkey({
      scopeId: setPreferredLightScope.commandScopeId,
      description: `${theme.name}`,
      keyDownHandler: () => {
        setLightModeTheme(theme.id);
        analytics.track('theme_changed', { themeId: theme.id });
        return true;
      },
      runWithInputFocused: true,
      displayComponent: () => <ThemeDisplay theme={theme} />,
      onHighlight: () => previewTheme(theme.id),
      onHighlightEnd: scheduleThemePreviewEnd,
    });
  });

  const setPreferredDarkScope = registerHotkey({
    scopeId: 'global',
    description: () => t('commands.setDefaultDarkTheme'),
    keyDownHandler: () => {
      return true;
    },
    activateCommandScope: true,
    runWithInputFocused: true,
  });

  themes().forEach((theme) => {
    registerHotkey({
      scopeId: setPreferredDarkScope.commandScopeId,
      description: `${theme.name}`,
      keyDownHandler: () => {
        setDarkModeTheme(theme.id);
        analytics.track('theme_changed', { themeId: theme.id });
        return true;
      },
      runWithInputFocused: true,
      displayComponent: () => <ThemeDisplay theme={theme} />,
      onHighlight: () => previewTheme(theme.id),
      onHighlightEnd: scheduleThemePreviewEnd,
    });
  });

  registerHotkey({
    scopeId: 'global',
    description: () =>
      themeMode() === 'system'
        ? t('commands.turnOffAutoDetectColorScheme')
        : t('commands.autoDetectColorScheme'),
    keyDownHandler: () => {
      // Toggle system (auto-detect) on/off; turning it off pins the theme to the
      // OS's current scheme so the appearance doesn't visibly change.
      setThemeMode((prev) => (prev === 'system' ? systemMode() : 'system'));
      return true;
    },
    runWithInputFocused: true,
  });

  registerHotkey({
    scopeId: 'global',
    description: () => t('commands.uploadFiles'),
    icon: () => <Upload class="size-4" />,
    keyDownHandler: () => {
      openFilePicker({ multiple: true }, async (files) => {
        await handleFileUpload(files, false);
      });
      return true;
    },
  });

  if (LOCAL_ONLY) {
    registerHotkey({
      scopeId: 'global',
      description: 'Open hotkey debugger',
      tags: ['debug', 'dev', 'hotkey'],
      keyDownHandler: () => {
        openWithSplit(
          { type: 'component', id: 'hotkey-debugger' },
          {
            referredFrom: 'hotkey',
            allowDuplicate: true,
            preferNewSplit: true,
          }
        );
        return true;
      },
      runWithInputFocused: true,
    });
  }

  registerHotkey({
    scopeId: 'global',
    description: () => t('commands.uploadFolders'),
    icon: () => <Upload class="size-4" />,
    keyDownHandler: () => {
      openFolderPicker({ multiple: true }, async (files) => {
        await handleFolderSelect(files, async (entries) => {
          await handleFileUpload(entries, false);
        });
      });
      return true;
    },
  });

  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',
    scopeId: 'global',
    description: () => t('commands.undo'),
    keyDownHandler: (e) => {
      if (!undoCtx.canUndo()) return false;
      e?.preventDefault();
      fireAndForget(
        undoCtx.undo({
          onError: () => toast.failure(t('commands.failedToUndo')),
        }),
        'global-hotkeys'
      );
      return true;
    },
    condition: () => undoCtx.canUndo(),
  });

  registerHotkey({
    hotkeyToken: TOKENS.global.redo,
    hotkey: 'shift+cmd+z',
    scopeId: 'global',
    description: () => t('commands.redo'),
    keyDownHandler: (e) => {
      if (!undoCtx.canRedo()) return false;
      e?.preventDefault();
      fireAndForget(
        undoCtx.redo({
          onError: () => toast.failure(t('commands.failedToRedo')),
        }),
        'global-hotkeys'
      );
      return true;
    },
    condition: () => undoCtx.canRedo(),
  });

  return null;
}