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.

13.9 KB
Raw Blame
import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
import { isListViewID, type ListView } from '@app/constants/list-views';
import { CommandState } from '@app/features/command/state';
import { VIEW_TAB_PRESETS } from '@app/features/next-soup/sidebar/soup-filter-presets';
import {
  markChannelNotificationsSeenOnOpen,
  openEntityInSplitFromUnifiedList,
} from '@app/features/next-soup/utils';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { globalSplitManager } from '@app/signal/splitLayout';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import type { SplitHandle } from '@components/app/split-layout/layoutManager';
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isScopeInActiveBranch } from '@core/hotkey/utils';
import {
  type EntityData,
  filterNotDoneNotifications,
  filterValidNotifications,
  isSearchEntity,
  isWithNotification,
  type SearchLocation,
} from '@entity';
import { Telemetry } from '@macro-inc/observability';
import { openSingleStackNotification } from '@notifications';
import { markRowNotificationsSeenOnOpen } from '@notifications/mark-row-seen';
import { type Accessor, onCleanup } from 'solid-js';
import type { VirtualizerHandle } from 'virtua/solid';
import type { SoupState } from '../create-soup-state';
import {
  type TabbedListView,
  useVisibleViewTabs,
  VIEW_TAB_LISTS,
} from './soup-view-tabs';

const reportSoupViewError = (error: unknown) =>
  Telemetry.error(error, { surface: 'soup-view' });

type UseSoupViewHotkeysOptions = {
  onOpenProject?: (id: string) => void;
  onOpenEntity?: (entity: EntityData, event?: KeyboardEvent) => boolean;
  disableTabHotkeys?: boolean;
  scopeId: string;
  soup: SoupState;
  splitHandle: SplitHandle;
  virtualizerHandle: Accessor<VirtualizerHandle | undefined>;
  currentView: Accessor<ListView | undefined>;
  activeTab: Accessor<string | undefined>;
  applyTabPreset: (view: ListView, tabId: string) => void;
  fetchNextGroupPage: (groupKey: string) => Promise<void>;
};

// Escape belongs to the split, not the mounted list. Do not capture view
// props, virtualizers, or the other view hotkeys in its persistent callbacks.
function registerSplitEscapeHotkey(
  scopeId: string,
  selection: SoupState['selection'],
  splitHandle: SplitHandle
) {
  const splitIsUnifiedList = () => isListViewID(splitHandle.content().id);

  // escape - Multi-purpose: Clear selection / Close spotlight
  const clearMultiCondition = () =>
    selection.count() > 0 && splitIsUnifiedList();
  const closeSpotlightCondition = () => splitHandle.isSpotLight();

  const escapeDescription = () => {
    if (clearMultiCondition()) {
      return 'Clear multi selection';
    }
    if (closeSpotlightCondition()) {
      return 'Close spotlight';
    }
    return '';
  };

  // escape - Multi-purpose: Clear selection / Close spotlight
  // Deliberately outside the group and kept past this view's unmount: the
  // soup selection and split spotlight it acts on live at the split-panel
  // level, so escape keeps working after a list entity is opened in place.
  // The token is required for a persistent registration: same-token override
  // replacement is what dedupes it when this view remounts on the same split.
  registerHotkey({
    hotkey: ['escape'],
    scopeId,
    hotkeyToken: TOKENS.soup.dismiss,
    description: escapeDescription,
    condition: () => clearMultiCondition() || closeSpotlightCondition(),
    keyDownHandler: () => {
      if (clearMultiCondition()) {
        const length = selection.count();
        selection.clear();
        return length > 1;
      }
      if (closeSpotlightCondition()) {
        splitHandle.toggleSpotlight();
        return true;
      }
      return false;
    },
    disposeWithOwner: false,
  });
}

export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {
  const {
    scopeId,
    soup,
    splitHandle,
    virtualizerHandle,
    currentView,
    activeTab,
    applyTabPreset,
    fetchNextGroupPage,
  } = options;

  const analytics = useAnalytics();
  const notificationSource = useGlobalNotificationSource();
  registerSplitEscapeHotkey(scopeId, soup.selection, splitHandle);

  const group = createHotkeyGroup();

  // home, cmd+arrowup - Jump to top of list
  registerHotkey({
    hotkey: ['home', 'cmd+arrowup'],
    scopeId,
    hotkeyToken: TOKENS.entity.jump.home,
    description: 'Go to top of list',
    keyDownHandler: () => {
      const next = soup.navigate.toFirst();
      if (next) {
        virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
      }
      return true;
    },
    hide: true,
  }).withGroup(group);

  // Register 'g' in the global GO_TO command scope for g+g (jump to top)
  // Uses condition to only run for the soup-view that was focused when 'g' was pressed
  registerHotkey({
    hotkey: GO_TO_LEADER_KEY,
    scopeId: GO_TO_COMMAND_SCOPE,
    description: 'Go to top of list',
    condition: () => isScopeInActiveBranch(scopeId),
    keyDownHandler: () => {
      const next = soup.navigate.toFirst();
      if (next) {
        virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
      }
      return true;
    },
    registrationType: 'add',
  }).withGroup(group);

  // shift+g, end, cmd+arrowdown - Jump to bottom of list
  registerHotkey({
    hotkey: ['shift+g', 'end', 'cmd+arrowdown'],
    scopeId,
    hotkeyToken: TOKENS.entity.jump.end,
    description: 'Go to bottom of list',
    keyDownHandler: () => {
      const next = soup.navigate.toLast();
      if (next) {
        virtualizerHandle()?.scrollToIndex(next.index, { align: 'nearest' });
      }
      return true;
    },
    hide: true,
  }).withGroup(group);

  const tryOpenChannelNotification = (newSplit: boolean): boolean => {
    const entity = soup.focus.item();
    if (!entity) return false;
    if (entity.type !== 'channel' || !isWithNotification(entity)) return false;
    const validNotifs = filterNotDoneNotifications(
      filterValidNotifications(entity.notifications?.() ?? [])
    );
    const splitManager = globalSplitManager();
    const didOpen =
      !!splitManager &&
      openSingleStackNotification(
        validNotifs,
        splitManager,
        newSplit,
        splitHandle
      );
    if (didOpen) {
      markChannelNotificationsSeenOnOpen(entity, notificationSource);
    }
    return didOpen;
  };

  const openEntityFromList = async (
    entity: EntityData,
    openOptions: { location?: SearchLocation; openInNewSplit?: boolean }
  ) => {
    markRowNotificationsSeenOnOpen(entity, notificationSource);
    await openEntityInSplitFromUnifiedList(entity, {
      ...openOptions,
      splitHandle,
      referredFrom: currentView(),
      notificationSource,
    });
  };

  const loadMoreInGroup = async (groupKey: string, index: number) => {
    await fetchNextGroupPage(groupKey);
    soup.navigate.toIndex(index);
    virtualizerHandle()?.scrollToIndex(index, { align: 'nearest' });
  };

  // enter - Open entity in split, toggle group, or load more
  registerHotkey({
    hotkey: ['enter'],
    hotkeyToken: TOKENS.entity.open,
    scopeId,
    description: 'Open',
    hide: true,
    keyDownHandler: (event) => {
      // Native row controls own Enter. The document hotkey runs during capture,
      // before the reminder button's propagation guards can handle the event.
      if (
        event?.target instanceof Element &&
        event.target.closest('button[data-reminder-action]')
      )
        return false;
      const focusedRow = soup.focus.row();
      if (!focusedRow) return false;

      // If focused on a group header, toggle expand/collapse
      if (focusedRow.getIsGrouped() && focusedRow.group) {
        focusedRow.group.toggle();
        return true;
      }

      // If focused on a load more row, trigger load more and stay at same index
      if (focusedRow.getIsLoadMore() && focusedRow.group) {
        loadMoreInGroup(focusedRow.group.key, focusedRow.index).catch(
          reportSoupViewError
        );
        return true;
      }

      if (tryOpenChannelNotification(false)) return true;

      const entity = soup.focus.item();
      if (!entity) return false;

      if (entity.type === 'project' && options.onOpenProject) {
        options.onOpenProject(entity.id);
        return true;
      }
      if (options.onOpenEntity?.(entity, event)) return true;

      const contentHitData = isSearchEntity(entity)
        ? entity.search.contentHitData
        : undefined;
      // Only navigate to specific location if there's exactly one hit
      const location =
        contentHitData?.length === 1 ? contentHitData[0]?.location : undefined;

      openEntityFromList(entity, { location }).catch(reportSoupViewError);
      return true;
    },
    displayPriority: 4,
  }).withGroup(group);

  // x - Toggle select item
  registerHotkey({
    hotkey: ['x'],
    scopeId,
    description: 'Toggle select item',
    keyDownHandler: () => {
      const entity = soup.focus.item();
      if (!entity) return false;
      soup.selection.toggle(entity);
      return true;
    },
    displayPriority: 10,
  }).withGroup(group);

  // cmd+a - Toggle select all items
  registerHotkey({
    hotkey: ['cmd+a'],
    scopeId,
    description: 'Toggle select all',
    keyDownHandler: (e) => {
      const rows = soup.rows();
      if (rows.length === 0) return false;
      e?.preventDefault();
      if (soup.selection.count() === rows.length) {
        soup.selection.clear();
      } else {
        soup.selection.set(rows.map((r) => r.original));
      }
      return true;
    },
    displayPriority: 10,
  }).withGroup(group);

  // cmd+k - Open command menu with selection context
  // When there's a selection, opens in entity action mode showing only
  // selection modification commands with a preview of the selected entities
  registerHotkey({
    scopeId,
    description: () => {
      return CommandState.isOpen() ? 'Close command menu' : 'Open command menu';
    },
    hotkeyToken: TOKENS.global.commandMenu,
    hotkey: 'cmd+k',
    condition: () => !CommandState.isOpen(),
    keyDownHandler: (e) => {
      console.log('## CMD K - soup view');
      e?.preventDefault();
      const multiSelectEntities = soup.selection.selected();

      if (multiSelectEntities.length > 0) {
        analytics.track('command_menu_open', {
          from: 'soup_view_entity_action',
        });
        // Open in entity action mode with selection
        CommandState.openForEntityAction(multiSelectEntities.slice());
      } else {
        analytics.track('command_menu_open', {
          from: 'soup_view',
        });
        // Normal toggle
        CommandState.toggle();
      }
      return true;
    },
    displayPriority: 10,
    hide: CommandState.isOpen,
    runWithInputFocused: true,
  }).withGroup(group);

  // shift+enter - Open in new split
  registerHotkey({
    hotkey: ['shift+enter'],
    scopeId,
    description: 'Open in new split',
    condition: () => soup.focus.id() !== undefined,
    keyDownHandler: () => {
      if (tryOpenChannelNotification(true)) return true;

      const entity = soup.focus.item();
      if (!entity) return false;
      openEntityFromList(entity, { openInNewSplit: true }).catch(
        reportSoupViewError
      );
      return true;
    },
    hide: true,
  }).withGroup(group);

  const isTabbedView = (v: string): v is TabbedListView => v in VIEW_TAB_LISTS;

  const visibleViewTabs = useVisibleViewTabs();
  const getTabKeys = () => {
    if (options.disableTabHotkeys) return [];
    const view = currentView();
    if (!view || !isTabbedView(view)) return [];
    return visibleViewTabs(view).map((t) => t.value);
  };

  const switchToTabIndex = (index: number) => {
    const view = currentView();
    if (!view) return false;
    const tabKeys = getTabKeys();
    if (index < 0 || index >= tabKeys.length) return false;
    applyTabPreset(view, tabKeys[index]!);
    return true;
  };

  // 1-9 number keys to jump to specific tabs
  const tabNumberKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] as const;
  for (let i = 0; i < tabNumberKeys.length; i++) {
    const index = i;
    const key = tabNumberKeys[i]!;
    registerHotkey({
      hotkey: key,
      scopeId,
      hotkeyToken: TOKENS.soup.tabs[key],
      description: `Switch to tab ${key}`,
      condition: () => getTabKeys().length > index,
      keyDownHandler: () => switchToTabIndex(index),
      hide: true,
    }).withGroup(group);
  }

  // fall back to the view's default tab if the soup view active tab accessor
  // returns undefined
  const getCurrentTabIndex = () => {
    const tabKeys = getTabKeys();
    const current = activeTab();
    if (current) {
      const idx = tabKeys.indexOf(current);
      if (idx !== -1) return idx;
    }
    const view = currentView();
    if (!view) return 0;
    const config = VIEW_TAB_PRESETS[view];
    if (!config) return 0;
    const defaultIdx = tabKeys.indexOf(config.default);
    return defaultIdx !== -1 ? defaultIdx : 0;
  };

  // tab - Next tab
  registerHotkey({
    hotkey: ['tab'],
    scopeId,
    hotkeyToken: TOKENS.soup.tabs.next,
    description: 'Next tab',
    condition: () => getTabKeys().length > 1,
    keyDownHandler: () => {
      const view = currentView();
      if (!view) return false;
      const tabKeys = getTabKeys();
      const nextIndex = (getCurrentTabIndex() + 1) % tabKeys.length;
      applyTabPreset(view, tabKeys[nextIndex]!);
      return true;
    },
  }).withGroup(group);

  // shift+tab - Previous tab
  registerHotkey({
    hotkey: ['shift+tab'],
    scopeId,
    hotkeyToken: TOKENS.soup.tabs.prev,
    description: 'Previous tab',
    condition: () => getTabKeys().length > 1,
    keyDownHandler: () => {
      const view = currentView();
      if (!view) return false;
      const tabKeys = getTabKeys();
      const prevIndex =
        (getCurrentTabIndex() - 1 + tabKeys.length) % tabKeys.length;
      applyTabPreset(view, tabKeys[prevIndex]!);
      return true;
    },
  }).withGroup(group);

  onCleanup(() => group.dispose());
};