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.

27.1 KB
Raw Blame
import {
  TutorialRow,
  TutorialSidebarItem,
} from '@app/features/video-tutorials';
import { usePending } from '@app/observability/flow';
import { markRowNotificationsSeenOnOpen } from '@notifications/mark-row-seen';
import '@entity/composed/ListEntity.css';
import {
  createListController,
  type ListActivation,
  listOwnedSlotName,
  useListInteractions,
} from '@app/components/list';
import {
  type EntityActionNavigationHandler,
  resolveEntityActionViewContext,
  toEntityActionListState,
  useEntityActionHotkeys,
} from '@app/features/next-soup/actions';
import {
  createSoupEntityActions,
  MaybeSoupEntityActionDrawerManager,
  SoupEntityContextMenu,
  useSoupListNavigationHotkeys,
  viewedProjectIdFromContent,
} from '@app/features/soup';
import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
import { makePersistedState } from '@app/lib/persistence';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { PullToRefresh } from '@components/app/mobile/PullToRefresh';
import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';
import type { PreviewSelection } from '@components/app/previewTarget';
import {
  useSplitPanelOrThrow,
  withSplitPanelOwner,
} from '@components/app/split-layout/layoutUtils';
import { useChannelsContext } from '@core/context/channels';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { fireAndForget } from '@core/util/fireAndForget';
import {
  type EntityData,
  EntitySelectionToolbar,
  isNonMemberChannelEntity,
  ListLayoutProvider,
  type WithNotification,
} from '@entity';
import { getChannelThreadName } from '@entity/utils/channel-thread-name';
import CheckIcon from '@icon/system/regular/check.svg';
import { createElementSize } from '@solid-primitives/resize-observer';
import { debounce } from '@solid-primitives/scheduled';
import { Button } from '@ui';
import {
  createEffect,
  createMemo,
  createSignal,
  Match,
  onCleanup,
  type Setter,
  Show,
  Switch,
} from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import {
  persistSoupNavigationTouchHighlight,
  soupNavigationTouchHighlight,
} from '../../next-soup/soup-view/soup-navigation-touch-highlight';
import { InboxListEntity } from '../../next-soup/soup-view/views/inbox/InboxListEntity';
import {
  markChannelNotificationsSeenOnOpen,
  openEntityInSplitFromUnifiedList,
} from '../../next-soup/utils';
import { useHomeView } from '../home-view-context';
import {
  createHomeListEntryStorage,
  DEFAULT_HOME_LIST_STATE,
  type HomeListStateSnapshot,
} from '../persistence';
import {
  type HomeDataSourceItem,
  useHomeDataSource,
} from '../queries/use-home-query';
import { HomeDateGroupHeader } from './HomeDateGroupHeader';
import { HomeEmptyState } from './HomeEmptyState';
import { HomeListEntity } from './HomeListEntity';
import { HomeListSkeleton } from './HomeListSkeleton';

type HomeActionRow = {
  entity: WithNotification<EntityData>;
  rowId: string;
};

type HomeListActivationMetadata = {
  event?: MouseEvent;
  newSplit?: boolean;
};

type HomeListProps = {
  hasPreview: boolean;
  onPreviewEntityChange: (
    entity: PreviewSelection | undefined,
    options?: { activate?: boolean }
  ) => void;
  onPreviewActivate?: () => void;
};

/**
 * Home's tutorial entry, shaped like the rows under it: desktop Home is a rail
 * of sidebar items, touch Home a list of inbox rows.
 */
function HomeTutorial() {
  return (
    <Show
      when={isTouchDevice()}
      fallback={
        <div class="mx-(--sidebar-gutter) my-(--sidebar-row-gap) empty:hidden">
          <TutorialSidebarItem tutorial="home" />
        </div>
      }
    >
      <TutorialRow tutorial="home" />
    </Show>
  );
}

/** Compact notification list used by the Notifications workspace. */
export function HomeList(props: HomeListProps) {
  const channels = useChannelsContext();
  const channelName = (entity: WithNotification<EntityData>) =>
    entity.type === 'channel_thread'
      ? getChannelThreadName(entity, channels.channelsById())
      : undefined;
  const { state } = useHomeView();
  const panel = useSplitPanelOrThrow();
  const notificationSource = useGlobalNotificationSource();

  const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>
    useHomeDataSource(state)
  );

  usePending('home.items', source.isLoading);

  const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>
    createListController<HomeDataSourceItem, HomeListActivationMetadata>({
      items: source.items,
      getKey: (row) => row.id,
      selection: {
        getKey: (row) => (row.kind === 'entity' ? row.entity.id : row.id),
      },
      isNavigable: (row) => row.kind === 'entity',
      isSelectable: (row) => row.kind === 'entity',
      onActivate,
    })
  );

  withSplitPanelOwner(listOwnedSlotName('navigation-hotkeys'), () => {
    useSoupListNavigationHotkeys({
      splitHotkeyScope: panel.splitHotkeyScope,
      viewId: 'home',
      dataSource: source,
      controller: list,
      handle: panel.handle,
      openEntityInSplit: (entity, options) => {
        markRowNotificationsSeenOnOpen(entity, notificationSource);
        fireAndForget(
          openEntityInSplitFromUnifiedList(entity, {
            splitHandle: panel.handle,
            ...options,
          }),
          'open-entity-in-split'
        );
      },
    });
  });

  const { buildActionGroups } = createSoupEntityActions({
    markDoneDelegate: source.markDoneDelegate,
  });
  const entityActionViewContext = () =>
    resolveEntityActionViewContext({
      activeListView: panel.handle.content().id,
      activeTab: state.tab,
    });

  function onActivate({
    item,
    metadata,
  }: ListActivation<HomeDataSourceItem, HomeListActivationMetadata>) {
    if (item.kind !== 'entity') return;

    const sourceRow = source.items().find((row) => row.id === item.id);

    if (sourceRow?.kind !== 'entity') return;

    previewAfterNavigation.clear();

    const newSplit =
      metadata?.newSplit === true || metadata?.event?.shiftKey === true;

    if (!isTouchDevice() && !newSplit) {
      if (!isNonMemberChannelEntity(sourceRow.entity)) {
        markChannelNotificationsSeenOnOpen(
          sourceRow.entity,
          notificationSource
        );
      }
      showPreview(sourceRow.entity, { activate: true });
      props.onPreviewActivate?.();
      // Home keeps the keyboard only when the item opened in Home itself.
      if (panel.isPanelActive()) listRoot()?.focus({ preventScroll: true });
      return;
    }

    fireAndForget(
      openEntity(sourceRow.entity, {
        event: metadata?.event,
        newSplit,
      }),
      'home'
    );
  }

  function markEntitySeen(entity: WithNotification<EntityData>) {
    markRowNotificationsSeenOnOpen(entity, notificationSource);
    if (!isNonMemberChannelEntity(entity)) {
      markChannelNotificationsSeenOnOpen(entity, notificationSource);
    }
  }

  function showPreview(
    entity: WithNotification<EntityData> | undefined,
    options?: { activate?: boolean }
  ) {
    if (entity) markRowNotificationsSeenOnOpen(entity, notificationSource);
    props.onPreviewEntityChange(entity, options);
  }

  const previewAfterNavigation = debounce(showPreview, 150);
  onCleanup(() => previewAfterNavigation.clear());

  async function openEntity(
    entity: WithNotification<EntityData>,
    options: {
      event?: MouseEvent;
      newSplit: boolean;
      mergeHistory?: boolean;
    }
  ) {
    markEntitySeen(entity);

    const finishTouchHighlight = options.event
      ? persistSoupNavigationTouchHighlight(options.event)
      : undefined;

    try {
      await openEntityInSplitFromUnifiedList(entity, {
        openInNewSplit: options.newSplit,
        splitHandle: panel.handle,
        referredFrom: 'home',
        mergeHistory: options.mergeHistory,
      });
    } finally {
      finishTouchHighlight?.();
    }
  }

  const [viewport, setViewport] = createSignal<HTMLDivElement>();
  const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();
  const topSpacerSize = createElementSize(topSpacer);
  const [emptyViewport, setEmptyViewport] = createSignal<HTMLDivElement>();
  const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
  const [isPullRefreshing, setIsPullRefreshing] = createSignal(false);
  const forceEmptyState = useDebugSetting(
    DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES
  );

  let scrollOffset = DEFAULT_HOME_LIST_STATE.scrollOffset;
  const readListState = (): HomeListStateSnapshot => ({
    focusKey: list.focus.requestedKey(),
    scrollOffset: virtualizer()?.scrollOffset ?? scrollOffset,
  });

  const applyListState: Setter<HomeListStateSnapshot> = (next) => {
    const current = readListState();
    const value = typeof next === 'function' ? next(current) : next;

    if (value.focusKey !== current.focusKey) {
      list.focus.restore(value.focusKey, { reason: 'restore' });
    }

    scrollOffset = value.scrollOffset;
    if (value.scrollOffset !== current.scrollOffset) {
      virtualizer()?.scrollTo(value.scrollOffset);
    }

    return value;
  };
  const [, setPersistedListState] = makePersistedState(
    [readListState, applyListState],
    { storages: createHomeListEntryStorage(panel.handle) }
  );

  const rows = source.items;

  const swipeRowsById = createMemo(() => {
    const entities = new Map<string, HomeActionRow>();

    for (const row of rows()) {
      if (row.kind !== 'entity') continue;

      entities.set(row.id, { entity: row.entity, rowId: row.id });
    }

    return entities;
  });

  const selectedEntities = createMemo(() =>
    list.selection
      .items()
      .flatMap((row) => (row.kind === 'entity' ? [row.entity] : []))
  );

  const focusedEntity = () => {
    const row = list.focus.result()?.item;
    return row?.kind === 'entity' ? row.entity : undefined;
  };

  const createActionNavigationHandler = ():
    | EntityActionNavigationHandler
    | undefined => {
    if (!props.hasPreview) return;

    return ({ entity }) => {
      previewAfterNavigation.clear();
      showPreview(entity);
    };
  };

  const [listRoot, setListRoot] = createSignal<HTMLDivElement>();
  const [collapseRow, setCollapseRow] =
    createSignal<(rowId: string) => Promise<void>>();

  const actionState = toEntityActionListState({
    controller: list,
    getEntity: (row) => (row.kind === 'entity' ? row.entity : undefined),
    collapse: {
      enabled: isTouchDevice,
      run: async (entityId) => {
        const collapse = collapseRow();
        if (!collapse) return;

        // Actions target entities; swipe rows are keyed by notification occurrence.
        await Promise.all(
          rows().flatMap((row) =>
            row.kind === 'entity' && row.entity.id === entityId
              ? [collapse(row.id)]
              : []
          )
        );
      },
    },
    onFocus: (target) => {
      if (target) {
        virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });
      }

      listRoot()?.focus();
    },
  });

  const listInteractions = useListInteractions({
    controller: list,
    scopeId: panel.splitHotkeyScope,
    scrollHandle: virtualizer,
    enabled: panel.isPanelActive,
    navigation: {
      onNavigate: (event) => {
        previewAfterNavigation.clear();

        const row = event.result?.item;
        if (!isTouchDevice() && row?.kind === 'entity') {
          previewAfterNavigation(row.entity);
        }

        if (event.kind !== 'move' || event.direction !== 1) return;
        if (source.isLoadingMore() || !source.hasMore()) return;

        const distanceFromEnd = event.result
          ? list.items.count() - event.result.index - 1
          : 0;

        if (distanceFromEnd > 3) return;

        fireAndForget(source.loadMore(), 'home');
      },
    },
    activation: {
      createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),
      alternateDescription: 'Open in new split',
    },
  });

  const onRowClick = (rowId: string, event: MouseEvent) => {
    // Rows cancel their press, so the browser never moves focus into Home.
    // Activate Home before opening: an item that opens in another split
    // activates that split afterwards, without a focus change in Home that
    // the split focus tracker could later use to take activation back.
    panel.handle.activate();
    if (
      event.metaKey ||
      event.ctrlKey ||
      (isTouchDevice() && list.selection.count() > 0)
    ) {
      listInteractions.selection.toggle(rowId);
      listRoot()?.focus({ preventScroll: true });
      return;
    }

    list.activate.key(rowId, {
      reason: 'pointer',
      metadata: { event },
    });
  };

  useEntityActionHotkeys({
    enableDeleteHotkey: false,
    scopeId: panel.splitHotkeyScope,
    list: actionState,
    selectedEntities,
    focusedEntity,
    restoreFocus: () => listRoot()?.focus(),
    viewContext: entityActionViewContext,
    splitHandle: panel.handle,
    createActionNavigationHandler,
    condition: panel.isPanelActive,
    markDoneDelegate: source.markDoneDelegate,
  });

  function actionGroupsFor(row: HomeActionRow) {
    const content = panel.handle.content();

    return buildActionGroups(actionState, [row.entity], {
      viewContext: entityActionViewContext(),
      viewedProjectId: viewedProjectIdFromContent(content),
      splitHandle: panel.handle,
      createActionNavigationHandler,
    });
  }

  const markDoneActionFor = (row: HomeActionRow) =>
    actionGroupsFor(row)
      .flatMap((group) => group.items)
      .find((action) => action.id === 'mark-done');

  function focusActionRow(row: HomeActionRow) {
    list.focus.set(row.rowId, { reason: 'pointer', force: true });
    list.selection.setAnchor(row.rowId);
  }

  let restoredScroll = false;
  function registerVirtualizer(handle?: VirtualizerHandle) {
    setVirtualizer(handle);
    if (!handle || restoredScroll) return;

    handle.scrollTo(scrollOffset);
    restoredScroll = true;
  }

  function showsEmptyViewport() {
    return (
      forceEmptyState() ||
      (!source.isLoading() && (Boolean(source.error()) || rows().length === 0))
    );
  }

  function pullScrollContainer() {
    return showsEmptyViewport() ? emptyViewport() : viewport();
  }

  async function pullRefresh() {
    setIsPullRefreshing(true);

    try {
      await source.refresh();
    } finally {
      setIsPullRefreshing(false);
    }
  }

  let activeTab = state.tab;
  createEffect(() => {
    const nextTab = state.tab;
    if (nextTab === activeTab) return;

    activeTab = nextTab;
    previewAfterNavigation.clear();
    listInteractions.selection.clear();
    list.focus.clear({ reason: 'programmatic' });
    setPersistedListState((current) => ({ ...current, scrollOffset: 0 }));
  });

  createEffect(() => {
    rows();
    if (source.isLoading()) return;

    if (list.focus.result()) return;

    list.focus.restore(list.focus.requestedKey(), {
      retainUnavailable: false,
    });
  });

  function checkNearEnd() {
    if (
      forceEmptyState() ||
      source.isLoading() ||
      source.isFetching() ||
      source.error() ||
      !source.hasMore()
    )
      return;

    const container = pullScrollContainer();
    if (!container || container.clientHeight === 0) return;

    const distance =
      container.scrollHeight - container.scrollTop - container.clientHeight;
    if (distance < 300) {
      fireAndForget(source.loadMore(), 'home');
    }
  }

  const scrollContainerSize = createElementSize(pullScrollContainer);
  createEffect(() => {
    rows();
    source.isFetching();
    scrollContainerSize.height;

    // Fill short or filtered pages without waiting for a scroll event.
    const frame = requestAnimationFrame(checkNearEnd);
    onCleanup(() => cancelAnimationFrame(frame));
  });

  return (
    <MaybeSoupEntityActionDrawerManager>
      <div
        ref={setListRoot}
        role="grid"
        aria-label="Home"
        aria-busy={source.isLoading() || source.isLoadingMore()}
        aria-multiselectable="true"
        aria-activedescendant={list.focus.key()}
        tabIndex={0}
        class="soup-list relative mt-3 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden outline-none touch:mt-0"
      >
        <Show when={source.warning()}>
          {(warning) => (
            <div
              role="status"
              class="flex items-center gap-2 px-4 pb-2 text-xs text-ink-muted"
            >
              <span>{warning()}</span>
              <button
                type="button"
                class="underline"
                onClick={() => fireAndForget(source.refresh(), 'home')}
              >
                Retry
              </button>
            </div>
          )}
        </Show>
        <PullToRefresh
          scrollContainer={pullScrollContainer}
          onRefresh={pullRefresh}
        />

        <ListLayoutProvider ref={listRoot}>
          <SwipableRowProvider
            container={viewport}
            setCollapseEntity={setCollapseRow}
            canSwipeLeft={(rowId) => {
              const row = swipeRowsById().get(rowId);
              return row ? markDoneActionFor(row) !== undefined : false;
            }}
            onSwipeLeft={(rowId) => {
              const row = swipeRowsById().get(rowId);
              if (!row) return;

              const action = markDoneActionFor(row);
              if (!action) return;

              focusActionRow(row);
              fireAndForget(action.onClick(), 'home');
            }}
          >
            <Switch>
              <Match
                when={
                  !forceEmptyState() &&
                  source.isLoading() &&
                  !isPullRefreshing()
                }
              >
                <div class="min-h-0 flex-1 overflow-hidden touch:pt-(--mobile-content-inset-top)">
                  <HomeListSkeleton
                    grouped={state.groupBy === 'date' && !state.search.trim()}
                  />
                </div>
              </Match>

              <Match when={!forceEmptyState() && source.error()}>
                <div
                  ref={setEmptyViewport}
                  class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-y-auto pb-[max(1rem,var(--mobile-content-inset-bottom,0px))] touch:pt-(--mobile-content-inset-top) text-sm text-ink-muted"
                >
                  <span>Home couldn’t be loaded.</span>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => fireAndForget(source.refresh(), 'home')}
                  >
                    Try again
                  </Button>
                </div>
              </Match>

              <Match when={forceEmptyState() || rows().length === 0}>
                <div
                  ref={setEmptyViewport}
                  class="min-h-0 flex-1 overflow-y-auto pb-[max(1rem,var(--mobile-content-inset-bottom,0px))]"
                >
                  {/* A new account's Home starts empty, when the tutorial
                      matters most. The row then takes the touch top inset. */}
                  <Show
                    when={state.tab === 'signal'}
                    fallback={<HomeEmptyState />}
                  >
                    <div class="touch:pt-(--mobile-content-inset-top)">
                      <HomeTutorial />
                    </div>
                    <div class="contents touch:[--mobile-content-inset-top:0px]">
                      <HomeEmptyState />
                    </div>
                  </Show>
                </div>
              </Match>

              <Match when={true}>
                <div
                  ref={(element) => {
                    setViewport(element);
                    soupNavigationTouchHighlight(element);
                  }}
                  class="scrollbar-hidden min-h-0 flex-1 overflow-y-auto overscroll-none pb-[max(0.5rem,var(--mobile-content-inset-bottom,0px))]"
                  onScroll={checkNearEnd}
                >
                  {/* The spacer scrolls away; the viewport stays behind the filters.
                      It holds the touch inset and the pinned tutorial row. */}
                  <div ref={setTopSpacer}>
                    <div
                      aria-hidden="true"
                      class="h-0 touch:h-(--mobile-content-inset-top)"
                    />
                    <Show when={state.tab === 'signal'}>
                      <HomeTutorial />
                    </Show>
                  </div>
                  <Virtualizer
                    ref={registerVirtualizer}
                    data={rows()}
                    scrollRef={viewport()}
                    startMargin={topSpacerSize.height ?? 0}
                    bufferSize={500}
                    itemSize={isTouchDevice() ? 44 : 36}
                    keepMounted={
                      list.focus.index() >= 0 ? [list.focus.index()] : undefined
                    }
                  >
                    {(row, index) => (
                      <Switch>
                        <Match
                          when={row.kind === 'group-header' ? row : undefined}
                        >
                          {(group) => (
                            <HomeDateGroupHeader
                              row={group()}
                              isFirst={rows()[0]?.id === group().id}
                            />
                          )}
                        </Match>
                        <Match when={row.kind === 'entity' ? row : undefined}>
                          {(entityRow) => (
                            <SoupEntityContextMenu
                              entity={entityRow().entity}
                              list={actionState}
                              selectedEntities={selectedEntities}
                              viewContext={entityActionViewContext()}
                              markDoneDelegate={source.markDoneDelegate}
                              createActionNavigationHandler={
                                createActionNavigationHandler
                              }
                              onOpenChange={(open) => {
                                if (!open) return;
                                focusActionRow({
                                  entity: entityRow().entity,
                                  rowId: entityRow().id,
                                });
                              }}
                            >
                              <div
                                id={entityRow().id}
                                role="row"
                                data-soup-entity
                              >
                                <div role="gridcell">
                                  {/* Touch keeps the legacy Notifications row;
                                    the compact Home row is desktop-rail only. */}
                                  <Show
                                    when={isTouchDevice()}
                                    fallback={
                                      <HomeListEntity
                                        channelName={channelName(
                                          entityRow().entity
                                        )}
                                        timestamp={
                                          state.tab === 'signal'
                                            ? entityRow().entity.sortTs
                                            : (entityRow().entity.notifiedAt ??
                                              entityRow().entity.sortTs)
                                        }
                                        entity={entityRow().entity}
                                        occurrenceKey={entityRow().id}
                                        checked={list.selection.isSelected(
                                          entityRow().id
                                        )}
                                        hideCheckbox
                                        highlighted={
                                          list.focus.key() === entityRow().id
                                        }
                                        entityRowConfig={{
                                          swipeLeftColor: 'bg-success',
                                          swipeLeftRevealedComponent: (
                                            <CheckIcon class="size-8 text-surface" />
                                          ),
                                        }}
                                        onClick={(event) =>
                                          onRowClick(entityRow().id, event)
                                        }
                                      />
                                    }
                                  >
                                    <InboxListEntity
                                      entity={entityRow().entity}
                                      occurrenceKey={entityRow().id}
                                      checked={list.selection.isSelected(
                                        entityRow().id
                                      )}
                                      onChecked={(checked, shiftKey) =>
                                        listInteractions.selection.set(
                                          entityRow().id,
                                          checked,
                                          { range: shiftKey }
                                        )
                                      }
                                      highlighted={
                                        list.focus.key() === entityRow().id
                                      }
                                      isLastInGroup={(() => {
                                        const next = rows()[index() + 1];
                                        return !next || next.kind !== 'entity';
                                      })()}
                                      entityRowConfig={{
                                        swipeLeftColor: 'bg-success',
                                        swipeLeftRevealedComponent: (
                                          <CheckIcon class="size-8 text-surface" />
                                        ),
                                      }}
                                      onClick={(event) =>
                                        onRowClick(entityRow().id, event)
                                      }
                                    />
                                  </Show>
                                </div>
                              </div>
                            </SoupEntityContextMenu>
                          )}
                        </Match>
                      </Switch>
                    )}
                  </Virtualizer>
                  <Show when={source.isLoadingMore()}>
                    <HomeListSkeleton loadingMore />
                  </Show>
                </div>
              </Match>
            </Switch>
          </SwipableRowProvider>
        </ListLayoutProvider>

        <Show when={selectedEntities().length > 0}>
          <EntitySelectionToolbar
            selected={selectedEntities()}
            onClear={listInteractions.selection.clear}
            analyticsSource="home_view_selection_toolbar"
          />
        </Show>
      </div>
    </MaybeSoupEntityActionDrawerManager>
  );
}