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.

12.9 KB
Raw Blame
import { listOwnedSlotName } from '@app/components/list';
import { isListViewID } from '@app/constants/list-views';
import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import type { SplitHandle } from '@components/app/split-layout/layoutManager';
import { withSplitPanelOwner } from '@components/app/split-layout/layoutUtils';
import { entityIdSelector } from '@core/dom-selectors';
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { type EntityData, isTaskEntity } from '@entity/types/entity';
import { Telemetry } from '@macro-inc/observability';
import { type Accessor, onCleanup } from 'solid-js';
import type { VirtualizerHandle } from 'virtua/solid';
import type { SoupState } from '../create-soup-state';

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

type UseSoupNavigationHotkeysOptions = {
  scopeId: string;
  soup: SoupState;
  splitHandle: SplitHandle;
  virtualizerHandle: Accessor<VirtualizerHandle | undefined>;
  hasNextPage?: Accessor<boolean>;
  isFetching?: Accessor<boolean>;
  isFetchingNextPage?: Accessor<boolean>;
  fetchNextPage?: () => Promise<void>;
  error?: Accessor<Error | null>;
  /** Server-grouped lists continue each group with its own pages. */
  groupPaging?: {
    load: (groupKey: string) => Promise<void>;
    isLoading: (groupKey: string) => boolean;
    failed: (groupKey: string) => boolean;
  };
};

// These callbacks outlive SoupViewList. Keep their closure separate from the
// mounted view, and release the only route back to its virtualizer on cleanup.
function createPersistentNavigation(
  options: Omit<UseSoupNavigationHotkeysOptions, 'virtualizerHandle'>,
  viewport: { current?: Accessor<VirtualizerHandle | undefined> }
) {
  const { scopeId, soup, splitHandle } = options;
  const notificationSource = useGlobalNotificationSource();

  const scrollTo = (index: number) => {
    const handle = viewport.current?.();

    if (!handle) return;

    handle.scrollToIndex(index, {
      align: 'nearest',
    });
  };

  const navigationReferredFrom = () => {
    const content = splitHandle.content();

    if (content.type === 'component' && isListViewID(content.id)) {
      return content.id;
    }

    const referredFrom = splitHandle.referredFrom();
    return isListViewID(referredFrom) ? referredFrom : undefined;
  };

  const viewId = navigationReferredFrom();
  if (viewId) {
    // Keep navigation available when the list view leaves the split's content.
    withSplitPanelOwner(listOwnedSlotName('navigation-source'), () =>
      registerListNavigationSource(splitHandle, {
        viewId,
        entities: () =>
          soup
            .rows()
            .flatMap((row) =>
              row.getIsGrouped() || row.getIsLoadMore() ? [] : [row.original]
            ),
        hasMore: () => options.hasNextPage?.() ?? false,
        loadMore: async () => {
          await options.fetchNextPage?.();
          const error = options.error?.();
          if (error) throw error;
        },
      })
    );
  }

  const openEntity = async (entity: EntityData) => {
    const handleContent = splitHandle.content().type;

    if (handleContent === 'component' || handleContent === 'project') return;

    await openEntityInSplitFromUnifiedList(entity, {
      splitHandle,
      mergeHistory: true,
      referredFrom: navigationReferredFrom(),
      notificationSource,
    });
  };

  const navigateToOpenableEntity = (offset: -1 | 1) =>
    soup.navigate.by(offset, { skipGroupHeaders: true, skipLoadMore: true });

  // A group's next page continues right after the focused row: wait for it
  // rather than skipping the rest of the group. A failed page lets focus move on.
  const pendingGroupPage = () => {
    const { groupPaging } = options;
    if (!groupPaging) return;
    const next = soup.rows()[soup.focus.index() + 1];
    if (!next?.getIsLoadMore() || !next.group?.isExpanded()) return;
    if (groupPaging.failed(next.group.key)) return;
    return next.group.key;
  };

  const { fetchNextPage, isFetching, isFetchingNextPage, hasNextPage } =
    options;

  const LOAD_MORE_DISTANCE_FROM_END = 3;

  const fetchNextPageIfNeeded = () => {
    if (!hasNextPage?.() || isFetching?.() || isFetchingNextPage?.()) return;
    fetchNextPage?.().catch(reportSoupNavigationError);
  };

  const navigateDown = () => {
    const groupKey = pendingGroupPage();
    if (groupKey !== undefined) {
      if (!options.groupPaging?.isLoading(groupKey))
        options.groupPaging?.load(groupKey).catch(reportSoupNavigationError);
      return true;
    }

    const rowCount = soup.rows().length;
    const next = navigateToOpenableEntity(1);

    if (!next) {
      fetchNextPageIfNeeded();
      return true;
    }

    scrollTo(next.index);
    openEntity(next.row.original).catch(reportSoupNavigationError);

    if (next.index >= rowCount - 1 - LOAD_MORE_DISTANCE_FROM_END) {
      fetchNextPageIfNeeded();
    }

    return true;
  };

  const navigateUp = () => {
    const next = navigateToOpenableEntity(-1);

    if (!next) return true;

    scrollTo(next.index);
    openEntity(next.row.original).catch(reportSoupNavigationError);

    return true;
  };

  const canRunListNavigation = () => {
    const contentType = splitHandle.content().type;
    const referredFrom = navigationReferredFrom();
    return (
      contentType === 'component' ||
      contentType === 'project' ||
      referredFrom === 'home' ||
      referredFrom === 'mail'
    );
  };

  // Keep j/k registered on the split scope after the list unmounts. When an
  // entity is opened from a list into the same split, this lets j/k continue
  // navigating the originating soup list and update the split content.
  registerHotkey({
    hotkey: ['j'],
    scopeId,
    description: 'Down',
    hotkeyToken: TOKENS.entity.step.end,
    condition: canRunListNavigation,
    keyDownHandler: navigateDown,
    hide: true,
    disposeWithOwner: false,
  });

  // Keep j/k registered on the split scope after the list unmounts. When an
  // entity is opened from a list into the same split, this lets j/k continue
  // navigating the originating soup list and update the split content.
  registerHotkey({
    hotkey: ['k'],
    scopeId,
    hotkeyToken: TOKENS.entity.step.start,
    description: 'Up',
    condition: canRunListNavigation,
    keyDownHandler: navigateUp,
    hide: true,
    disposeWithOwner: false,
  });

  return { scrollTo, navigateDown, navigateUp };
}

export const useSoupNavigationHotkeys = (
  options: UseSoupNavigationHotkeysOptions
) => {
  const { scopeId, soup, splitHandle } = options;
  const viewport: { current?: Accessor<VirtualizerHandle | undefined> } = {
    current: options.virtualizerHandle,
  };
  onCleanup(() => {
    viewport.current = undefined;
  });
  const { scrollTo, navigateDown, navigateUp } = createPersistentNavigation(
    {
      scopeId,
      soup,
      splitHandle,
      hasNextPage: options.hasNextPage,
      isFetching: options.isFetching,
      isFetchingNextPage: options.isFetchingNextPage,
      fetchNextPage: options.fetchNextPage,
      error: options.error,
      groupPaging: options.groupPaging,
    },
    viewport
  );

  const navigateAndSelectEntity = (offset: number) => {
    const nextRow = soup.navigate.by(offset, {
      skipGroupHeaders: true,
      skipLoadMore: true,
    });
    if (!nextRow) return true;
    soup.selection.select(nextRow.row.original);
    scrollTo(nextRow.index);
    return true;
  };

  const handleNavigationSelection = (offset: number) => {
    const focusedEntity = soup.focus.item();
    const next = soup.navigate.peekOffset(offset, {
      skipGroupHeaders: true,
      skipLoadMore: true,
    });

    const selection = soup.selection;

    const nextEntity = next?.row.original;
    if (!nextEntity) return true;

    // At the boundary (top/bottom), peekOffset clamps and returns the
    // same item we're already focused on. No-op to avoid toggling.
    if (focusedEntity && nextEntity.id === focusedEntity.id) return true;

    if (!focusedEntity) {
      navigateAndSelectEntity(offset);
      return true;
    }

    if (selection.count() === 0) {
      selection.toggle(focusedEntity);
      return true;
    }

    if (
      !selection.isSelected(focusedEntity.id) &&
      !selection.isSelected(nextEntity.id)
    ) {
      selection.toggle(focusedEntity);
      navigateAndSelectEntity(offset);
      return true;
    }

    if (selection.isSelected(nextEntity.id)) {
      selection.toggle(focusedEntity);
      soup.navigate.by(offset, { skipGroupHeaders: true, skipLoadMore: true });
      scrollTo(next.index);
      return true;
    }

    navigateAndSelectEntity(offset);

    return true;
  };

  const group = createHotkeyGroup();

  registerHotkey({
    hotkey: ['arrowdown'],
    scopeId,
    description: 'Down',
    keyDownHandler: navigateDown,
    hide: true,
  }).withGroup(group);

  registerHotkey({
    hotkey: ['arrowup'],
    scopeId,
    description: 'Up',
    keyDownHandler: navigateUp,
    hide: true,
  }).withGroup(group);

  // Select up - 'shift+arrowup', 'shift+k'
  registerHotkey({
    hotkey: ['shift+arrowup', 'shift+k'],
    scopeId,
    description: 'Select up',
    hotkeyToken: TOKENS.entity.select.start,
    keyDownHandler: () => {
      return handleNavigationSelection(-1);
    },
    hide: true,
  }).withGroup(group);

  // Select down - 'shift+arrowdown', 'shift+j'
  registerHotkey({
    hotkey: ['shift+arrowdown', 'shift+j'],
    scopeId,
    description: 'Select down',
    hotkeyToken: TOKENS.entity.select.end,
    keyDownHandler: () => {
      return handleNavigationSelection(1);
    },
    hide: true,
  }).withGroup(group);

  const getCollapsibleToggle = () => {
    const focusedId = soup.focus.id();
    if (!focusedId) return undefined;
    const splitEl = document.querySelector(
      `[data-split-id="${splitHandle.id}"]`
    );
    if (!splitEl) return undefined;
    const entityEl = splitEl.querySelector(entityIdSelector(focusedId));
    if (!entityEl) return undefined;
    return entityEl.querySelector(
      'button[data-collapsible-toggle]'
    ) as HTMLButtonElement | null;
  };

  // When the focused row is a group header, drive it toward `targetExpanded`.
  // Returns true if it toggled, false if already in that state, or undefined
  // when the focused row isn't a group header so the caller can fall through.
  const toggleFocusedGroupHeader = (
    targetExpanded: boolean
  ): boolean | undefined => {
    const focusedRow = soup.focus.row();
    if (!focusedRow?.getIsGrouped() || !focusedRow.group) return undefined;
    if (focusedRow.group.isExpanded() === targetExpanded) return false;
    focusedRow.group.toggle();
    return true;
  };

  registerHotkey({
    hotkey: ['h'],
    scopeId,
    description: 'Collapse group',
    hotkeyToken: TOKENS.unifiedList.navigation.collapseGroup,
    // Consume H on headers even when already collapsed; selected entities
    // elsewhere must not turn this into a reminder action.
    keyDownHandler: () => toggleFocusedGroupHeader(false) !== undefined,
    registrationType: 'add',
    handlerPriority: 4,
    hide: true,
  }).withGroup(group);

  registerHotkey({
    hotkey: ['arrowleft', 'h'],
    scopeId,
    description: 'Collapse item',
    hotkeyToken: TOKENS.unifiedList.navigation.parent,
    keyDownHandler: (event) => {
      if (
        event?.key.toLowerCase() === 'h' &&
        (!soup.focus.row() || !isTaskEntity(soup.focus.row()!.original))
      )
        return false;
      const groupHandled = toggleFocusedGroupHeader(false);
      if (groupHandled !== undefined) return groupHandled;

      const toggle = getCollapsibleToggle();
      if (toggle?.dataset.collapsibleState === 'expanded') {
        toggle.click();
        return true;
      }

      // From a child row, collapse its parent group and focus the header.
      const focusedGroup = soup.focus.row()?.group;
      if (focusedGroup?.isExpanded()) {
        focusedGroup.toggle();
        const header = soup.navigate.toId(`header:${focusedGroup.key}`);
        if (header) scrollTo(header.index);
        return true;
      }

      return false;
    },
    registrationType: 'add',
    handlerPriority: 4,
    hide: true,
  }).withGroup(group);

  registerHotkey({
    hotkey: ['l', 'arrowright'],
    scopeId,
    description: 'Expand item',
    hotkeyToken: TOKENS.unifiedList.navigation.child,
    keyDownHandler: () => {
      const groupHandled = toggleFocusedGroupHeader(true);
      if (groupHandled !== undefined) return groupHandled;

      const toggle = getCollapsibleToggle();
      if (toggle?.dataset.collapsibleState === 'collapsed') {
        toggle.click();
        return true;
      }

      return false;
    },
    registrationType: 'add',
    handlerPriority: 4,
    hide: true,
  }).withGroup(group);

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