Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(spaces): give tree session rows cards, menus and a way into the space (#78742)

Adam Leith17dd573d12ce
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 2c5df489f998..af235a8fb0ae 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -193,6 +193,16 @@ export interface TaskRunSessionLogsResult {
complete: boolean;
}
+export interface TaskListOptions {
+ repository?: string;
+ createdBy?: number;
+ originProduct?: string;
+ internal?: boolean;
+ channel?: string;
+ /** Caller-side cap for surfaces that only show the newest few. */
+ limit?: number;
+}
+
export interface TaskSessionStorageAccess {
id: string;
download_url: string | null;
@@ -2162,16 +2172,20 @@ export class PostHogAPIClient {
}
}
- async getTasks(options?: {
- repository?: string;
- createdBy?: number;
- originProduct?: string;
- internal?: boolean;
- channel?: string;
- }): Promise<Task[]> {
+ async getTasks(options?: TaskListOptions): Promise<Task[]> {
+ return (await this.getTasksPage(options)).tasks;
+ }
+
+ /**
+ * The same list with the total behind it, for surfaces that ask for a short
+ * page and still have to say how much they are not showing.
+ */
+ async getTasksPage(
+ options?: TaskListOptions,
+ ): Promise<{ tasks: Task[]; count: number }> {
const teamId = await this.getTeamId();
const params: Record<string, string | number | boolean> = {
- limit: 500,
+ limit: options?.limit ?? 500,
};
if (options?.repository) {
@@ -2199,9 +2213,10 @@ export class PostHogAPIClient {
query: params,
});
- return (data.results ?? []).map((task) =>
+ const tasks = (data.results ?? []).map((task) =>
normalizeTaskResponse(task, { teamId }),
);
+ return { tasks, count: data.count ?? tasks.length };
}
async getTaskSummaries(ids: string[]) {
diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
index 325fda2ff007..4cf404e25e0a 100644
--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md
@@ -50,9 +50,84 @@ The root `AGENTS.md` architecture rules still apply.
slide and returning to the list doesn't rebuild every row. A two-finger
horizontal swipe moves between them (`useChannelPaneSwipe`, wheel `deltaX`
accumulated per gesture and locked until the wheel goes quiet).
-- In the list, "Starred"/"Spaces" are headings above lightly indented shared
- rows; the pinned private "me" row aligns with the headings. The alpha's more
- deeply indented Channels tree and hash glyphs are unchanged.
+- In the list, "Starred"/"Spaces" are headings above lightly indented rows. The
+ private "me" row leads the Starred section and takes the same inset as the
+ spaces beside it. No row carries a glyph: "me" drops its lock here so every
+ name starts in the same column, and it still marks the space everywhere it is
+ named on its own (the back row, the breadcrumb). The alpha's more deeply
+ indented Channels tree and hash glyphs are unchanged.
+- **The list is a tree.** Each space has a disclosure caret that opens it onto
+ its most recent sessions (`useRecentSpaceTasks` — one task query per open
+ space, polling slower than the channel feed; expansion lives in
+ `spaceTreeStore` and persists). Session rows wear the space's own session
+ vocabulary (`TaskStatusDot` + `TaskBadgeStack`) but are hand-built rather than
+ `ChannelItemRow`: a row has to be an `AutocompleteItem` to stay on the
+ keyboard's path, and that row is a `SidebarItem` button.
+- **An open space offers the sessions it isn't showing.** A "View all" leaf
+ closes the list with what's left over and opens the space.
+ Its number comes from `getTasksPage`, which returns the page's total alongside
+ its rows: a page that came back under the fetch limit is the whole space
+ (exact once archived ones are dropped), a full one falls back to the server's
+ count, which still counts archived tasks.
+ `hasViewAllRow` decides whether that leaf exists, and both the rendered list
+ and the keyboard's flat node list have to call it: a row the keyboard doesn't
+ know about throws the highlight index off from there down.
+- **A session row carries the same card and menu as the space's own list.**
+ Both surfaces render `ChannelItemHoverCard` and `TaskRowContextMenu` from one
+ `TaskRowMenuProps`, so the facts and the actions can't drift.
+ Rename is the one item the tree drops, because it edits in place and there is
+ no inline editor on a row the keyboard is walking.
+ The card also opens on the keyboard's highlight, 350ms after it lands.
+ Rows read that highlight from `spaceTreeStore` as a boolean
+ (`highlightedValue === item.key`) so a keypress re-renders two rows, and the
+ list still writes it to a ref as well, because the arrow handlers read the
+ highlight during the event, before any render.
+ Only a `reason: "keyboard"` highlight is stored: a pointer one is the row's
+ own hover, and `keepHighlight` would otherwise strand a card open after the
+ pointer left the list.
+ The actions behind the menu (`useSpaceTaskActions`) are built once for the
+ whole list and passed through `SpaceTaskActionsProvider`, which keeps one pin
+ and one archive mutation for the tree instead of one per row and keeps them
+ out of the memo comparisons.
+- **A row's own colour utilities outrank quill's highlight styling.** quill
+ brings a highlighted option's contents to `--foreground` with
+ `.quill-autocomplete__item[data-highlighted] *`, but that rule lives in the
+ components layer, so anything carrying a colour utility of its own wins and
+ keeps its resting colour under the keyboard.
+ Row labels therefore state the highlight themselves (`ROW_LABEL_TONE`), and
+ the disclosure caret, which must stay dim while its row is highlighted, needs
+ `!` on a rule aimed at the glyph's descendants, because the `*` reaches the
+ icon's `<path>` where `fill: currentColor` resolves.
+- **The tree's rows are memoized, and have to stay that way.** A space row
+ carries a context menu, two dropdowns, a tooltip and two dialogs, and there
+ are dozens of them; before `ChannelSection`/`PersonalChannelRow`/`SpaceTaskRow`
+ were `memo`ed, expanding one space rebuilt every other row (350-540ms per
+ expand, in 300ms chunks). Keeping that means keeping their props stable: the
+ toggle callback takes a space id instead of closing over one, empty session
+ lists are a shared constant, `useRecentSpaceTasks` caches each space's item
+ list against the query data it was built from, and its `combine` is defined at
+ module scope so `useQueries` can memoize on it. A row's `channel` is compared
+ field by field, because the channel list is polled and hands out new objects.
+- **The tree stays off the host.** Its rows skip the per-task PR lookup
+ (`useChannelTaskStatus(item, { withPrStatus: false })`) — that is a query per
+ row into git, and the tree can show a dozen spaces' worth at once; the PR's
+ existence still shows, because `prUrl` comes from the task itself. Its feed
+ query is its own key with a 20-row page, not the channel feed's 500: sharing
+ the feed's key would hand the space's own list a truncated feed.
+- **Hover prefetch waits for the pointer to rest** (250ms). Arrowing through the
+ tree scrolls rows under a stationary cursor, so prefetching straight from
+ `pointerenter` fired a request for every row the list passed and made each
+ keypress take a second.
+- **Keyboard contract of the list.** The search box holds focus and drives
+ everything: ↑/↓ walk every visible row, → opens the highlighted space (and
+ again steps into it), ← closes the space you're in and puts the highlight back
+ on it. Both arrows defer to the text caret first, so they still edit the
+ query. ⌘⇧S from anywhere opens the sidebar, slides back to the list and takes
+ the keyboard; it is advertised on the search box (until a query replaces it
+ with the clear button) and on the space's back row, which is what it does from
+ inside a space. Autocomplete has no API for setting the highlight, so moving it
+ means synthesizing the arrow keys it listens for — and moving *before*
+ collapsing, while the rows still exist.
- One `ChannelsFab` serves both panes: given a `channelId` it creates inside
that channel (task, canvas), and either way it can create a channel. Off the
layout it keeps its original two-item menu. Archived moves out of the sidebar
@@ -62,6 +137,10 @@ The root `AGENTS.md` architecture rules still apply.
browses the list while the route, the main pane and the scoped channel stay
put. Every way into a channel — a row click, a deep link, a mention, ⌘1-9 —
ends at `showChannelPane()`, directly or through the route effect.
+ The one exception is a session opened from the list's tree: it loads in the
+ main window and leaves the sidebar on the list, because picking a session
+ while browsing across spaces is not a request to go into one. It says so with
+ `keepListForNextRoute()`, which the route effect consumes in place of sliding.
## Breadcrumbs
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelBackRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelBackRow.tsx
index e809f6f72e3a..ec0828adefd4 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelBackRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelBackRow.tsx
@@ -1,6 +1,8 @@
import { CaretLeftIcon, StarIcon } from "@phosphor-icons/react";
import {
Button,
+ cn,
+ Kbd,
Skeleton,
Tooltip,
TooltipContent,
@@ -15,6 +17,10 @@ import {
} from "@posthog/ui/features/canvas/hooks/useChannels";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { showChannelList } from "@posthog/ui/features/canvas/stores/channelPaneStore";
+import {
+ formatHotkey,
+ SHORTCUTS,
+} from "@posthog/ui/features/command/keyboard-shortcuts";
import { track } from "@posthog/ui/shell/analytics";
// An overlay rather than a sibling: the back button fills the row, and nesting
@@ -79,11 +85,13 @@ export function ChannelBackRow({ channelId }: { channelId: string }) {
showChannelList();
}}
// Quill's own height and radius, so this reads as one of the rows
- // under it rather than a control sitting on top. The star well is
- // unconditional (see the reserved span below): sized off its
- // contents, a starrable channel ran taller than #me and everything
- // below shifted on switch.
- className="w-full gap-1.5 text-left"
+ // under it rather than a control sitting on top. The right padding
+ // is the star's well — the star is an overlay, because a button
+ // can't nest one, so without it the row's own content runs under
+ // the star. Padding rather than a spacer element: quill hides an
+ // empty one (`empty:hidden`), which is how the shortcut hint ended
+ // up sitting beneath the star.
+ className={cn("w-full gap-1.5 text-left", showStar && "pr-8")}
>
<CaretLeftIcon
size={12}
@@ -109,11 +117,27 @@ export function ChannelBackRow({ channelId }: { channelId: string }) {
"Unavailable"
)}
</span>
- <span aria-hidden className="size-6 shrink-0" />
+ {/* Same key as the search box's hint: from inside a space it is
+ the way back to the list, which is what this row does. */}
+ <Kbd className="mr-0! shrink-0 opacity-50">
+ {formatHotkey(SHORTCUTS.FOCUS_SPACE_SEARCH)}
+ </Kbd>
+ {/* The star's well. Its height is unconditional — it is what
+ sets the row's height, and a row that changed height between a
+ starrable space and #me made everything below it jump on
+ switch. Its width is not: with no star to hold, an empty
+ column just pushes the shortcut hint off the edge. */}
+ <span
+ aria-hidden
+ className={cn(
+ "h-6 shrink-0 empty:hidden",
+ showStar ? "w-6" : "w-0",
+ )}
+ />
</Button>
}
/>
- <TooltipContent side="bottom">Back to spaces</TooltipContent>
+ <TooltipContent side="bottom">Go back</TooltipContent>
</Tooltip>
{/* #me can't be starred, so its well stays empty — a greyed-out star read
as a control you were being denied. The well itself is unconditional
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
index 59a839e04185..9d9a2abe0890 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHotkeys.tsx
@@ -1,8 +1,14 @@
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { useStarredChannelSlots } from "@posthog/ui/features/canvas/hooks/useStarredChannelSlots";
+import {
+ showChannelList,
+ showChannelPane,
+} from "@posthog/ui/features/canvas/stores/channelPaneStore";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
+import { requestSpaceSearchFocus } from "@posthog/ui/features/canvas/stores/spaceTreeStore";
import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";
+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { navigateToChannel } from "@posthog/ui/router/navigationBridge";
import { track } from "@posthog/ui/shell/analytics";
import { useHotkeys } from "react-hotkeys-hook";
@@ -34,6 +40,10 @@ export function ChannelHotkeys() {
const channel = slots[slot - 1];
if (!channel) return;
setCurrentChannel(channel.id);
+ // Said outright rather than left to the route effect: this key is a
+ // request to be in the space, and the effect skips the slide for a
+ // navigation the list asked to stay out of.
+ showChannelPane();
navigateToChannel(channel.id);
track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
action_type: "open_channel",
@@ -50,5 +60,24 @@ export function ChannelHotkeys() {
[slots, setCurrentChannel],
);
+ // Jump to the space list from anywhere: open the sidebar if it's collapsed,
+ // slide it back to the list, and hand the keyboard to the search box, which
+ // is also the tree's keyboard driver.
+ useHotkeys(
+ SHORTCUTS.FOCUS_SPACE_SEARCH,
+ () => {
+ useSidebarStore.getState().setOpen(true);
+ showChannelList();
+ requestSpaceSearchFocus();
+ },
+ {
+ enabled: channelsLayout,
+ enableOnFormTags: true,
+ enableOnContentEditable: true,
+ preventDefault: true,
+ },
+ [],
+ );
+
return null;
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx
new file mode 100644
index 000000000000..9bc5d8ca9b4a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.tsx
@@ -0,0 +1,196 @@
+import { PreviewCard } from "@base-ui/react/preview-card";
+import { ChatCircleIcon } from "@phosphor-icons/react";
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import {
+ runStatusLabel,
+ runStatusVariant,
+} from "@posthog/core/canvas/runStatus";
+import {
+ Avatar,
+ AvatarFallback,
+ Badge,
+ Card,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemSeparator,
+ ItemTitle,
+} from "@posthog/quill";
+import { formatRelativeTimeShort } from "@posthog/shared";
+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+import {
+ TaskRowMenuList,
+ type TaskRowMenuProps,
+} from "@posthog/ui/features/canvas/components/TaskRowMenu";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { type ReactNode, useCallback, useEffect, useState } from "react";
+
+/**
+ * What the card leads with. A canvas gets its template glyph in canvas violet; a
+ * task gets the chat glyph the sidebar uses for a task with nothing going on —
+ * before this, a task was shown wearing a canvas's icon.
+ */
+function previewGlyph(item: ChannelItemModel): ReactNode {
+ if (item.kind !== "canvas") {
+ return <ChatCircleIcon size={15} className="text-gray-10" />;
+ }
+ // Matches the schema's own default for boards saved before templating.
+ return iconForTemplate(item.templateId ?? "freeform", {
+ size: 15,
+ className: "text-violet-9",
+ });
+}
+
+function authorLabel(item: ChannelItemModel): string | null {
+ if (item.authorUser) return userDisplayName(item.authorUser);
+ return item.authorName;
+}
+
+/**
+ * How long the keyboard has to rest on a row before its card opens. Long enough
+ * that arrowing through the list doesn't flash a card on every row it passes.
+ */
+const KEYBOARD_OPEN_DELAY_MS = 350;
+
+/**
+ * The row's hover card: what the thing is, who made it, and what you can do to
+ * it. Shared by the channel sidebar's rows and the space tree's session rows so
+ * the two can't drift into showing different facts or actions for one task.
+ *
+ * `children` is the row itself, handed to the trigger.
+ */
+export function ChannelItemHoverCard({
+ item,
+ menu,
+ highlighted = false,
+ children,
+}: {
+ item: ChannelItemModel;
+ menu: TaskRowMenuProps;
+ /** The keyboard is on this row, which opens the card as hovering does. */
+ highlighted?: boolean;
+ children: ReactNode;
+}) {
+ const [cardOpen, setCardOpen] = useState(false);
+ const [submenuOpen, setSubmenuOpen] = useState(false);
+ const [keyboardOpen, setKeyboardOpen] = useState(false);
+ // Stable: `TaskRowMenuList` builds its item components from these, so a new
+ // identity each render would remount every button in the card.
+ const closeCard = useCallback(() => setCardOpen(false), []);
+ const statusLabel = runStatusLabel(item.rawStatus);
+ const author = authorLabel(item);
+
+ // Closing is immediate: once the highlight has moved, a card still open
+ // points at the wrong row.
+ useEffect(() => {
+ if (!highlighted) {
+ setKeyboardOpen(false);
+ return;
+ }
+ const timer = setTimeout(
+ () => setKeyboardOpen(true),
+ KEYBOARD_OPEN_DELAY_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [highlighted]);
+
+ return (
+ // Controlled so the card survives its own submenu: "File to…" opens in a
+ // portal outside the card, and the pointer moving there reads as leaving the
+ // card, which would take the menu down with it.
+ <PreviewCard.Root
+ open={cardOpen || submenuOpen || keyboardOpen}
+ onOpenChange={setCardOpen}
+ >
+ <PreviewCard.Trigger
+ delay={400}
+ closeDelay={100}
+ render={<div className="min-w-0">{children}</div>}
+ />
+ <PreviewCard.Portal>
+ <PreviewCard.Positioner
+ side="right"
+ align="start"
+ sideOffset={10}
+ className="z-50"
+ >
+ {/* The card is quill's `Card` and `Item` parts throughout — the popup
+ itself carries no surface styling, so this window's hover card
+ matches every other card in the app rather than a hand-tuned
+ shadow of its own. The card's own padding is off (`gap-0 py-0`):
+ each section pays for its own inset, which is what lets the rules
+ run edge to edge and the action rows highlight full width. */}
+ <PreviewCard.Popup
+ render={
+ <Card
+ size="sm"
+ className="w-64 gap-0 border border-border py-0 shadow-md"
+ />
+ }
+ >
+ <ItemGroup className="gap-0!">
+ <Item size="xs" className="p-2">
+ <ItemMedia variant="icon" className="size-5">
+ {previewGlyph(item)}
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>{item.title}</ItemTitle>
+ <ItemDescription>
+ {item.kind === "canvas" ? "Canvas" : "Task"} · updated{" "}
+ {formatRelativeTimeShort(item.ts)}
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ {statusLabel && (
+ <div className="px-2 pb-2">
+ <Badge variant={runStatusVariant(item.rawStatus)}>
+ {statusLabel}
+ </Badge>
+ </div>
+ )}
+ {author && (
+ <>
+ {/* Every section of the card gets the rule above it, canvases
+ included — the author is a different fact from the thing's
+ identity whether or not there are actions under it. */}
+ <ItemSeparator className="my-0" />
+ <Item size="xs" className="p-2">
+ <ItemMedia variant="icon">
+ {item.authorUser ? (
+ <UserAvatar size="xs" user={item.authorUser} />
+ ) : (
+ <Avatar size="xs">
+ <AvatarFallback>
+ {author.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ )}
+ </ItemMedia>
+ <ItemContent className="gap-0">
+ <ItemTitle>{author}</ItemTitle>
+ <ItemDescription>Created by</ItemDescription>
+ </ItemContent>
+ </Item>
+ </>
+ )}
+ {/* The row's actions live here now: a row at rest shows its
+ status, and the card is already the surface you're pointing at
+ when you want to do something to it. */}
+ <ItemSeparator className="my-0" />
+ <div className="p-1">
+ <TaskRowMenuList
+ menu={menu}
+ onAction={closeCard}
+ onSubmenuOpenChange={setSubmenuOpen}
+ />
+ </div>
+ </ItemGroup>
+ </PreviewCard.Popup>
+ </PreviewCard.Positioner>
+ </PreviewCard.Portal>
+ </PreviewCard.Root>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index e2362f90afaa..1353d27d245a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -1,10 +1,4 @@
-import { PreviewCard } from "@base-ui/react/preview-card";
-import { ChatCircleIcon } from "@phosphor-icons/react";
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
-import {
- runStatusLabel,
- runStatusVariant,
-} from "@posthog/core/canvas/runStatus";
import {
AlertDialog,
AlertDialogClose,
@@ -16,31 +10,20 @@ import {
Avatar,
AvatarFallback,
AvatarGroup,
- Badge,
Button,
- Card,
- Item,
- ItemContent,
- ItemDescription,
- ItemGroup,
- ItemMedia,
- ItemSeparator,
- ItemTitle,
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@posthog/quill";
import { formatRelativeTimeShort } from "@posthog/shared";
-import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
+import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
import {
TaskRowContextMenu,
- TaskRowMenuList,
type TaskRowMenuProps,
} from "@posthog/ui/features/canvas/components/TaskRowMenu";
import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
import { useIsCanvasPendingDelete } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";
-import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
import { InlineEditInput } from "@posthog/ui/features/sidebar/components/items/TaskItem";
import {
PinnedBadge,
@@ -76,22 +59,6 @@ const TIMESTAMP_CLASS = "shrink-0 text-[11px] text-muted-foreground";
// between stacks (a pin, then the status badges), not within one.
const TRAILING_CLASS = "flex shrink-0 items-center gap-1";
-/**
- * What the card leads with. A canvas gets its template glyph in canvas violet; a
- * task gets the chat glyph the sidebar uses for a task with nothing going on —
- * before this, a task was shown wearing a canvas's icon.
- */
-function previewGlyph(item: ChannelItemModel): ReactNode {
- if (item.kind !== "canvas") {
- return <ChatCircleIcon size={15} className="text-gray-10" />;
- }
- // Matches the schema's own default for boards saved before templating.
- return iconForTemplate(item.templateId ?? "freeform", {
- size: 15,
- className: "text-violet-9",
- });
-}
-
/**
* A canvas waiting out its delete-undo window. Red and flashing because it is
* the one row state that is about to stop existing — everything else in this
@@ -104,11 +71,6 @@ const DELETING_DOT: TaskDot = {
label: "Deleting…",
};
-function authorLabel(item: ChannelItemModel): string | null {
- if (item.authorUser) return userDisplayName(item.authorUser);
- return item.authorName;
-}
-
/**
* One badge in a row's trailing stack, named on hover like the ones
* `TaskBadgeStack` draws — the row's tooltip provider is already up, so this
@@ -192,18 +154,11 @@ export function ChannelItemRow({
onEditCancel?: () => void;
}) {
const status = useChannelTaskStatus(item);
- const [cardOpen, setCardOpen] = useState(false);
- const [submenuOpen, setSubmenuOpen] = useState(false);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
// A canvas inside its undo window stays in the list rather than vanishing and
// reappearing on Undo, so the row has to say what's happening to it.
const pendingDelete = useIsCanvasPendingDelete(item.id);
const deleting = item.kind === "canvas" && pendingDelete;
- // Stable: `TaskRowMenuList` builds its item components from these, so a new
- // identity each render would remount every button in the card.
- const closeCard = useCallback(() => setCardOpen(false), []);
- const statusLabel = runStatusLabel(item.rawStatus);
- const author = authorLabel(item);
const handleDragStart = useCallback(
(event: DragEvent) => {
if (item.kind !== "task") return;
@@ -220,7 +175,6 @@ export function ChannelItemRow({
const rowIcon = (
<TaskStatusDot dot={deleting ? DELETING_DOT : taskDot(status ?? {})} />
);
- const previewIcon = previewGlyph(item);
// A canvas gets the same menu with the items it actually has: pin, and delete
// instead of archive. Filing and command-centre cells are task-shaped, and the
// menu drops them rather than showing them dead.
@@ -264,140 +218,43 @@ export function ChannelItemRow({
// One tooltip provider per task row, shared by its dot and badges so moving
// between them doesn't re-wait the open delay. Canvas rows have neither.
const row = (
- // Controlled so the card survives its own submenu: "File to…" opens in a
- // portal outside the card, and the pointer moving there reads as leaving the
- // card, which would take the menu down with it.
- <PreviewCard.Root open={cardOpen || submenuOpen} onOpenChange={setCardOpen}>
- <PreviewCard.Trigger
- delay={400}
- closeDelay={100}
- render={
- <div className="min-w-0">
- <SidebarItem
- depth={0}
- icon={rowIcon}
- // A non-string label opts out of SidebarItem's truncation tooltip.
- label={<span>{item.title}</span>}
- isActive={isActive}
- draggable={item.kind === "task"}
- onDragStart={handleDragStart}
- onClick={() => actions.open(item)}
- endContent={
- <span className={TRAILING_CLASS}>
- {/* Badges take the timestamp's slot on a task row: the row's
+ <ChannelItemHoverCard item={item} menu={menu}>
+ <SidebarItem
+ depth={0}
+ icon={rowIcon}
+ // A non-string label opts out of SidebarItem's truncation tooltip.
+ label={<span>{item.title}</span>}
+ isActive={isActive}
+ draggable={item.kind === "task"}
+ onDragStart={handleDragStart}
+ onClick={() => actions.open(item)}
+ endContent={
+ <span className={TRAILING_CLASS}>
+ {/* Badges take the timestamp's slot on a task row: the row's
identity (pin, source, cloud, PR) is what you scan a task
list for, and the relative age is still in the preview
card. The pin joins whichever stack the row has, rather
than standing beside it as a badge of its own. */}
- {status ? (
- <TaskBadgeStack status={status} pinned={item.pinned} />
- ) : item.kind === "canvas" ? (
- <CanvasBadgeStack item={item} pinned={item.pinned} />
- ) : (
- <>
- {item.pinned && (
- <AvatarGroup
- stacked
- reverse
- size="xs"
- className="shrink-0"
- >
- <PinnedBadge />
- </AvatarGroup>
- )}
- <span className={TIMESTAMP_CLASS}>
- {formatRelativeTimeShort(item.ts)}
- </span>
- </>
- )}
+ {status ? (
+ <TaskBadgeStack status={status} pinned={item.pinned} />
+ ) : item.kind === "canvas" ? (
+ <CanvasBadgeStack item={item} pinned={item.pinned} />
+ ) : (
+ <>
+ {item.pinned && (
+ <AvatarGroup stacked reverse size="xs" className="shrink-0">
+ <PinnedBadge />
+ </AvatarGroup>
+ )}
+ <span className={TIMESTAMP_CLASS}>
+ {formatRelativeTimeShort(item.ts)}
</span>
- }
- />
- </div>
+ </>
+ )}
+ </span>
}
/>
- <PreviewCard.Portal>
- <PreviewCard.Positioner
- side="right"
- align="start"
- sideOffset={10}
- className="z-50"
- >
- {/* The card is quill's `Card` and `Item` parts throughout — the popup
- itself carries no surface styling, so this window's hover card
- matches every other card in the app rather than a hand-tuned
- shadow of its own. The card's own padding is off (`gap-0 py-0`):
- each section pays for its own inset, which is what lets the rules
- run edge to edge and the action rows highlight full width. */}
- <PreviewCard.Popup
- render={
- <Card
- size="sm"
- className="w-64 gap-0 border border-border py-0 shadow-md"
- />
- }
- >
- <ItemGroup className="gap-0!">
- <Item size="xs" className="p-2">
- <ItemMedia variant="icon" className="size-5">
- {previewIcon}
- </ItemMedia>
- <ItemContent>
- <ItemTitle>{item.title}</ItemTitle>
- <ItemDescription>
- {item.kind === "canvas" ? "Canvas" : "Task"} · updated{" "}
- {formatRelativeTimeShort(item.ts)}
- </ItemDescription>
- </ItemContent>
- </Item>
- {statusLabel && (
- <div className="px-2 pb-2">
- <Badge variant={runStatusVariant(item.rawStatus)}>
- {statusLabel}
- </Badge>
- </div>
- )}
- {author && (
- <>
- {/* Every section of the card gets the rule above it, canvases
- included — the author is a different fact from the thing's
- identity whether or not there are actions under it. */}
- <ItemSeparator className="my-0" />
- <Item size="xs" className="p-2">
- <ItemMedia variant="icon">
- {item.authorUser ? (
- <UserAvatar size="xs" user={item.authorUser} />
- ) : (
- <Avatar size="xs">
- <AvatarFallback>
- {author.charAt(0).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- )}
- </ItemMedia>
- <ItemContent className="gap-0">
- <ItemTitle>{author}</ItemTitle>
- <ItemDescription>Created by</ItemDescription>
- </ItemContent>
- </Item>
- </>
- )}
- {/* The row's actions live here now: a row at rest shows its
- status, and the card is already the surface you're pointing at
- when you want to do something to it. */}
- <ItemSeparator className="my-0" />
- <div className="p-1">
- <TaskRowMenuList
- menu={menu}
- onAction={closeCard}
- onSubmenuOpenChange={setSubmenuOpen}
- />
- </div>
- </ItemGroup>
- </PreviewCard.Popup>
- </PreviewCard.Positioner>
- </PreviewCard.Portal>
- </PreviewCard.Root>
+ </ChannelItemHoverCard>
);
const tipped = <TaskStatusTooltips>{row}</TaskStatusTooltips>;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
index c83b5684e767..e17a0ef1f5da 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
@@ -10,6 +10,13 @@ const mocks = vi.hoisted(() => ({
channelType: "public" | "personal";
starred: boolean;
}[],
+ tasks: [] as {
+ id: string;
+ title: string;
+ channel: string;
+ updated_at: string;
+ }[],
+ totals: {} as Record<string, number>,
channelsLayout: true,
navigate: vi.fn(),
}));
@@ -34,6 +41,54 @@ vi.mock("@posthog/ui/features/canvas/hooks/useDashboards", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useUnreadChannels", () => ({
useIsChannelUnread: () => () => false,
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useRecentSpaceTasks", () => ({
+ NO_TASKS: { items: [], total: 0 },
+ usePrefetchSpaceTasks: () => () => undefined,
+ useRecentSpaceTasks: (spaceIds: string[]) =>
+ new Map(
+ spaceIds.map((spaceId) => {
+ const items = mocks.tasks
+ .filter((task) => task.channel === spaceId)
+ .map((task) => ({
+ key: `task:${task.id}`,
+ kind: "task",
+ id: task.id,
+ title: task.title,
+ ts: Date.parse(task.updated_at),
+ pinned: false,
+ rawStatus: null,
+ authorUser: null,
+ authorName: null,
+ authorUuid: null,
+ task: null,
+ }));
+ // `total` is what the space holds, not what the tree shows — the tests
+ // that exercise "View all" set it above the row count.
+ return [
+ spaceId,
+ { items, total: mocks.totals[spaceId] ?? items.length },
+ ];
+ }),
+ ),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskStatus", () => ({
+ useChannelTaskStatus: () => null,
+}));
+vi.mock(
+ "@posthog/ui/features/canvas/hooks/useSpaceTaskActions",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@posthog/ui/features/canvas/hooks/useSpaceTaskActions")
+ >()),
+ // The real one is a pin mutation and an archive mutation; the tree's rows
+ // only need something to hand their menus.
+ useSpaceTaskActions: () => ({
+ togglePin: vi.fn(),
+ archive: vi.fn(),
+ commandCenterAssigner: () => undefined,
+ }),
+ }),
+);
vi.mock("@posthog/ui/features/canvas/components/RenameChannelModal", () => ({
RenameChannelModal: () => null,
}));
@@ -43,10 +98,16 @@ vi.mock("@tanstack/react-router", () => ({
}));
import {
+ consumeKeepListForNextRoute,
showChannelList,
showChannelPane,
+ useChannelPaneStore,
} from "@posthog/ui/features/canvas/stores/channelPaneStore";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
+import {
+ requestSpaceSearchFocus,
+ useSpaceTreeStore,
+} from "@posthog/ui/features/canvas/stores/spaceTreeStore";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { ChannelsList } from "./ChannelsList";
@@ -88,6 +149,27 @@ describe("ChannelsList", () => {
// Same for the collapse state — a test that folds a group away would
// otherwise hide its rows from every test that runs after it.
useSidebarStore.setState({ collapsedSections: new Set() });
+ useSpaceTreeStore.setState({
+ expandedSpaceIds: new Set(),
+ searchFocusRequest: 0,
+ highlightedValue: undefined,
+ });
+ mocks.totals = {};
+ useCurrentChannelStore.setState({ currentChannelId: null });
+ mocks.tasks = [
+ {
+ id: "task-new",
+ title: "Ship the tree",
+ channel: ENG.id,
+ updated_at: "2026-08-02T00:00:00Z",
+ },
+ {
+ id: "task-old",
+ title: "Write the tests",
+ channel: ENG.id,
+ updated_at: "2026-08-01T00:00:00Z",
+ },
+ ];
});
it("opens a space in the sidebar without navigating the main window", async () => {
@@ -112,30 +194,11 @@ describe("ChannelsList", () => {
expect(me.parentElement?.textContent).toMatch(/me(⌘|Ctrl)/);
});
- // "Starred" and "Spaces" are headings over the rows. Spaces receive a small
- // Slack-style inset; the alpha keeps its deeper tree indentation.
describe("group headings", () => {
beforeEach(() => {
mocks.channels = [ME, { ...ENG, starred: true }, DESIGN];
});
- it("slightly indents rows under the layout", () => {
- renderList();
- expect(screen.getByText("engineering").closest("button")).toHaveClass(
- "pl-4",
- );
- expect(screen.getByText("me").closest("button")).not.toHaveClass("pl-4");
- });
-
- it("keeps the indented tree off the layout", () => {
- mocks.channelsLayout = false;
- renderList();
- expect(screen.getByText("engineering").closest(".pl-5")).toBeTruthy();
- expect(screen.getByText("engineering").closest("button")).not.toHaveClass(
- "pl-4",
- );
- });
-
it("rebrands only the spaces layout", () => {
renderList();
expect(screen.getByText("Spaces")).toBeTruthy();
@@ -296,9 +359,122 @@ describe("ChannelsList", () => {
});
});
+ // The list is a tree: a space opens onto its most recent tasks, and the whole
+ // of it is reachable from the search box without ever leaving the keyboard.
+ describe("space tree", () => {
+ it("opens a space onto its recent tasks with ArrowRight", async () => {
+ const user = userEvent.setup();
+ renderList();
+
+ await user.click(screen.getByLabelText("Search spaces"));
+ // #me is highlighted to begin with, so one press down is "engineering".
+ await user.keyboard("{ArrowDown}{ArrowRight}");
+
+ expect(screen.getByText("Ship the tree")).toBeTruthy();
+ expect(screen.getByText("Write the tests")).toBeTruthy();
+ // Opening the tree is not opening the space.
+ expect(useCurrentChannelStore.getState().currentChannelId).toBeNull();
+ });
+
+ // The fiddly half: the highlight is an index into a flat list, so walking
+ // back to the parent has to happen before its children stop existing.
+ it("walks into the tasks and back out to their space", async () => {
+ const user = userEvent.setup();
+ renderList();
+
+ await user.click(screen.getByLabelText("Search spaces"));
+ await user.keyboard("{ArrowDown}{ArrowRight}{ArrowDown}{ArrowDown}");
+ // On the second task, two rows below its space.
+ await user.keyboard("{ArrowLeft}");
+
+ expect(screen.queryByText("Ship the tree")).toBeNull();
+ // The highlight came back to the space it closed, so ⏎ opens that space
+ // rather than whatever row inherited the index.
+ await user.keyboard("{Enter}");
+ expect(useCurrentChannelStore.getState().currentChannelId).toBe(ENG.id);
+ });
+
+ it("toggles from the caret without opening the space", async () => {
+ const user = userEvent.setup();
+ renderList();
+
+ await user.click(screen.getByLabelText("Expand engineering"));
+ expect(screen.getByText("Ship the tree")).toBeTruthy();
+ expect(useCurrentChannelStore.getState().currentChannelId).toBeNull();
+
+ await user.click(screen.getByLabelText("Collapse engineering"));
+ expect(screen.queryByText("Ship the tree")).toBeNull();
+ });
+
+ // Picking a session out of the tree is browsing across spaces, not a
+ // request to go into one — sliding into the space would take the tree the
+ // reader is working through off the screen.
+ it("opens a session without leaving the list", async () => {
+ const user = userEvent.setup();
+ renderList();
+ act(() => showChannelList());
+
+ await user.click(screen.getByLabelText("Expand engineering"));
+ await user.click(screen.getByText("Ship the tree"));
+
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: { channelId: ENG.id, taskId: "task-new" },
+ }),
+ );
+ expect(useChannelPaneStore.getState().pane).toBe("list");
+ // The other half of it: the route effect in ChannelsSidebar slides into
+ // the space unless the navigation says to stay put.
+ expect(consumeKeepListForNextRoute()).toBe(true);
+ // Still scoped, so whatever asks for the channel pane next opens on the
+ // space the session came from.
+ expect(useCurrentChannelStore.getState().currentChannelId).toBe(ENG.id);
+ });
+
+ // The row after the last session: the keyboard has to know about it, or the
+ // highlight index and the rendered options disagree from there down.
+ it("walks onto View all and opens the space from it", async () => {
+ const user = userEvent.setup();
+ mocks.totals[ENG.id] = 7;
+ renderList();
+
+ await user.click(screen.getByLabelText("Search spaces"));
+ await user.keyboard("{ArrowDown}{ArrowRight}");
+ expect(screen.getByText("View all")).toBeTruthy();
+
+ // Past both sessions and onto the row below them.
+ await user.keyboard("{ArrowDown}{ArrowDown}{ArrowDown}{Enter}");
+
+ expect(useCurrentChannelStore.getState().currentChannelId).toBe(ENG.id);
+ });
+
+ it("says when an expanded space has nothing in it", async () => {
+ const user = userEvent.setup();
+ renderList();
+
+ await user.click(screen.getByLabelText("Expand design"));
+
+ expect(screen.getByText("No sessions yet")).toBeTruthy();
+ });
+ });
+
// Sliding back from a space, the list is what you came here for — so it hands
// the search box the caret rather than making you click it.
describe("focus on returning to the list", () => {
+ // ⌘⇧S is bound in ChannelHotkeys, which can only ask; the list is what
+ // actually takes the keyboard.
+ it("takes the keyboard on a focus request", async () => {
+ renderList();
+
+ act(() => requestSpaceSearchFocus());
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByLabelText("Search spaces"),
+ ),
+ );
+ });
+
it("focuses the search box when the pane slides back", async () => {
renderList();
expect(document.activeElement).not.toBe(
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index 1c22a74b4bef..bb58f867fa74 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -13,6 +13,7 @@ import {
StarIcon,
TrashIcon,
} from "@phosphor-icons/react";
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
import {
AlertDialogClose,
AlertDialogContent,
@@ -49,8 +50,13 @@ import {
TooltipTrigger,
} from "@posthog/quill";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";
import { RenameChannelModal } from "@posthog/ui/features/canvas/components/RenameChannelModal";
+import {
+ TaskRowContextMenu,
+ type TaskRowMenuProps,
+} from "@posthog/ui/features/canvas/components/TaskRowMenu";
import { trackAndCreateCanvas } from "@posthog/ui/features/canvas/createCanvasAnalytics";
import { useChannelStarToggle } from "@posthog/ui/features/canvas/hooks/useChannelStars";
import {
@@ -59,11 +65,24 @@ import {
useChannels,
} from "@posthog/ui/features/canvas/hooks/useChannels";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
+import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
import { useCreateAndOpenDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";
+import {
+ NO_TASKS,
+ type SpaceTasks,
+ usePrefetchSpaceTasks,
+ useRecentSpaceTasks,
+} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
+import {
+ SpaceTaskActionsProvider,
+ useSpaceTaskActions,
+ useSpaceTaskActionsContext,
+} from "@posthog/ui/features/canvas/hooks/useSpaceTaskActions";
import { useStarredChannelSlots } from "@posthog/ui/features/canvas/hooks/useStarredChannelSlots";
import { PERSONAL_CHANNEL_NAME } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
import { useIsChannelUnread } from "@posthog/ui/features/canvas/hooks/useUnreadChannels";
import {
+ keepListForNextRoute,
showChannelPane,
useChannelPaneStore,
} from "@posthog/ui/features/canvas/stores/channelPaneStore";
@@ -71,8 +90,18 @@ import {
resetCurrentChannel,
useCurrentChannelStore,
} from "@posthog/ui/features/canvas/stores/currentChannelStore";
+import { useSpaceTreeStore } from "@posthog/ui/features/canvas/stores/spaceTreeStore";
import { copyChannelLink } from "@posthog/ui/features/canvas/utils/copyChannelLink";
-import { formatHotkey } from "@posthog/ui/features/command/keyboard-shortcuts";
+import {
+ formatHotkey,
+ SHORTCUTS,
+} from "@posthog/ui/features/command/keyboard-shortcuts";
+import {
+ TaskBadgeStack,
+ TaskStatusDot,
+ TaskStatusTooltips,
+} from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";
+import { taskDot } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import {
OverflowTickerText,
@@ -86,8 +115,12 @@ import { useNavigate, useRouterState } from "@tanstack/react-router";
import {
type ComponentProps,
Fragment,
+ memo,
+ type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
+ type SyntheticEvent as ReactSyntheticEvent,
useEffect,
+ useMemo,
useRef,
useState,
} from "react";
@@ -139,8 +172,16 @@ function SpaceRowSurface({
"w-full min-w-0 pr-1 data-selected:bg-fill-selected data-selected:text-foreground",
// quill wraps an option's children in its own flex row; widening it is
// what keeps the shortcut hint at the row's right edge and lets the
- // name truncate, exactly as they do in the button above.
- "[&>span]:w-full [&>span]:gap-2",
+ // name truncate, exactly as they do in the button above. Its `truncate`
+ // also clips, which would cut off the disclosure's hit box where that
+ // hangs past the wrapper; every child that needs clipping does its own.
+ "[&>span]:w-full [&>span]:gap-2 [&>span]:overflow-visible",
+ // An icon's own colour lives on its `<svg>`, but quill repaints a
+ // highlighted option's contents down to the `<path>` that `fill:
+ // currentColor` resolves against, which drops every badge to the row's
+ // colour. Sending the marks back to their icon keeps a pinned row's pin
+ // and a status badge's tone under the pointer and the keyboard.
+ "[&_svg_*]:text-inherit!",
// quill highlights an option with an offset focus ring, which suits a
// popup listbox but reads as a stray outline on a sidebar row — and at
// dark-theme contrast it outshouts the selected row it sits next to.
@@ -158,6 +199,348 @@ function SpaceRowSurface({
);
}
+/**
+ * A row in the flat list the keyboard walks. The rows render as a tree, but
+ * Autocomplete only knows a sequence — so the tree's shape lives here, as the
+ * parent each task hangs off and the space each row belongs to.
+ */
+type SpaceTreeNode =
+ | { kind: "space"; value: string; spaceId: string | undefined }
+ | { kind: "task"; value: string; spaceId: string; parentValue: string };
+
+/** How long the pointer has to rest on a space before its sessions are warmed. */
+const SESSION_PREFETCH_DELAY_MS = 250;
+
+/**
+ * A row label's resting colour and the two states that bring it up to full
+ * contrast: the pointer on the row, and the keyboard's highlight on it.
+ *
+ * The highlight needs saying here. quill brings a highlighted option's contents
+ * to `--foreground` with `.quill-autocomplete__item[data-highlighted] *`, but
+ * that rule is in the components layer, so any label carrying a colour utility
+ * of its own outranks it and stays muted under the keyboard while brightening
+ * under the pointer.
+ */
+const ROW_LABEL_TONE =
+ "text-muted-foreground group-hover/button:text-foreground group-data-highlighted/button:text-foreground";
+
+/**
+ * Hand the pane's keyboard to the search box: focus it, send the highlight back
+ * to the top, and select whatever query was left there so it types over.
+ */
+function focusSearch(input: HTMLInputElement): void {
+ input.focus();
+ // Autocomplete leaves its highlight where it was and exposes no way to move
+ // it, so the list would open mid-scroll. Home is the key it listens for;
+ // sending it is how the list reopens at the top.
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
+ );
+ // After Home, so the caret it parks at the start doesn't undo the selection.
+ input.select();
+}
+
+/**
+ * Walk Autocomplete's highlight by synthesizing the arrow keys it already
+ * listens for. There is no API to set the highlighted row, and the input keeps
+ * focus throughout — it is the list's only cursor. Base UI holds the index in a
+ * ref, so a run of dispatches steps that many rows rather than collapsing into
+ * one.
+ */
+function moveHighlight(
+ input: HTMLInputElement,
+ key: "ArrowUp" | "ArrowDown",
+ steps: number,
+): void {
+ for (let step = 0; step < steps; step++) {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
+ }
+}
+
+/**
+ * The tree's disclosure caret, in its own fixed slot ahead of the space glyph.
+ * Always drawn: a control that only appears on hover moves the row's contents
+ * as the pointer crosses the list, and leaves the tree invisible to anyone who
+ * hasn't hovered a row yet.
+ *
+ * Not a `<button>` — the row around it already is one (quill's option renders a
+ * button too), and nesting buttons is invalid. Keyboard users get ArrowRight /
+ * ArrowLeft on the row instead, which is the point of the tree.
+ */
+function SpaceDisclosure({
+ expanded,
+ spaceName,
+ onToggle,
+}: {
+ expanded: boolean;
+ spaceName: string;
+ onToggle: () => void;
+}) {
+ const toggle = (event: ReactSyntheticEvent) => {
+ // The row opens the space; the caret only opens the tree, so its events
+ // stop before they reach the row underneath.
+ event.preventDefault();
+ event.stopPropagation();
+ onToggle();
+ };
+
+ return (
+ // biome-ignore lint/a11y/useSemanticElements: a nested clickable inside the row's own <button>
+ <span
+ role="button"
+ // Out of the tab order on purpose: the search box is the pane's single
+ // focus holder, and a stop per space would bury it.
+ tabIndex={-1}
+ aria-expanded={expanded}
+ aria-label={`${expanded ? "Collapse" : "Expand"} ${spaceName}`}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={toggle}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") toggle(event);
+ }}
+ className={cn(
+ "relative flex size-3.5 shrink-0 items-center justify-center",
+ // Half-lit at rest, open or closed, because a column of carets down the
+ // list would out-draw the names beside it. It brightens for its own
+ // hover only, which is what says it opens the tree rather than the row's
+ // space.
+ //
+ // Forced, and aimed at the glyph's descendants, because quill repaints
+ // a highlighted option's contents (see `ROW_LABEL_TONE`) and that rule's
+ // `*` reaches the icon's `<path>`, which is what `fill: currentColor`
+ // resolves against, so a colour on this span or on the `<svg>` still
+ // leaves the mark drawn in the row's colour.
+ "**:text-muted-foreground/50! hover:**:text-foreground!",
+ // A 24px hit target on a 14px mark, hung off the caret's left so it
+ // reaches the row's edge and stops before the name. Absolute rather than
+ // padding, so the caret keeps its slot and nothing in the row moves.
+ "before:-left-1.5 before:absolute before:inset-auto before:size-6 before:content-['']",
+ "before:-translate-y-1/2 before:top-1/2 before:rounded-[calc(var(--radius)-5px)]",
+ "hover:before:bg-fill-hover",
+ )}
+ >
+ {expanded ? <CaretDownIcon size={10} /> : <CaretRightIcon size={10} />}
+ </span>
+ );
+}
+
+/**
+ * Opening a session from the tree: load it in the main window and leave the
+ * sidebar where it is.
+ *
+ * Picking a session out of the tree is not a request to go into its space — you
+ * are browsing across spaces, and sliding into one would take the tree you are
+ * reading off the screen. Entering a space is what its own row is for.
+ */
+function useOpenSpaceTask(): (spaceId: string, taskId: string) => void {
+ const navigate = useNavigate();
+ const setCurrentChannel = useCurrentChannelStore((s) => s.setCurrentChannel);
+
+ return (spaceId, taskId) => {
+ keepListForNextRoute();
+ // Still scoped: the space is where the session lives, so anything that then
+ // asks for the channel pane opens on the right one.
+ setCurrentChannel(spaceId);
+ void navigate({
+ to: "/website/$channelId/tasks/$taskId",
+ params: { channelId: spaceId, taskId },
+ });
+ };
+}
+
+/**
+ * One session under an expanded space, a leaf of the tree.
+ *
+ * Wears the space's own session list vocabulary: the state dot on the left, the
+ * identity badges on the right, and the hover card and right-click menu that
+ * list gives the same task. The row itself is hand-built rather than
+ * `ChannelItemRow`, which is a `SidebarItem` button and so cannot be an
+ * Autocomplete option, and being one is what keeps ↑/↓/⏎ walking the tree.
+ */
+const SpaceTaskRow = memo(function SpaceTaskRow({
+ item,
+ spaceId,
+ asOption,
+}: {
+ item: ChannelItemModel;
+ spaceId: string;
+ asOption: boolean;
+}) {
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const openTask = useOpenSpaceTask();
+ // No PR lookup here: that is a host round trip per row, and the tree can show
+ // a dozen spaces' worth of rows at once.
+ const status = useChannelTaskStatus(item, { withPrStatus: false });
+ const isActive = pathname.endsWith(`/tasks/${item.id}`);
+ const actions = useSpaceTaskActionsContext();
+ // A boolean rather than the value itself, so a keypress re-renders only the
+ // two rows whose answer changed.
+ const isHighlighted = useSpaceTreeStore(
+ (s) => s.highlightedValue === item.key,
+ );
+
+ // The tree only lists sessions, so this is always the task menu. Rename is
+ // the one item the space's own list has and this doesn't, because it edits in
+ // place and there is no inline editor on a row the keyboard is walking.
+ const menu: TaskRowMenuProps = {
+ kind: "task",
+ id: item.id,
+ title: item.title,
+ isPinned: item.pinned,
+ // Ticks the space the session is already in, inside "File to…".
+ channelId: spaceId,
+ onAddToCommandCenter: actions.commandCenterAssigner(item.id),
+ onTogglePin: () => actions.togglePin(item),
+ onArchive: () => actions.archive(item),
+ };
+
+ const row = (
+ <SpaceRowSurface
+ asOption={asOption}
+ optionValue={item.key}
+ data-selected={isActive || undefined}
+ onClick={() => openTask(spaceId, item.id)}
+ // A step in from its space's name, so the depth reads off that column
+ // without a guide line to draw it.
+ className="pl-6"
+ >
+ {/* The dot belongs to the title, not to the row: its own tighter gap
+ keeps them one mark rather than two columns. */}
+ <span className="flex min-w-0 items-center gap-1.5">
+ <TaskStatusDot dot={taskDot(status ?? {})} />
+ <span
+ className={cn(
+ "truncate text-[13px]",
+ isActive ? "text-foreground" : ROW_LABEL_TONE,
+ )}
+ >
+ {item.title}
+ </span>
+ </span>
+ {status && (
+ <span className="ml-auto flex shrink-0 items-center gap-1">
+ <TaskBadgeStack status={status} pinned={item.pinned} />
+ </span>
+ )}
+ </SpaceRowSurface>
+ );
+
+ return (
+ <TaskRowContextMenu menu={menu}>
+ {/* One tooltip provider per row, shared by its dot and badges so moving
+ between them doesn't re-wait the open delay. */}
+ <TaskStatusTooltips>
+ {/* Not on the row you are already in: ⏎ opens the session and leaves
+ the highlight where it was, so the card would sit over the session
+ it just opened. */}
+ <ChannelItemHoverCard
+ item={item}
+ menu={menu}
+ highlighted={isHighlighted && !isActive}
+ >
+ {row}
+ </ChannelItemHoverCard>
+ </TaskStatusTooltips>
+ </TaskRowContextMenu>
+ );
+});
+
+/** How the keyboard and the row itself name the "View all" leaf. */
+const viewAllValue = (spaceId: string) => `view-all:${spaceId}`;
+
+/**
+ * Whether a space has sessions the tree isn't showing. The list and the
+ * keyboard's flat node list both ask, and they have to agree: a "View all" row
+ * the keyboard doesn't know about throws the highlight index off from there
+ * down.
+ */
+function hasViewAllRow(tasks: SpaceTasks): boolean {
+ return tasks.items.length > 0 && tasks.total > tasks.items.length;
+}
+
+/**
+ * The last leaf under an expanded space: how many sessions the tree isn't
+ * showing, and the way into the space that has them. Quieter than a session row
+ * at rest, because it leads out of the tree rather than being another thing in
+ * it, and it comes up to full contrast under the pointer or the keyboard.
+ */
+function ViewAllRow({
+ spaceId,
+ remaining,
+ asOption,
+ onOpenSpace,
+}: {
+ spaceId: string;
+ remaining: number;
+ asOption: boolean;
+ onOpenSpace: () => void;
+}) {
+ return (
+ <SpaceRowSurface
+ asOption={asOption}
+ optionValue={viewAllValue(spaceId)}
+ onClick={onOpenSpace}
+ className={cn("pl-6.5 text-[13px]", ROW_LABEL_TONE)}
+ >
+ {/* An empty slot the width of a session's status dot, so the label starts
+ in the same column as the titles above it. */}
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span aria-hidden className="size-2 shrink-0" />
+ <span className="truncate">View all</span>
+ </span>
+ <span className="shrink-0 text-muted-foreground/50 text-xxs">
+ {remaining}
+ </span>
+ </SpaceRowSurface>
+ );
+}
+
+/**
+ * The sessions under one expanded space, or the fact that it has none. The
+ * empty line is not an option: ↓ walking onto "No sessions yet" would be a dead
+ * end.
+ */
+function SpaceTaskRows({
+ spaceId,
+ tasks,
+ asOption,
+ onOpenSpace,
+}: {
+ spaceId: string;
+ tasks: SpaceTasks;
+ asOption: boolean;
+ /** Where "View all" goes: the space itself, in the sidebar. */
+ onOpenSpace: () => void;
+}) {
+ if (tasks.items.length === 0) {
+ return (
+ <div className="py-1 pl-12 text-subtle-foreground text-xs">
+ No sessions yet
+ </div>
+ );
+ }
+ return (
+ <>
+ {tasks.items.map((item) => (
+ <SpaceTaskRow
+ key={item.key}
+ item={item}
+ spaceId={spaceId}
+ asOption={asOption}
+ />
+ ))}
+ {hasViewAllRow(tasks) && (
+ <ViewAllRow
+ spaceId={spaceId}
+ remaining={tasks.total - tasks.items.length}
+ asOption={asOption}
+ onOpenSpace={onOpenSpace}
+ />
+ )}
+ </>
+ );
+}
+
// One actionable entry in a channel's menu, rendered the same whether it
// surfaces in the hover "..." dropdown or the right-click context menu.
type ChannelActionItem = {
@@ -386,230 +769,315 @@ function ChannelMenu({
);
}
-// One channel in the list: a "# name" row that opens its sidebar.
-// No expansion — the channel's surfaces live in the in-channel top nav.
-function ChannelSection({
- channel,
- isUnread,
- hotkeySlot,
-}: {
- channel: Channel;
- /** Bolds the name: activity here the viewer hasn't seen. */
- isUnread?: boolean;
- /** ⌘1-9 slot, shown as a hint while the row isn't hovered. */
- hotkeySlot?: number;
-}) {
- const spacesLayout = useChannelsLayout();
- const noun = spacesLayout ? "space" : "channel";
- const pathname = useRouterState({ select: (s) => s.location.pathname });
- const openChannel = useOpenChannel();
- const base = `/website/${channel.id}`;
- // Highlight the row whenever any of the channel's routes is open.
- const isActive = pathname === base || pathname.startsWith(`${base}/`);
- // Lifted so the hover button group stays visible while the menu is open.
- const [menuOpen, setMenuOpen] = useState(false);
- // The "+" dropdown (New task / New canvas). Keeps the hover actions pinned
- // while open.
- const [newMenuOpen, setNewMenuOpen] = useState(false);
- const { reveal, hoverProps, focusProps } = useOverflowTickerReveal();
- const createAndOpenCanvas = useCreateAndOpenDashboard(channel.id);
- // Shared by the "..." dropdown and the right-click context menu so both offer
- // the same star / edit / rename / delete actions.
- const {
- actions,
- renameOpen,
- setRenameOpen,
- confirmDeleteOpen,
- setConfirmDeleteOpen,
- confirmDelete,
- isDeleting,
- } = useChannelActions(channel);
+// One channel in the list: a "# name" row that opens its sidebar, above the
+// space's most recent tasks when it's expanded. The channel's other surfaces
+// live in the in-channel top nav.
+const ChannelSection = memo(
+ function ChannelSection({
+ channel,
+ isUnread,
+ hotkeySlot,
+ expanded = false,
+ tasks,
+ onToggleExpanded,
+ }: {
+ channel: Channel;
+ /** Bolds the name: activity here the viewer hasn't seen. */
+ isUnread?: boolean;
+ /** ⌘1-9 slot, shown as a hint while the row isn't hovered. */
+ hotkeySlot?: number;
+ expanded?: boolean;
+ /** The space's recent sessions and its total; only read while expanded. */
+ tasks?: SpaceTasks;
+ /**
+ * Absent while searching, where the list is flat. Takes the space id rather
+ * than closing over it, so the list can hand every row the same function and
+ * the memo below survives a parent render.
+ */
+ onToggleExpanded?: (spaceId: string) => void;
+ }) {
+ const spacesLayout = useChannelsLayout();
+ const noun = spacesLayout ? "space" : "channel";
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const openChannel = useOpenChannel();
+ const base = `/website/${channel.id}`;
+ // Highlight the row whenever any of the channel's routes is open.
+ const isActive = pathname === base || pathname.startsWith(`${base}/`);
+ // Lifted so the hover button group stays visible while the menu is open.
+ const [menuOpen, setMenuOpen] = useState(false);
+ // The "+" dropdown (New task / New canvas). Keeps the hover actions pinned
+ // while open.
+ const [newMenuOpen, setNewMenuOpen] = useState(false);
+ const { reveal, hoverProps, focusProps } = useOverflowTickerReveal();
+ const prefetchSessions = usePrefetchSpaceTasks();
+ const prefetchTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
+ undefined,
+ );
+ useEffect(() => () => clearTimeout(prefetchTimer.current), []);
+ const createAndOpenCanvas = useCreateAndOpenDashboard(channel.id);
+ // Shared by the "..." dropdown and the right-click context menu so both offer
+ // the same star / edit / rename / delete actions.
+ const {
+ actions,
+ renameOpen,
+ setRenameOpen,
+ confirmDeleteOpen,
+ setConfirmDeleteOpen,
+ confirmDelete,
+ isDeleting,
+ } = useChannelActions(channel);
- return (
- <Box className="group/chan relative" {...hoverProps}>
- {/* A single, non-expandable row: the "# name" opens the channel sidebar.
- Right-clicking opens the same actions as the "..." menu. */}
- <ContextMenu>
- <ContextMenuTrigger
- render={
- <SpaceRowSurface
- asOption={spacesLayout}
- optionValue={channel.id}
- data-selected={isActive || undefined}
- onClick={() => openChannel(channel)}
- {...focusProps}
- className={spacesLayout ? "pl-4" : undefined}
- >
- {channelGlyph(channel.name, {
- size: 14,
- space: spacesLayout,
- weight: isUnread ? "bold" : undefined,
- className: cn(
- "shrink-0",
- isUnread || isActive
- ? "text-foreground"
- : "text-muted-foreground group-hover/button:text-foreground",
- ),
- })}
- <OverflowTickerText
- reveal={reveal}
- className={cn(
- // mr-11 clears the two icon-xs hover buttons pinned at right-1.
- "text-[13px] group-hover/chan:mr-11",
- // Bold is unread's alone; full contrast is shared with the
- // channel you're in. Either way there's no hover brighten
- // left to do, so those rows skip it.
- isUnread ? "font-bold" : "font-medium",
- isUnread || isActive
- ? "text-foreground"
- : "text-muted-foreground group-hover/button:text-foreground",
- menuOpen && "mr-11",
- )}
- >
- {channel.name}
- </OverflowTickerText>
- {/* `!mr-0` undoes quill's `.quill-button kbd { margin-right: -4px }`,
+ const glyph = channelGlyph(channel.name, {
+ size: 14,
+ space: spacesLayout,
+ weight: isUnread ? "bold" : undefined,
+ className: cn(
+ "shrink-0",
+ isUnread || isActive
+ ? "text-foreground"
+ : "text-muted-foreground group-hover/button:text-foreground",
+ ),
+ });
+
+ return (
+ <>
+ <Box
+ className="group/chan relative"
+ {...hoverProps}
+ // Warm the sessions while the pointer is on the row, so opening the
+ // space is a render rather than a round trip.
+ onPointerEnter={() => {
+ hoverProps.onPointerEnter();
+ // Only once the pointer rests. Arrowing through the tree scrolls
+ // rows under a stationary cursor, and prefetching on the enter
+ // itself turned every keypress into a fetch per row it passed.
+ clearTimeout(prefetchTimer.current);
+ prefetchTimer.current = setTimeout(
+ () => prefetchSessions(channel.id),
+ SESSION_PREFETCH_DELAY_MS,
+ );
+ }}
+ onPointerLeave={() => {
+ hoverProps.onPointerLeave();
+ clearTimeout(prefetchTimer.current);
+ }}
+ >
+ {/* The "# name" opens the channel sidebar; the glyph doubles as the
+ caret that opens the space's recent tasks below it. Right-clicking
+ opens the same actions as the "..." menu. */}
+ <ContextMenu>
+ <ContextMenuTrigger
+ render={
+ <SpaceRowSurface
+ asOption={spacesLayout}
+ optionValue={channel.id}
+ // An open space hands the fill to the session under it: the row
+ // you are in is the one the fill is for, and two of them stacked
+ // reads as two selections.
+ data-selected={(isActive && !expanded) || undefined}
+ onClick={() => openChannel(channel)}
+ {...focusProps}
+ className={spacesLayout ? "pl-4" : undefined}
+ >
+ {onToggleExpanded && (
+ <SpaceDisclosure
+ expanded={expanded}
+ spaceName={channel.name}
+ onToggle={() => onToggleExpanded(channel.id)}
+ />
+ )}
+ {glyph}
+ <OverflowTickerText
+ reveal={reveal}
+ className={cn(
+ "text-[13px]",
+ // mr-11 clears the two icon-xs hover buttons pinned at
+ // right-1. With a count beside it, that margin moves to
+ // the count, which is the one nearer the buttons.
+ "group-hover/chan:mr-11",
+ // Bold is unread's alone; full contrast is shared with the
+ // channel you're in. Either way there's no hover brighten
+ // left to do, so those rows skip it.
+ isUnread ? "font-bold" : "font-medium",
+ isUnread || isActive ? "text-foreground" : ROW_LABEL_TONE,
+ menuOpen && "mr-11",
+ )}
+ >
+ {channel.name}
+ </OverflowTickerText>
+ {/* `!mr-0` undoes quill's `.quill-button kbd { margin-right: -4px }`,
which is meant to let a shortcut hang into a button's own
- padding. Here the row's inner span is `truncate` (overflow
- hidden) and `ml-auto` eats every pixel of slack, so the hang
- had nowhere to go and the last 4px of the hint was cut off. */}
- {hotkeySlot != null && (
- <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:opacity-0">
- {formatHotkey(`mod+${hotkeySlot}`)}
- </Kbd>
- )}
- </SpaceRowSurface>
- }
- />
- <ContextMenuContent>
- <ChannelActionItems actions={actions} kind="context" />
- </ContextMenuContent>
- </ContextMenu>
- {/* Hover actions: the "+" dropdown (New task / New canvas) and the
+ padding. Here `ml-auto` takes every pixel of slack, so the
+ hang had nowhere to go and cut off the last 4px of the hint. */}
+ {/* Dropped from the row rather than faded on hover: the label
+ already reserves mr-11 for the buttons that replace the hint,
+ and a hint still taking part in the row's width and its gap
+ there is what cut a starred name shorter than an unstarred
+ one. */}
+ {hotkeySlot != null && (
+ <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:hidden">
+ {formatHotkey(`mod+${hotkeySlot}`)}
+ </Kbd>
+ )}
+ </SpaceRowSurface>
+ }
+ />
+ <ContextMenuContent>
+ <ChannelActionItems actions={actions} kind="context" />
+ </ContextMenuContent>
+ </ContextMenu>
+ {/* Hover actions: the "+" dropdown (New task / New canvas) and the
options menu. Stay visible while either is open. */}
- <div className="absolute top-1 right-1">
- <ButtonGroup>
- <DropdownMenu open={newMenuOpen} onOpenChange={setNewMenuOpen}>
- <Tooltip>
- <TooltipTrigger
- render={
- <DropdownMenuTrigger
+ <div className="absolute top-1 right-1">
+ <ButtonGroup>
+ <DropdownMenu open={newMenuOpen} onOpenChange={setNewMenuOpen}>
+ <Tooltip>
+ <TooltipTrigger
render={
- <Button
- variant="outline"
- size="icon-xs"
- aria-label={`New in ${channel.name}`}
- className={cn(
- "gap-1 transition-opacity group-hover:border-border",
- menuOpen || newMenuOpen
- ? "opacity-100"
- : "opacity-0 group-hover/chan:opacity-100",
- )}
- >
- <PlusIcon size={12} weight="bold" />
- </Button>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon-xs"
+ aria-label={`New in ${channel.name}`}
+ className={cn(
+ "gap-1 transition-opacity group-hover:border-border",
+ menuOpen || newMenuOpen
+ ? "opacity-100"
+ : "opacity-0 group-hover/chan:opacity-100",
+ )}
+ >
+ <PlusIcon size={12} weight="bold" />
+ </Button>
+ }
+ />
}
/>
- }
+ <TooltipContent side="top">New…</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent
+ align="start"
+ side="bottom"
+ sideOffset={4}
+ className="w-auto min-w-fit"
+ >
+ <DropdownMenuItem
+ onClick={() => {
+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
+ action_type: "new_task_open",
+ surface: "sidebar",
+ channel_id: channel.id,
+ });
+ openTaskInput({ channelId: channel.id });
+ }}
+ >
+ <FileTextIcon size={14} />
+ New task
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ // Create + open a canvas with the default template directly;
+ // the canvas's own composer drives what gets built.
+ trackAndCreateCanvas(
+ channel.id,
+ undefined,
+ "sidebar",
+ () => void createAndOpenCanvas(),
+ );
+ }}
+ >
+ <ChartBarIcon size={14} />
+ New canvas
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <ChannelMenu
+ channelName={channel.name}
+ actions={actions}
+ open={menuOpen}
+ onOpenChange={setMenuOpen}
/>
- <TooltipContent side="top">New…</TooltipContent>
- </Tooltip>
- <DropdownMenuContent
- align="start"
- side="bottom"
- sideOffset={4}
- className="w-auto min-w-fit"
- >
- <DropdownMenuItem
- onClick={() => {
- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
- action_type: "new_task_open",
- surface: "sidebar",
- channel_id: channel.id,
- });
- openTaskInput({ channelId: channel.id });
- }}
- >
- <FileTextIcon size={14} />
- New task
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => {
- // Create + open a canvas with the default template directly;
- // the canvas's own composer drives what gets built.
- trackAndCreateCanvas(
- channel.id,
- undefined,
- "sidebar",
- () => void createAndOpenCanvas(),
- );
- }}
- >
- <ChartBarIcon size={14} />
- New canvas
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- <ChannelMenu
- channelName={channel.name}
- actions={actions}
- open={menuOpen}
- onOpenChange={setMenuOpen}
+ </ButtonGroup>
+ </div>
+ {/* One modal for both the dropdown and context-menu "Rename" actions. */}
+ <RenameChannelModal
+ channel={channel}
+ open={renameOpen}
+ onOpenChange={setRenameOpen}
/>
- </ButtonGroup>
- </div>
- {/* One modal for both the dropdown and context-menu "Rename" actions. */}
- <RenameChannelModal
- channel={channel}
- open={renameOpen}
- onOpenChange={setRenameOpen}
- />
- {/* Destructive confirm for "Delete channel" — spells out what's removed. */}
- <ConfirmDialog
- open={confirmDeleteOpen}
- onOpenChange={setConfirmDeleteOpen}
- >
- <AlertDialogContent className="max-w-md">
- <AlertDialogHeader>
- <AlertDialogTitle>Delete {channel.name}?</AlertDialogTitle>
- <AlertDialogDescription>
- This permanently deletes the {noun} and can’t be undone.
- <ul className="list-disc ps-4">
- <li>
- The {noun} and its{" "}
- <span className="font-medium">CONTEXT.md</span> are deleted.
- </li>
- <li>
- Every canvas saved in this {noun} is permanently deleted.
- </li>
- <li>
- Filed tasks are removed from the {noun}, but the tasks
- themselves are not deleted.
- </li>
- </ul>
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogClose
- render={<Button variant="outline">Cancel</Button>}
- />
- <Button
- variant="primary"
- loading={isDeleting}
- onClick={() =>
- void confirmDelete().then((ok) => {
- if (ok) setConfirmDeleteOpen(false);
- })
- }
- >
- Delete {noun}
- </Button>
- </AlertDialogFooter>
- </AlertDialogContent>
- </ConfirmDialog>
- </Box>
- );
-}
+ {/* Destructive confirm for "Delete channel" — spells out what's removed. */}
+ <ConfirmDialog
+ open={confirmDeleteOpen}
+ onOpenChange={setConfirmDeleteOpen}
+ >
+ <AlertDialogContent className="max-w-md">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {channel.name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This permanently deletes the {noun} and can’t be undone.
+ <ul className="list-disc ps-4">
+ <li>
+ The {noun} and its{" "}
+ <span className="font-medium">CONTEXT.md</span> are
+ deleted.
+ </li>
+ <li>
+ Every canvas saved in this {noun} is permanently deleted.
+ </li>
+ <li>
+ Filed tasks are removed from the {noun}, but the tasks
+ themselves are not deleted.
+ </li>
+ </ul>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ render={<Button variant="outline">Cancel</Button>}
+ />
+ <Button
+ variant="primary"
+ loading={isDeleting}
+ onClick={() =>
+ void confirmDelete().then((ok) => {
+ if (ok) setConfirmDeleteOpen(false);
+ })
+ }
+ >
+ Delete {noun}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </ConfirmDialog>
+ </Box>
+ {expanded && (
+ <SpaceTaskRows
+ spaceId={channel.id}
+ tasks={tasks ?? NO_TASKS}
+ asOption={spacesLayout}
+ onOpenSpace={() => openChannel(channel)}
+ />
+ )}
+ </>
+ );
+ },
+ // A space row is expensive — a context menu, two dropdowns, a tooltip and two
+ // dialogs each — and there are dozens of them. Without this, expanding one
+ // space rebuilt every other row: ~350-540ms per expand, in 300ms chunks that
+ // blocked the keyboard. The channel object is compared by the fields the row
+ // actually draws, because the channel list is polled and hands out new objects
+ // on every refetch.
+ (prev, next) =>
+ prev.expanded === next.expanded &&
+ prev.isUnread === next.isUnread &&
+ prev.hotkeySlot === next.hotkeySlot &&
+ prev.tasks === next.tasks &&
+ prev.onToggleExpanded === next.onToggleExpanded &&
+ prev.channel.id === next.channel.id &&
+ prev.channel.name === next.channel.name &&
+ prev.channel.starred === next.channel.starred &&
+ prev.channel.channelType === next.channel.channelType,
+);
// The user's private "#me" channel, pinned above the shared channel list.
// Provisioned lazily server-side when the channel list is fetched, so the row
@@ -680,7 +1148,18 @@ function useOpenChannel(): (channel: Channel) => void {
};
}
-function PersonalChannelRow({ hotkeySlot }: { hotkeySlot?: number }) {
+const PersonalChannelRow = memo(function PersonalChannelRow({
+ hotkeySlot,
+ expanded = false,
+ tasks,
+ onToggleExpanded,
+}: {
+ hotkeySlot?: number;
+ expanded?: boolean;
+ tasks?: SpaceTasks;
+ /** Absent while searching; takes the space id, like the shared rows. */
+ onToggleExpanded?: (spaceId: string) => void;
+}) {
const spacesLayout = useChannelsLayout();
const pathname = useRouterState({ select: (s) => s.location.pathname });
const { channels } = useChannels();
@@ -720,90 +1199,117 @@ function PersonalChannelRow({ hotkeySlot }: { hotkeySlot?: number }) {
);
};
+ // No glyph in the list of spaces: nothing else in that column carries one, and
+ // a lock on this row alone would start its name a glyph's width right of every
+ // other. `channelGlyph` keeps the lock for a private channel whatever the
+ // layout, so dropping it is this row's call. It still appears everywhere the
+ // space is named on its own — the back row, the breadcrumb.
+ const glyph = spacesLayout
+ ? null
+ : channelGlyph(PERSONAL_CHANNEL_NAME, {
+ size: 14,
+ weight: isUnread ? "bold" : undefined,
+ className: cn(
+ "shrink-0",
+ isUnread || isActive
+ ? "text-foreground"
+ : "text-muted-foreground group-hover/button:text-foreground",
+ ),
+ });
+
return (
- <Box className="group/chan relative">
- <SpaceRowSurface
- asOption={spacesLayout}
- // "me" is provisioned server-side with the first list fetch, so before
- // it loads there is no id to identify the option by — its name is
- // unique among spaces either way.
- optionValue={meChannel?.id ?? PERSONAL_CHANNEL_NAME}
- data-selected={isActive || undefined}
- onClick={openPersonalChannel}
- >
- {channelGlyph(PERSONAL_CHANNEL_NAME, {
- size: 14,
- weight: isUnread ? "bold" : undefined,
- className: cn(
- "shrink-0",
- isUnread || isActive
- ? "text-foreground"
- : "text-muted-foreground group-hover/button:text-foreground",
- ),
- })}
- <span
- className={cn(
- "truncate text-[13px]",
- isUnread ? "font-bold" : "font-medium",
- isUnread || isActive
- ? "text-foreground"
- : "text-muted-foreground group-hover/button:text-foreground",
- )}
+ <>
+ <Box className="group/chan relative">
+ <SpaceRowSurface
+ asOption={spacesLayout}
+ // "me" is provisioned server-side with the first list fetch, so before
+ // it loads there is no id to identify the option by — its name is
+ // unique among spaces either way.
+ optionValue={meChannel?.id ?? PERSONAL_CHANNEL_NAME}
+ data-selected={(isActive && !expanded) || undefined}
+ onClick={openPersonalChannel}
+ // "me" is a starred space among the others now, so it takes the same
+ // inset rather than sitting out at the heading's margin.
+ className={spacesLayout ? "pl-4" : undefined}
>
- {PERSONAL_CHANNEL_NAME}
- </span>
- {hotkeySlot != null && (
- <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:opacity-0">
- {formatHotkey(`mod+${hotkeySlot}`)}
- </Kbd>
- )}
- </SpaceRowSurface>
- <div className="absolute top-0 right-1">
- <DropdownMenu open={newMenuOpen} onOpenChange={setNewMenuOpen}>
- <Tooltip>
- <TooltipTrigger
- render={
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="icon-xs"
- aria-label={`New in ${PERSONAL_CHANNEL_NAME}`}
- className={cn(
- "gap-1 transition-opacity group-hover:border-border",
- newMenuOpen
- ? "opacity-100"
- : "opacity-0 group-hover/chan:opacity-100",
- )}
- >
- <PlusIcon size={12} weight="bold" />
- </Button>
- }
- />
- }
+ {onToggleExpanded && meChannel && (
+ <SpaceDisclosure
+ expanded={expanded}
+ spaceName={PERSONAL_CHANNEL_NAME}
+ onToggle={() => onToggleExpanded(meChannel.id)}
/>
- <TooltipContent side="top">New…</TooltipContent>
- </Tooltip>
- <DropdownMenuContent
- align="start"
- side="bottom"
- sideOffset={4}
- className="w-auto min-w-fit"
+ )}
+ {glyph}
+ <span
+ className={cn(
+ "truncate text-[13px]",
+ isUnread ? "font-bold" : "font-medium",
+ isUnread || isActive ? "text-foreground" : ROW_LABEL_TONE,
+ )}
>
- <DropdownMenuItem onClick={newTask}>
- <FileTextIcon size={14} />
- New task
- </DropdownMenuItem>
- <DropdownMenuItem onClick={newCanvas}>
- <ChartBarIcon size={14} />
- New canvas
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Box>
+ {PERSONAL_CHANNEL_NAME}
+ </span>
+ {hotkeySlot != null && (
+ <Kbd className="!mr-0 ml-auto shrink-0 opacity-50 group-hover/chan:opacity-0">
+ {formatHotkey(`mod+${hotkeySlot}`)}
+ </Kbd>
+ )}
+ </SpaceRowSurface>
+ <div className="absolute top-0 right-1">
+ <DropdownMenu open={newMenuOpen} onOpenChange={setNewMenuOpen}>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon-xs"
+ aria-label={`New in ${PERSONAL_CHANNEL_NAME}`}
+ className={cn(
+ "gap-1 transition-opacity group-hover:border-border",
+ newMenuOpen
+ ? "opacity-100"
+ : "opacity-0 group-hover/chan:opacity-100",
+ )}
+ >
+ <PlusIcon size={12} weight="bold" />
+ </Button>
+ }
+ />
+ }
+ />
+ <TooltipContent side="top">New…</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent
+ align="start"
+ side="bottom"
+ sideOffset={4}
+ className="w-auto min-w-fit"
+ >
+ <DropdownMenuItem onClick={newTask}>
+ <FileTextIcon size={14} />
+ New task
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={newCanvas}>
+ <ChartBarIcon size={14} />
+ New canvas
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Box>
+ {expanded && meChannel && (
+ <SpaceTaskRows
+ spaceId={meChannel.id}
+ tasks={tasks ?? NO_TASKS}
+ asOption={spacesLayout}
+ onOpenSpace={openPersonalChannel}
+ />
+ )}
+ </>
);
-}
+});
// Collapse state is keyed per section in the shared sidebar store, so it
// persists across navigation and restarts. Prefixed to stay clear of the Code
@@ -855,7 +1361,7 @@ function ChannelGroup({
onOpenChange={(open) => {
if (open !== isOpen) toggleSection(sectionId);
}}
- className={className}
+ className={cn(className, "mb-2")}
>
{/* MenuLabel carries the sidebar's label styling; `render` keeps it a
real button so the whole row is clickable. */}
@@ -929,29 +1435,100 @@ export function ChannelsList() {
const noMatches =
normalizedQuery !== "" && !meMatches && !searchResults.length;
- // The option values, in the order the rows below render them. The rows are
- // elements rather than a rendered collection, but Autocomplete still needs the
- // list to map a highlight index onto — without it the first ArrowDown after a
- // keystroke is swallowed re-establishing the highlight it already shows.
- // A collapsed group renders no rows, so it contributes none.
+ // The tree's expansion, and the tasks the expanded spaces show. Searching
+ // flattens the list — a query is a request for the space you named, and rows
+ // for tasks you didn't would sit between you and it.
+ const expandedSpaceIds = useSpaceTreeStore((s) => s.expandedSpaceIds);
+ const toggleSpace = useSpaceTreeStore((s) => s.toggleSpace);
+ const expandSpace = useSpaceTreeStore((s) => s.expandSpace);
+ const collapseSpace = useSpaceTreeStore((s) => s.collapseSpace);
+ const setHighlightedValue = useSpaceTreeStore((s) => s.setHighlightedValue);
+ const treeOn = !normalizedQuery;
+ const isExpanded = (spaceId: string | undefined) =>
+ treeOn && spaceId != null && expandedSpaceIds.has(spaceId);
+ // One feed query per open space, and none for the rest. Sorted so the array
+ // only changes when the set of open spaces does.
+ const openSpaceIds = useMemo(
+ () =>
+ treeOn
+ ? allChannels
+ .map((channel) => channel.id)
+ .filter((id) => expandedSpaceIds.has(id))
+ .sort()
+ : [],
+ [allChannels, expandedSpaceIds, treeOn],
+ );
+ const tasksBySpace = useRecentSpaceTasks(openSpaceIds);
+ // Pin / archive / command centre for every session row, built once here
+ // rather than once per row.
+ const spaceTaskActions = useSpaceTaskActions();
+ const tasksOf = (spaceId: string | undefined): SpaceTasks =>
+ (spaceId && tasksBySpace.get(spaceId)) || NO_TASKS;
+
+ // The rows below, in render order, as the flat list the keyboard walks.
+ // Autocomplete needs the values to map a highlight index onto — without it the
+ // first ArrowDown after a keystroke is swallowed re-establishing the highlight
+ // it already shows — and ArrowLeft needs to know which space a task hangs off.
+ // A collapsed group or space renders no rows, so it contributes none.
const collapsedSections = useSidebarStore((s) => s.collapsedSections);
// "me" is provisioned server-side with the first list fetch; before it loads
// it has no id to go by.
const meValue = me?.id ?? PERSONAL_CHANNEL_NAME;
- const optionValues = normalizedQuery
+ const spaceNodes = (
+ value: string,
+ spaceId: string | undefined,
+ ): SpaceTreeNode[] => {
+ const space: SpaceTreeNode = { kind: "space", value, spaceId };
+ if (!isExpanded(spaceId) || !spaceId) return [space];
+ const tasks = tasksOf(spaceId);
+ return [
+ space,
+ ...tasks.items.map(
+ (item): SpaceTreeNode => ({
+ kind: "task",
+ value: item.key,
+ spaceId,
+ parentValue: value,
+ }),
+ ),
+ // "View all" is a leaf like any other, so ⏎ lands on it and ← from it
+ // closes the space the way it does from a session.
+ ...(hasViewAllRow(tasks)
+ ? [
+ {
+ kind: "task" as const,
+ value: viewAllValue(spaceId),
+ spaceId,
+ parentValue: value,
+ },
+ ]
+ : []),
+ ];
+ };
+ const nodes: SpaceTreeNode[] = normalizedQuery
? [
- ...(meMatches ? [meValue] : []),
- ...searchResults.map((channel) => channel.id),
+ ...(meMatches ? spaceNodes(meValue, me?.id) : []),
+ ...searchResults.flatMap((channel) =>
+ spaceNodes(channel.id, channel.id),
+ ),
]
: [
- meValue,
+ // "me" leads the starred section rather than floating above it: it is
+ // the space you always keep, so it belongs with the ones you chose to
+ // keep. Folding the section away takes it with them.
...(collapsedSections.has(STARRED_SECTION_ID)
? []
- : starred.map((channel) => channel.id)),
+ : [
+ ...spaceNodes(meValue, me?.id),
+ ...starred.flatMap((channel) =>
+ spaceNodes(channel.id, channel.id),
+ ),
+ ]),
...(collapsedSections.has(CHANNELS_SECTION_ID)
? []
- : others.map((channel) => channel.id)),
+ : others.flatMap((channel) => spaceNodes(channel.id, channel.id))),
];
+ const optionValues = nodes.map((node) => node.value);
// Coming back from a space, the list is what you came here to browse — so the
// search box takes focus and any previous query is selected, ready to be typed
@@ -965,18 +1542,71 @@ export function ChannelsList() {
previousPane.current = pane;
if (!channelsLayout || pane !== "list" || !cameFromChannel) return;
const input = searchRef.current;
- if (!input) return;
- input.focus();
- // Autocomplete leaves its highlight on the row you opened and exposes no
- // way to move it, so the pane would come back mid-list. Home is the key it
- // listens for; sending it is how the list reopens at the top.
- input.dispatchEvent(
- new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
- );
- // After Home, so the caret it parks at the start doesn't undo the selection.
- input.select();
+ if (input) focusSearch(input);
}, [pane, channelsLayout]);
+ // ⌘⇧S from anywhere in the app ends here. A counter, not a flag: pressing the
+ // key again while the box already has focus has to reach the list again, to
+ // put the highlight back at the top and select the query.
+ const searchFocusRequest = useSpaceTreeStore((s) => s.searchFocusRequest);
+ useEffect(() => {
+ if (!channelsLayout || searchFocusRequest === 0) return;
+ const input = searchRef.current;
+ if (input) focusSearch(input);
+ }, [searchFocusRequest, channelsLayout]);
+
+ // Which row the keyboard is on. A ref rather than state: the arrow handlers
+ // read it during the event, and re-rendering the whole list on every ↑/↓ is
+ // exactly the cost this pane can't afford.
+ const highlightedValue = useRef<string | undefined>(undefined);
+
+ // ArrowRight opens a space (then steps into it); ArrowLeft closes the one
+ // you're in and puts the highlight back on its space. Both defer to the text
+ // caret first — the same box holds the query, so a key that would move the
+ // caret through it belongs to the text.
+ const onTreeKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
+ if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;
+ if (!treeOn) return;
+ const input = event.currentTarget;
+ const { selectionStart, selectionEnd, value } = input;
+ const atStart = selectionStart === 0 && selectionEnd === 0;
+ const atEnd =
+ selectionStart === value.length && selectionEnd === value.length;
+ const node = nodes.find((n) => n.value === highlightedValue.current);
+ if (!node) return;
+
+ if (event.key === "ArrowRight") {
+ if (!atEnd || node.kind !== "space" || !node.spaceId) return;
+ event.preventDefault();
+ if (!expandedSpaceIds.has(node.spaceId)) {
+ expandSpace(node.spaceId);
+ return;
+ }
+ // Already open: the next press walks into it, so ArrowRight then ArrowDown
+ // and ArrowRight twice land in the same place.
+ moveHighlight(input, "ArrowDown", 1);
+ return;
+ }
+
+ if (!atStart) return;
+ if (node.kind === "task") {
+ event.preventDefault();
+ // Move first, while the children are still rendered — the highlight is an
+ // index into the list, so walking up to the parent has to happen before
+ // the rows between here and it stop existing.
+ const steps =
+ optionValues.indexOf(node.value) -
+ optionValues.indexOf(node.parentValue);
+ moveHighlight(input, "ArrowUp", steps);
+ collapseSpace(node.spaceId);
+ return;
+ }
+ if (node.spaceId && expandedSpaceIds.has(node.spaceId)) {
+ event.preventDefault();
+ collapseSpace(node.spaceId);
+ }
+ };
+
const rows = normalizedQuery ? (
<>
{meMatches && <PersonalChannelRow />}
@@ -997,28 +1627,32 @@ export function ChannelsList() {
</>
) : (
<>
- <PersonalChannelRow
- hotkeySlot={channelsLayout && me ? slotFor(me) : undefined}
- />
-
- {starred.length > 0 && (
- <ChannelGroup
- sectionId={STARRED_SECTION_ID}
- label="Starred"
- flat={channelsLayout}
- keepMounted={!channelsLayout}
- icon={<StarIcon size={14} />}
- >
- {starred.map((channel) => (
- <ChannelSection
- key={channel.id}
- channel={channel}
- isUnread={isUnread(channel.id)}
- hotkeySlot={channelsLayout ? slotFor(channel) : undefined}
- />
- ))}
- </ChannelGroup>
- )}
+ {/* Always rendered: "me" lives here, so the section is never empty. */}
+ <ChannelGroup
+ sectionId={STARRED_SECTION_ID}
+ label="Starred"
+ flat={channelsLayout}
+ keepMounted={!channelsLayout}
+ icon={<StarIcon size={14} />}
+ >
+ <PersonalChannelRow
+ hotkeySlot={channelsLayout && me ? slotFor(me) : undefined}
+ expanded={isExpanded(me?.id)}
+ tasks={tasksOf(me?.id)}
+ onToggleExpanded={toggleSpace}
+ />
+ {starred.map((channel) => (
+ <ChannelSection
+ key={channel.id}
+ channel={channel}
+ isUnread={isUnread(channel.id)}
+ hotkeySlot={channelsLayout ? slotFor(channel) : undefined}
+ expanded={isExpanded(channel.id)}
+ tasks={tasksOf(channel.id)}
+ onToggleExpanded={toggleSpace}
+ />
+ ))}
+ </ChannelGroup>
<ChannelGroup
sectionId={CHANNELS_SECTION_ID}
@@ -1041,6 +1675,9 @@ export function ChannelsList() {
key={channel.id}
channel={channel}
isUnread={isUnread(channel.id)}
+ expanded={isExpanded(channel.id)}
+ tasks={tasksOf(channel.id)}
+ onToggleExpanded={toggleSpace}
/>
))}
</ChannelGroup>
@@ -1050,14 +1687,14 @@ export function ChannelsList() {
// Bottom padding clears the floating create button (ChannelsFab), so the last
// channel stays reachable at full scroll.
const scrollClass =
- "scroll-mask-4 min-h-0 flex-1 overflow-y-auto px-2 pt-2 pb-16";
+ "scroll-mask-8 min-h-0 flex-1 overflow-y-auto px-2 pt-2 pb-16";
// quill sizes its list as a popup — a ~250px cap and its own 4px padding —
// and ships it unlayered, so plain utilities lose to it however they're
// ordered. Here the list *is* the pane, so the cap has to go and the pane's
// own padding has to win: `!` is what outranks an unlayered rule.
const listClass = cn(
"flex flex-col gap-px",
- "!max-h-none !px-2 !pt-2 !pb-16",
+ "!max-h-none !px-2 !pt-2 !pb-16 scroll-py-8",
scrollClass,
);
@@ -1072,6 +1709,7 @@ export function ChannelsList() {
showSearchIcon={false}
className="h-7 text-[13px]"
onKeyDown={(event) => {
+ onTreeKeyDown(event);
// Base UI's clear is a tabIndex=-1 decoration, so Escape is the
// keyboard way out of a query. With the box already empty there's
// nothing to clear, and Escape belongs to whoever is listening
@@ -1082,13 +1720,22 @@ export function ChannelsList() {
setQuery("");
}}
>
- {/* Rendered here rather than via `showClear` so it can be given a
- tab stop: quill passes no props to the one it renders itself. */}
- <AutocompleteClear
- tabIndex={0}
- aria-label="Clear search"
- onClick={() => setQuery("")}
- />
+ {/* The key that lands here from anywhere, advertised where it lands.
+ It gives way to the clear button once there's a query — by then
+ you are in the box and clearing is the useful action. */}
+ {query === "" ? (
+ <Kbd className="!mr-0 shrink-0 opacity-50">
+ {formatHotkey(SHORTCUTS.FOCUS_SPACE_SEARCH)}
+ </Kbd>
+ ) : (
+ /* Rendered here rather than via `showClear` so it can be given a
+ tab stop: quill passes no props to the one it renders itself. */
+ <AutocompleteClear
+ tabIndex={0}
+ aria-label="Clear search"
+ onClick={() => setQuery("")}
+ />
+ )}
</AutocompleteInput>
</Box>
)}
@@ -1108,40 +1755,56 @@ export function ChannelsList() {
// One shared provider groups every row tooltip so that once one shows,
// moving to the next row reveals its tooltip instantly (no re-delay).
<TooltipProvider delay={600}>
- {channelsLayout ? (
- // The rows render as elements — they're a tree of collapsible groups,
- // not a flat collection — so `items` carries their values alone, in the
- // same order. Filtering is ours (hence `filter={null}`; Base UI's matcher
- // would run over an already-narrowed set). `inline` renders the list in
- // the pane instead of a popup, and `defaultOpen` keeps it rendered
- // without a trigger to open it.
- <Autocomplete<string>
- inline
- // Pinned open, not `defaultOpen`: picking a row closes an ordinary
- // combobox, and a closed one stops answering the arrow keys. This list
- // is the pane itself — there is nothing to close, and coming back from
- // a space has to find it live.
- open
- items={optionValues}
- filter={null}
- value={query}
- autoHighlight="always"
- // Without this the highlight resets on pointer-leave, and "always"
- // then snaps it back to the first row — so drifting the mouse across
- // the gap between two rows threw the keyboard back to the top.
- keepHighlight
- onValueChange={(value, eventDetails) => {
- // Selecting a row would otherwise write the row's value back into
- // the input; only what the user types moves the query.
- if (eventDetails.reason !== "input-change") return;
- if (typeof value === "string") setQuery(value);
- }}
- >
- {body}
- </Autocomplete>
- ) : (
- body
- )}
+ <SpaceTaskActionsProvider value={spaceTaskActions}>
+ {channelsLayout ? (
+ // The rows render as elements — they're a tree of collapsible groups,
+ // not a flat collection — so `items` carries their values alone, in the
+ // same order. Filtering is ours (hence `filter={null}`; Base UI's matcher
+ // would run over an already-narrowed set). `inline` renders the list in
+ // the pane instead of a popup, and `defaultOpen` keeps it rendered
+ // without a trigger to open it.
+ <Autocomplete<string>
+ inline
+ // Pinned open, not `defaultOpen`: picking a row closes an ordinary
+ // combobox, and a closed one stops answering the arrow keys. This list
+ // is the pane itself — there is nothing to close, and coming back from
+ // a space has to find it live.
+ open
+ items={optionValues}
+ filter={null}
+ value={query}
+ autoHighlight="always"
+ // Without this the highlight resets on pointer-leave, and "always"
+ // then snaps it back to the first row — so drifting the mouse across
+ // the gap between two rows threw the keyboard back to the top.
+ keepHighlight
+ // ArrowRight / ArrowLeft act on the row the keyboard is on, and this
+ // is the only way to know which one that is.
+ onItemHighlighted={(value, eventDetails) => {
+ highlightedValue.current = value;
+ // The store copy is what opens a session's card under the
+ // keyboard; the ref stays because the arrow handlers read the
+ // highlight during the event, before any render has happened.
+ // Only a keyboard highlight is stored: a pointer one is the row's
+ // own hover, and `keepHighlight` keeps it set after the pointer
+ // has left the list, which would strand that card open.
+ setHighlightedValue(
+ eventDetails.reason === "keyboard" ? value : undefined,
+ );
+ }}
+ onValueChange={(value, eventDetails) => {
+ // Selecting a row would otherwise write the row's value back into
+ // the input; only what the user types moves the query.
+ if (eventDetails.reason !== "input-change") return;
+ if (typeof value === "string") setQuery(value);
+ }}
+ >
+ {body}
+ </Autocomplete>
+ ) : (
+ body
+ )}
+ </SpaceTaskActionsProvider>
</TooltipProvider>
);
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
index 3686c28c8ee1..e955687b4c53 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx
@@ -12,6 +12,7 @@ import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannels
import { useCurrentChannel } from "@posthog/ui/features/canvas/hooks/useCurrentChannel";
import { useTrackChannelsSpaceViewed } from "@posthog/ui/features/canvas/hooks/useTrackChannelsSpaceViewed";
import {
+ consumeKeepListForNextRoute,
showChannelList,
showChannelPane,
useChannelPaneStore,
@@ -176,7 +177,9 @@ export function ChannelsSidebar() {
setCurrentChannel(routeChannelId);
// Landing on a channel — a deep link, a mention, ⌘1-9 — is a request to see
// it, so the slider follows the route even if the list was being browsed.
- showChannelPane();
+ // Unless the navigation said otherwise: opening a session from the list's
+ // tree loads it without taking the tree off the screen.
+ if (!consumeKeepListForNextRoute()) showChannelPane();
}, [channelsLayout, routeChannelId, setCurrentChannel]);
// Browsing the list is view state, not navigation: you stay in the channel
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
index f92790e58244..41f577cabb75 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts
@@ -17,12 +17,23 @@ import { useWorkspace } from "@posthog/ui/features/workspace/useWorkspace";
*/
export function useChannelTaskStatus(
item: ChannelItemModel,
+ options?: {
+ /**
+ * Whether to resolve the PR's state. It is a query per row into the host,
+ * where it hits git (and GitHub), so a list that only glances at its rows —
+ * the space tree in the sidebar — leaves it off and shows the rest. The
+ * PR's existence still comes through `prUrl`, which costs nothing.
+ */
+ withPrStatus?: boolean;
+ },
): TaskStatusInput | null {
const task = item.task ?? undefined;
const taskData = useChannelTaskData(task);
const workspace = useWorkspace(task?.id);
const { prState, hasDiff } = useTaskPrStatus({
- id: task?.id ?? "",
+ // An empty id is the hook's own "nothing to look up", so this asks for no
+ // query rather than one it throws away.
+ id: options?.withPrStatus === false ? "" : (task?.id ?? ""),
cloudPrUrl: taskData?.cloudPrUrl ?? null,
taskRunEnvironment: taskData?.taskRunEnvironment ?? null,
});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
new file mode 100644
index 000000000000..f34dc468a65c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
@@ -0,0 +1,191 @@
+import {
+ buildChannelItems,
+ type ChannelItemModel,
+} from "@posthog/core/canvas/channelItems";
+import type { Task } from "@posthog/shared/domain-types";
+import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
+import { useQueries, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useMemo, useRef } from "react";
+import {
+ SPACE_QUERY_GC_TIME_MS,
+ SPACE_QUERY_STALE_TIME_MS,
+} from "./spaceQueryPolicy";
+
+/**
+ * Its own key rather than the channel feed's: the tree asks for a short page,
+ * and handing that truncated list to the space's own feed through a shared
+ * cache would quietly cut it off at the same length.
+ */
+const spaceTreeTasksQueryKey = (spaceId: string) =>
+ ["space-tree-tasks", spaceId] as const;
+
+/** How many sessions a space shows when expanded in the list. */
+export const RECENT_TASKS_PER_SPACE = 5;
+
+/**
+ * A little more than the tree shows, because archived tasks are filtered out
+ * client-side. Nothing like the feed's 500: a dozen open spaces would otherwise
+ * pull thousands of full task records to draw sixty rows.
+ */
+const TREE_FETCH_LIMIT = 20;
+
+/** One page of a space's sessions, with the total the page was cut from. */
+interface SpaceTaskPage {
+ tasks: Task[];
+ count: number;
+}
+
+const NO_PAGE: SpaceTaskPage = { tasks: [], count: 0 };
+
+/** A space's rows: the newest few, and how many sessions it holds in all. */
+export interface SpaceTasks {
+ items: ChannelItemModel[];
+ /** Everything in the space, not just the rows shown. */
+ total: number;
+}
+
+/**
+ * One object for every space with nothing to show, so a collapsed row's props
+ * are identical between renders and its memo holds.
+ */
+export const NO_TASKS: SpaceTasks = { items: [], total: 0 };
+
+/** What a space's rows were built from, so they can be reused unchanged. */
+interface CachedSpaceTasks {
+ page: SpaceTaskPage;
+ archivedTaskIds: ReadonlySet<string>;
+ pinnedTaskIds: ReadonlySet<string>;
+ built: SpaceTasks;
+}
+
+/**
+ * Module-level so `useQueries` can memoize on it: an inline combine is a new
+ * function every render, which makes every render rebuild the lists — and with
+ * them the item models and every row's props.
+ */
+function combineTaskPages(
+ queries: { data?: SpaceTaskPage }[],
+): SpaceTaskPage[] {
+ return queries.map((query) => query.data ?? NO_PAGE);
+}
+
+// Slower than the open channel's own feed (5s): the tree is a glance at what's
+// been happening, not the surface you watch a run on, and every expanded space
+// pays this interval.
+const SPACE_TREE_POLL_INTERVAL_MS = 30_000;
+
+/**
+ * The newest sessions in each of the given spaces, keyed by space id, as the
+ * same item model the space's own session list is built from — so a tree row
+ * can wear the status dot and badges those rows do.
+ *
+ * One query per space, and only for the spaces actually expanded. The flat task
+ * list can't stand in for this: it is capped, and most of its rows carry no
+ * channel at all.
+ */
+export function useRecentSpaceTasks(
+ spaceIds: string[],
+): Map<string, SpaceTasks> {
+ const client = useOptionalAuthenticatedClient();
+ const archivedTaskIds = useArchivedTaskIds();
+ const { pinnedTaskIds } = usePinnedTasks();
+
+ const pagePerSpace = useQueries({
+ queries: spaceIds.map((spaceId) => ({
+ queryKey: spaceTreeTasksQueryKey(spaceId),
+ queryFn: async (): Promise<SpaceTaskPage> => {
+ if (!client) throw new Error("Not authenticated");
+ return (await client.getTasksPage({
+ channel: spaceId,
+ limit: TREE_FETCH_LIMIT,
+ })) as SpaceTaskPage;
+ },
+ enabled: !!client,
+ gcTime: SPACE_QUERY_GC_TIME_MS,
+ meta: AUTH_SCOPED_QUERY_META,
+ refetchInterval: SPACE_TREE_POLL_INTERVAL_MS,
+ staleTime: SPACE_QUERY_STALE_TIME_MS,
+ })),
+ combine: combineTaskPages,
+ });
+
+ // Per-space memo, not one over the whole map: opening another space changes
+ // the id list, and rebuilding every space's items from that would hand each
+ // already-open row a new array — enough to re-render every session row in the
+ // tree on every expand.
+ const cache = useRef(new Map<string, CachedSpaceTasks>());
+
+ return useMemo(() => {
+ const bySpace = new Map<string, SpaceTasks>();
+ spaceIds.forEach((spaceId, index) => {
+ const page = pagePerSpace[index] ?? NO_PAGE;
+ const cached = cache.current.get(spaceId);
+ if (
+ cached &&
+ cached.page === page &&
+ cached.archivedTaskIds === archivedTaskIds &&
+ cached.pinnedTaskIds === pinnedTaskIds
+ ) {
+ bySpace.set(spaceId, cached.built);
+ return;
+ }
+ // Canvases are the space's own list to show; the tree answers "what has
+ // been running here lately".
+ const available = buildChannelItems({
+ dashboards: [],
+ feedTasks: page.tasks,
+ archivedTaskIds,
+ pinnedTaskIds,
+ ownedBy: null,
+ });
+ // A page that came back short is the whole space, so the count is exact
+ // once the archived ones are dropped. A full page falls back to the
+ // server's total, which still counts anything archived in it.
+ const built: SpaceTasks = {
+ items: available.slice(0, RECENT_TASKS_PER_SPACE),
+ total:
+ page.tasks.length < TREE_FETCH_LIMIT ? available.length : page.count,
+ };
+ cache.current.set(spaceId, {
+ page,
+ archivedTaskIds,
+ pinnedTaskIds,
+ built,
+ });
+ bySpace.set(spaceId, built);
+ });
+ return bySpace;
+ }, [spaceIds, pagePerSpace, archivedTaskIds, pinnedTaskIds]);
+}
+
+/**
+ * Warm a space's sessions before it is expanded — from the row's hover, the way
+ * the channel pane's own queries are warmed. A cold expand pays a round trip
+ * (over a second on a slow one); a warm one renders from cache.
+ */
+export function usePrefetchSpaceTasks(): (spaceId: string) => void {
+ const client = useOptionalAuthenticatedClient();
+ const queryClient = useQueryClient();
+
+ return useCallback(
+ (spaceId: string) => {
+ if (!client) return;
+ void queryClient.prefetchQuery({
+ queryKey: spaceTreeTasksQueryKey(spaceId),
+ queryFn: async (): Promise<SpaceTaskPage> =>
+ (await client.getTasksPage({
+ channel: spaceId,
+ limit: TREE_FETCH_LIMIT,
+ })) as SpaceTaskPage,
+ gcTime: SPACE_QUERY_GC_TIME_MS,
+ meta: AUTH_SCOPED_QUERY_META,
+ // Same staleTime as the live query, so a warm cache is a no-op.
+ staleTime: SPACE_QUERY_STALE_TIME_MS,
+ });
+ },
+ [client, queryClient],
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useSpaceTaskActions.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useSpaceTaskActions.ts
new file mode 100644
index 000000000000..01525d30e467
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useSpaceTaskActions.ts
@@ -0,0 +1,85 @@
+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";
+import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
+import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
+import { toast } from "@posthog/ui/primitives/toast";
+import { navigateToCommandCenter } from "@posthog/ui/router/navigationBridge";
+import { createContext, useContext, useEffect, useMemo, useRef } from "react";
+
+/**
+ * What a session row in the space tree can do to its task, from its hover card
+ * and its right-click menu. The same actions the space's own list offers,
+ * without the ones that need the list around them (inline rename) and without
+ * canvases, which the tree doesn't show.
+ */
+export interface SpaceTaskActions {
+ togglePin: (item: ChannelItemModel) => void;
+ archive: (item: ChannelItemModel) => void;
+ /**
+ * The handler for "Add to Command Center", or nothing when every cell is
+ * taken or this task already holds one, which is what greys the item out.
+ */
+ commandCenterAssigner: (taskId: string) => (() => void) | undefined;
+}
+
+/**
+ * Built once for the whole list rather than per row: each of these hooks is a
+ * mutation or a store subscription, and the tree can show dozens of session
+ * rows at once. The object is handed to memoized rows, so its identity has to
+ * survive the list's own re-renders.
+ */
+export function useSpaceTaskActions(): SpaceTaskActions {
+ const { togglePin } = usePinnedTasks();
+ const { archiveTask } = useArchiveTask({ navigateSpace: "website" });
+ const cells = useCommandCenterStore((state) => state.cells);
+ const assignTask = useCommandCenterStore((state) => state.assignTask);
+
+ // `archiveTask` is a new function every render, so it goes through a ref to
+ // keep the object below stable while still calling the current one. The ref
+ // is written after the commit, not during the render, because a render can be
+ // thrown away and a row only reads this from an event handler.
+ const archiveRef = useRef(archiveTask);
+ useEffect(() => {
+ archiveRef.current = archiveTask;
+ });
+
+ return useMemo<SpaceTaskActions>(
+ () => ({
+ togglePin: (item) => {
+ togglePin(item.id).catch(() => {
+ toast.error("Couldn't update pin");
+ });
+ },
+ archive: (item) => {
+ void archiveRef.current({ taskId: item.id });
+ },
+ commandCenterAssigner: (taskId) => {
+ if (cells.includes(taskId)) return undefined;
+ const cellIndex = cells.findIndex((cell) => cell == null);
+ if (cellIndex === -1) return undefined;
+ return () => {
+ assignTask(cellIndex, taskId);
+ navigateToCommandCenter();
+ };
+ },
+ }),
+ [togglePin, cells, assignTask],
+ );
+}
+
+/**
+ * The list hands its rows one actions object through context rather than a
+ * prop, because the rows are memoized on their props and threading it through
+ * the space rows between them would put it in every one of those comparisons.
+ */
+const SpaceTaskActionsContext = createContext<SpaceTaskActions | null>(null);
+
+export const SpaceTaskActionsProvider = SpaceTaskActionsContext.Provider;
+
+export function useSpaceTaskActionsContext(): SpaceTaskActions {
+ const actions = useContext(SpaceTaskActionsContext);
+ if (!actions) {
+ throw new Error("Space task rows must render inside ChannelsList");
+ }
+ return actions;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
index 10257adf58c2..90482b225bc9 100644
--- a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
+++ b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts
@@ -22,12 +22,37 @@ export const useChannelPaneStore = create<ChannelPaneState>()((set) => ({
setPane: (pane) => set({ pane }),
}));
+/**
+ * Set by a navigation that is not a request to enter the space it belongs to —
+ * opening a session from the list's tree. The route effect that otherwise
+ * slides into the space consumes it.
+ *
+ * Deliberately not store state: it decides what a single navigation does, and a
+ * render pass is the wrong lifetime for that. Any explicit pane change below
+ * drops it, so it can't outlive the navigation it was set for.
+ */
+let keepListOnNextRoute = false;
+
+/** Keep the sidebar on the list through the navigation that follows. */
+export function keepListForNextRoute(): void {
+ keepListOnNextRoute = true;
+}
+
+/** Reads the flag and clears it. */
+export function consumeKeepListForNextRoute(): boolean {
+ const keep = keepListOnNextRoute;
+ keepListOnNextRoute = false;
+ return keep;
+}
+
/** Slide back to the channel list, keeping the scoped channel as it is. */
export function showChannelList(): void {
+ keepListOnNextRoute = false;
useChannelPaneStore.getState().setPane("list");
}
/** Slide to the channel pane — every channel entry point goes through here. */
export function showChannelPane(): void {
+ keepListOnNextRoute = false;
useChannelPaneStore.getState().setPane("channel");
}
diff --git a/products/desktop/packages/ui/src/features/canvas/stores/spaceTreeStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/spaceTreeStore.ts
new file mode 100644
index 000000000000..ef26adc2fa49
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/stores/spaceTreeStore.ts
@@ -0,0 +1,89 @@
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+/**
+ * The space list's tree state: which spaces are expanded to show their recent
+ * tasks, plus the request to put the keyboard back in the search box.
+ *
+ * Expansion persists — a space you opened to keep an eye on is still open after
+ * a restart. The focus request is a counter rather than a boolean because it is
+ * an event, not a state: pressing the shortcut twice in a row has to reach the
+ * list twice.
+ */
+interface SpaceTreeState {
+ expandedSpaceIds: Set<string>;
+ searchFocusRequest: number;
+ /**
+ * The row the keyboard is on, so a session row can open its card as the
+ * highlight lands on it. Not persisted. Only the rows read it, each through a
+ * boolean selector, so a keypress re-renders the two rows whose answer
+ * changed instead of the whole list.
+ */
+ highlightedValue: string | undefined;
+ toggleSpace: (spaceId: string) => void;
+ expandSpace: (spaceId: string) => void;
+ collapseSpace: (spaceId: string) => void;
+ requestSearchFocus: () => void;
+ setHighlightedValue: (value: string | undefined) => void;
+}
+
+export const useSpaceTreeStore = create<SpaceTreeState>()(
+ persist(
+ (set) => ({
+ expandedSpaceIds: new Set<string>(),
+ searchFocusRequest: 0,
+ highlightedValue: undefined,
+ toggleSpace: (spaceId) =>
+ set((state) => {
+ const expanded = new Set(state.expandedSpaceIds);
+ if (!expanded.delete(spaceId)) expanded.add(spaceId);
+ return { expandedSpaceIds: expanded };
+ }),
+ expandSpace: (spaceId) =>
+ set((state) => {
+ if (state.expandedSpaceIds.has(spaceId)) return state;
+ return {
+ expandedSpaceIds: new Set(state.expandedSpaceIds).add(spaceId),
+ };
+ }),
+ collapseSpace: (spaceId) =>
+ set((state) => {
+ if (!state.expandedSpaceIds.has(spaceId)) return state;
+ const expanded = new Set(state.expandedSpaceIds);
+ expanded.delete(spaceId);
+ return { expandedSpaceIds: expanded };
+ }),
+ requestSearchFocus: () =>
+ set((state) => ({ searchFocusRequest: state.searchFocusRequest + 1 })),
+ setHighlightedValue: (value) =>
+ set((state) =>
+ state.highlightedValue === value
+ ? state
+ : { highlightedValue: value },
+ ),
+ }),
+ {
+ name: "space-tree-storage",
+ // A Set doesn't survive JSON, so it's stored as an array and rebuilt on
+ // load — the same shape sidebarStore uses for its collapsed sections.
+ partialize: (state) => ({
+ expandedSpaceIds: Array.from(state.expandedSpaceIds),
+ }),
+ merge: (persisted, current) => ({
+ ...current,
+ expandedSpaceIds: new Set(
+ (persisted as { expandedSpaceIds?: string[] })?.expandedSpaceIds ??
+ [],
+ ),
+ }),
+ },
+ ),
+);
+
+/**
+ * Ask the space list to take the keyboard — the ⌘⇧S shortcut's half of the job,
+ * the list itself owns the focus.
+ */
+export function requestSpaceSearchFocus(): void {
+ useSpaceTreeStore.getState().requestSearchFocus();
+}
diff --git a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
index 81d746b5c4ca..0105127deea6 100644
--- a/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
+++ b/products/desktop/packages/ui/src/features/command/keyboard-shortcuts.ts
@@ -25,6 +25,7 @@ export const SHORTCUTS = {
// takes slot 1 instead.
SWITCH_STARRED_CHANNEL:
"mod+1,mod+2,mod+3,mod+4,mod+5,mod+6,mod+7,mod+8,mod+9",
+ FOCUS_SPACE_SEARCH: "mod+shift+s",
TOGGLE_FOCUS: "mod+r",
PASTE_AS_FILE: "mod+shift+v",
INBOX: "mod+i",
@@ -144,6 +145,14 @@ export const KEYBOARD_SHORTCUTS: KeyboardShortcut[] = [
context: "Spaces",
availability: "channels-layout",
},
+ {
+ id: "focus-space-search",
+ keys: SHORTCUTS.FOCUS_SPACE_SEARCH,
+ description: "Search spaces",
+ category: "navigation",
+ context: "Spaces",
+ availability: "channels-layout",
+ },
{
id: "prev-task",
keys: "mod+shift+[",
diff --git a/products/desktop/packages/ui/src/primitives/OverflowTickerText.test.tsx b/products/desktop/packages/ui/src/primitives/OverflowTickerText.test.tsx
index 8740913fd970..314dcf79f960 100644
--- a/products/desktop/packages/ui/src/primitives/OverflowTickerText.test.tsx
+++ b/products/desktop/packages/ui/src/primitives/OverflowTickerText.test.tsx
@@ -68,6 +68,14 @@ describe("OverflowTickerText", () => {
reveal: true,
fades: [FADE_IN, FADE_OUT],
},
+ // A sliver of overflow keeps the resting mask: the text holds still, so
+ // there is no head to fade in.
+ {
+ name: "overflow below the ticking threshold",
+ overflowPx: 8,
+ reveal: true,
+ fades: [FADE_OUT],
+ },
])("masks $name", ({ overflowPx, reveal, fades }) => {
const { tickerContainer } = renderTicker(reveal, overflowPx);
const mask = tickerContainer.style.maskImage ?? "";
diff --git a/products/desktop/packages/ui/src/primitives/OverflowTickerText.tsx b/products/desktop/packages/ui/src/primitives/OverflowTickerText.tsx
index c1f9ad2e983e..51f0ae2a4747 100644
--- a/products/desktop/packages/ui/src/primitives/OverflowTickerText.tsx
+++ b/products/desktop/packages/ui/src/primitives/OverflowTickerText.tsx
@@ -4,6 +4,12 @@ import { useEffect, useRef, useState } from "react";
const TICKER_SPEED_PX_PER_SECOND = 50;
const TICKER_FADE_PX = 24;
+/**
+ * Below this, the text stays put and keeps its tail fade rather than scrolling.
+ * A name that overflows by a character or two costs more to read while it moves
+ * than the last glyphs are worth, and the fade already says there is more.
+ */
+const TICKER_MIN_OVERFLOW_PX = 12;
function tickerMask(overflowPx: number, isTicking: boolean, showsEnd: boolean) {
if (overflowPx === 0) return undefined;
@@ -70,7 +76,7 @@ export function OverflowTickerText({
}, []);
const prefersReducedMotion = useReducedMotion();
- const isTicking = reveal && overflowPx > 0;
+ const isTicking = reveal && overflowPx >= TICKER_MIN_OVERFLOW_PX;
const showsEnd = reachedEnd || (isTicking && prefersReducedMotion === true);
const maskImage = tickerMask(overflowPx, isTicking, showsEnd);