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.3 KB
Raw Blame
import {
  CollapsibleSection,
  SearchBar,
  useViewTabHotkeys,
  ViewSidebar,
} from '@app/components/view-shell';
import { ViewCreateMenu } from '@app/features/command/view-create-menu';
import { FavoriteUnreadIndicator } from '@app/features/favorites/FavoriteUnreadIndicator';
import { t } from '@app/lib/i18n';
import { globalSplitManager } from '@app/signal/splitLayout';
import { PrOriginIcon } from '@block-pr/component/PrLinks';
import { PrStatusIcon } from '@block-pr/component/PrStatus';
import { PR_ORIGIN_LABELS, type PrOriginTool } from '@block-pr/data/pr-origin';
import {
  type PrForeignEntityData,
  prForeignEntityQueryOptions,
} from '@block-pr/data/queries';
import { prDisplayName } from '@block-pr/util/prKey';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { githubLabelColor } from '@entity/components/GithubLabelPill';
import type { GithubPullRequestLabel } from '@entity/types/entity';
import SplitIcon from '@icon/system/regular/columns.svg';
import EyeIcon from '@icon/system/regular/eye.svg';
import GitPullRequestIcon from '@icon/system/regular/git-pull-request.svg';
import StarIcon from '@icon/system/regular/star.svg';
import UserIcon from '@icon/system/regular/user.svg';
import UserCircleCheckIcon from '@icon/system/regular/user-circle-check.svg';
import UsersThreeIcon from '@icon/system/regular/users-three.svg';
import { ContextMenu } from '@kobalte/core/context-menu';
import { selectSidebarTag } from '@property/tags/SidebarTagsSection';
import {
  useFavoritesData,
  useRemoveFavoriteMutation,
} from '@queries/favorites/favorites';
import type { Favorite } from '@service-storage/generated/schemas/favorite';
import { makePersisted } from '@solid-primitives/storage';
import { useQueries } from '@tanstack/solid-query';
import { TagDot } from '@ui';
import { type Component, createMemo, createSignal, For, Show } from 'solid-js';
import {
  REVIEWS_SCOPES,
  type ReviewsScope,
  type ReviewsStatusTabId,
} from '../reviews-types';
import { RepositoriesPromotion } from './RepositoriesPromotion';
import { ReviewsStatusTabs } from './ReviewsStatusTabs';

const SCOPE_ITEMS: Record<
  ReviewsScope,
  { label: string; icon: Component<{ class?: string }> }
> = {
  all: { label: 'Pull requests', icon: GitPullRequestIcon },
  authored: { label: 'Authored by me', icon: UserIcon },
  assigned: { label: 'Assigned to me', icon: UserCircleCheckIcon },
  involving: { label: 'Involves me', icon: UsersThreeIcon },
  review_requests: { label: 'Review requests', icon: EyeIcon },
};

function ReviewFavoriteRow(props: {
  favorite: Favorite;
  data: PrForeignEntityData;
  onOpenReview: (id: string, newSplit: boolean) => void;
  activeForeignEntityId?: string;
}) {
  const removeFavorite = useRemoveFavoriteMutation();
  const name = () =>
    props.data.pullRequest.name ?? prDisplayName(props.data.prRef);

  return (
    <ContextMenu>
      <ContextMenu.Trigger as="div" class="w-full">
        <ViewSidebar.Item
          title={name()}
          active={props.activeForeignEntityId === props.favorite.entityId}
          onClick={(event) =>
            props.onOpenReview(props.favorite.entityId, event.shiftKey)
          }
        >
          <ViewSidebar.Icon>
            <PrStatusIcon
              status={props.data.pullRequest.status ?? 'open'}
              class="size-4"
            />
          </ViewSidebar.Icon>
          <span class="truncate">{name()}</span>
          <FavoriteUnreadIndicator favorite={props.favorite} />
        </ViewSidebar.Item>
      </ContextMenu.Trigger>
      <ContextMenu.Portal>
        <ContextMenuContent class="min-w-56 max-w-[22rem] text-xs text-ink-muted">
          <MenuItem
            icon={SplitIcon}
            text={t('entityActions.openInNewSplit')}
            disabled={!globalSplitManager()?.canAppendSplit()}
            onClick={() => {
              if (globalSplitManager()?.canAppendSplit())
                props.onOpenReview(props.favorite.entityId, true);
            }}
          />
          <MenuItem
            icon={StarIcon}
            text={t('entityActions.removeFromFavorites')}
            onClick={() =>
              removeFavorite.mutate({
                entityType: 'foreign_entity',
                entityId: props.favorite.entityId,
              })
            }
          />
        </ContextMenuContent>
      </ContextMenu.Portal>
    </ContextMenu>
  );
}

function ReviewFavorites(props: {
  onOpenReview: (id: string, newSplit: boolean) => void;
  activeForeignEntityId?: string;
}) {
  const favoritesData = useFavoritesData({ entityType: ['foreign_entity'] });
  const favorites = createMemo(() =>
    (favoritesData()?.favorites ?? [])
      .filter((favorite) => favorite.entityType === 'foreign_entity')
      .sort((left, right) => left.sortOrder - right.sortOrder)
  );
  const queries = useQueries(() => ({
    queries: favorites().map((favorite) =>
      prForeignEntityQueryOptions(favorite.entityId)
    ),
  }));
  const pullRequests = () =>
    favorites().flatMap((favorite, index) => {
      const query = queries[index];
      const data = query?.isPending ? undefined : query?.data;
      return data?.id === favorite.entityId ? [{ favorite, data }] : [];
    });
  const [open, setOpen] = makePersisted(createSignal(true), {
    name: 'reviews-favorites-open',
  });

  return (
    <Show when={pullRequests().length > 0}>
      <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
        <CollapsibleSection.Trigger>
          <span class="min-w-0 truncate">Favorites</span>
          <CollapsibleSection.Indicator />
        </CollapsibleSection.Trigger>
        <CollapsibleSection.Content>
          <ViewSidebar.Nav aria-label="Favorite pull requests">
            <For each={pullRequests()}>
              {({ favorite, data }) => (
                <ReviewFavoriteRow
                  favorite={favorite}
                  data={data}
                  onOpenReview={props.onOpenReview}
                  activeForeignEntityId={props.activeForeignEntityId}
                />
              )}
            </For>
          </ViewSidebar.Nav>
        </CollapsibleSection.Content>
      </CollapsibleSection.Root>
    </Show>
  );
}

/**
 * GitHub labels among the visible pull requests, drawn like the email Tags
 * section. A row is a destination: choosing a label shows it alone, and
 * choosing the active label clears it.
 */
function ReviewLabels(props: {
  labels: GithubPullRequestLabel[];
  activeLabels: readonly string[];
  onActiveLabelsChange: (labels: string[]) => void;
}) {
  const [open, setOpen] = makePersisted(createSignal(true), {
    name: 'reviews-labels-open',
  });

  return (
    <Show when={props.labels.length > 0}>
      <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
        <CollapsibleSection.Trigger>
          <span class="min-w-0 truncate">Labels</span>
          <CollapsibleSection.Indicator />
        </CollapsibleSection.Trigger>
        <CollapsibleSection.Content>
          <ViewSidebar.Nav aria-label="Pull request labels">
            <For each={props.labels}>
              {(label) => (
                <ViewSidebar.Item
                  title={label.name}
                  active={props.activeLabels.includes(label.name)}
                  onClick={() =>
                    props.onActiveLabelsChange(
                      selectSidebarTag(props.activeLabels, label.name)
                    )
                  }
                >
                  <ViewSidebar.Icon>
                    <TagDot fill={githubLabelColor(label.color)} />
                  </ViewSidebar.Icon>
                  <span class="truncate">{label.name}</span>
                </ViewSidebar.Item>
              )}
            </For>
          </ViewSidebar.Nav>
        </CollapsibleSection.Content>
      </CollapsibleSection.Root>
    </Show>
  );
}

/**
 * The tools the visible pull requests were started from, such as Claude or
 * Codex. Like Labels, choosing one shows it alone and choosing it again clears it.
 */
function ReviewAgents(props: {
  tools: readonly PrOriginTool[];
  activeTools: readonly string[];
  onActiveToolsChange: (tools: string[]) => void;
}) {
  const [open, setOpen] = makePersisted(createSignal(true), {
    name: 'reviews-agents-open',
  });

  return (
    <Show when={props.tools.length > 0}>
      <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
        <CollapsibleSection.Trigger>
          <span class="min-w-0 truncate">Agents</span>
          <CollapsibleSection.Indicator />
        </CollapsibleSection.Trigger>
        <CollapsibleSection.Content>
          <ViewSidebar.Nav aria-label="Pull request agents">
            <For each={props.tools}>
              {(tool) => (
                <ViewSidebar.Item
                  title={t('viewMenus.startedFrom', {
                    origin: PR_ORIGIN_LABELS[tool],
                  })}
                  active={props.activeTools.includes(tool)}
                  onClick={() =>
                    props.onActiveToolsChange(
                      selectSidebarTag(props.activeTools, tool)
                    )
                  }
                >
                  <ViewSidebar.Icon>
                    <PrOriginIcon tool={tool} class="size-4" />
                  </ViewSidebar.Icon>
                  <span class="truncate">{PR_ORIGIN_LABELS[tool]}</span>
                </ViewSidebar.Item>
              )}
            </For>
          </ViewSidebar.Nav>
        </CollapsibleSection.Content>
      </CollapsibleSection.Root>
    </Show>
  );
}

export function ReviewsSidebar(props: {
  search: string;
  onSearchChange: (search: string) => void;
  /** The status toggle; omitted when the status selection is custom or the board shows. */
  status?: {
    value: ReviewsStatusTabId | undefined;
    onChange: (value: ReviewsStatusTabId) => void;
  };
  scope: ReviewsScope;
  onScopeChange: (scope: ReviewsScope) => void;
  labels: GithubPullRequestLabel[];
  activeLabels: readonly string[];
  onActiveLabelsChange: (labels: string[]) => void;
  /** Tools the visible pull requests were started from, in display order. */
  agents: readonly PrOriginTool[];
  activeAgents: readonly string[];
  onActiveAgentsChange: (tools: string[]) => void;
  onOpenReview: (id: string, newSplit: boolean) => void;
  activeForeignEntityId?: string;
}) {
  const panel = useSplitPanelOrThrow();
  useViewTabHotkeys({
    scopeId: panel.splitHotkeyScope,
    enabled: panel.isPanelActive,
    ids: () => [...REVIEWS_SCOPES],
    activeId: () => props.scope,
    setActiveId: props.onScopeChange,
  });

  return (
    <ViewSidebar.Root aria-label="Reviews navigation">
      <ViewSidebar.Header
        searchLabel="Search reviews"
        search={() => (
          <SearchBar
            label="Search reviews"
            placeholder="Search reviews"
            autocomplete="off"
            value={props.search}
            onValueChange={props.onSearchChange}
            onEscape={() => props.onSearchChange('')}
          />
        )}
      >
        <div class="flex min-w-0 items-center gap-1">
          <ViewSidebar.CloseButton />
          <ViewSidebar.Title>Reviews</ViewSidebar.Title>
        </div>
      </ViewSidebar.Header>
      <Show when={!isTouchDevice()}>
        <ViewSidebar.Primary>
          <ViewCreateMenu presentation="sidebar" />
        </ViewSidebar.Primary>
      </Show>
      <Show when={isTouchDevice()}>
        <ViewSidebar.Primary class="flex flex-col gap-2">
          <SearchBar
            label="Search reviews"
            placeholder="Search reviews"
            autocomplete="off"
            value={props.search}
            onValueChange={props.onSearchChange}
            class="border-0 bg-ink/5 shadow-none"
            onEscape={() => props.onSearchChange('')}
          />
          <Show when={props.status}>
            {(status) => (
              <ReviewsStatusTabs
                value={status().value}
                onChange={status().onChange}
              />
            )}
          </Show>
        </ViewSidebar.Primary>
      </Show>
      <ViewSidebar.Content>
        <ViewSidebar.Nav aria-label="Pull request views">
          <For each={REVIEWS_SCOPES}>
            {(scope) => {
              const Icon = SCOPE_ITEMS[scope].icon;
              return (
                <ViewSidebar.Item
                  active={props.scope === scope}
                  onClick={() => props.onScopeChange(scope)}
                >
                  <ViewSidebar.Icon>
                    <Icon class="size-4" />
                  </ViewSidebar.Icon>
                  <span class="truncate">{SCOPE_ITEMS[scope].label}</span>
                </ViewSidebar.Item>
              );
            }}
          </For>
        </ViewSidebar.Nav>
        <ReviewFavorites
          onOpenReview={props.onOpenReview}
          activeForeignEntityId={props.activeForeignEntityId}
        />
        <ReviewAgents
          tools={props.agents}
          activeTools={props.activeAgents}
          onActiveToolsChange={props.onActiveAgentsChange}
        />
        <ReviewLabels
          labels={props.labels}
          activeLabels={props.activeLabels}
          onActiveLabelsChange={props.onActiveLabelsChange}
        />
        <RepositoriesPromotion class="mt-auto" />
      </ViewSidebar.Content>
    </ViewSidebar.Root>
  );
}