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.

11.9 KB
Raw Blame
import { ViewSidebar } from '@app/components/view-shell';
import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
import { usePending } from '@app/observability/flow';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { createElementSize } from '@solid-primitives/resize-observer';
import {
  createEffect,
  createMemo,
  createSignal,
  For,
  type JSX,
  on,
  onCleanup,
  Show,
  Suspense,
} from 'solid-js';
import { match } from 'ts-pattern';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import { ActionGraph } from '../components/action-graph';
import {
  ActivityScopePills,
  ActivityScopeTabs,
} from '../components/activity-scope-tabs';
import { ActivityTimelineRow as ActivityTimelineRowView } from '../components/activity-timeline-row';
import { TopEntitiesSection, TopEntityChip } from '../components/top-entities';
import {
  type OpenEntityTarget,
  useActivityContext,
} from '../context/activity-context';
import { entryHead, type FeedEntry } from '../core/collapse-runs';
import type { ActivityScope, ActivityTopEntity } from '../core/event';
import {
  type FeedRow,
  pinnedDayLabel,
  type RailEnds,
  shouldFetchMore,
} from '../core/feed-rows';
import { placeholderOverview } from '../core/placeholder-overview';
import { createActorName } from '../primitives/actor-name';
import { createEntityOpener } from '../primitives/entity-opener';
import {
  createMyActivityState,
  type MyActivityState,
} from '../primitives/my-activity';
import { ActivityTimelineRow } from './activity-timeline-row';

/** Pixels of rows virtua keeps mounted beyond the viewport on each side. */
const FEED_BUFFER_PX = 400;

function OverviewInset(props: { children: JSX.Element }) {
  return (
    <div class="mx-1 flex w-[calc(100%-0.5rem)] min-w-0 flex-col gap-2 pb-2">
      {props.children}
    </div>
  );
}

function FeedStatus(props: { children: JSX.Element }) {
  return (
    <p class="mx-1 w-[calc(100%-0.5rem)] px-2 py-2 text-ink-muted text-sm">
      {props.children}
    </p>
  );
}

/**
 * The user's own activity or their team's, newest first, as one virtualized
 * list; the user's own feed has the overview card as its first row. The
 * host owns the selected `scope` and decides what a row click opens.
 * Scrolling near the end fetches the next page. Reads `ActivityContext`.
 *
 * Rows are absolutely positioned by the virtualizer, so a day header cannot
 * stick on its own. Instead a zero-height sticky slot at the head of the
 * scroller repeats the day header that governs the first visible row.
 *
 * On full-frame touch devices the split header floats over the content, so
 * an in-scroll spacer (measured, then handed to virtua as `startMargin`, the
 * `SoupList` pattern) rests the list and the You / Team pills below it and
 * the pinned header sticks under it; a matching spacer clears the bottom
 * toolbar.
 */
export function MyActivityView(props: {
  scope: ActivityScope;
  onScopeChange: (scope: ActivityScope) => void;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  const context = useActivityContext();
  const state = createMyActivityState(context, () => props.scope);
  usePending('activity.feed', () => state.feed().t === 'loading');
  usePending(
    'activity.overview',
    () => props.scope !== 'team' && state.overview().t === 'loading'
  );
  const [scroller, setScroller] = createSignal<HTMLDivElement>();
  const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();
  const topSpacerSize = createElementSize(topSpacer);
  const [startIndex, setStartIndex] = createSignal(0);
  const [scrollOffset, setScrollOffset] = createSignal(0);
  let handle: VirtualizerHandle | undefined;

  // Until the list itself reaches the top edge its first day header is in
  // view, so nothing pins (the team feed has no overview row above it, and
  // on touch the You / Team pills sit where the pinned copy would).
  const pinnedDay = createMemo(() =>
    scrollOffset() > (topSpacerSize.height ?? 0)
      ? pinnedDayLabel(state.rows(), startIndex())
      : undefined
  );

  const fetchMoreIfNearEnd = (offset: number) => {
    if (!handle) return;
    if (
      shouldFetchMore({
        scrollSize: handle.scrollSize,
        viewportSize: handle.viewportSize,
        offset,
      })
    ) {
      state.loadMore();
    }
  };

  const onScroll = (offset: number) => {
    setScrollOffset(offset);
    if (handle) setStartIndex(handle.findItemIndex(offset));
    fetchMoreIfNearEnd(offset);
  };

  // The other tab's rows replace these wholesale, so its feed opens at the top.
  createEffect(
    on(
      () => props.scope,
      () => handle?.scrollTo(0),
      { defer: true }
    )
  );

  // A page that does not fill the viewport never scrolls, so re-check once
  // virtua has laid out the new rows.
  createEffect(
    on(state.rows, () => {
      const frame = requestAnimationFrame(() =>
        fetchMoreIfNearEnd(handle?.scrollOffset ?? 0)
      );
      onCleanup(() => cancelAnimationFrame(frame));
    })
  );

  return (
    <div class="@container/u-list flex size-full flex-col">
      <SplitHeaderLeft>
        <div class="flex items-center gap-3">
          <ViewSidebar.Title caret={false}>Activity</ViewSidebar.Title>
          <Show when={!isTouchDevice()}>
            <ActivityScopeTabs
              value={props.scope}
              onChange={props.onScopeChange}
            />
          </Show>
        </div>
      </SplitHeaderLeft>
      <StaticMarkdownContext>
        <div ref={setScroller} class="min-h-0 flex-1 overflow-y-auto py-1">
          <div class="pointer-events-none sticky top-0 z-10 mx-auto h-0 w-full max-w-[1000px] touch:top-(--mobile-content-inset-top)">
            <Show when={pinnedDay()}>
              {(label) => (
                <div class="pt-1" data-activity-pinned-day>
                  <SoupSectionHeader>{label()}</SoupSectionHeader>
                </div>
              )}
            </Show>
          </div>
          <div ref={setTopSpacer} class="touch:pt-(--mobile-content-inset-top)">
            <Show when={isTouchDevice()}>
              <div class="px-(--mobile-chrome-gutter) pb-2">
                <ActivityScopePills
                  value={props.scope}
                  onChange={props.onScopeChange}
                />
              </div>
            </Show>
          </div>
          <div class="mx-auto w-full max-w-[1000px]">
            <Virtualizer
              data={state.rows()}
              scrollRef={scroller()}
              ref={(next) => {
                handle = next;
              }}
              startMargin={topSpacerSize.height ?? 0}
              bufferSize={FEED_BUFFER_PX}
              onScroll={onScroll}
            >
              {(row) => (
                <FeedRowView
                  row={row}
                  state={state}
                  scope={props.scope}
                  onOpen={props.onOpen}
                />
              )}
            </Virtualizer>
          </div>
          <div
            aria-hidden
            class="h-0 touch:h-(--mobile-content-inset-bottom)"
          />
        </div>
      </StaticMarkdownContext>
    </div>
  );
}

function FeedRowView(props: {
  row: FeedRow;
  state: MyActivityState;
  scope: ActivityScope;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  return match(props.row)
    .with({ kind: 'overview' }, () => (
      <OverviewRow state={props.state} onOpen={props.onOpen} />
    ))
    .with({ kind: 'day' }, (row) => (
      <SoupSectionHeader>{row.label}</SoupSectionHeader>
    ))
    .with({ kind: 'entry' }, (row) => (
      <NamedActivityRow
        entry={row.entry}
        rail={row.rail}
        onOpen={props.onOpen}
      />
    ))
    .with({ kind: 'status', status: 'loading' }, () => (
      <FeedStatus>Loading…</FeedStatus>
    ))
    .with({ kind: 'status', status: 'error' }, () => (
      <FeedStatus>
        Activity is unavailable right now. Try again in a moment.
      </FeedStatus>
    ))
    .with({ kind: 'status', status: 'empty' }, () => (
      <FeedStatus>
        {props.scope === 'team'
          ? 'No activity from your team yet.'
          : 'No activity yet.'}
      </FeedStatus>
    ))
    .with({ kind: 'tail' }, () => <FeedTail state={props.state} />)
    .exhaustive();
}

function FeedTail(props: { state: MyActivityState }) {
  const ready = () => {
    const feed = props.state.feed();
    return feed.t === 'ready' ? feed : undefined;
  };
  return (
    <div
      class="flex h-10 items-center justify-center gap-2 text-ink-muted text-sm"
      aria-live="polite"
      data-activity-feed-tail
    >
      <Show when={ready()?.loadingMore}>Loading…</Show>
      <Show when={!ready()?.loadingMore && ready()?.moreFailed}>
        <span>Couldn't load more.</span>
        <button
          type="button"
          class="text-ink underline-offset-2 hover:underline"
          onClick={() => props.state.retryMore()}
        >
          Retry
        </button>
      </Show>
    </div>
  );
}

function OverviewRow(props: {
  state: MyActivityState;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  const overview = () => {
    const current = props.state.overview();
    return current.t === 'ready' ? current.overview : undefined;
  };
  return (
    <Show
      when={overview()}
      fallback={
        <OverviewInset>
          <Show
            when={props.state.overview().t === 'error'}
            fallback={
              <ActionGraph
                overview={placeholderOverview(new Date())}
                skeleton
              />
            }
          >
            <p class="px-2 py-1 text-ink-extra-muted text-xs">
              Activity overview is unavailable right now.
            </p>
          </Show>
        </OverviewInset>
      }
    >
      {(overview) => (
        <OverviewInset>
          <ActionGraph overview={overview()} />
          <Show when={overview().topEntities.length > 0}>
            <TopEntitiesSection>
              <For each={overview().topEntities}>
                {(entity) => (
                  <OpenableTopEntityChip
                    entity={entity}
                    onOpen={props.onOpen}
                  />
                )}
              </For>
            </TopEntitiesSection>
          </Show>
        </OverviewInset>
      )}
    </Show>
  );
}

// Rows mount as the user scrolls, and a row whose entity preview is still a
// cold query suspends the nearest boundary. Each row carries its own so the
// pane boundary never re-inserts the scroller, which would reset its scroll
// position to the top.
function NamedActivityRow(props: {
  entry: FeedEntry;
  rail: RailEnds;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  const context = useActivityContext();
  const name = createActorName(context, () => entryHead(props.entry).actorId);
  return (
    <Suspense
      fallback={
        <ActivityTimelineRowView
          entry={props.entry}
          actorName={name()}
          rail={props.rail}
        />
      }
    >
      <ActivityTimelineRow
        entry={props.entry}
        actorName={name()}
        rail={props.rail}
        onOpen={props.onOpen}
      />
    </Suspense>
  );
}

function OpenableTopEntityChip(props: {
  entity: ActivityTopEntity;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  return (
    <Suspense fallback={<TopEntityChip entity={props.entity} />}>
      <ResolvedTopEntityChip entity={props.entity} onOpen={props.onOpen} />
    </Suspense>
  );
}

function ResolvedTopEntityChip(props: {
  entity: ActivityTopEntity;
  onOpen: (target: OpenEntityTarget) => void;
}) {
  const context = useActivityContext();
  const opener = createEntityOpener(
    context,
    () => props.entity.entityId,
    () => props.entity.entityType,
    props.onOpen
  );
  return (
    <TopEntityChip
      entity={props.entity}
      display={opener()?.display}
      rowProps={opener()?.handlers}
    />
  );
}