: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): virtualize the canvas sidebar (#98933)
Charles Vienef5165ac4f1c
diff --git a/products/desktop/docs/CANVAS_SIDEBAR.md b/products/desktop/docs/CANVAS_SIDEBAR.mdnew file mode 100644index 000000000000..fb19d492053d--- /dev/null+++ b/products/desktop/docs/CANVAS_SIDEBAR.md@@ -0,0 +1,11 @@+# Canvas sidebar++Canvas lists above 40 entries mount the visible rows and four rows of overscan on each side.+Group headers keep their positions in the virtual list, and keyboard indexes follow the displayed group order.+The highlighted option stays mounted when scrolling so Enter can still open it.+Each mounted row states its position in the whole list, because a screen reader can only count what is mounted.+Search and filter changes return the list to the top.++The `Canvases/CanvasList` stories provide small and 1,000-canvas fixtures.+The keyboard story checks Home, End, Enter, filtering, and clearing a search across the virtualization threshold.+Compare mounted option counts and search-clear long tasks at both narrow and wide pane widths.diff --git a/products/desktop/packages/ui/src/features/canvas/components/CanvasList.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/CanvasList.stories.tsxnew file mode 100644index 000000000000..6d326087f970--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/CanvasList.stories.tsx@@ -0,0 +1,103 @@+import {+ CanvasListService,+ DEFAULT_CANVAS_LIST_SETTINGS,+} from "@posthog/core/canvas/canvasListService";+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { type ReactElement, useMemo, useState } from "react";+import { expect, waitFor } from "storybook/test";+import { CanvasList } from "./CanvasList";++const service = new CanvasListService();+const canvases: DashboardRecord[] = Array.from({ length: 1000 }, (_, i) => ({+ id: `canvas-${i}`,+ channelId: "example-space",+ name: `Canvas ${String(i + 1).padStart(4, "0")}`,+ kind: "freeform",+ description: "",+ templateId: "freeform",+ createdBy: "Example author",+ createdAt: new Date(2026, 0, 1).getTime() - i * 1000,+ updatedAt: new Date(2026, 0, 1).getTime() - i * 1000,+}));+function Harness({ count }: { count: number }): ReactElement {+ const [query, setQuery] = useState("");+ const [selectedId, setSelectedId] = useState<string>();+ const [openedName, setOpenedName] = useState<string>();+ const viewModel = useMemo(+ () =>+ service.buildViewModel({+ canvases: canvases.slice(0, count),+ spaces: [],+ settings: DEFAULT_CANVAS_LIST_SETTINGS,+ query,+ lastViewedAtByCanvasId: {},+ now: new Date(2026, 0, 1, 12),+ }),+ [count, query],+ );+ return (+ <div className="flex h-[600px] w-full flex-col">+ <CanvasList+ className="min-h-0 flex-1"+ viewModel={viewModel}+ query={query}+ setQuery={setQuery}+ lastViewedAtByCanvasId={{}}+ selectedId={selectedId}+ open={(canvas) => {+ setSelectedId(canvas.id);+ setOpenedName(canvas.name);+ }}+ />+ <output className="border-t p-2 text-xs">+ {openedName ? `Opened ${openedName}` : "Nothing opened"}+ </output>+ </div>+ );+}+const meta = {+ title: "Canvases/CanvasList",+ component: Harness,+ args: { count: 1000 },+} satisfies Meta<typeof Harness>;+export default meta;+type Story = StoryObj<typeof meta>;+export const Large: Story = {};+export const Small: Story = { args: { count: 3 } };++export const KeyboardNavigation: Story = {+ play: async ({ canvas, userEvent }): Promise<void> => {+ const input = canvas.getByRole("combobox");+ await canvas.findByRole("option", { name: /Canvas 0001/ });+ await expect(canvas.getAllByRole("option").length).toBeLessThan(40);+ await expect(+ canvas.getByRole("option", { name: /Canvas 0001/ }),+ ).toHaveAttribute("aria-setsize", "1000");+ await userEvent.click(input);+ await userEvent.keyboard("{End}");+ const last = await canvas.findByRole("option", { name: /Canvas 1000/ });+ await waitFor(() =>+ expect(input).toHaveAttribute("aria-activedescendant", last.id),+ );+ await userEvent.keyboard("{Enter}");+ await canvas.findByText("Opened Canvas 1000");+ await userEvent.click(input);+ await userEvent.keyboard("{Home}");+ const first = await canvas.findByRole("option", { name: /Canvas 0001/ });+ await waitFor(() =>+ expect(input).toHaveAttribute("aria-activedescendant", first.id),+ );+ await userEvent.keyboard("{Enter}");+ await canvas.findByText("Opened Canvas 0001");+ await userEvent.type(input, "Canvas 0500");+ await canvas.findByRole("option", { name: /Canvas 0500/ });+ await expect(canvas.getAllByRole("option")).toHaveLength(1);+ await userEvent.keyboard("{ArrowDown}{Enter}");+ await canvas.findByText("Opened Canvas 0500");+ await userEvent.click(input);+ await userEvent.keyboard("{Escape}");+ await canvas.findByRole("option", { name: /Canvas 0001/ });+ await expect(canvas.getAllByRole("option").length).toBeLessThan(40);+ },+};diff --git a/products/desktop/packages/ui/src/features/canvas/components/CanvasList.tsx b/products/desktop/packages/ui/src/features/canvas/components/CanvasList.tsxnew file mode 100644index 000000000000..ec187bcf1c16--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/CanvasList.tsx@@ -0,0 +1,239 @@+import { BlueprintIcon } from "@phosphor-icons/react";+import type { CanvasListViewModel } from "@posthog/core/canvas/canvasListService";+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";+import {+ Autocomplete,+ AutocompleteItem,+ AutocompleteList,+ cn,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ MenuLabel,+} from "@posthog/quill";+import { formatAbsoluteDateTime, formatRelativeAge } from "@posthog/shared";+import { LoadingState } from "@posthog/ui/primitives/LoadingState";+import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";+import {+ type ReactElement,+ type ReactNode,+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { iconForTemplate } from "./canvasTemplateIcon";+import { SidebarSearchHeader } from "./SidebarSearchHeader";++interface CanvasListProps {+ viewModel: CanvasListViewModel;+ lastViewedAtByCanvasId: Readonly<Record<string, number>>;+ selectedId?: string;+ query: string;+ setQuery: (query: string) => void;+ open: (canvas: DashboardRecord) => void;+ isLoading?: boolean;+ actions?: ReactNode;+ className?: string;+}++type CanvasRow =+ | { key: string; label: string; canvas?: never; optionIndex?: never }+ | {+ key: string;+ canvas: DashboardRecord;+ optionIndex: number;+ label?: never;+ };++export function CanvasList({+ viewModel,+ lastViewedAtByCanvasId,+ selectedId,+ query,+ setQuery,+ open,+ isLoading,+ actions,+ className,+}: CanvasListProps): ReactElement {+ const viewportRef = useRef<HTMLDivElement>(null);+ const [highlightedId, setHighlightedId] = useState<string>();+ const { rows, optionValues, rowIndexById } = useMemo(() => {+ const rows: CanvasRow[] = [];+ const optionValues: string[] = [];+ const rowIndexById = new Map<string, number>();+ for (const section of viewModel.sections) {+ if (section.label)+ rows.push({ key: `heading:${section.key}`, label: section.label });+ for (const canvas of section.canvases) {+ rowIndexById.set(canvas.id, rows.length);+ rows.push({ key: canvas.id, canvas, optionIndex: optionValues.length });+ optionValues.push(canvas.id);+ }+ }+ return { rows, optionValues, rowIndexById };+ }, [viewModel.sections]);+ const virtualized = optionValues.length > 40 && !isLoading;+ const highlightedIndex =+ highlightedId === undefined ? undefined : rowIndexById.get(highlightedId);+ const virtualizer = useVirtualizer({+ count: rows.length,+ enabled: virtualized,+ getScrollElement: () => viewportRef.current,+ estimateSize: (index) => (rows[index].canvas ? 46 : 26),+ getItemKey: useCallback((index: number) => rows[index].key, [rows]),+ gap: 1,+ measureElement: (element) => element.getBoundingClientRect().height,+ overscan: 4,+ rangeExtractor: useCallback(+ (range: Parameters<typeof defaultRangeExtractor>[0]) => {+ const indexes = defaultRangeExtractor(range);+ // Keep the keyboard target mounted if the pointer scrolls it out of view.+ if (+ highlightedIndex !== undefined &&+ !indexes.includes(highlightedIndex)+ ) {+ indexes.push(highlightedIndex);+ indexes.sort((a, b) => a - b);+ }+ return indexes;+ },+ [highlightedIndex],+ ),+ });+ // The view model gets a new identity on every canvas refetch, so the reset+ // keys on the inputs that actually reorder the list.+ const filterKey = JSON.stringify([query, viewModel.settings]);+ // biome-ignore lint/correctness/useExhaustiveDependencies: filterKey is the trigger, not a body dependency+ useLayoutEffect(() => {+ if (virtualized) virtualizer.scrollToOffset(0);+ else if (viewportRef.current) viewportRef.current.scrollTop = 0;+ }, [filterKey, virtualized, virtualizer]);+ const renderRow = (row: CanvasRow): ReactElement => {+ if (!row.canvas) return <MenuLabel>{row.label}</MenuLabel>;+ const canvas = row.canvas;+ const lastViewedAt = lastViewedAtByCanvasId[canvas.id];+ const lastViewedLabel = lastViewedAt+ ? `Last viewed ${formatRelativeAge(lastViewedAt)}`+ : "Not viewed yet";+ const lastViewedTitle = lastViewedAt+ ? `Last viewed ${formatAbsoluteDateTime(lastViewedAt)}`+ : lastViewedLabel;+ return (+ <AutocompleteItem+ value={canvas.id}+ index={virtualized ? row.optionIndex : undefined}+ // Only the mounted rows reach the accessibility tree, so screen readers+ // need the position within the whole list stated outright.+ aria-posinset={virtualized ? row.optionIndex + 1 : undefined}+ aria-setsize={virtualized ? optionValues.length : undefined}+ nativeButton+ className={cn(+ "h-auto w-full items-start py-1.5 text-left ring-offset-0 data-highlighted:border-transparent data-highlighted:bg-fill-hover data-highlighted:ring-0 [&>span]:w-full [&>span]:items-start [&>span]:gap-2",+ canvas.id === selectedId && "bg-fill-selected",+ )}+ onClick={() => open(canvas)}+ >+ {iconForTemplate(canvas.templateId, { size: 14 })}+ <span className="min-w-0">+ <span className="block truncate text-[13px]">{canvas.name}</span>+ <span+ className="block truncate text-muted-foreground text-xxs"+ title={lastViewedTitle}+ >+ {canvas.createdBy ?? "Unknown"} · {lastViewedLabel}+ </span>+ </span>+ </AutocompleteItem>+ );+ };+ return (+ <Autocomplete<string>+ inline+ open+ value={query}+ items={optionValues}+ filter={null}+ virtualized={virtualized}+ onItemHighlighted={(value, details) => {+ setHighlightedId(value);+ const index = value === undefined ? undefined : rowIndexById.get(value);+ if (+ virtualized &&+ index !== undefined &&+ details.reason === "keyboard"+ ) {+ virtualizer.scrollToIndex(index, { align: "auto" });+ }+ }}+ onValueChange={(value, eventDetails) => {+ if (+ eventDetails.reason === "input-change" &&+ typeof value === "string"+ ) {+ setQuery(value);+ }+ }}+ >+ <div className={cn("flex min-h-0 flex-col", className)}>+ <SidebarSearchHeader+ title="Canvases"+ query={query}+ placeholder="Search canvases…"+ searchLabel="Search canvases"+ onClear={() => setQuery("")}+ actions={actions}+ />+ <AutocompleteList+ ref={viewportRef}+ className="sidebar-autocomplete-tree scroll-mask-8 !max-h-none !p-1.5 min-h-0 flex-1 overflow-y-auto"+ >+ {isLoading ? (+ <LoadingState className="py-10" />+ ) : viewModel.canvases.length === 0 ? (+ <Empty className="border-0 py-8">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <BlueprintIcon />+ </EmptyMedia>+ <EmptyTitle>No canvases match</EmptyTitle>+ <EmptyDescription>+ Try another search or filter.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : virtualized ? (+ <div+ className="relative w-full"+ style={{ height: virtualizer.getTotalSize() }}+ >+ {virtualizer.getVirtualItems().map((item) => (+ <div+ key={item.key}+ ref={virtualizer.measureElement}+ data-index={item.index}+ className="absolute top-0 left-0 flex w-full flex-col"+ style={{ transform: `translateY(${item.start}px)` }}+ >+ {renderRow(rows[item.index])}+ </div>+ ))}+ </div>+ ) : (+ <div className="flex flex-col gap-px">+ {rows.map((row) => (+ <div className="flex flex-col" key={row.key}>+ {renderRow(row)}+ </div>+ ))}+ </div>+ )}+ </AutocompleteList>+ </div>+ </Autocomplete>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/CanvasesPane.tsx b/products/desktop/packages/ui/src/features/canvas/components/CanvasesPane.tsxindex 9edc3e5e2ffe..b73d69f88e6e 100644--- a/products/desktop/packages/ui/src/features/canvas/components/CanvasesPane.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/CanvasesPane.tsx@@ -1,4 +1,3 @@-import { BlueprintIcon } from "@phosphor-icons/react";import {type CanvasListService,type CanvasListSettings,@@ -7,40 +6,19 @@ import {import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";import { CANVAS_LIST_SERVICE } from "@posthog/core/canvas/identifiers";import { useService } from "@posthog/di/react";-import {- Autocomplete,- AutocompleteItem,- AutocompleteList,- cn,- Empty,- EmptyDescription,- EmptyHeader,- EmptyMedia,- EmptyTitle,- MenuLabel,-} from "@posthog/quill";-import { formatAbsoluteDateTime, formatRelativeAge } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";import { CanvasFilterMenu } from "@posthog/ui/features/canvas/components/CanvasFilterMenu";import { buildCanvasSpaceOptions } from "@posthog/ui/features/canvas/components/canvasSpaceOptions";-import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";-import { SidebarSearchHeader } from "@posthog/ui/features/canvas/components/SidebarSearchHeader";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useAllCanvases } from "@posthog/ui/features/canvas/hooks/useDashboards";import { useSelectedCanvasId } from "@posthog/ui/features/canvas/hooks/useSelectedCanvasId";import { useCanvasViewedStore } from "@posthog/ui/features/canvas/stores/canvasViewedStore";import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";-import { LoadingState } from "@posthog/ui/primitives/LoadingState";import { track } from "@posthog/ui/shell/analytics";import { useNavigate } from "@tanstack/react-router";-import {- Fragment,- type ReactElement,- useEffect,- useMemo,- useState,-} from "react";+import { type ReactElement, useEffect, useMemo, useState } from "react";+import { CanvasList } from "./CanvasList";export function CanvasesPane({className,@@ -105,7 +83,6 @@ export function CanvasesPane({settings,],);- const optionValues = viewModel.canvases.map((canvas) => canvas.id);const changeSettings = (nextSettings: CanvasListSettings): void => {const update = canvasListService.updateSettings({canvases: dashboards,@@ -132,101 +109,24 @@ export function CanvasesPane({void navigate({ to: "/canvases", search: { canvas: canvas.id } });};return (- <Autocomplete<string>- inline- open- value={query}- items={optionValues}- filter={null}- onValueChange={(value, eventDetails) => {- if (- eventDetails.reason === "input-change" &&- typeof value === "string"- ) {- setQuery(value);- }- }}- >- <div className={cn("flex min-h-0 flex-col", className)}>- <SidebarSearchHeader- title="Canvases"- query={query}- placeholder="Search canvases…"- searchLabel="Search canvases"- onClear={() => setQuery("")}- actions={- <CanvasFilterMenu- spaceOptions={spaceOptions}- creatorOptions={viewModel.creatorOptions}- createdByDisabled={viewModel.personalSpaceSelected}- settings={viewModel.settings}- onChange={changeSettings}- />- }+ <CanvasList+ viewModel={viewModel}+ lastViewedAtByCanvasId={lastViewedAtByCanvasId}+ selectedId={selectedId}+ query={query}+ setQuery={setQuery}+ open={open}+ isLoading={isLoading}+ className={className}+ actions={+ <CanvasFilterMenu+ spaceOptions={spaceOptions}+ creatorOptions={viewModel.creatorOptions}+ createdByDisabled={viewModel.personalSpaceSelected}+ settings={viewModel.settings}+ onChange={changeSettings}/>- <AutocompleteList className="sidebar-autocomplete-tree scroll-mask-8 !max-h-none !p-1.5 min-h-0 flex-1 overflow-y-auto">- {isLoading ? (- <LoadingState className="py-10" />- ) : viewModel.canvases.length === 0 ? (- <Empty className="border-0 py-8">- <EmptyHeader>- <EmptyMedia variant="icon">- <BlueprintIcon />- </EmptyMedia>- <EmptyTitle>No canvases match</EmptyTitle>- <EmptyDescription>- Try another search or filter.- </EmptyDescription>- </EmptyHeader>- </Empty>- ) : (- <div className="flex flex-col gap-px">- {viewModel.sections.map((section) => (- <Fragment key={section.key}>- {section.label ? (- <MenuLabel>{section.label}</MenuLabel>- ) : null}- {section.canvases.map((canvas) => {- const lastViewedAt = lastViewedAtByCanvasId[canvas.id];- const lastViewedLabel = lastViewedAt- ? `Last viewed ${formatRelativeAge(lastViewedAt)}`- : "Not viewed yet";- const lastViewedTitle = lastViewedAt- ? `Last viewed ${formatAbsoluteDateTime(lastViewedAt)}`- : lastViewedLabel;-- return (- <AutocompleteItem- key={canvas.id}- value={canvas.id}- nativeButton- className={cn(- "h-auto w-full items-start py-1.5 text-left ring-offset-0 data-highlighted:border-transparent data-highlighted:bg-fill-hover data-highlighted:ring-0 [&>span]:w-full [&>span]:items-start [&>span]:gap-2",- canvas.id === selectedId && "bg-fill-selected",- )}- onClick={() => open(canvas)}- >- {iconForTemplate(canvas.templateId, { size: 14 })}- <span className="min-w-0">- <span className="block truncate text-[13px]">- {canvas.name}- </span>- <span- className="block truncate text-muted-foreground text-xxs"- title={lastViewedTitle}- >- {canvas.createdBy ?? "Unknown"} · {lastViewedLabel}- </span>- </span>- </AutocompleteItem>- );- })}- </Fragment>- ))}- </div>- )}- </AutocompleteList>- </div>- </Autocomplete>+ }+ />);}