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(desktop): add pinned section and vs code style panes to work sidebar (#105416)

Shy Altere9150f0aaad9
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.stories.tsx
index b3f1f2235f23..8dbe98cda8aa 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.stories.tsx
@@ -1,4 +1,5 @@
import type { Task, TaskChannel } from "@posthog/shared/domain-types";
+import { NavRail } from "@posthog/ui/features/canvas/components/NavRail";
import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";
import type { Meta, StoryObj } from "@storybook/react-vite";
@@ -74,10 +75,6 @@ const CHANNELS: TaskChannel[] = [
channel("web-analytics"),
];
-/**
- * The column reads its rows through authenticated queries that never resolve in
- * Storybook, so seed their caches — a disabled query still serves cached data.
- */
function seededClient({
pinnedTaskIds = [],
tasks = TASKS,
@@ -95,12 +92,10 @@ function seededClient({
return client;
}
-/** The same sessions, with the facts a row draws a badge for. */
const MARKED_TASKS: Task[] = TASKS.map((entry, index) =>
index === 1 ? { ...entry, origin_product: "slack" } : entry,
);
-/** The column at the width the app gives it, against one seeded cache. */
function column(client: QueryClient) {
return function Decorator(Story: () => ReactElement) {
return (
@@ -113,24 +108,47 @@ function column(client: QueryClient) {
};
}
+function app(client: QueryClient) {
+ return function Decorator(Story: () => ReactElement) {
+ return (
+ <QueryClientProvider client={client}>
+ <div className="flex h-screen bg-chrome">
+ <NavRail />
+ <div className="w-[280px] shrink-0">
+ <Story />
+ </div>
+ <div className="flex-1 rounded-tl-sm border-border border-t border-l bg-background" />
+ </div>
+ </QueryClientProvider>
+ );
+ };
+}
+
const meta = {
title: "Canvas/WorkColumn",
component: WorkColumn,
parameters: { layout: "fullscreen" },
- decorators: [column(seededClient())],
} satisfies Meta<typeof WorkColumn>;
export default meta;
type Story = StoryObj<typeof meta>;
-/** Recent capped at five rows, spaces below it. */
-export const Default: Story = {};
+export const Default: Story = {
+ decorators: [column(seededClient())],
+};
+
+export const WithPinned: Story = {
+ decorators: [
+ column(seededClient({ pinnedTaskIds: ["task-2", "task-5", "task-9"] })),
+ ],
+};
+
+export const InTheApp: Story = {
+ decorators: [
+ app(seededClient({ pinnedTaskIds: ["task-2", "task-5", "task-9"] })),
+ ],
+};
-/**
- * The marks a row carries: a pin, and where a session came from. Recent has no
- * pinned run, so a pinned session keeps its place in the list and says so with
- * its badge alone.
- */
export const WithBadges: Story = {
decorators: [
column(seededClient({ pinnedTaskIds: ["task-3"], tasks: MARKED_TASKS })),
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
index eafb9913d153..f8d8b6974a6b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
@@ -1,8 +1,6 @@
import {
- CaretDownIcon,
- CaretRightIcon,
- CaretUpIcon,
ListMagnifyingGlassIcon,
+ MagnifyingGlassIcon,
PlusIcon,
} from "@phosphor-icons/react";
import {
@@ -23,7 +21,6 @@ import {
ContextMenuContent,
ContextMenuTrigger,
cn,
- MenuLabel,
Skeleton,
Tooltip,
TooltipContent,
@@ -46,10 +43,11 @@ import {
import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";
import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";
import { PresenceAvatars } from "@posthog/ui/features/canvas/components/PresenceAvatars";
-import { SidebarSearchInput } from "@posthog/ui/features/canvas/components/SidebarSearchHeader";
import { SpaceActionDialogs } from "@posthog/ui/features/canvas/components/SpaceActionDialogs";
import type { SpacePreviewPayload } from "@posthog/ui/features/canvas/components/SpacePreview";
import { WorkRowSurface } from "@posthog/ui/features/canvas/components/WorkRowSurface";
+import { WorkSearchField } from "@posthog/ui/features/canvas/components/work/WorkSearchField";
+import { WorkSection } from "@posthog/ui/features/canvas/components/work/WorkSection";
import { useBlockedSessionCount } from "@posthog/ui/features/canvas/hooks/useBlockedSessionCount";
import { useChannelItemSelection } from "@posthog/ui/features/canvas/hooks/useChannelItemSelection";
import { useChannelItemActions } from "@posthog/ui/features/canvas/hooks/useChannelItems";
@@ -64,10 +62,16 @@ import {
useSpacePresence,
} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
import { useRecentWorkItems } from "@posthog/ui/features/canvas/hooks/useRecentWorkItems";
-import { useSidebarSearchFocus } from "@posthog/ui/features/canvas/hooks/useSidebarSearchFocus";
import { useIsChannelUnread } from "@posthog/ui/features/canvas/hooks/useUnreadChannels";
import { useUnreadSessionCount } from "@posthog/ui/features/canvas/hooks/useUnreadSessionCount";
+import { useWorkSectionLayout } from "@posthog/ui/features/canvas/hooks/useWorkSectionLayout";
import { useCurrentChannelStore } from "@posthog/ui/features/canvas/stores/currentChannelStore";
+import { useSidebarSearchStore } from "@posthog/ui/features/canvas/stores/sidebarSearchStore";
+import type { WorkSectionId } from "@posthog/ui/features/canvas/workSectionLayout";
+import {
+ formatHotkey,
+ SHORTCUTS,
+} from "@posthog/ui/features/command/keyboard-shortcuts";
import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
import { EditListItemAppearanceDialog } from "@posthog/ui/features/sidebar/components/EditListItemAppearanceDialog";
import { MarqueeOverlay } from "@posthog/ui/features/sidebar/components/MarqueeOverlay";
@@ -90,7 +94,6 @@ import {
Fragment,
type ReactNode,
useCallback,
- useDeferredValue,
useEffect,
useMemo,
useRef,
@@ -99,40 +102,18 @@ import {
const log = logger.scope("work-column");
-const RECENT_COLLAPSED_COUNT = 5;
-
const SESSION_PREFETCH_DELAY_MS = 250;
-// Recent leads with the newest work, so a pin neither floats a row to the top
-// nor opens a section of its own. The row's badge is what says it is pinned.
const NO_PINNED_RUN = { pinnedRun: false } as const;
-function SectionHeading({
- label,
- expanded,
- onToggle,
- trailing,
-}: {
- label: string;
- expanded: boolean;
- onToggle: () => void;
- trailing?: ReactNode;
-}) {
- const Caret = expanded ? CaretDownIcon : CaretRightIcon;
- return (
- <div className="flex items-center gap-1">
- <MenuLabel
- render={<button type="button" />}
- aria-expanded={expanded}
- onClick={onToggle}
- className="flex min-w-0 flex-1 items-center gap-1 rounded-sm py-1 font-semibold text-foreground/70 hover:text-foreground"
- >
- {label}
- <Caret size={11} className="shrink-0 opacity-60" />
- </MenuLabel>
- {trailing}
- </div>
- );
+const SECTIONS: Record<WorkSectionId, { key: string; label: string }> = {
+ pinned: { key: "work-pinned", label: "Pinned" },
+ recent: { key: "work-recent", label: "Recent" },
+ spaces: { key: "work-spaces", label: "Spaces" },
+};
+
+function isPinnedTask(item: ChannelItemModel): boolean {
+ return item.kind === "task" && item.pinned;
}
function IconAction({
@@ -150,7 +131,7 @@ function IconAction({
render={
<Button
variant="default"
- size="icon-sm"
+ size="icon-xs"
aria-label={label}
onClick={onClick}
className="text-muted-foreground"
@@ -291,12 +272,10 @@ export function SpaceRow({
export function WorkColumn() {
const [query, setQuery] = useState("");
- const [recentOpen, setRecentOpen] = useState(true);
+ const [searchOpen, setSearchOpen] = useState(false);
const [appearanceOpen, setAppearanceOpen] = useState(false);
const searchRef = useRef<HTMLInputElement | null>(null);
- useSidebarSearchFocus(searchRef);
- const [recentExpanded, setRecentExpanded] = useState(false);
- const [spacesExpanded, setSpacesExpanded] = useState(true);
+ const columnRef = useRef<HTMLDivElement | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const { items, isLoading } = useRecentWorkItems();
@@ -321,6 +300,14 @@ export function WorkColumn() {
const setSort = useSidebarStore((state) => state.setChannelItemSort);
const grouping = useSidebarStore((state) => state.channelItemGrouping);
const setGrouping = useSidebarStore((state) => state.setChannelItemGrouping);
+ const collapsedSections = useSidebarStore((state) => state.collapsedSections);
+ const toggleSection = useSidebarStore((state) => state.toggleSection);
+ const workSectionHeights = useSidebarStore(
+ (state) => state.workSectionHeights,
+ );
+ const setWorkSectionHeights = useSidebarStore(
+ (state) => state.setWorkSectionHeights,
+ );
const client = useOptionalAuthenticatedClient();
const { data: currentUser } = useCurrentUser({ client });
const meUuid = currentUser?.uuid ?? null;
@@ -330,9 +317,15 @@ export function WorkColumn() {
[items],
);
const dayStart = useLocalDayStart();
+ const pinnedItems = useMemo(
+ () => items.map((entry) => entry.item).filter(isPinnedTask),
+ [items],
+ );
const matchingItems = useMemo(() => {
- const all = items.map((entry) => entry.item);
- const filtered = filterChannelItems(all, { query, filters, me });
+ const unpinned = items
+ .map((entry) => entry.item)
+ .filter((item) => !isPinnedTask(item));
+ const filtered = filterChannelItems(unpinned, { query, filters, me });
return sortChannelItems(filtered, sort, NO_PINNED_RUN);
}, [items, query, filters, me, sort]);
const spaceNameById = useMemo(
@@ -355,7 +348,7 @@ export function WorkColumn() {
},
[channelIdOf, spaceNameById],
);
- const sections = useMemo(
+ const recentSections = useMemo(
() =>
groupChannelItems(
matchingItems,
@@ -367,6 +360,10 @@ export function WorkColumn() {
),
[matchingItems, sort, dayStart, grouping, spaceOf],
);
+ const recentItems = useMemo(
+ () => recentSections.flatMap((section) => section.items),
+ [recentSections],
+ );
const starredSpaces = useMemo(
() => [
...channels.filter((c) => c.channelType === "personal"),
@@ -375,6 +372,47 @@ export function WorkColumn() {
[channels],
);
+ const isOpen = (id: WorkSectionId) =>
+ !collapsedSections.has(SECTIONS[id].key);
+ const pinnedOpen = isOpen("pinned");
+ const recentOpen = isOpen("recent");
+ const spacesOpen = isOpen("spaces");
+ const hasPinned = pinnedItems.length > 0;
+ const layoutSections = useMemo(
+ () => [
+ ...(hasPinned ? [{ id: "pinned" as const, open: pinnedOpen }] : []),
+ { id: "recent" as const, open: recentOpen },
+ { id: "spaces" as const, open: spacesOpen },
+ ],
+ [hasPinned, pinnedOpen, recentOpen, spacesOpen],
+ );
+ const layout = useWorkSectionLayout({
+ sections: layoutSections,
+ preferred: workSectionHeights,
+ onPreferredChange: setWorkSectionHeights,
+ });
+
+ const searchVisible = recentOpen && (searchOpen || query !== "");
+ const openSearch = useCallback(() => {
+ if (!recentOpen) toggleSection(SECTIONS.recent.key);
+ setSearchOpen(true);
+ searchRef.current?.select();
+ }, [recentOpen, toggleSection]);
+ const closeSearch = () => {
+ setQuery("");
+ setSearchOpen(false);
+ };
+
+ useEffect(() => {
+ if (searchVisible) searchRef.current?.focus();
+ }, [searchVisible]);
+
+ const focusRequest = useSidebarSearchStore((state) => state.focusRequest);
+ useEffect(() => {
+ if (focusRequest === 0 || columnRef.current?.closest("[inert]")) return;
+ if (useSidebarSearchStore.getState().claimFocus(focusRequest)) openSearch();
+ }, [focusRequest, openSearch]);
+
const presenceBySpace = useSpacePresence();
const unreadSessionCount = useUnreadSessionCount();
const blockedSessionCount = useBlockedSessionCount();
@@ -398,26 +436,13 @@ export function WorkColumn() {
);
const actions = useChannelItemActions({ channelIdOf, open });
- const showAllRecent = useDeferredValue(recentExpanded || needle !== "");
- const recentRebuilding = showAllRecent !== (recentExpanded || needle !== "");
- const shownSections = useMemo(() => {
- if (showAllRecent) return sections;
- const out: typeof sections = [];
- let left = RECENT_COLLAPSED_COUNT;
- for (const section of sections) {
- if (left <= 0) break;
- out.push({ ...section, items: section.items.slice(0, left) });
- left -= section.items.length;
- }
- return out;
- }, [sections, showAllRecent]);
- const shownItems = useMemo(
- () => shownSections.flatMap((section) => section.items),
- [shownSections],
+ const listItems = useMemo(
+ () => [
+ ...(hasPinned && pinnedOpen ? pinnedItems : []),
+ ...(recentOpen ? recentItems : []),
+ ],
+ [hasPinned, pinnedOpen, pinnedItems, recentOpen, recentItems],
);
- const canExpandRecent =
- needle === "" && matchingItems.length > RECENT_COLLAPSED_COUNT;
- const recentFills = recentOpen && recentExpanded;
const {
selectedTaskIds,
clearSelection,
@@ -426,24 +451,239 @@ export function WorkColumn() {
marquee,
listAnchorRef,
onRowClick,
- } = useChannelItemSelection({ listItems: shownItems, activeKey, open });
+ } = useChannelItemSelection({ listItems, activeKey, open });
const commandCenterCells = useCommandCenterStore((state) => state.cells);
const { renameTask } = useRenameTask();
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
+ const measureArea = layout.measureRefs.area;
+ const sectionsRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ listAnchorRef.current = element;
+ return measureArea(element);
+ },
+ [listAnchorRef, measureArea],
+ );
+
const optionValues = useMemo(
() => [
- ...shownItems
+ ...listItems
.filter((item) => item.id !== editingTaskId)
.map((item) => item.key),
- ...starredSpaces.map((channel) => channel.id),
+ ...(spacesOpen ? starredSpaces.map((channel) => channel.id) : []),
],
- [shownItems, starredSpaces, editingTaskId],
+ [listItems, spacesOpen, starredSpaces, editingTaskId],
);
const spaceNameFor = (item: ChannelItemModel): string | undefined =>
spaceOf(item)?.label;
+ const renderItemRow = (
+ item: ChannelItemModel,
+ { showPinBadge }: { showPinBadge: boolean },
+ ) => {
+ const inSelection =
+ item.kind === "task" && selectedTaskIds.includes(item.id);
+ return (
+ <ChannelItemRow
+ key={item.key}
+ item={item}
+ optionValue={item.key}
+ channelId={channelIdOf(item)}
+ spaceName={spaceNameFor(item)}
+ showPinBadge={showPinBadge}
+ isActive={item.key === activeKey}
+ isSelected={inSelection}
+ actions={actions}
+ onClick={(event) => onRowClick(item, event)}
+ bulk={
+ inSelection && selectedTaskIds.length > 1
+ ? {
+ actions: bulkActions,
+ onArchive: archiveConfirm.requestArchive,
+ }
+ : null
+ }
+ onContextMenuOpenChange={(menuOpen) => {
+ if (menuOpen && !inSelection) clearSelection();
+ }}
+ isEditing={item.kind === "task" && editingTaskId === item.id}
+ onRename={
+ item.kind === "task" ? () => setEditingTaskId(item.id) : undefined
+ }
+ onAddToCommandCenter={
+ isInCommandCenter(item, commandCenterCells)
+ ? undefined
+ : commandCenterAssigner(item)
+ }
+ onEditSubmit={
+ item.kind === "task"
+ ? async (newTitle) => {
+ setEditingTaskId(null);
+ searchRef.current?.focus();
+ try {
+ await renameTask({
+ taskId: item.id,
+ currentTitle: item.title,
+ newTitle,
+ });
+ } catch (error) {
+ log.error("Failed to rename task", error);
+ }
+ }
+ : undefined
+ }
+ onEditCancel={() => {
+ setEditingTaskId(null);
+ searchRef.current?.focus();
+ }}
+ />
+ );
+ };
+
+ const renderRecent = () => {
+ if (isLoading && items.length === 0) {
+ return (
+ <div className="flex flex-col gap-2 px-2 py-1.5">
+ <Skeleton className="h-3.5 w-4/5" />
+ <Skeleton className="h-3.5 w-3/5" />
+ <Skeleton className="h-3.5 w-2/3" />
+ </div>
+ );
+ }
+ if (recentItems.length === 0) {
+ return (
+ <p className="px-2 py-1 text-[12px] text-muted-foreground">
+ {needle || hasActiveChannelItemFilters(filters)
+ ? "Nothing here matches."
+ : "Sessions and canvases you open show up here."}
+ </p>
+ );
+ }
+ return recentSections.map((section, index) => (
+ <Fragment key={section.key}>
+ {section.label && (
+ <div
+ className={cn(
+ "px-2 pb-1 font-medium text-[11px] text-muted-foreground",
+ index === 0 ? "pt-1" : "mt-2 border-border/70 border-t pt-2",
+ )}
+ >
+ {section.label}
+ </div>
+ )}
+ {section.items.map((item) =>
+ renderItemRow(item, { showPinBadge: true }),
+ )}
+ </Fragment>
+ ));
+ };
+
+ const spacesBody = (
+ <>
+ {starredSpaces.map((channel) => (
+ <SpaceRow
+ key={channel.id}
+ channel={channel}
+ isActive={channel.id === activeChannelId}
+ unread={isChannelUnread(channel.id)}
+ unreadSessions={unreadSessionCount(channel.id)}
+ blockedSessions={blockedSessionCount(channel.id)}
+ presence={presenceBySpace.get(channel.id)}
+ />
+ ))}
+ {starredSpaces.length <= 1 && needle === "" && (
+ <button
+ type="button"
+ className="mt-1 flex items-center gap-1.5 rounded-md border border-border border-dashed px-2 py-1.5 text-left font-medium text-[12px] text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"
+ onClick={navigateToSpaces}
+ >
+ <PlusIcon size={13} aria-hidden />
+ Add the spaces you work in
+ </button>
+ )}
+ </>
+ );
+
+ const filterMenu = (
+ <ChannelFilterMenu
+ filters={filters}
+ onFilterChange={(key, value) => setFilters({ ...filters, [key]: value })}
+ onClearFilters={() => setFilters(DEFAULT_CHANNEL_ITEM_FILTERS)}
+ sort={sort}
+ onSortChange={setSort}
+ grouping={grouping}
+ onGroupingChange={setGrouping}
+ onEditAppearance={() => setAppearanceOpen(true)}
+ sources={sources}
+ showCreatedBy
+ showRunFilters
+ showKindFilter
+ groupings={["date", "space", "repository"]}
+ active={hasActiveChannelItemFilters(filters)}
+ />
+ );
+
+ const sectionContent: Record<
+ WorkSectionId,
+ {
+ count: number;
+ actions?: ReactNode;
+ replaceHeading?: ReactNode;
+ body: ReactNode;
+ }
+ > = {
+ pinned: {
+ count: pinnedItems.length,
+ body: pinnedItems.map((item) =>
+ renderItemRow(item, { showPinBadge: false }),
+ ),
+ },
+ recent: {
+ count: recentItems.length,
+ actions: (
+ <>
+ {!searchVisible && (
+ <IconAction
+ label={`Search recent (${formatHotkey(SHORTCUTS.FOCUS_SIDEBAR_SEARCH)})`}
+ onClick={openSearch}
+ >
+ <MagnifyingGlassIcon size={14} />
+ </IconAction>
+ )}
+ {filterMenu}
+ </>
+ ),
+ replaceHeading: searchVisible ? (
+ <WorkSearchField
+ ref={searchRef}
+ query={query}
+ matchCount={recentItems.length}
+ onClear={() => {
+ setQuery("");
+ searchRef.current?.focus();
+ }}
+ onClose={closeSearch}
+ />
+ ) : undefined,
+ body: renderRecent(),
+ },
+ spaces: {
+ count: starredSpaces.length,
+ actions: (
+ <>
+ <IconAction label="New space…" onClick={() => setCreateOpen(true)}>
+ <PlusIcon size={14} />
+ </IconAction>
+ <IconAction label="Browse spaces" onClick={navigateToSpaces}>
+ <ListMagnifyingGlassIcon size={14} />
+ </IconAction>
+ </>
+ ),
+ body: spacesBody,
+ },
+ };
+
return (
<Autocomplete<string>
inline
@@ -460,239 +700,44 @@ export function WorkColumn() {
}
}}
>
- <div className="flex h-full min-h-0 flex-col">
+ <div ref={columnRef} className="flex h-full min-h-0 flex-col">
<ChromeBar>
<h2 className="font-bold text-base">Work</h2>
</ChromeBar>
<AutocompleteList className="sidebar-autocomplete-tree !max-h-none !px-2 !pt-2 !pb-2 flex min-h-0 flex-1 flex-col overflow-hidden">
- {/* The expanded list keeps a share of the column instead of all of it,
- so the spaces below it stay on screen. */}
- {/* Positioned and non-scrolling, because the marquee measures its band
- against this box and reads the rows inside it. */}
<div
- ref={listAnchorRef}
- className={cn(
- "relative flex min-h-0 flex-col",
- recentFills && "flex-[3]",
- )}
+ ref={sectionsRef}
+ className="relative flex min-h-0 flex-1 flex-col overflow-hidden"
>
- <SectionHeading
- label="Recent"
- expanded={recentOpen}
- onToggle={() => setRecentOpen((value) => !value)}
- />
- {recentOpen && (
- <div className="flex items-center gap-1 px-1 pt-0.5 pb-1.5">
- <SidebarSearchInput
- ref={searchRef}
- query={query}
- placeholder="Search recent…"
- searchLabel="Search recent"
- onClear={() => setQuery("")}
- className="min-w-0 flex-1"
- />
- <ChannelFilterMenu
- filters={filters}
- onFilterChange={(key, value) =>
- setFilters({ ...filters, [key]: value })
+ {layoutSections.map((section, index) => {
+ const content = sectionContent[section.id];
+ const previous = index > 0 ? layoutSections[index - 1] : null;
+ const resizable = previous?.open && section.open;
+ return (
+ <WorkSection
+ key={section.id}
+ label={SECTIONS[section.id].label}
+ open={section.open}
+ count={content.count}
+ onToggle={() => toggleSection(SECTIONS[section.id].key)}
+ actions={content.actions}
+ replaceHeading={content.replaceHeading}
+ height={layout.heights[section.id]}
+ animate={layout.measured && layout.dragging === null}
+ divider={index > 0}
+ resizer={
+ resizable && previous
+ ? layout.resizer(previous.id, section.id)
+ : undefined
}
- onClearFilters={() =>
- setFilters(DEFAULT_CHANNEL_ITEM_FILTERS)
- }
- sort={sort}
- onSortChange={setSort}
- grouping={grouping}
- onGroupingChange={setGrouping}
- onEditAppearance={() => setAppearanceOpen(true)}
- sources={sources}
- showCreatedBy
- showRunFilters
- showKindFilter
- groupings={["date", "space", "repository"]}
- active={hasActiveChannelItemFilters(filters)}
- />
- </div>
- )}
- <div className="scroll-mask-8 flex min-h-0 flex-1 scroll-py-8 flex-col gap-px overflow-y-auto">
- {recentOpen &&
- (isLoading && items.length === 0 ? (
- <div className="flex flex-col gap-2 px-2 py-1.5">
- <Skeleton className="h-3.5 w-4/5" />
- <Skeleton className="h-3.5 w-3/5" />
- <Skeleton className="h-3.5 w-2/3" />
- </div>
- ) : shownItems.length === 0 ? (
- <p className="px-2 py-1 text-[12px] text-muted-foreground">
- {needle || hasActiveChannelItemFilters(filters)
- ? "Nothing here matches."
- : "Sessions and canvases you open show up here."}
- </p>
- ) : (
- <div
- className={cn(
- "flex flex-col gap-px transition-opacity duration-150",
- recentRebuilding && "pointer-events-none opacity-50",
- )}
- >
- {shownSections.map((section, index) => (
- <Fragment key={section.key}>
- {section.label && (
- <div
- className={cn(
- "px-2 pb-1 font-medium text-[11px] text-muted-foreground",
- index === 0
- ? "pt-1"
- : "mt-2 border-border/70 border-t pt-2",
- )}
- >
- {section.label}
- </div>
- )}
- {section.items.map((item) => {
- const inSelection =
- item.kind === "task" &&
- selectedTaskIds.includes(item.id);
- return (
- <ChannelItemRow
- key={item.key}
- item={item}
- optionValue={item.key}
- channelId={channelIdOf(item)}
- spaceName={spaceNameFor(item)}
- isActive={item.key === activeKey}
- isSelected={inSelection}
- actions={actions}
- onClick={(event) => onRowClick(item, event)}
- bulk={
- inSelection && selectedTaskIds.length > 1
- ? {
- actions: bulkActions,
- onArchive: archiveConfirm.requestArchive,
- }
- : null
- }
- onContextMenuOpenChange={(open) => {
- if (open && !inSelection) clearSelection();
- }}
- isEditing={
- item.kind === "task" &&
- editingTaskId === item.id
- }
- onRename={
- item.kind === "task"
- ? () => setEditingTaskId(item.id)
- : undefined
- }
- onAddToCommandCenter={
- isInCommandCenter(item, commandCenterCells)
- ? undefined
- : commandCenterAssigner(item)
- }
- onEditSubmit={
- item.kind === "task"
- ? async (newTitle) => {
- setEditingTaskId(null);
- searchRef.current?.focus();
- try {
- await renameTask({
- taskId: item.id,
- currentTitle: item.title,
- newTitle,
- });
- } catch (error) {
- log.error(
- "Failed to rename task",
- error,
- );
- }
- }
- : undefined
- }
- onEditCancel={() => {
- setEditingTaskId(null);
- searchRef.current?.focus();
- }}
- />
- );
- })}
- </Fragment>
- ))}
- </div>
- ))}
- </div>
+ resizing={layout.dragging === section.id}
+ contentRef={layout.measureRefs[section.id]}
+ >
+ {content.body}
+ </WorkSection>
+ );
+ })}
<MarqueeOverlay rect={marquee} />
- {recentOpen && canExpandRecent && (
- <button
- type="button"
- aria-expanded={recentExpanded}
- className="group/expand mt-0.5 flex h-6 w-full shrink-0 items-center justify-center gap-1 rounded-md text-[11px] text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground"
- onClick={() => setRecentExpanded((value) => !value)}
- >
- {recentExpanded ? (
- <>
- <CaretUpIcon size={11} weight="bold" />
- Show fewer
- </>
- ) : (
- <>
- <CaretDownIcon size={11} weight="bold" />
- {matchingItems.length - shownItems.length} more
- </>
- )}
- </button>
- )}
- </div>
-
- <div
- className={cn(
- "mt-2 flex min-h-0 flex-col",
- recentFills ? "flex-[2]" : "flex-1",
- )}
- >
- <SectionHeading
- label="Spaces"
- expanded={spacesExpanded}
- onToggle={() => setSpacesExpanded((value) => !value)}
- trailing={
- <div className="flex items-center">
- <IconAction
- label="New space…"
- onClick={() => setCreateOpen(true)}
- >
- <PlusIcon size={14} />
- </IconAction>
-
- <IconAction label="Browse spaces…" onClick={navigateToSpaces}>
- <ListMagnifyingGlassIcon size={14} />
- </IconAction>
- </div>
- }
- />
- {spacesExpanded && (
- <div className="scroll-mask-8 flex min-h-0 flex-1 scroll-py-8 flex-col gap-px overflow-y-auto">
- {starredSpaces.map((channel) => (
- <SpaceRow
- key={channel.id}
- channel={channel}
- isActive={channel.id === activeChannelId}
- unread={isChannelUnread(channel.id)}
- unreadSessions={unreadSessionCount(channel.id)}
- blockedSessions={blockedSessionCount(channel.id)}
- presence={presenceBySpace.get(channel.id)}
- />
- ))}
- {starredSpaces.length <= 1 && needle === "" && (
- <button
- type="button"
- className="mt-1 flex items-center gap-1.5 rounded-md border border-border border-dashed px-2 py-1.5 text-left font-medium text-[12px] text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"
- onClick={navigateToSpaces}
- >
- <PlusIcon size={13} aria-hidden />
- Add the spaces you work in
- </button>
- )}
- </div>
- )}
</div>
</AutocompleteList>
<SidebarBulkActionBar
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkSearchField.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkSearchField.tsx
new file mode 100644
index 000000000000..acd2ef4fecea
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkSearchField.tsx
@@ -0,0 +1,53 @@
+import { XIcon } from "@phosphor-icons/react";
+import { AutocompleteInput, InputGroupButton } from "@posthog/quill";
+import type { Ref } from "react";
+
+export function WorkSearchField({
+ ref,
+ query,
+ matchCount,
+ onClear,
+ onClose,
+}: {
+ ref: Ref<HTMLInputElement>;
+ query: string;
+ matchCount: number;
+ onClear: () => void;
+ onClose: () => void;
+}) {
+ const hasQuery = query !== "";
+ return (
+ <div className="min-w-0 flex-1">
+ <AutocompleteInput
+ ref={ref}
+ placeholder="Search recent…"
+ aria-label="Search recent"
+ className="h-6 text-[13px]"
+ onKeyDown={(event) => {
+ if (event.defaultPrevented || event.key !== "Escape") return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (hasQuery) onClear();
+ else onClose();
+ }}
+ onBlur={() => {
+ if (!hasQuery) onClose();
+ }}
+ >
+ {hasQuery && (
+ <span className="shrink-0 text-[11px] text-muted-foreground tabular-nums">
+ {matchCount === 0 ? "No results" : matchCount}
+ </span>
+ )}
+ <InputGroupButton
+ size="icon-xs"
+ aria-label={hasQuery ? "Clear search" : "Close search"}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={hasQuery ? onClear : onClose}
+ >
+ <XIcon size={12} />
+ </InputGroupButton>
+ </AutocompleteInput>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkSection.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkSection.tsx
new file mode 100644
index 000000000000..26ad48adfaa8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkSection.tsx
@@ -0,0 +1,120 @@
+import { CaretDownIcon, CaretRightIcon } from "@phosphor-icons/react";
+import { cn, MenuLabel } from "@posthog/quill";
+import type { WorkSectionResizer } from "@posthog/ui/features/canvas/hooks/useWorkSectionLayout";
+import type { ReactNode, RefCallback } from "react";
+
+function WorkSectionResizeHandle({
+ label,
+ active,
+ resizer,
+}: {
+ label: string;
+ active: boolean;
+ resizer: WorkSectionResizer;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={`Resize ${label}`}
+ title="Drag to resize. Double-click to reset."
+ onPointerDown={resizer.onPointerDown}
+ onPointerMove={resizer.onPointerMove}
+ onPointerUp={resizer.onPointerUp}
+ onPointerCancel={resizer.onPointerUp}
+ onKeyDown={resizer.onKeyDown}
+ onDoubleClick={resizer.onDoubleClick}
+ className="group/resize -top-1 absolute inset-x-0 z-10 flex h-2 cursor-row-resize items-center outline-none"
+ >
+ <span
+ className={cn(
+ "h-0.5 w-full rounded-full bg-primary opacity-0 transition-opacity group-hover/resize:opacity-100 group-focus-visible/resize:opacity-100",
+ active && "opacity-100",
+ )}
+ />
+ </button>
+ );
+}
+
+export function WorkSection({
+ label,
+ open,
+ count,
+ onToggle,
+ actions,
+ replaceHeading,
+ height,
+ animate,
+ divider,
+ resizer,
+ resizing = false,
+ contentRef,
+ children,
+}: {
+ label: string;
+ open: boolean;
+ count: number;
+ onToggle: () => void;
+ actions?: ReactNode;
+ replaceHeading?: ReactNode;
+ height: number;
+ animate: boolean;
+ divider: boolean;
+ resizer?: WorkSectionResizer;
+ resizing?: boolean;
+ contentRef: RefCallback<HTMLElement>;
+ children: ReactNode;
+}) {
+ const Caret = open ? CaretDownIcon : CaretRightIcon;
+ return (
+ <section aria-label={label} className="flex shrink-0 flex-col">
+ <div
+ className={cn(
+ "relative flex h-7 shrink-0 items-center gap-1",
+ divider && "border-border border-t",
+ )}
+ >
+ {resizer && (
+ <WorkSectionResizeHandle
+ label={label}
+ active={resizing}
+ resizer={resizer}
+ />
+ )}
+ {replaceHeading ?? (
+ <MenuLabel
+ render={<button type="button" />}
+ aria-expanded={open}
+ onClick={onToggle}
+ className="flex min-w-0 flex-1 items-center gap-1 rounded-sm py-1 font-semibold text-foreground/70 hover:text-foreground"
+ >
+ {label}
+ <Caret size={11} className="shrink-0 opacity-60" />
+ {!open && count > 0 && (
+ <span className="ml-0.5 font-normal text-muted-foreground tabular-nums">
+ {count}
+ </span>
+ )}
+ </MenuLabel>
+ )}
+ {open && actions && (
+ <div className="flex shrink-0 items-center">{actions}</div>
+ )}
+ </div>
+ <div
+ style={{ height: open ? height : 0 }}
+ className={cn(
+ "min-h-0 overflow-hidden",
+ animate && "transition-[height] duration-200 ease-out",
+ )}
+ >
+ {open && (
+ <div className="scroll-mask-8 h-full scroll-py-8 overflow-y-auto">
+ <div ref={contentRef} className="flex flex-col gap-px pb-1">
+ {children}
+ </div>
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
index ddc200db7a8d..0643b8a09b94 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
@@ -57,7 +57,10 @@ export function selectRecentWorkItems({
sessionFacts,
})
.sort((a, b) => b.ts - a.ts)
- .slice(0, RECENT_WORK_CAP)
+ .filter(
+ (item, index) =>
+ index < RECENT_WORK_CAP || (item.kind === "task" && item.pinned),
+ )
.map((item) => ({
item,
channelId: item.task?.channel ?? canvasChannelId.get(item.id),
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useWorkSectionLayout.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useWorkSectionLayout.ts
new file mode 100644
index 000000000000..8ee88755f329
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useWorkSectionLayout.ts
@@ -0,0 +1,169 @@
+import {
+ layoutWorkSections,
+ type PreferredWorkSectionHeights,
+ resizeWorkSections,
+ WORK_SECTION_HEADER_HEIGHT,
+ type WorkSectionHeights,
+ type WorkSectionId,
+} from "@posthog/ui/features/canvas/workSectionLayout";
+import {
+ type KeyboardEvent,
+ type PointerEvent,
+ type RefCallback,
+ useMemo,
+ useState,
+} from "react";
+
+const KEYBOARD_STEP = 16;
+
+type MeasuredKey = WorkSectionId | "area";
+
+export interface WorkSectionResizer {
+ onPointerDown: (event: PointerEvent<HTMLElement>) => void;
+ onPointerMove: (event: PointerEvent<HTMLElement>) => void;
+ onPointerUp: (event: PointerEvent<HTMLElement>) => void;
+ onKeyDown: (event: KeyboardEvent<HTMLElement>) => void;
+ onDoubleClick: () => void;
+}
+
+interface Drag {
+ lower: WorkSectionId;
+ startY: number;
+ start: WorkSectionHeights;
+ preferred: PreferredWorkSectionHeights;
+}
+
+function useMeasuredHeights(): {
+ measuredHeights: Partial<Record<MeasuredKey, number>>;
+ measureRefs: Record<MeasuredKey, RefCallback<HTMLElement>>;
+} {
+ const [measuredHeights, setMeasuredHeights] = useState<
+ Partial<Record<MeasuredKey, number>>
+ >({});
+ const measureRefs = useMemo(() => {
+ const elements = new Map<MeasuredKey, HTMLElement>();
+ const measure = () =>
+ setMeasuredHeights((previous) => {
+ const next = { ...previous };
+ for (const [key, element] of elements) {
+ next[key] =
+ key === "area" ? element.clientHeight : element.offsetHeight;
+ }
+ return Object.entries(next).every(
+ ([key, value]) => previous[key as MeasuredKey] === value,
+ )
+ ? previous
+ : next;
+ });
+ const observer = new ResizeObserver(measure);
+ const ref =
+ (key: MeasuredKey): RefCallback<HTMLElement> =>
+ (element) => {
+ if (!element) return;
+ elements.set(key, element);
+ observer.observe(element);
+ measure();
+ return () => {
+ observer.unobserve(element);
+ elements.delete(key);
+ };
+ };
+ return {
+ area: ref("area"),
+ pinned: ref("pinned"),
+ recent: ref("recent"),
+ spaces: ref("spaces"),
+ };
+ }, []);
+ return { measuredHeights, measureRefs };
+}
+
+export function useWorkSectionLayout({
+ sections,
+ preferred,
+ onPreferredChange,
+}: {
+ sections: readonly { id: WorkSectionId; open: boolean }[];
+ preferred: PreferredWorkSectionHeights;
+ onPreferredChange: (heights: PreferredWorkSectionHeights) => void;
+}): {
+ measureRefs: Record<MeasuredKey, RefCallback<HTMLElement>>;
+ heights: WorkSectionHeights;
+ measured: boolean;
+ dragging: WorkSectionId | null;
+ resizer: (upper: WorkSectionId, lower: WorkSectionId) => WorkSectionResizer;
+} {
+ const { measuredHeights, measureRefs } = useMeasuredHeights();
+ const [drag, setDrag] = useState<Drag | null>(null);
+
+ const areaHeight = measuredHeights.area ?? 0;
+ const inputs = sections.map((section) => ({
+ ...section,
+ contentHeight: measuredHeights[section.id] ?? 0,
+ }));
+ const heights = layoutWorkSections(
+ inputs,
+ areaHeight - WORK_SECTION_HEADER_HEIGHT * sections.length,
+ drag?.preferred ?? preferred,
+ );
+ const measured =
+ areaHeight > 0 &&
+ sections.every(
+ (section) => !section.open || measuredHeights[section.id] !== undefined,
+ );
+
+ const resizer = (
+ upper: WorkSectionId,
+ lower: WorkSectionId,
+ ): WorkSectionResizer => {
+ const resize = (delta: number, base: WorkSectionHeights) =>
+ resizeWorkSections({
+ sections: inputs,
+ heights: base,
+ upper,
+ lower,
+ delta,
+ preferred,
+ });
+ const active = drag?.lower === lower ? drag : null;
+ return {
+ onPointerDown: (event) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ setDrag({ lower, startY: event.clientY, start: heights, preferred });
+ },
+ onPointerMove: (event) => {
+ if (!active) return;
+ setDrag({
+ ...active,
+ preferred: resize(event.clientY - active.startY, active.start),
+ });
+ },
+ onPointerUp: (event) => {
+ if (!active) return;
+ onPreferredChange(resize(event.clientY - active.startY, active.start));
+ setDrag(null);
+ },
+ onKeyDown: (event) => {
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
+ event.preventDefault();
+ onPreferredChange(
+ resize(
+ event.key === "ArrowUp" ? -KEYBOARD_STEP : KEYBOARD_STEP,
+ heights,
+ ),
+ );
+ },
+ onDoubleClick: () => onPreferredChange({}),
+ };
+ };
+
+ return {
+ measureRefs,
+ heights,
+ measured,
+ dragging: drag?.lower ?? null,
+ resizer,
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/workSectionLayout.test.ts b/products/desktop/packages/ui/src/features/canvas/workSectionLayout.test.ts
new file mode 100644
index 000000000000..7ce1fcd9d10b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/workSectionLayout.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from "vitest";
+import {
+ layoutWorkSections,
+ resizeWorkSections,
+ type WorkSectionInput,
+} from "./workSectionLayout";
+
+function sections(
+ pinned: [boolean, number],
+ recent: [boolean, number],
+ spaces: [boolean, number],
+): WorkSectionInput[] {
+ return [
+ { id: "pinned", open: pinned[0], contentHeight: pinned[1] },
+ { id: "recent", open: recent[0], contentHeight: recent[1] },
+ { id: "spaces", open: spaces[0], contentHeight: spaces[1] },
+ ];
+}
+
+describe("layoutWorkSections", () => {
+ it.each([
+ {
+ name: "recent fills what pinned and spaces leave",
+ input: sections([true, 90], [true, 1400], [true, 290]),
+ expected: { pinned: 90, recent: 270, spaces: 240 },
+ },
+ {
+ name: "spaces fills when recent is folded",
+ input: sections([true, 90], [false, 1400], [true, 900]),
+ expected: { pinned: 90, recent: 0, spaces: 510 },
+ },
+ {
+ name: "pinned keeps its own height when it is the only open section",
+ input: sections([true, 90], [false, 1400], [false, 290]),
+ expected: { pinned: 90, recent: 0, spaces: 0 },
+ },
+ {
+ name: "a short recent still fills the column",
+ input: sections([true, 90], [true, 120], [true, 150]),
+ expected: { pinned: 90, recent: 360, spaces: 150 },
+ },
+ {
+ name: "a short recent fills the column when spaces is folded",
+ input: sections([true, 90], [true, 120], [false, 290]),
+ expected: { pinned: 90, recent: 510, spaces: 0 },
+ },
+ {
+ name: "spaces keeps its own height when recent is folded",
+ input: sections([true, 90], [false, 1400], [true, 150]),
+ expected: { pinned: 90, recent: 0, spaces: 150 },
+ },
+ {
+ name: "nothing is open",
+ input: sections([false, 90], [false, 1400], [false, 290]),
+ expected: { pinned: 0, recent: 0, spaces: 0 },
+ },
+ ])("$name", ({ input, expected }) => {
+ expect(layoutWorkSections(input, 600)).toEqual(expected);
+ });
+
+ it("keeps a height the user dragged to", () => {
+ const input = sections([true, 400], [true, 1400], [true, 290]);
+
+ expect(layoutWorkSections(input, 600, { pinned: 300 })).toEqual({
+ pinned: 300,
+ recent: 60,
+ spaces: 240,
+ });
+ });
+
+ it("shrinks the other sections so the filling one keeps a usable height", () => {
+ const input = sections([true, 400], [true, 1400], [true, 400]);
+
+ const heights = layoutWorkSections(input, 200, {
+ pinned: 150,
+ spaces: 150,
+ });
+
+ expect(heights.recent).toBeGreaterThanOrEqual(56);
+ expect(
+ heights.pinned + heights.recent + heights.spaces,
+ ).toBeLessThanOrEqual(200);
+ });
+});
+
+describe("resizeWorkSections", () => {
+ const input = sections([true, 300], [true, 1400], [true, 290]);
+ const heights = layoutWorkSections(input, 600);
+
+ it.each([
+ {
+ name: "drags the line under pinned down",
+ upper: "pinned" as const,
+ lower: "recent" as const,
+ delta: 50,
+ expected: { pinned: heights.pinned + 50 },
+ },
+ {
+ name: "stops pinned at the height of its items",
+ upper: "pinned" as const,
+ lower: "recent" as const,
+ delta: 500,
+ expected: { pinned: 300 },
+ },
+ {
+ name: "drags the line above spaces up",
+ upper: "recent" as const,
+ lower: "spaces" as const,
+ delta: -30,
+ expected: { spaces: heights.spaces + 30 },
+ },
+ {
+ name: "stops spaces at the smallest height a drag allows",
+ upper: "recent" as const,
+ lower: "spaces" as const,
+ delta: 500,
+ expected: { spaces: 40 },
+ },
+ ])("$name", ({ upper, lower, delta, expected }) => {
+ expect(
+ resizeWorkSections({
+ sections: input,
+ heights,
+ upper,
+ lower,
+ delta,
+ preferred: {},
+ }),
+ ).toEqual(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/workSectionLayout.ts b/products/desktop/packages/ui/src/features/canvas/workSectionLayout.ts
new file mode 100644
index 000000000000..070d76106584
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/workSectionLayout.ts
@@ -0,0 +1,119 @@
+export type WorkSectionId = "pinned" | "recent" | "spaces";
+
+export type WorkSectionHeights = Record<WorkSectionId, number>;
+
+export type PreferredWorkSectionHeights = Partial<
+ Record<WorkSectionId, number>
+>;
+
+export interface WorkSectionInput {
+ id: WorkSectionId;
+ open: boolean;
+ contentHeight: number;
+}
+
+const FILL_ORDER: readonly WorkSectionId[] = ["recent", "spaces", "pinned"];
+
+export const WORK_SECTION_HEADER_HEIGHT = 28;
+const SHARE_CAP = 0.4;
+const MIN_FILL_HEIGHT = 56;
+const MIN_DRAG_HEIGHT = 40;
+const STRETCHING_SECTION: WorkSectionId = "recent";
+
+function fillingWorkSection(
+ sections: readonly WorkSectionInput[],
+): WorkSectionId | null {
+ return (
+ FILL_ORDER.find((id) =>
+ sections.some((section) => section.id === id && section.open),
+ ) ?? null
+ );
+}
+
+export function layoutWorkSections(
+ sections: readonly WorkSectionInput[],
+ available: number,
+ preferred: PreferredWorkSectionHeights = {},
+): WorkSectionHeights {
+ const heights: WorkSectionHeights = { pinned: 0, recent: 0, spaces: 0 };
+ const fill = fillingWorkSection(sections);
+ if (fill === null || available <= 0) return heights;
+
+ const open = sections.filter((section) => section.open);
+ const fillSection = open.find((section) => section.id === fill);
+ if (!fillSection) return heights;
+ const others = open.filter((section) => section.id !== fill);
+ const share = Math.round(available * SHARE_CAP);
+
+ let used = 0;
+ for (const section of others) {
+ const wanted = preferred[section.id] ?? share;
+ heights[section.id] = Math.floor(
+ Math.max(0, Math.min(section.contentHeight, wanted)),
+ );
+ used += heights[section.id];
+ }
+
+ const fillFloor = Math.min(fillSection.contentHeight, MIN_FILL_HEIGHT);
+ if (available - used < fillFloor && used > 0) {
+ const scale = Math.max(0, available - fillFloor) / used;
+ used = 0;
+ for (const section of others) {
+ heights[section.id] = Math.floor(heights[section.id] * scale);
+ used += heights[section.id];
+ }
+ }
+
+ const rest = Math.max(0, available - used);
+ heights[fill] = Math.floor(
+ fill === STRETCHING_SECTION
+ ? rest
+ : Math.min(fillSection.contentHeight, rest),
+ );
+
+ let leftover = available - used - heights[fill];
+ for (const id of FILL_ORDER) {
+ if (leftover <= 0) break;
+ const section = others.find((candidate) => candidate.id === id);
+ if (!section || preferred[id] !== undefined) continue;
+ const grow = Math.min(leftover, section.contentHeight - heights[id]);
+ if (grow <= 0) continue;
+ heights[id] += Math.floor(grow);
+ leftover -= Math.floor(grow);
+ }
+
+ return heights;
+}
+
+export function resizeWorkSections({
+ sections,
+ heights,
+ upper,
+ lower,
+ delta,
+ preferred,
+}: {
+ sections: readonly WorkSectionInput[];
+ heights: WorkSectionHeights;
+ upper: WorkSectionId;
+ lower: WorkSectionId;
+ delta: number;
+ preferred: PreferredWorkSectionHeights;
+}): PreferredWorkSectionHeights {
+ const contentOf = (id: WorkSectionId): number =>
+ sections.find((section) => section.id === id)?.contentHeight ?? 0;
+ const shrinkable = (id: WorkSectionId): number =>
+ Math.max(0, heights[id] - MIN_DRAG_HEIGHT);
+ const growable = (id: WorkSectionId): number =>
+ id === STRETCHING_SECTION
+ ? Number.POSITIVE_INFINITY
+ : Math.max(0, contentOf(id) - heights[id]);
+ const min = -Math.min(shrinkable(upper), growable(lower));
+ const max = Math.min(growable(upper), shrinkable(lower));
+ const applied = Math.max(min, Math.min(max, delta));
+ const fill = fillingWorkSection(sections);
+ const next = { ...preferred };
+ if (upper !== fill) next[upper] = heights[upper] + applied;
+ if (lower !== fill) next[lower] = heights[lower] - applied;
+ return next;
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
index ebb9e83c8052..11ffca493f77 100644
--- a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
@@ -8,6 +8,7 @@ import {
} from "@posthog/core/canvas/channelItems";
import { ALL_WORKSPACE_MODES } from "@posthog/core/sidebar/buildSidebarData";
import type { WorkspaceMode } from "@posthog/shared";
+import type { PreferredWorkSectionHeights } from "@posthog/ui/features/canvas/workSectionLayout";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { SIDEBAR_MIN_WIDTH } from "./constants";
@@ -35,6 +36,7 @@ interface SidebarStoreState {
channelItemFilters: ChannelItemFilters;
channelItemSort: ChannelItemSort;
channelItemGrouping: ChannelItemGrouping;
+ workSectionHeights: PreferredWorkSectionHeights;
// Reveals the Channels feature in the unified sidebar (channel tree replaces
// the task list, Canvas nav item appears). Off by default — Code merged into
// the Bluebird chrome ships with channels hidden until the user opts in.
@@ -62,6 +64,7 @@ interface SidebarStoreActions {
setChannelItemFilters: (filters: ChannelItemFilters) => void;
setChannelItemSort: (sort: ChannelItemSort) => void;
setChannelItemGrouping: (grouping: ChannelItemGrouping) => void;
+ setWorkSectionHeights: (heights: PreferredWorkSectionHeights) => void;
setChannelsEnabled: (channelsEnabled: boolean) => void;
}
@@ -86,6 +89,7 @@ export const useSidebarStore = create<SidebarStore>()(
channelItemFilters: DEFAULT_CHANNEL_ITEM_FILTERS,
channelItemSort: DEFAULT_CHANNEL_ITEM_SORT,
channelItemGrouping: DEFAULT_CHANNEL_ITEM_GROUPING,
+ workSectionHeights: {},
channelsEnabled: false,
setOpen: (open) => set({ open, hasUserSetOpen: true }),
setOpenAuto: (open) =>
@@ -151,6 +155,8 @@ export const useSidebarStore = create<SidebarStore>()(
setChannelItemSort: (channelItemSort) => set({ channelItemSort }),
setChannelItemGrouping: (channelItemGrouping) =>
set({ channelItemGrouping }),
+ setWorkSectionHeights: (workSectionHeights) =>
+ set({ workSectionHeights }),
}),
{
name: "sidebar-storage",
@@ -170,6 +176,7 @@ export const useSidebarStore = create<SidebarStore>()(
channelItemFilters: state.channelItemFilters,
channelItemSort: state.channelItemSort,
channelItemGrouping: state.channelItemGrouping,
+ workSectionHeights: state.workSectionHeights,
channelsEnabled: state.channelsEnabled,
}),
merge: (persisted, current) => {
@@ -189,6 +196,7 @@ export const useSidebarStore = create<SidebarStore>()(
channelItemFilters?: Partial<ChannelItemFilters>;
channelItemSort?: ChannelItemSort;
channelItemGrouping?: ChannelItemGrouping;
+ workSectionHeights?: PreferredWorkSectionHeights;
channelsEnabled?: boolean;
};
return {
@@ -223,6 +231,8 @@ export const useSidebarStore = create<SidebarStore>()(
persistedState.channelItemSort ?? current.channelItemSort,
channelItemGrouping:
persistedState.channelItemGrouping ?? current.channelItemGrouping,
+ workSectionHeights:
+ persistedState.workSectionHeights ?? current.workSectionHeights,
channelsEnabled:
persistedState.channelsEnabled ?? current.channelsEnabled,
};