: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
feat(canvas): add editable blocks and agent params to canvases (#105041)
Shy Altereeeedcc839b4
diff --git a/products/canvas/packages/canvas_builder/canvas-sdk.mjs b/products/canvas/packages/canvas_builder/canvas-sdk.mjsindex 1157f27e00bb..06588f0838a4 100644--- a/products/canvas/packages/canvas_builder/canvas-sdk.mjs+++ b/products/canvas/packages/canvas_builder/canvas-sdk.mjs@@ -7,3 +7,30 @@// module in the edit preview. Change one, change the other.export const ph = globalThis.phexport default globalThis.ph++export function editable(name, props, params) {+ const schema = params || {}+ const values = {}+ for (const key of Object.keys(schema)) {+ const value = props ? props[key] : undefined+ if (value === undefined || typeof value === 'function') {+ continue+ }+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {+ continue+ }+ values[key] = value+ }+ const attributes = {+ 'data-ph-block': name,+ 'data-ph-params': JSON.stringify(schema),+ 'data-ph-props': JSON.stringify(values),+ }+ if (props && props['data-ph-src']) {+ attributes['data-ph-src'] = props['data-ph-src']+ }+ if (props && props.blockId) {+ attributes['data-ph-block-id'] = props.blockId+ }+ return attributes+}diff --git a/products/canvas/packages/canvas_builder/manifest.json b/products/canvas/packages/canvas_builder/manifest.jsonindex 628a72ce18f3..0e2fbff00182 100644--- a/products/canvas/packages/canvas_builder/manifest.json+++ b/products/canvas/packages/canvas_builder/manifest.json@@ -16,7 +16,7 @@"three": { "version": "0.179.1", "url": "https://esm.sh/[email protected]" },"framer-motion": {"version": "12.23.12",- "url": "https://esm.sh/[email protected]?external=react,react-dom"+ "url": "https://esm.sh/[email protected]?external=react,react-dom&[email protected],[email protected]"},"zod": { "version": "3.25.76", "url": "https://esm.sh/[email protected]" },"@tanstack/react-table": {diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex dc1ac37ea73d..746cf864310c 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -67,6 +67,46 @@ graphics code owns a canvas element, or a mostly static page can mount one interThis is a judgment call, not a persisted mode — ask the user only when the choice changes auser-visible requirement you cannot infer.+## Blocks++A canvas can contain premade blocks: numbers, goals, trends, top lists, funnels, retention, saved insights, live event feeds, SQL tables, filters, compare and refresh controls, and callouts.+They are React components in `src/blocks/` that people drag into the canvas in the desktop app, so they are part of your source.+Read [references/blocks.md](references/blocks.md) before you change a canvas that has `src/blocks/runtime.tsx`.++## Params++Expose the values a person may want to change as params. They can then change them in the desktop editor without a new task.+Params are optional, but add them to each panel, card, or tool that has values worth changing: titles, copy, events, properties, thresholds, limits, colors.+Params need React components. A plain HTML canvas has no params.++1. Put each panel in its own component. The component takes these values as props, with defaults.+2. Spread `editable(name, props, params)` from `@posthog/canvas-sdk` on the root element of the component. `name` is the component name. `params` maps each prop name to its field.+3. Use the component with literal props, for example `<SignupFunnel title="Signup" windowDays={14} />`. The editor writes changes into these props, so do not compute them inline.++```tsx+import { editable } from '@posthog/canvas-sdk'++export function SignupFunnel(props: { title?: string; steps?: string[]; windowDays?: number }) {+ const { title = 'Signup funnel', steps = ['$pageview', 'signed_up'], windowDays = 14 } = props+ return (+ <Card+ {...editable('SignupFunnel', props, {+ title: { type: 'text', label: 'Title', default: 'Signup funnel' },+ steps: { type: 'events', label: 'Steps', default: ['$pageview', 'signed_up'] },+ windowDays: { type: 'number', label: 'Conversion window (days)', min: 1, max: 90, default: 14 },+ })}+ >+ …+ </Card>+ )+}+```++Field types: `text`, `longtext`, `number` (`min`, `max`, `step`; with both `min` and `max` the editor shows a slider), `boolean`, `select` (`options`: strings or `{ value, label }`), `event`, `events`, `property`, `insight` (a saved insight's short id), `color`. Each field can also have a `description`.+Give each field the same `default` as its prop default, for example `{ type: "boolean", label: "Show legend", default: true }`. The editor shows `default` when the prop is not set.+A `color` param defaults to a theme token such as `var(--primary)`, so the canvas follows light and dark mode until a person picks a hex in the editor.+Pass only JSON values (strings, numbers, booleans, string arrays) through params. Keep functions and query results out of them.+## ImagesUse public media library URLs for images in a canvas. Call `posthog:media-images-list` withdiff --git a/products/canvas/skills/building-canvases/references/blocks.md b/products/canvas/skills/building-canvases/references/blocks.mdnew file mode 100644index 000000000000..d698ceae7238--- /dev/null+++ b/products/canvas/skills/building-canvases/references/blocks.md@@ -0,0 +1,61 @@+# Canvas blocks (`src/blocks/`)++Blocks are premade React components that live in the canvas source.+People drag them into a canvas in the desktop app, and the app writes them into the code: the component file goes into `src/blocks/`, and a JSX line goes where the person dropped it.+They are ordinary code. Read them, import them, and change them like any other file.++## When a canvas has blocks++The canvas has blocks when `src/blocks/runtime.tsx` exists.+Blocks that are already in the source show as JSX with a `blockId` prop, for example:++```tsx+<Metric blockId="b-mf3k2a" title="Weekly active users" event="$pageview" math="weekly_active" />+```++## Rules++1. Keep every block that is in the source, with its `blockId`, unless the person asks you to remove it.+2. To add a block yourself, import it from `./blocks/<Name>` and give it a new unique `blockId` such as `b-` plus six letters or digits. Use only blocks whose file is in `src/blocks/`. For a block that is not there, build your own component with `useCanvasFilters()`; do not write block files or `runtime.tsx` from memory.+3. All blocks share the canvas filters through `useCanvasFilters()` and `setCanvasFilters()` in `src/blocks/runtime.tsx`. When you build your own chart or number, read `useCanvasFilters()` too, so the date range and property filters apply to it.+4. A block file is yours to change. Keep its exported name and its props, because the desktop reads them to edit the block.+5. `src/blocks/library.json` records which library version each block file is a copy of. Do not edit it. While a block file is unchanged, the desktop updates it to the newest library version; after you change a file, the desktop leaves it alone.+6. Blocks call `ph.query` and `ph.state` with the user scope. Keep `inlineQueries: true` and `"user"` in `capabilities.posthog.state`.+7. An `Insight` block loads a saved insight with `ph.loadInsight`. Put each `shortId` it uses in `capabilities.posthog.insights`. The desktop adds them when a person saves, but a publish of your own must list them.++## Blocks++| Component | Props |+| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `Metric` | `title`, `event`, `math` (`total`, `dau`, `weekly_active`, `monthly_active`), `format` (`number`, `percent`, `currency`, `duration`), `compare`, `followFilters` |+| `Trend` | `title`, `events` (string array), `math`, `display` (`line`, `bar`, `area`), `breakdown`, `followFilters` |+| `TopList` | `title`, `event`, `math`, `breakdown`, `limit`, `followFilters` |+| `Funnel` | `title`, `steps` (string array), `windowDays`, `followFilters` |+| `Retention` | `title`, `startEvent`, `returnEvent`, `period` (`Day`, `Week`, `Month`), `intervals`, `followFilters` |+| `Insight` | `shortId` (a saved insight), `title` (leave it out to use the insight's name) |+| `Goal` | `title`, `event`, `math`, `target`, `format`, `followFilters` |+| `RecentEvents` | `title`, `limit`, `followFilters` |+| `SqlTable` | `title`, `query` (HogQL; put `{filters}` in the WHERE clause) |+| `Filters` | `label` |+| `PropertyFilter` | `property`, `label` |+| `DateRange` | none |+| `Interval` | none |+| `Compare` | none. It draws the previous period on every `Trend`, as a dashed line. |+| `Refresh` | none. It reloads every block and shows when the data last loaded. |+| `Callout` | `tone` (`info`, `success`, `warning`), `title`, `text` |++Every data block also takes:++- `description`: a short line under the title that tells readers what to take from the block.+- `span`: `wide` or `full` makes the block take two columns or the full row of its grid.++## SQL mode++`Metric`, `Goal`, `Trend`, `TopList`, `Funnel` and `RecentEvents` also take a `sql` prop with HogQL. When `sql` is set, the block runs it instead of its builder settings. `Retention` and `Insight` have no SQL mode, and `SqlTable` takes its HogQL in `query`. Put `{filters}` in the WHERE clause so the canvas filters apply. The block reads the result by column position:++- `Metric`: one row. The first column is the value, an optional second column is the previous value.+- `Goal`: one row with the value in the first column.+- `Trend`: the first column is the x axis. Each other column is a series, named by its column name.+- `TopList`: each row is a label, then a number.+- `Funnel`: each row is a step in order, the step name, then the count.+- `RecentEvents`: each row is a time, the event, then a detail.diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.mdindex ed17f4a24c99..e09e95505ea2 100644--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md@@ -18,6 +18,7 @@ Start from the working scaffold in [references/starter-scaffold.md](references/son a first build: it already wires the date picker, theme tokens, per-query loading state (everycard fills in independently as its own data lands), and correct typed-node result reading. Keepthat wiring; replace the sample metrics and layout.+Keep its pattern of one component per card with `editable()` params, and follow the "Params" section of the `building-canvases` skill for each card you add.## Importsdiff --git a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.mdindex 7296170b1876..ce9873310f60 100644--- a/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md+++ b/products/canvas/skills/building-react-quill-canvases/references/starter-scaffold.md@@ -3,7 +3,7 @@A known-good baseline for a React + Quill data canvas. It already wires the pieces that are easyto get wrong — the date picker (self-sizing, no `compact`), theme-aware tokens, per-query loadingstate so every card fills in the moment its own data lands, reading a typed-node result correctly,-and the "View query" verification dialog every ad-hoc data card must carry. Start from it on a+the "View query" verification dialog every ad-hoc data card must carry, and cards that expose their titles, colors and sizes as params with `editable()`. Start from it on afirst build: keep the wiring, replace the sample metrics and the layout with what the user askedfor. Ideally swap the inline `ph.query` typed nodes for saved insights loaded with`ph.loadInsight(shortId, { dateRange })` (see the `querying-canvas-data` skill) — then replace the@@ -38,6 +38,7 @@ import {SkeletonText,} from '@posthog/quill'import { RefreshCw } from 'lucide-react'+import { editable, ph } from '@posthog/canvas-sdk'import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'// One builder per query feeds both the ph.query call and its "View query"@@ -124,6 +125,69 @@ function ViewQueryDialog({ query }) {)}+function NumberCard(props) {+ const { title = 'Total', state, onRetry, query } = props+ return (+ <Card size="sm" {...editable('NumberCard', props, { title: { type: 'text', label: 'Title', default: 'Total' } })}>+ <CardHeader>+ <div className="flex items-center justify-between gap-2">+ <CardTitle>{title}</CardTitle>+ {query ? <ViewQueryDialog query={query} /> : null}+ </div>+ </CardHeader>+ <CardContent>+ {state.loading ? (+ <SkeletonText lines={1} className="text-3xl" />+ ) : state.error ? (+ <CardError message={state.error} onRetry={onRetry} />+ ) : (+ <Heading size="2xl">{state.data.toLocaleString()}</Heading>+ )}+ </CardContent>+ </Card>+ )+}++function TrendCard(props) {+ const { title = 'Over time', color = 'var(--primary)', height = 280, state, onRetry, query } = props+ return (+ <Card+ size="sm"+ {...editable('TrendCard', props, {+ title: { type: 'text', label: 'Title', default: 'Over time' },+ color: { type: 'color', label: 'Line color', default: 'var(--primary)' },+ height: { type: 'number', label: 'Chart height', min: 160, max: 520, step: 20, default: 280 },+ })}+ >+ <CardHeader>+ <div className="flex items-center justify-between gap-2">+ <CardTitle>{title}</CardTitle>+ <ViewQueryDialog query={query} />+ </div>+ </CardHeader>+ <CardContent>+ {state.loading ? (+ <SkeletonText lines={6} />+ ) : state.error ? (+ <CardError message={state.error} onRetry={onRetry} />+ ) : (+ <div className="w-full" style={{ height }}>+ <ResponsiveContainer>+ <LineChart data={state.data.series}>+ <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />+ <XAxis dataKey="day" stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} />+ <YAxis stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} />+ <Tooltip />+ <Line type="monotone" dataKey="value" stroke={color} dot={false} strokeWidth={2} />+ </LineChart>+ </ResponsiveContainer>+ </div>+ )}+ </CardContent>+ </Card>+ )+}+export default function Canvas() {const def = quickRanges.find((r) => r.name === 'Last 30 days') ?? quickRanges[0]const [win, setWin] = useState({@@ -199,66 +263,23 @@ export default function Canvas() {</div><div className="grid gap-4 md:grid-cols-3">- <Card size="sm">- <CardHeader>- <CardTitle>Total events</CardTitle>- </CardHeader>- <CardContent>- {events.loading ? (- <SkeletonText lines={1} className="text-3xl" />- ) : events.error ? (- <CardError message={events.error} onRetry={retry} />- ) : (- <Heading size="2xl">{events.data.total.toLocaleString()}</Heading>- )}- </CardContent>- </Card>- <Card size="sm">- <CardHeader>- <div className="flex items-center justify-between gap-2">- <CardTitle>Unique users</CardTitle>- <ViewQueryDialog query={uniqueUsersQuery(dateRange)} />- </div>- </CardHeader>- <CardContent>- {visitors.loading ? (- <SkeletonText lines={1} className="text-3xl" />- ) : visitors.error ? (- <CardError message={visitors.error} onRetry={retry} />- ) : (- <Heading size="2xl">{visitors.data.toLocaleString()}</Heading>- )}- </CardContent>- </Card>+ <NumberCard+ title="Total events"+ state={{ ...events, data: events.data?.total }}+ onRetry={retry}+ query={totalEventsQuery(dateRange)}+ />+ <NumberCard title="Unique users" state={visitors} onRetry={retry} query={uniqueUsersQuery(dateRange)} /></div>- <Card size="sm">- <CardHeader>- <div className="flex items-center justify-between gap-2">- <CardTitle>Events over time</CardTitle>- <ViewQueryDialog query={totalEventsQuery(dateRange)} />- </div>- </CardHeader>- <CardContent>- {events.loading ? (- <SkeletonText lines={6} />- ) : events.error ? (- <CardError message={events.error} onRetry={retry} />- ) : (- <div className="h-[280px] w-full">- <ResponsiveContainer>- <LineChart data={events.data.series}>- <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />- <XAxis dataKey="day" stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} />- <YAxis stroke="var(--muted-foreground)" tick={{ fontSize: 12 }} />- <Tooltip />- <Line type="monotone" dataKey="value" stroke="var(--primary)" dot={false} strokeWidth={2} />- </LineChart>- </ResponsiveContainer>- </div>- )}- </CardContent>- </Card>+ <TrendCard+ title="Events over time"+ color="var(--primary)"+ height={280}+ state={events}+ onRetry={retry}+ query={totalEventsQuery(dateRange)}+ /></div>)}diff --git a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.tsindex 8a52c9b4f38a..4cf6baeba8b3 100644--- a/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts+++ b/products/canvas/skills/querying-canvas-data/references/canvas-sdk.d.ts@@ -195,6 +195,35 @@ export interface CanvasSdk {navigate?: CanvasNavigate}+export type CanvasParamType =+ | 'text'+ | 'longtext'+ | 'number'+ | 'boolean'+ | 'select'+ | 'event'+ | 'events'+ | 'property'+ | 'insight'+ | 'color'++export interface CanvasParam {+ type: CanvasParamType+ label?: string+ description?: string+ default?: string | number | boolean | string[]+ options?: Array<string | { value: string; label: string }>+ min?: number+ max?: number+ step?: number+}++export declare function editable(+ name: string,+ props: Record<string, unknown>,+ params: Record<string, CanvasParam>+): Record<string, string>+/*** The canvas's PostHog bridge, the same object as the `window.ph` global. Both* are installed on the document, so a `?worker` bundle cannot reach them.diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockDefinitions.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockDefinitions.tsnew file mode 100644index 000000000000..09d761ba4ca4--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockDefinitions.ts@@ -0,0 +1,283 @@+export type BlockGroup = "Data" | "Controls" | "Content";++export type BlockPropValue = string | number | boolean | string[] | undefined;+export type BlockPropsRecord = Record<string, BlockPropValue>;++export interface BlockDefinition {+ type: string;+ label: string;+ description: string;+ group: BlockGroup;+ component?: string;+ presets?: BlockPropsRecord[];+ element?: string;+ needsSetup?: boolean;+}++export const BLOCKS_DIR = "src/blocks";+export const BLOCK_RUNTIME_PATH = `${BLOCKS_DIR}/runtime.tsx`;+export const BLOCK_ICONS_PATH = `${BLOCKS_DIR}/icons.tsx`;++const DEFINITIONS: Omit<BlockDefinition, "component">[] = [+ {+ type: "Metric",+ label: "Number",+ description: "One big number with the change from the previous period",+ group: "Data",+ presets: [+ { title: "Pageviews", event: "$pageview", math: "total" },+ { title: "Daily active users", event: "$pageview", math: "dau" },+ {+ title: "Weekly active users",+ event: "$pageview",+ math: "weekly_active",+ },+ {+ title: "Monthly active users",+ event: "$pageview",+ math: "monthly_active",+ },+ { title: "Autocaptured events", event: "$autocapture", math: "total" },+ ],+ },+ {+ type: "Trend",+ label: "Trend",+ description: "Events over time as a line, bar or area chart",+ group: "Data",+ presets: [+ { title: "Pageviews over time", events: ["$pageview"], display: "line" },+ {+ title: "Active users over time",+ events: ["$pageview"],+ math: "dau",+ display: "area",+ },+ {+ title: "Pageviews by browser",+ events: ["$pageview"],+ breakdown: "$browser",+ display: "bar",+ },+ ],+ },+ {+ type: "TopList",+ label: "Top list",+ description: "The top values of a property, ranked by count",+ group: "Data",+ presets: [+ {+ title: "Top pages",+ event: "$pageview",+ breakdown: "$pathname",+ limit: 8,+ },+ {+ title: "Browsers",+ event: "$pageview",+ breakdown: "$browser",+ limit: 8,+ },+ {+ title: "Referring domains",+ event: "$pageview",+ breakdown: "$referring_domain",+ limit: 8,+ },+ {+ title: "Countries",+ event: "$pageview",+ breakdown: "$geoip_country_name",+ limit: 8,+ },+ {+ title: "Devices",+ event: "$pageview",+ breakdown: "$device_type",+ limit: 8,+ },+ ],+ },+ {+ type: "Funnel",+ label: "Funnel",+ description: "Conversion through a series of steps",+ group: "Data",+ presets: [+ {+ title: "Conversion",+ steps: ["$pageview", "$autocapture"],+ windowDays: 14,+ },+ ],+ },+ {+ type: "SqlTable",+ label: "SQL",+ description: "Any HogQL query as a table",+ group: "Data",+ presets: [+ {+ title: "Top events",+ query:+ "SELECT event, count() AS total FROM events WHERE {filters} GROUP BY event ORDER BY total DESC LIMIT 10",+ },+ ],+ },+ {+ type: "Goal",+ label: "Goal",+ description: "A number against a target, with progress",+ group: "Data",+ presets: [+ { title: "Pageviews goal", event: "$pageview", target: 50000 },+ {+ title: "Active users goal",+ event: "$pageview",+ math: "dau",+ target: 100,+ },+ ],+ },+ {+ type: "Insight",+ label: "Saved insight",+ description: "Any saved insight from PostHog, kept in sync",+ group: "Data",+ presets: [{ span: "wide" }],+ needsSetup: true,+ },+ {+ type: "Retention",+ label: "Retention",+ description: "How many people come back, period by period",+ group: "Data",+ presets: [+ {+ title: "Weekly retention",+ startEvent: "$pageview",+ returnEvent: "$pageview",+ period: "Week",+ intervals: 8,+ span: "wide",+ },+ ],+ },+ {+ type: "RecentEvents",+ label: "Recent events",+ description: "A live feed of the latest events",+ group: "Data",+ presets: [{ title: "Recent events", limit: 12 }],+ },+ {+ type: "DateRange",+ label: "Date range",+ description: "Sets the time range for every block on the canvas",+ group: "Controls",+ },+ {+ type: "Interval",+ label: "Interval",+ description: "Group charts by day, week or month",+ group: "Controls",+ },+ {+ type: "Filters",+ label: "Filters",+ description: "Let viewers filter every block by any property",+ group: "Controls",+ },+ {+ type: "PropertyFilter",+ label: "Quick filter",+ description: "A dropdown for the values of one property",+ group: "Controls",+ presets: [{ property: "$browser", label: "Browser" }],+ },+ {+ type: "Compare",+ label: "Compare",+ description: "Draw the previous period on every trend chart",+ group: "Controls",+ },+ {+ type: "Refresh",+ label: "Refresh",+ description: "Reload every block and show when data last loaded",+ group: "Controls",+ },+ {+ type: "Heading",+ label: "Heading",+ description: "A section title",+ group: "Content",+ element:+ '<h2 className="text-lg font-semibold tracking-tight">Section title</h2>',+ },+ {+ type: "Paragraph",+ label: "Text",+ description: "A short note or explanation",+ group: "Content",+ element:+ '<p className="text-sm text-muted-foreground">Write a note about what this shows.</p>',+ },+ {+ type: "Divider",+ label: "Divider",+ description: "A line between parts of the canvas",+ group: "Content",+ element: '<hr className="border-border" />',+ },+ {+ type: "Callout",+ label: "Callout",+ description: "A highlighted note or warning",+ group: "Content",+ presets: [+ {+ tone: "info",+ title: "Worth knowing",+ text: "Add a short note for the people who read this canvas.",+ },+ ],+ },+];++export const BLOCK_DEFINITIONS: BlockDefinition[] = DEFINITIONS.map(+ (definition) =>+ definition.element+ ? definition+ : { ...definition, component: definition.type },+);++const BY_TYPE = new Map(+ BLOCK_DEFINITIONS.map((definition) => [definition.type, definition]),+);++export function blockDefinition(type: string): BlockDefinition | undefined {+ return BY_TYPE.get(type);+}++export function componentPath(component: string): string {+ return `${BLOCKS_DIR}/${component}.tsx`;+}++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++export function freshBlockProps(+ definition: BlockDefinition,+ files: Record<string, string>,+): BlockPropsRecord {+ const presets = definition.presets ?? [{}];+ const source = Object.values(files).join("\n");+ const used = (preset: BlockPropsRecord) =>+ new RegExp(+ `<${definition.component}\\b[^>]*\\btitle="${escapeRegExp(String(preset.title ?? ""))}"`,+ ).test(source);+ return presets.find((preset) => !used(preset)) ?? presets[0];+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.test.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.test.tsnew file mode 100644index 000000000000..c6e5f49c2cfb--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { BLOCK_RUNTIME_PATH, componentPath } from "./blockDefinitions";+import {+ BLOCK_MANIFEST_PATH,+ hashText,+ syncBlockLibrary,+ withLibraryFile,+} from "./blockLibrarySync";+import { BLOCK_COMPONENT_SOURCES } from "./componentSources";+import { BLOCK_RUNTIME_SOURCE } from "./runtimeSource";++const METRIC_PATH = componentPath("Metric");+const OLD_COPY = "export function Metric() { return null; }\n";++function copiedEarlier(+ current: string,+ runtime?: string,+): Record<string, string> {+ return {+ [METRIC_PATH]: current,+ ...(runtime === undefined ? {} : { [BLOCK_RUNTIME_PATH]: runtime }),+ [BLOCK_MANIFEST_PATH]: JSON.stringify({+ [METRIC_PATH]: hashText(OLD_COPY),+ ...(runtime === undefined+ ? {}+ : { [BLOCK_RUNTIME_PATH]: hashText(BLOCK_RUNTIME_SOURCE) }),+ }),+ };+}++describe("syncBlockLibrary", () => {+ it.each([+ {+ name: "updates an untouched copy",+ current: OLD_COPY,+ expected: BLOCK_COMPONENT_SOURCES.Metric,+ },+ {+ name: "keeps a copy someone changed",+ current: `${OLD_COPY}// edited\n`,+ expected: `${OLD_COPY}// edited\n`,+ },+ {+ name: "keeps every copy when someone changed the runtime",+ current: OLD_COPY,+ runtime: `${BLOCK_RUNTIME_SOURCE}// edited\n`,+ expected: OLD_COPY,+ },+ ])("$name", ({ current, runtime, expected }) => {+ expect(syncBlockLibrary(copiedEarlier(current, runtime))[METRIC_PATH]).toBe(+ expected,+ );+ });++ it("records the copy so a later sync sees it as untouched", () => {+ const files = withLibraryFile({}, METRIC_PATH);+ expect(syncBlockLibrary(files)).toBe(files);+ });+});diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.tsnew file mode 100644index 000000000000..378854b0f785--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockLibrarySync.ts@@ -0,0 +1,95 @@+import {+ BLOCK_ICONS_PATH,+ BLOCK_RUNTIME_PATH,+ BLOCKS_DIR,+} from "./blockDefinitions";+import { BLOCK_COMPONENT_SOURCES } from "./componentSources";+import { BLOCK_ICONS_SOURCE } from "./iconsSource";+import { BLOCK_RUNTIME_SOURCE } from "./runtimeSource";++export type LibraryFiles = Record<string, string>;++export const BLOCK_MANIFEST_PATH = `${BLOCKS_DIR}/library.json`;++function librarySource(path: string): string | undefined {+ if (path === BLOCK_RUNTIME_PATH) return BLOCK_RUNTIME_SOURCE;+ if (path === BLOCK_ICONS_PATH) return BLOCK_ICONS_SOURCE;+ const match = new RegExp(`^${BLOCKS_DIR}/([A-Za-z0-9]+)\\.tsx$`).exec(path);+ return match?.[1] ? BLOCK_COMPONENT_SOURCES[match[1]] : undefined;+}++export function hashText(text: string): string {+ let hash = 0x811c9dc5;+ for (let index = 0; index < text.length; index += 1) {+ hash ^= text.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193);+ }+ return (hash >>> 0).toString(16).padStart(8, "0");+}++function readManifest(files: LibraryFiles): Record<string, string> {+ const raw = files[BLOCK_MANIFEST_PATH];+ if (!raw) return {};+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== "object") return {};+ return Object.fromEntries(+ Object.entries(parsed as Record<string, unknown>).filter(+ (entry): entry is [string, string] => typeof entry[1] === "string",+ ),+ );+ } catch {+ return {};+ }+}++function writeManifest(+ files: LibraryFiles,+ manifest: Record<string, string>,+): LibraryFiles {+ const sorted = Object.fromEntries(+ Object.entries(manifest).sort(([a], [b]) => a.localeCompare(b)),+ );+ return {+ ...files,+ [BLOCK_MANIFEST_PATH]: `${JSON.stringify(sorted, null, 2)}\n`,+ };+}++export function withLibraryFile(+ files: LibraryFiles,+ path: string,+): LibraryFiles {+ const source = librarySource(path);+ if (files[path] !== undefined || source === undefined) return files;+ return writeManifest(+ { ...files, [path]: source },+ { ...readManifest(files), [path]: hashText(source) },+ );+}++export function syncBlockLibrary(input: LibraryFiles): LibraryFiles {+ const files =+ input[BLOCK_RUNTIME_PATH] !== undefined+ ? withLibraryFile(input, BLOCK_ICONS_PATH)+ : input;+ const manifest = readManifest(files);+ const isUntouched = (path: string) =>+ files[path] !== undefined && hashText(files[path]) === manifest[path];+ const sharedEdited = [BLOCK_RUNTIME_PATH, BLOCK_ICONS_PATH].some(+ (path) => files[path] !== undefined && !isUntouched(path),+ );+ if (sharedEdited) return files;+ let next = files;+ let changed = false;+ for (const [path, copiedHash] of Object.entries(manifest)) {+ const current = files[path];+ const latest = librarySource(path);+ const untouched = current !== undefined && hashText(current) === copiedHash;+ if (!untouched || latest === undefined || latest === current) continue;+ next = { ...next, [path]: latest };+ manifest[path] = hashText(latest);+ changed = true;+ }+ return changed ? writeManifest(next, manifest) : files;+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.test.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.test.tsnew file mode 100644index 000000000000..cf2735db82fb--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { BLOCK_RUNTIME_PATH } from "./blockDefinitions";+import { canvasCapabilities } from "./blockProject";++describe("canvasCapabilities", () => {+ it("allows the insights that Insight blocks show and keeps the ones already allowed", () => {+ const files = {+ [BLOCK_RUNTIME_PATH]: "",+ "src/canvas.tsx":+ '<Insight blockId="a" shortId="Abc123" />\n<Insight\n blockId="b"\n title="Signups"\n shortId="Xyz789"\n/>\n<Insight blockId="c" />',+ };+ const capabilities = canvasCapabilities(+ { posthog: { insights: ["Old111", "Abc123"] } },+ files,+ );+ expect(capabilities?.posthog?.insights).toEqual([+ "Old111",+ "Abc123",+ "Xyz789",+ ]);+ expect(capabilities?.posthog?.inlineQueries).toBe(true);+ });+});diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.tsnew file mode 100644index 000000000000..8ee924db02f4--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockProject.ts@@ -0,0 +1,197 @@+import { CANVAS_PLATFORM_MANIFEST } from "@posthog/shared";+import type { CanvasSourceProject } from "../dashboardSchemas";+import {+ BLOCK_ICONS_PATH,+ BLOCK_RUNTIME_PATH,+ componentPath,+} from "./blockDefinitions";+import { withLibraryFile } from "./blockLibrarySync";+import { BLOCK_COMPONENT_SOURCES } from "./componentSources";++export const CANVAS_ENTRY_PATH = "src/canvas.tsx";++const ENTRY_HTML = `<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/canvas.tsx"></script>+ </body>+</html>+`;++const BLANK_CANVAS = `import { DateRange } from "./blocks/DateRange";++export default function Canvas() {+ return (+ <main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-8">+ <header className="flex flex-wrap items-end justify-between gap-4">+ <div className="flex flex-col gap-1">+ <h1 className="text-2xl font-semibold tracking-tight">Untitled canvas</h1>+ <p className="text-sm text-muted-foreground">What this canvas shows, in one sentence.</p>+ </div>+ <DateRange blockId="b-range" />+ </header>+ </main>+ );+}+`;++const PRODUCT_OVERVIEW_CANVAS = `import { DateRange } from "./blocks/DateRange";+import { Interval } from "./blocks/Interval";+import { Metric } from "./blocks/Metric";+import { PropertyFilter } from "./blocks/PropertyFilter";+import { TopList } from "./blocks/TopList";+import { Trend } from "./blocks/Trend";++export default function Canvas() {+ return (+ <main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-8">+ <header className="flex flex-wrap items-end justify-between gap-4">+ <div className="flex flex-col gap-1">+ <h1 className="text-2xl font-semibold tracking-tight">Product overview</h1>+ <p className="text-sm text-muted-foreground">How many people use the product, and what they do.</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <PropertyFilter blockId="b-browser" property="$browser" label="Browser" />+ <Interval blockId="b-interval" />+ <DateRange blockId="b-range" />+ </div>+ </header>+ <div className="grid gap-4 sm:grid-cols-3">+ <Metric blockId="b-wau" title="Weekly active users" event="$pageview" math="weekly_active" />+ <Metric blockId="b-dau" title="Daily active users" event="$pageview" math="dau" />+ <Metric blockId="b-views" title="Pageviews" event="$pageview" math="total" />+ </div>+ <Trend blockId="b-trend" title="Active users over time" events={["$pageview"]} math="dau" display="area" />+ <div className="grid gap-4 sm:grid-cols-2">+ <TopList blockId="b-pages" title="Top pages" event="$pageview" breakdown="$pathname" limit={8} />+ <TopList blockId="b-browsers" title="Browsers" event="$pageview" breakdown="$browser" limit={8} />+ </div>+ </main>+ );+}+`;++export interface CanvasStarter {+ id: string;+ name: string;+ description: string;+ source: string;+}++export const CANVAS_STARTERS: CanvasStarter[] = [+ {+ id: "blank",+ name: "Blank",+ description: "A title and a date range, then add blocks from the panel",+ source: BLANK_CANVAS,+ },+ {+ id: "product-overview",+ name: "Product overview",+ description: "Active users, pageviews, top pages and browsers",+ source: PRODUCT_OVERVIEW_CANVAS,+ },+];++function platformDependencies(): Record<string, string> {+ return Object.fromEntries(+ Object.entries(CANVAS_PLATFORM_MANIFEST.dependencies).map(+ ([name, entry]) => [name, entry.version],+ ),+ );+}++function usedComponents(source: string): string[] {+ const used: string[] = [];+ for (const match of source.matchAll(+ /from\s+["']\.\/blocks\/([A-Za-z]+)["']/g,+ )) {+ const name = match[1];+ if (name && BLOCK_COMPONENT_SOURCES[name]) used.push(name);+ }+ return used;+}++interface Capabilities {+ posthog?: {+ insights?: string[];+ inlineQueries?: boolean;+ captureEvents?: string[];+ state?: string[];+ actions?: string[];+ agentRequests?: boolean;+ };+ network?: { origins?: string[] };+ connectors?: unknown[];+}++const INSIGHT_BLOCK_ID = /<Insight\b[^>]*?\bshortId="([^"]+)"/g;++function insightBlockIds(files: Record<string, string>): string[] {+ return Object.values(files).flatMap((source) =>+ Array.from(source.matchAll(INSIGHT_BLOCK_ID), (match) => match[1]),+ );+}++export function usesBlocks(files: Record<string, string>): boolean {+ return BLOCK_RUNTIME_PATH in files;+}++const POSTHOG_DEFAULTS = {+ insights: [] as string[],+ captureEvents: [] as string[],+ actions: [] as string[],+ agentRequests: false,+};++export function canvasCapabilities(+ capabilities: unknown,+ files: Record<string, string>,+): Capabilities | undefined {+ const current =+ capabilities && typeof capabilities === "object"+ ? (capabilities as Capabilities)+ : undefined;+ if (!usesBlocks(files)) {+ return current?.posthog+ ? { ...current, posthog: { ...POSTHOG_DEFAULTS, ...current.posthog } }+ : current;+ }+ const posthog = { ...POSTHOG_DEFAULTS, ...current?.posthog };+ return {+ ...current,+ posthog: {+ ...posthog,+ insights: Array.from(+ new Set([...posthog.insights, ...insightBlockIds(files)]),+ ),+ inlineQueries: true,+ state: Array.from(new Set([...(posthog.state ?? []), "user"])),+ },+ network: current?.network ?? { origins: [] },+ };+}++export function starterProject(starter: CanvasStarter): CanvasSourceProject {+ let files: Record<string, string> = withLibraryFile(+ { "index.html": ENTRY_HTML, [CANVAS_ENTRY_PATH]: starter.source },+ BLOCK_RUNTIME_PATH,+ );+ files = withLibraryFile(files, BLOCK_ICONS_PATH);+ for (const component of usedComponents(starter.source)) {+ files = withLibraryFile(files, componentPath(component));+ }+ return {+ schemaVersion: 1,+ entryHtml: "index.html",+ files,+ dependencies: platformDependencies(),+ canvasSdkVersion: CANVAS_PLATFORM_MANIFEST.canvasSdkVersion,+ capabilities: canvasCapabilities(undefined, files),+ };+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/blockSql.ts b/products/desktop/packages/core/src/canvas/blockLibrary/blockSql.tsnew file mode 100644index 000000000000..c51a98901e05--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/blockSql.ts@@ -0,0 +1,139 @@+import type { BlockPropsRecord } from "./blockDefinitions";++export const SQL_COLUMN_HINTS: Record<string, string> = {+ SqlTable: "Any columns. Each row of the result is a row of the table.",+ Metric:+ "Return one row. The first column is the value. An optional second column is the previous value, for the change badge.",+ Goal: "Return one row with the value in the first column.",+ Trend:+ "The first column is the x axis, a date or a label. Each other column is a series.",+ TopList: "Each row is a label, then a number.",+ Funnel: "Each row is a step, in order: the step name, then the count.",+ RecentEvents: "Each row is a time, the event, then a detail.",+};++export const SQL_BLOCK_TYPES = new Set(+ Object.keys(SQL_COLUMN_HINTS).filter((type) => type !== "SqlTable"),+);++const INTERVAL_FUNCTIONS: Record<string, string> = {+ hour: "toStartOfHour",+ day: "toStartOfDay",+ week: "toStartOfWeek",+ month: "toStartOfMonth",+};++const KNOWN_EVENTS: Record<string, string> = {+ $pageview: "Pageview",+ $autocapture: "Autocapture",+ $pageleave: "Pageleave",+};++function text(value: unknown, fallback: string): string {+ return typeof value === "string" && value ? value : fallback;+}++function texts(value: unknown, fallback: string[]): string[] {+ return Array.isArray(value) && value.every((item) => typeof item === "string")+ ? value+ : fallback;+}++function literal(value: string): string {+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;+}++function alias(value: string): string {+ return `\`${value.replace(/`/g, "")}\``;+}++function label(event: string): string {+ return KNOWN_EVENTS[event] ?? event;+}++function property(key: string): string {+ return /^[A-Za-z_$][\w$]*$/.test(key)+ ? `properties.${key}`+ : `properties.${alias(key)}`;+}++function unique(math: string): boolean {+ return math !== "total";+}++function aggregate(math: string): string {+ return unique(math) ? "count(DISTINCT person_id)" : "count()";+}++function aggregateFor(math: string, event: string): string {+ const condition = `event = ${literal(event)}`;+ return unique(math)+ ? `uniqIf(person_id, ${condition})`+ : `countIf(${condition})`;+}++function metricSql(props: BlockPropsRecord): string {+ const event = text(props.event, "$pageview");+ const math = text(props.math, "total");+ return `SELECT ${aggregate(math)} AS value\nFROM events\nWHERE event = ${literal(event)} AND {filters}`;+}++function trendSql(props: BlockPropsRecord, interval: string): string {+ const events = texts(props.events, ["$pageview"]);+ const math = text(props.math, "total");+ const bucket = INTERVAL_FUNCTIONS[interval] ?? INTERVAL_FUNCTIONS.day;+ const series = events+ .map((event) => ` ${aggregateFor(math, event)} AS ${alias(label(event))}`)+ .join(",\n");+ return `SELECT\n ${bucket}(timestamp) AS period,\n${series}\nFROM events\nWHERE event IN (${events.map(literal).join(", ")}) AND {filters}\nGROUP BY period\nORDER BY period`;+}++function topListSql(props: BlockPropsRecord): string {+ const event = text(props.event, "$pageview");+ const math = text(props.math, "total");+ const breakdown = text(props.breakdown, "$pathname");+ const limit = typeof props.limit === "number" ? props.limit : 8;+ return `SELECT ${property(breakdown)} AS value, ${aggregate(math)} AS total\nFROM events\nWHERE event = ${literal(event)} AND {filters}\nGROUP BY value\nORDER BY total DESC\nLIMIT ${limit}`;+}++function funnelSql(props: BlockPropsRecord): string {+ const steps = texts(props.steps, ["$pageview", "$autocapture"]);+ const windowDays =+ typeof props.windowDays === "number" ? props.windowDays : 14;+ const conditions = steps.map((step) => `event = ${literal(step)}`).join(", ");+ const levels = `SELECT person_id, windowFunnel(${windowDays * 86400})(toDateTime(timestamp), ${conditions}) AS level\n FROM events\n WHERE event IN (${Array.from(new Set(steps)).map(literal).join(", ")}) AND {filters}\n GROUP BY person_id`;+ const rows = steps+ .map(+ (step, index) =>+ ` SELECT ${literal(label(step))} AS step, countIf(level >= ${index + 1}) AS people, ${index + 1} AS position FROM levels`,+ )+ .join("\n UNION ALL\n");+ return `WITH levels AS (\n ${levels}\n)\nSELECT step, people FROM (\n${rows}\n)\nORDER BY position`;+}++function recentEventsSql(props: BlockPropsRecord): string {+ const limit = typeof props.limit === "number" ? props.limit : 12;+ return `SELECT timestamp, event, coalesce(toString(properties.$pathname), toString(properties.$current_url), '') AS place\nFROM events\nWHERE {filters}\nORDER BY timestamp DESC\nLIMIT ${limit}`;+}++export function builderSql(+ type: string,+ props: BlockPropsRecord,+ interval = "day",+): string {+ switch (type) {+ case "Metric":+ case "Goal":+ return metricSql(props);+ case "Trend":+ return trendSql(props, interval);+ case "TopList":+ return topListSql(props);+ case "Funnel":+ return funnelSql(props);+ case "RecentEvents":+ return recentEventsSql(props);+ default:+ return "SELECT event, count() AS total\nFROM events\nWHERE {filters}\nGROUP BY event\nORDER BY total DESC\nLIMIT 10";+ }+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/componentSources.ts b/products/desktop/packages/core/src/canvas/blockLibrary/componentSources.tsnew file mode 100644index 000000000000..7783d721c174--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/componentSources.ts@@ -0,0 +1,1324 @@+const METRIC = `import { Card, CardContent } from "@posthog/quill";+import { Area, AreaChart, ResponsiveContainer } from "recharts";+import {+ sqlNode,+ type BlockProps,+ BlockDescription,+ BlockState,+ CHART_COLORS,+ ChangeBadge,+ QueryButton,+ blockRoot,+ eventName,+ eventsNode,+ filterFields,+ formatNumber,+ formatValue,+ scopeLabel,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type MetricProps = BlockProps & {+ sql?: string;+ format?: "number" | "percent" | "currency" | "duration";+ title?: string;+ event?: string;+ math?: string;+ compare?: boolean;+ followFilters?: boolean;+};++export function Metric(props: MetricProps) {+ const { title, event = "$pageview", math = "total", compare = true, followFilters = true, sql, format = "number", description } = props;+ const filters = useCanvasFilters();+ const shared = { interval: filters.interval, ...filterFields(filters, followFilters) };+ const query = sql+ ? sqlNode(sql, filters, followFilters)+ : {+ kind: "TrendsQuery",+ series: [eventsNode(event, math)],+ trendsFilter: { display: "BoldNumber" },+ ...(compare ? { compareFilter: { compare: true } } : {}),+ ...shared,+ };+ const value = useBlockQuery(query);+ const spark = useBlockQuery(sql ? null : { kind: "TrendsQuery", series: [eventsNode(event, math)], ...shared });+ const rows = value.data?.results ?? [];+ const current = sql ? null : (rows.find((row) => row.compare_label !== "previous") ?? rows[0]);+ const previous = sql ? null : rows.find((row) => row.compare_label === "previous");+ const total = sql ? Number(rows[0]?.[0] ?? Number.NaN) : Number(current?.aggregated_value ?? current?.count ?? Number.NaN);+ const before = sql ? Number(rows[0]?.[1] ?? Number.NaN) : Number(previous?.aggregated_value ?? previous?.count ?? Number.NaN);+ const change = compare && Number.isFinite(before) && before !== 0 ? ((total - before) / Math.abs(before)) * 100 : null;+ const points = (spark.data?.results?.[0]?.data ?? []).map((point: number, index: number) => ({ index, value: Number(point) }));+ return (+ <Card {...blockRoot("Metric", props)} className="shrink-0 group relative flex min-w-0 flex-col">+ <QueryButton className="absolute top-3 right-3 rounded-md bg-card" query={query} hogql={value?.data?.hogql} />+ <CardContent className="flex flex-1 flex-col gap-1">+ <span className="truncate text-sm font-medium text-muted-foreground" title={title || eventName(event)}>{title || eventName(event)}</span>+ <BlockDescription text={description} />+ <BlockState loading={value.loading} error={value.error} empty={!Number.isFinite(total)} height={76}>+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <span className="text-3xl font-semibold tracking-tight tabular-nums">{formatValue(total, format)}</span>+ {change === null ? null : <ChangeBadge value={change} />}+ </div>+ <div className="text-xs text-muted-foreground">{scopeLabel(filters, followFilters)}</div>+ {points.length > 1 ? (+ <div className="mt-auto h-12 pt-2">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={points} margin={{ top: 2, right: 0, bottom: 0, left: 0 }}>+ <Area type="monotone" dataKey="value" stroke={CHART_COLORS[0]} fill={CHART_COLORS[0]} fillOpacity={0.12} strokeWidth={1.5} isAnimationActive={false} />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ ) : null}+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const TREND = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import { Area, AreaChart, Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";+import {+ BlockDescription,+ sqlNode,+ type BlockProps,+ BlockState,+ CHART_COLORS,+ QueryButton,+ blockRoot,+ breakdownLabel,+ eventName,+ eventsNode,+ filterFields,+ fillDateRows,+ formatDay,+ previousRowsByDay,+ previousSqlNode,+ formatNumber,+ propertyLabel,+ scopeLabel,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type TrendProps = BlockProps & {+ title?: string;+ events?: string[];+ math?: string;+ display?: "line" | "bar" | "area";+ breakdown?: string;+ followFilters?: boolean;+};++const CHARTS = { line: LineChart, bar: BarChart, area: AreaChart };++export function Trend(props: TrendProps) {+ const { title, events = ["$pageview"], math = "total", display = "line", breakdown, followFilters = true, sql } = props;+ const filters = useCanvasFilters();+ const query = sql+ ? sqlNode(sql, filters, followFilters)+ : {+ kind: "TrendsQuery",+ series: events.map((event) => eventsNode(event, math)),+ interval: filters.interval,+ ...(breakdown ? { breakdownFilter: { breakdown, breakdown_type: "event", breakdown_limit: 5 } } : {}),+ ...(filters.compare ? { compareFilter: { compare: true } } : {}),+ ...filterFields(filters, followFilters),+ };+ const result = useBlockQuery(query);+ const previous = useBlockQuery(sql && filters.compare ? previousSqlNode(sql, filters, followFilters) : null);+ const series = sql ? [] : (result.data?.results ?? []);+ const baseColumns = sql ? (result.data?.columns ?? []).slice(1) : [];+ const previousRows = previous.data?.results ?? [];+ const comparing = !!sql && filters.compare && previousRows.length > 0;+ const previousByDay = comparing ? previousRowsByDay(previousRows.map((row) => String(row[0])), previousRows, filters.dateFrom) : null;+ const sqlColumns = comparing ? [...baseColumns, ...baseColumns.map((name) => name + " (previous)")] : baseColumns;+ const filled = sql+ ? fillDateRows((result.data?.results ?? []).map((row) => String(row[0])), result.data?.results ?? [], filters.dateFrom)+ : null;+ const sqlRows = filled ? filled.rows : [];+ const days: string[] = filled ? filled.xs : (series[0]?.days ?? []);+ const names = sql+ ? sqlColumns+ : series.map((row, index) => {+ const base = breakdown ? breakdownLabel(row.breakdown_value) : eventName(row.action?.id ?? events[index % events.length] ?? row.label ?? "Series");+ return row.compare_label === "previous" ? base + " (previous)" : base;+ });+ const previousAt = (index: number) => (sql ? comparing && index >= baseColumns.length : series[index]?.compare_label === "previous");+ const sqlValue = (day: string, index: number, seriesIndex: number) => {+ if (seriesIndex < baseColumns.length) return Number(sqlRows[index]?.[seriesIndex + 1] ?? 0);+ return Number(previousByDay?.get(day.slice(0, 10))?.[seriesIndex - baseColumns.length + 1] ?? 0);+ };+ const rows = days.map((day, index) => {+ const row: Record<string, number | string> = { day };+ names.forEach((_, seriesIndex) => {+ row["s" + seriesIndex] = sql ? sqlValue(day, index, seriesIndex) : Number(series[seriesIndex]?.data?.[index] ?? 0);+ });+ return row;+ });+ const colorAt = (index: number) => {+ if (sql) return CHART_COLORS[(comparing ? index % Math.max(1, baseColumns.length) : index) % CHART_COLORS.length];+ return CHART_COLORS[(filters.compare ? index % Math.max(1, names.length / 2) : index) % CHART_COLORS.length];+ };+ const Chart = CHARTS[display] ?? LineChart;+ return (+ <Card {...blockRoot("Trend", props)} className="shrink-0 group min-w-0">+ <CardHeader className="flex flex-row items-start justify-between gap-2">+ <div className="min-w-0">+ <CardTitle className="truncate">{title || events.map(eventName).join(", ")}</CardTitle>+ <BlockDescription text={props.description} />+ <div className="text-xs text-muted-foreground">+ {scopeLabel(filters, followFilters)}+ {breakdown && !sql ? " · by " + propertyLabel(breakdown) : ""}+ </div>+ {names.length > 1 ? (+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1">+ {names.map((name, index) => (+ <span key={name + index} className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ <span className={"size-2 shrink-0 rounded-full" + (previousAt(index) ? " opacity-50" : "")} style={{ background: colorAt(index) }} />+ <span className="truncate">{name}</span>+ </span>+ ))}+ </div>+ ) : null}+ </div>+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={rows.length === 0} height={220}>+ <div className="h-56">+ <ResponsiveContainer width="100%" height="100%">+ <Chart data={rows} margin={{ top: 4, right: 8, bottom: 0, left: -12 }}>+ <CartesianGrid stroke="currentColor" strokeOpacity={0.08} vertical={false} />+ <XAxis dataKey="day" tickFormatter={formatDay} tick={{ fontSize: 11 }} stroke="currentColor" strokeOpacity={0.4} minTickGap={24} />+ <YAxis tickFormatter={formatNumber} tick={{ fontSize: 11 }} stroke="currentColor" strokeOpacity={0.4} width={48} />+ <Tooltip labelFormatter={formatDay} formatter={(value: number) => formatNumber(value)} />+ {names.map((_, index) => {+ const color = colorAt(index);+ const key = "s" + index;+ const dash = previousAt(index) ? "4 4" : undefined;+ const faded = previousAt(index) ? 0.5 : 1;+ if (display === "bar") return <Bar key={key} dataKey={key} name={names[index]} fill={color} fillOpacity={faded} stackId={breakdown ? "stack" : undefined} radius={[3, 3, 0, 0]} isAnimationActive={false} />;+ if (display === "area") return <Area key={key} dataKey={key} name={names[index]} type="monotone" stroke={color} strokeOpacity={faded} strokeDasharray={dash} fill={color} fillOpacity={previousAt(index) ? 0 : 0.15} strokeWidth={2} isAnimationActive={false} />;+ return <Line key={key} dataKey={key} name={names[index]} type="monotone" stroke={color} strokeOpacity={faded} strokeDasharray={dash} strokeWidth={2} dot={false} isAnimationActive={false} />;+ })}+ </Chart>+ </ResponsiveContainer>+ </div>+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const TOP_LIST = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import {+ BlockDescription,+ sqlNode,+ type BlockProps,+ BlockState,+ QueryButton,+ blockRoot,+ breakdownLabel,+ eventName,+ eventsNode,+ filterFields,+ formatNumber,+ formatPercent,+ scopeLabel,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type TopListProps = BlockProps & {+ title?: string;+ event?: string;+ math?: string;+ breakdown?: string;+ limit?: number;+ followFilters?: boolean;+};++const OTHER = "$$_posthog_breakdown_other_$$";++export function TopList(props: TopListProps) {+ const { title, event = "$pageview", math = "total", breakdown = "$pathname", limit = 8, followFilters = true, sql } = props;+ const filters = useCanvasFilters();+ const query = sql+ ? sqlNode(sql, filters, followFilters)+ : {+ kind: "TrendsQuery",+ series: [eventsNode(event, math)],+ interval: filters.interval,+ trendsFilter: { display: "ActionsTable" },+ breakdownFilter: { breakdown, breakdown_type: "event", breakdown_limit: limit },+ ...filterFields(filters, followFilters),+ };+ const result = useBlockQuery(query);+ const rows = (result.data?.results ?? [])+ .map((row) =>+ sql+ ? { label: breakdownLabel(row[0]), other: false, value: Number(row[1] ?? 0) }+ : {+ label: breakdownLabel(row.breakdown_value),+ other: row.breakdown_value === OTHER,+ value: Number(row.aggregated_value ?? row.count ?? 0),+ },+ )+ .sort((a, b) => Number(a.other) - Number(b.other) || b.value - a.value)+ .slice(0, limit);+ const max = Math.max(1, ...rows.filter((row) => !row.other).map((row) => row.value));+ const total = rows.reduce((sum, row) => sum + row.value, 0);+ return (+ <Card {...blockRoot("TopList", props)} className="shrink-0 group min-w-0">+ <CardHeader className="flex flex-row items-start justify-between gap-2">+ <div className="min-w-0">+ <CardTitle className="truncate">{title || "Top " + breakdown}</CardTitle>+ <BlockDescription text={props.description} />+ <div className="text-xs text-muted-foreground">{eventName(event)} · {scopeLabel(filters, followFilters)}</div>+ </div>+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={rows.length === 0} height={200}>+ <div className="flex flex-col gap-1">+ {rows.map((row) => (+ <div key={row.label} className="relative flex items-center gap-3 rounded px-2 py-1.5 text-sm">+ <div className="absolute inset-y-0 left-0 rounded bg-primary/10" style={{ width: (row.value / max) * 100 + "%" }} />+ <span className="relative min-w-0 flex-1 truncate" title={row.label}>{row.label}</span>+ <span className="relative tabular-nums">{formatNumber(row.value)}</span>+ <span className="relative w-12 text-right text-xs text-muted-foreground tabular-nums">+ {total > 0 ? formatPercent((row.value / total) * 100) : ""}+ </span>+ </div>+ ))}+ </div>+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const FUNNEL = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import {+ BlockDescription,+ sqlNode,+ type BlockProps,+ BlockState,+ QueryButton,+ blockRoot,+ eventName,+ filterFields,+ formatNumber,+ formatPercent,+ scopeLabel,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type FunnelProps = BlockProps & {+ title?: string;+ steps?: string[];+ windowDays?: number;+ followFilters?: boolean;+};++function literal(value: string) {+ return "'" + value.replace(/\\\\/g, "\\\\\\\\").replace(/'/g, "\\\\'") + "'";+}++export function Funnel(props: FunnelProps) {+ const { title, steps: builderSteps = ["$pageview", "$autocapture"], windowDays = 14, followFilters = true, sql } = props;+ const filters = useCanvasFilters();+ const conditions = builderSteps.map((step) => "event = " + literal(step)).join(", ");+ const builderQuery = {+ kind: "HogQLQuery",+ query:+ "SELECT level, count() AS people FROM (SELECT person_id, windowFunnel(" ++ windowDays * 86400 ++ ")(toDateTime(timestamp), " ++ conditions ++ ") AS level FROM events WHERE {filters} AND event IN (" ++ Array.from(new Set(builderSteps)).map(literal).join(", ") ++ ") GROUP BY person_id) GROUP BY level ORDER BY level",+ filters: filterFields(filters, followFilters),+ };+ const query = sql ? sqlNode(sql, filters, followFilters) : builderQuery;+ const result = useBlockQuery(query);+ const sqlRows = sql ? (result.data?.results ?? []) : [];+ const steps = sql ? sqlRows.map((row) => String(row[0])) : builderSteps;+ const byLevel = new Map<number, number>();+ if (!sql) for (const row of result.data?.results ?? []) byLevel.set(Number(row[0]), Number(row[1]));+ const counts = sql+ ? sqlRows.map((row) => Number(row[1] ?? 0))+ : steps.map((_, index) => {+ let reached = 0;+ for (const [level, people] of byLevel) if (level >= index + 1) reached += people;+ return reached;+ });+ const first = counts[0] ?? 0;+ const last = counts[counts.length - 1] ?? 0;+ return (+ <Card {...blockRoot("Funnel", props)} className="shrink-0 group min-w-0">+ <CardHeader className="flex flex-row items-start justify-between gap-2">+ <div className="min-w-0">+ <CardTitle className="truncate">{title || "Conversion"}</CardTitle>+ <BlockDescription text={props.description} />+ <div className="text-xs text-muted-foreground">+ {first > 0 ? formatPercent((last / first) * 100) + " convert · " : ""}+ {sql ? "" : windowDays + "-day window · "}+ {scopeLabel(filters, followFilters)}+ </div>+ </div>+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={first === 0} height={160}>+ <div className="flex flex-col gap-2.5">+ {steps.map((step, index) => {+ const share = first > 0 ? (counts[index] / first) * 100 : 0;+ return (+ <div key={step + index} className="flex flex-col gap-1">+ <div className="flex items-center justify-between text-sm">+ <span className="truncate">{index + 1}. {eventName(step)}</span>+ <span className="tabular-nums text-muted-foreground">+ {formatNumber(counts[index])} · {formatPercent(share)}+ </span>+ </div>+ <div className="h-2 overflow-hidden rounded-full bg-muted">+ <div className="h-full rounded-full bg-primary transition-[width] duration-500" style={{ width: share + "%" }} />+ </div>+ </div>+ );+ })}+ </div>+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const SQL_TABLE = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import {+ BlockDescription,+ type BlockProps,+ BlockState,+ QueryButton,+ ResultTable,+ blockRoot,+ filterFields,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type SqlTableProps = BlockProps & {+ title?: string;+ query?: string;+};++export function SqlTable(props: SqlTableProps) {+ const { title, query: hogql = "SELECT event, count() AS total FROM events WHERE {filters} GROUP BY event ORDER BY total DESC LIMIT 10" } = props;+ const filters = useCanvasFilters();+ const query = { kind: "HogQLQuery", query: hogql, filters: filterFields(filters) };+ const result = useBlockQuery(query);+ const columns = result.data?.columns ?? [];+ const rows = result.data?.results ?? [];+ return (+ <Card {...blockRoot("SqlTable", props)} className="shrink-0 group min-w-0">+ <CardHeader className="flex flex-row items-start justify-between gap-2">+ <CardTitle className="truncate">{title || "Query results"}</CardTitle>+ <BlockDescription text={props.description} />+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={rows.length === 0} height={160}>+ <ResultTable columns={columns} rows={rows} />+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const DATE_RANGE = `import { Button } from "@posthog/quill";+import { type BlockProps, DATE_RANGES, blockRoot, setCanvasFilters, useCanvasFilters } from "./runtime";++export function DateRange(props: BlockProps) {+ const filters = useCanvasFilters();+ return (+ <div {...blockRoot("DateRange", props)} className="shrink-0 inline-flex items-center gap-0.5 rounded-lg border border-border bg-card p-0.5 shadow-xs">+ {DATE_RANGES.map((range) => (+ <Button+ key={range.value}+ size="sm"+ variant={filters.dateFrom === range.value ? "primary" : "default"}+ onClick={() => setCanvasFilters({ ...filters, dateFrom: range.value })}+ >+ {range.label}+ </Button>+ ))}+ </div>+ );+}+`;++const INTERVAL = `import { Button } from "@posthog/quill";+import { type BlockProps, type CanvasInterval, blockRoot, setCanvasFilters, useCanvasFilters } from "./runtime";++const OPTIONS: Array<{ value: CanvasInterval; label: string }> = [+ { value: "day", label: "Day" },+ { value: "week", label: "Week" },+ { value: "month", label: "Month" },+];++export function Interval(props: BlockProps) {+ const filters = useCanvasFilters();+ return (+ <div {...blockRoot("Interval", props)} className="shrink-0 inline-flex items-center gap-0.5 rounded-lg border border-border bg-card p-0.5 shadow-xs">+ {OPTIONS.map((option) => (+ <Button+ key={option.value}+ size="sm"+ variant={filters.interval === option.value ? "primary" : "default"}+ onClick={() => setCanvasFilters({ ...filters, interval: option.value })}+ >+ {option.label}+ </Button>+ ))}+ </div>+ );+}+`;++const PROPERTY_FILTER = `import { type BlockProps, blockRoot, setCanvasFilters, useBlockQuery, useCanvasFilters } from "./runtime";++type PropertyFilterProps = BlockProps & {+ property?: string;+ label?: string;+};++export function PropertyFilter(props: PropertyFilterProps) {+ const { property = "$browser", label } = props;+ const filters = useCanvasFilters();+ const safe = property.replace(/[^A-Za-z0-9_$.-]/g, "");+ const values = useBlockQuery({+ kind: "HogQLQuery",+ query:+ "SELECT toString(properties." + "\`" + safe + "\`" + ") AS value, count() AS total FROM events WHERE timestamp > now() - INTERVAL 30 DAY AND properties." + "\`" + safe + "\`" + " IS NOT NULL GROUP BY value ORDER BY total DESC LIMIT 50",+ });+ const active = filters.properties.find((entry) => entry.key === property);+ const others = filters.properties.filter((entry) => entry.key !== property);+ const choose = (value: string) =>+ setCanvasFilters({+ ...filters,+ properties: value ? [...others, { key: property, value, type: "event" }] : others,+ });+ return (+ <label {...blockRoot("PropertyFilter", props)} className="shrink-0 inline-flex items-center gap-1 rounded-lg border border-border bg-card p-0.5 pl-2.5 text-sm shadow-xs">+ <span className="text-muted-foreground">{label || property}</span>+ <select+ className={"h-7 max-w-40 cursor-pointer truncate rounded-md bg-transparent px-1.5 text-sm font-medium outline-none hover:bg-muted " + (active ? "text-primary" : "text-foreground")}+ value={active?.value ?? ""}+ onChange={(event) => choose(event.target.value)}+ >+ <option value="">All</option>+ {(values.data?.results ?? []).map((row) => (+ <option key={String(row[0])} value={String(row[0])}>{String(row[0])}</option>+ ))}+ </select>+ </label>+ );+}+`;++const FILTERS = `import { useEffect, useMemo, useState } from "react";+import { Button, Input, Popover, PopoverContent, PopoverTrigger } from "@posthog/quill";+import { CaretLeftIcon, FunnelIcon, PlusIcon, XIcon } from "./icons";+import {+ type BlockProps,+ type CanvasPropertyFilter,+ FILTER_OPERATORS,+ type FilterOperator,+ blockRoot,+ filterLabel,+ propertyLabel,+ setCanvasFilters,+ useBlockQuery,+ useCanvasFilters,+} from "./runtime";++type FiltersProps = BlockProps & { label?: string };+type Scope = "event" | "person";++const KEY_SOURCES: Record<Scope, string> = {+ event: "SELECT arrayJoin(JSONExtractKeys(properties)) AS k FROM events WHERE timestamp > now() - INTERVAL 7 DAY LIMIT 100000",+ person: "SELECT arrayJoin(JSONExtractKeys(properties)) AS k FROM persons LIMIT 50000",+};++function keysQuery(scope: Scope, search: string): string {+ const needle = search.replace(/[^A-Za-z0-9_$ .-]/g, "").trim();+ const where = needle ? " WHERE k ILIKE '%" + needle + "%'" : "";+ return "SELECT k, count() AS c FROM (" + KEY_SOURCES[scope] + ")" + where + " GROUP BY k ORDER BY c DESC LIMIT 200";+}++function useDebounced(value: string, delay: number): string {+ const [settled, setSettled] = useState(value);+ useEffect(() => {+ const timer = setTimeout(() => setSettled(value), delay);+ return () => clearTimeout(timer);+ }, [value, delay]);+ return settled;+}++function column(scope: Scope, key: string): string {+ const safe = key.replace(/[^A-Za-z0-9_$.-]/g, "");+ return (scope === "person" ? "person.properties." : "properties.") + "\`" + safe + "\`";+}++function valuesQuery(scope: Scope, key: string): string {+ const field = column(scope, key);+ return (+ "SELECT toString(" + field + ") AS value, count() AS c FROM events WHERE timestamp > now() - INTERVAL 30 DAY AND " ++ field + " IS NOT NULL GROUP BY value ORDER BY c DESC LIMIT 50"+ );+}++const COMMON_KEYS = [+ "$browser",+ "$os",+ "$device_type",+ "$pathname",+ "$current_url",+ "$referring_domain",+ "$geoip_country_name",+ "$geoip_city_name",+ "utm_source",+ "utm_medium",+ "utm_campaign",+ "email",+ "name",+];++const INTERNAL_KEY = /^(\\$feature\\/|\\$feature_flag|\\$active_feature_flags|\\$set|\\$set_once|\\$lib|\\$sent_at|\\$insert_id|\\$time$|\\$window_id|\\$session_id|\\$device_id|\\$groups|\\$group_|\\$plugins|\\$raw_user_agent|\\$ip$|\\$process_person|\\$is_identified|\\$configured_session|\\$sdk|\\$exception|\\$debug|\\$replay|\\$recording|\\$web_vitals_|\\$heatmap|\\$dead_clicks|\\$surveys|\\$autocapture_disabled|\\$console_log|.*_server_side$|token$|distinct_id$)/;++function isInternalKey(name: string): boolean {+ return INTERNAL_KEY.test(name);+}++function commonRank(name: string): number {+ const index = COMMON_KEYS.indexOf(name);+ return index === -1 ? COMMON_KEYS.length : index;+}++function matchRank(name: string, needle: string): number {+ if (!needle) return 0;+ const key = name.toLowerCase().replace(/^\\$/, "");+ const label = propertyLabel(name).toLowerCase();+ if (key === needle || label === needle) return 0;+ if (key.startsWith(needle) || label.startsWith(needle)) return 1;+ if (key.includes(needle) || label.includes(needle)) return 2;+ return 3;+}++function needsValue(operator: FilterOperator): boolean {+ return operator !== "is_set" && operator !== "is_not_set";+}++function PickList({ items, onPick, empty }: { items: Array<{ value: string; label: string; hint?: string }>; onPick: (value: string) => void; empty: string }) {+ if (items.length === 0) return <div className="px-2 py-6 text-center text-xs text-muted-foreground">{empty}</div>;+ return (+ <div className="flex max-h-60 flex-col overflow-y-auto py-1">+ {items.map((item) => (+ <button+ key={item.value}+ type="button"+ onClick={() => onPick(item.value)}+ className="flex items-center justify-between gap-3 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-muted"+ >+ <span className="min-w-0 shrink truncate">{item.label}</span>+ {item.hint ? <span className="min-w-0 shrink-[3] truncate text-xs text-muted-foreground tabular-nums">{item.hint}</span> : null}+ </button>+ ))}+ </div>+ );+}++function FilterEditor({ initial, onApply }: { initial: CanvasPropertyFilter | null; onApply: (filter: CanvasPropertyFilter) => void }) {+ const [scope, setScope] = useState<Scope>(initial?.type ?? "event");+ const [key, setKey] = useState<string | null>(initial?.key ?? null);+ const [operator, setOperator] = useState<FilterOperator>(initial?.operator ?? "exact");+ const [search, setSearch] = useState("");+ const keySearch = useDebounced(search, 200);+ const keys = useBlockQuery(key ? null : { kind: "HogQLQuery", query: keysQuery(scope, keySearch) });+ const values = useBlockQuery(key && needsValue(operator) ? { kind: "HogQLQuery", query: valuesQuery(scope, key) } : null);+ const needle = search.trim().toLowerCase();+ const keyItems = useMemo(+ () =>+ (keys.data?.results ?? [])+ .map((row) => String(row[0]))+ .filter((name) => !isInternalKey(name))+ .map((name, order) => ({ name, order, rank: matchRank(name, needle), common: commonRank(name) }))+ .filter((item) => item.rank < 3)+ .sort((a, b) => a.rank - b.rank || a.common - b.common || a.order - b.order)+ .map((item) => item.name)+ .slice(0, 80)+ .map((name) => ({ value: name, label: propertyLabel(name), hint: name.startsWith("$") ? name : undefined })),+ [keys.data, needle],+ );+ const valueItems = useMemo(+ () =>+ (values.data?.results ?? [])+ .map((row) => ({ value: String(row[0]), hint: Number(row[1]).toLocaleString() }))+ .filter((row) => !needle || row.value.toLowerCase().includes(needle))+ .map((row) => ({ value: row.value, label: row.value, hint: row.hint })),+ [values.data, needle],+ );+ const apply = (value: string) => {+ if (!key) return;+ onApply({ key, type: scope, operator, value });+ };++ if (!key) {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex gap-1 rounded-md bg-muted p-0.5">+ {(["event", "person"] as Scope[]).map((option) => (+ <button+ key={option}+ type="button"+ onClick={() => setScope(option)}+ className={"flex-1 rounded px-2 py-1 text-xs font-medium transition-colors " + (scope === option ? "bg-background shadow-xs" : "text-muted-foreground")}+ >+ {option === "event" ? "Event properties" : "Person properties"}+ </button>+ ))}+ </div>+ <Input autoFocus placeholder="Search properties" value={search} onChange={(event) => setSearch(event.target.value)} className="h-8" />+ {keys.loading && keyItems.length === 0 && !search ? <div className="h-40 animate-pulse rounded-md bg-muted/60" /> : <PickList items={keyItems} onPick={(value) => { setKey(value); setSearch(""); }} empty={keys.loading || search !== keySearch ? "Searching…" : "No properties match"} />}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <button type="button" onClick={() => setKey(null)} className="flex items-center gap-1 self-start text-xs text-muted-foreground transition-colors hover:text-foreground">+ <CaretLeftIcon className="size-3.5" />+ {(scope === "person" ? "Person " : "") + propertyLabel(key)}+ </button>+ <div className="flex flex-wrap gap-1">+ {FILTER_OPERATORS.map((option) => (+ <button+ key={option.value}+ type="button"+ onClick={() => {+ setOperator(option.value);+ if (!needsValue(option.value)) onApply({ key, type: scope, operator: option.value, value: "" });+ }}+ className={"rounded-md border px-2 py-0.5 text-xs transition-colors " + (operator === option.value ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:text-foreground")}+ >+ {option.label}+ </button>+ ))}+ </div>+ <Input+ autoFocus+ placeholder="Search or type a value"+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && search.trim()) apply(search.trim());+ }}+ className="h-8"+ />+ {values.loading ? <div className="h-32 animate-pulse rounded-md bg-muted/60" /> : <PickList items={valueItems} onPick={apply} empty={search.trim() ? "Press Enter to use this value" : "No values yet"} />}+ </div>+ );+}++function FilterChip({ filter, onChange, onRemove }: { filter: CanvasPropertyFilter; onChange: (filter: CanvasPropertyFilter) => void; onRemove: () => void }) {+ const [open, setOpen] = useState(false);+ return (+ <div className="flex items-center rounded-lg border border-border bg-card shadow-xs">+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger render={<button type="button" className="px-2.5 py-1 text-sm transition-colors hover:text-primary" />}>+ {filterLabel(filter)}+ </PopoverTrigger>+ <PopoverContent align="start" className="w-72 p-2">+ <FilterEditor initial={filter} onApply={(next) => { onChange(next); setOpen(false); }} />+ </PopoverContent>+ </Popover>+ <button type="button" aria-label="Remove filter" onClick={onRemove} className="border-l border-border px-1.5 py-1.5 text-muted-foreground transition-colors hover:text-foreground">+ <XIcon className="size-3.5" />+ </button>+ </div>+ );+}++export function Filters(props: FiltersProps) {+ const filters = useCanvasFilters();+ const [adding, setAdding] = useState(false);+ const replace = (index: number, next: CanvasPropertyFilter | null) => {+ const properties = filters.properties.flatMap((current, position) => (position === index ? (next ? [next] : []) : [current]));+ setCanvasFilters({ ...filters, properties });+ };+ return (+ <div {...blockRoot("Filters", props)} className="flex shrink-0 flex-wrap items-center gap-1.5">+ <span className="flex items-center gap-1.5 pr-1 text-sm text-muted-foreground">+ <FunnelIcon className="size-4" />+ {props.label || "Filters"}+ </span>+ {filters.properties.map((filter, index) => (+ <FilterChip+ key={filter.type + filter.key + index}+ filter={filter}+ onChange={(next) => replace(index, next)}+ onRemove={() => replace(index, null)}+ />+ ))}+ <Popover open={adding} onOpenChange={setAdding}>+ <PopoverTrigger render={<Button variant="outline" size="sm" />}>+ <PlusIcon className="size-3.5" />+ Add filter+ </PopoverTrigger>+ <PopoverContent align="start" className="w-72 p-2">+ <FilterEditor+ initial={null}+ onApply={(next) => {+ setCanvasFilters({ ...filters, properties: [...filters.properties, next] });+ setAdding(false);+ }}+ />+ </PopoverContent>+ </Popover>+ </div>+ );+}+`;++const GOAL = `import { Card, CardContent } from "@posthog/quill";+import { sqlNode, type BlockProps, BlockDescription, BlockState, QueryButton, blockRoot, eventName, eventsNode, filterFields, formatNumber, formatValue, scopeLabel, useBlockQuery, useCanvasFilters } from "./runtime";++type GoalProps = BlockProps & {+ format?: "number" | "percent" | "currency" | "duration";+ title?: string;+ event?: string;+ math?: string;+ target?: number;+ followFilters?: boolean;+};++export function Goal(props: GoalProps) {+ const { title, event = "$pageview", math = "total", target = 1000, followFilters = true, sql, format = "number", description } = props;+ const filters = useCanvasFilters();+ const query = sql+ ? sqlNode(sql, filters, followFilters)+ : {+ kind: "TrendsQuery",+ series: [eventsNode(event, math)],+ trendsFilter: { display: "BoldNumber" },+ interval: filters.interval,+ ...filterFields(filters, followFilters),+ };+ const result = useBlockQuery(query);+ const row = result.data?.results?.[0];+ const total = sql ? Number(row?.[0] ?? Number.NaN) : Number(row?.aggregated_value ?? row?.count ?? Number.NaN);+ const share = target > 0 && Number.isFinite(total) ? total / target : 0;+ const reached = share >= 1;+ return (+ <Card+ {...blockRoot("Goal", props, {+ params: {+ title: { type: "text", label: "Title" },+ event: { type: "event", label: "Event" },+ math: {+ type: "select",+ label: "Measure",+ options: [+ { value: "total", label: "Total count" },+ { value: "dau", label: "Unique users" },+ { value: "weekly_active", label: "Weekly active" },+ { value: "monthly_active", label: "Monthly active" },+ ],+ },+ target: { type: "number", label: "Target", min: 1 },+ format: {+ type: "select",+ label: "Format",+ options: [+ { value: "number", label: "Number" },+ { value: "percent", label: "Percent" },+ { value: "currency", label: "Currency" },+ { value: "duration", label: "Duration" },+ ],+ },+ followFilters: { type: "boolean", label: "Use canvas filters", default: true },+ },+ })}+ className="group relative flex min-w-0 shrink-0 flex-col"+ >+ <QueryButton className="absolute top-3 right-3 rounded-md bg-card" query={query} hogql={result?.data?.hogql} />+ <CardContent className="flex flex-1 flex-col gap-2">+ <span className="truncate text-sm font-medium text-muted-foreground">{title || eventName(event) + " goal"}</span>+ <BlockDescription text={description} />+ <BlockState loading={result.loading} error={result.error} empty={!Number.isFinite(total)} height={72}>+ <div className="flex items-baseline gap-1.5">+ <span className="text-3xl font-semibold tracking-tight tabular-nums">{formatValue(total, format)}</span>+ <span className="text-sm text-muted-foreground tabular-nums">of {formatValue(target, format)}</span>+ </div>+ <div className="mt-3 h-2 overflow-hidden rounded-full bg-muted">+ <div+ className={"h-full origin-left rounded-full transition-transform duration-500 " + (reached ? "bg-emerald-500" : "bg-primary")}+ style={{ transform: "scaleX(" + Math.min(1, share) + ")", transitionTimingFunction: "cubic-bezier(0.23, 1, 0.32, 1)" }}+ />+ </div>+ <div className="mt-1.5 flex justify-between text-xs text-muted-foreground">+ <span>{reached ? "Goal reached" : Math.round(share * 100) + "% of goal"}</span>+ <span>{scopeLabel(filters, followFilters)}</span>+ </div>+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const RECENT_EVENTS = `import { useEffect, useState } from "react";+import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import { BlockDescription, sqlNode, type BlockProps, BlockState, QueryButton, blockRoot, eventName, filterFields, useBlockQuery, useCanvasFilters } from "./runtime";++type RecentEventsProps = BlockProps & {+ title?: string;+ limit?: number;+ followFilters?: boolean;+};++const REFRESH_MS = 15000;++function detailLabel(value: unknown): string {+ const text = value === null || value === undefined ? "" : String(value);+ return text === "/" ? "Home" : text;+}++function ago(value: unknown): string {+ const time = new Date(String(value)).getTime();+ if (!Number.isFinite(time)) return "";+ const seconds = Math.max(0, Math.round((Date.now() - time) / 1000));+ if (seconds < 60) return seconds + "s ago";+ if (seconds < 3600) return Math.round(seconds / 60) + "m ago";+ if (seconds < 86400) return Math.round(seconds / 3600) + "h ago";+ return Math.round(seconds / 86400) + "d ago";+}++export function RecentEvents(props: RecentEventsProps) {+ const { title = "Recent events", limit = 12, followFilters = true, sql } = props;+ const filters = useCanvasFilters();+ const [tick, setTick] = useState(0);+ useEffect(() => {+ const timer = setInterval(() => setTick((value) => value + 1), REFRESH_MS);+ return () => clearInterval(timer);+ }, []);+ const query = sqlNode(+ sql ||+ "SELECT timestamp, event, coalesce(toString(properties.$pathname), toString(properties.$current_url), '') AS place FROM events WHERE {filters} ORDER BY timestamp DESC LIMIT " ++ Math.max(1, Math.min(50, limit)),+ filters,+ followFilters,+ );+ const result = useBlockQuery(query, tick);+ const rows = result.data?.results ?? [];+ return (+ <Card+ {...blockRoot("RecentEvents", props, {+ params: {+ title: { type: "text", label: "Title" },+ limit: { type: "number", label: "Rows", min: 1, max: 50 },+ followFilters: { type: "boolean", label: "Use canvas filters", default: true },+ },+ })}+ className="group min-w-0 shrink-0"+ >+ <CardHeader className="flex flex-row items-center justify-between gap-2">+ <CardTitle className="flex items-center gap-2 truncate">+ <span className="relative flex size-2">+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-500/60 motion-reduce:hidden" />+ <span className="relative inline-flex size-2 rounded-full bg-emerald-500" />+ </span>+ {title}+ </CardTitle>+ <BlockDescription text={props.description} />+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={rows.length === 0} height={200}>+ <div className="flex flex-col">+ {rows.map((row, index) => (+ <div key={String(row[0]) + index} className="flex items-center gap-3 border-b border-border py-1.5 text-sm last:border-b-0">+ <span className="w-16 shrink-0 text-xs text-muted-foreground tabular-nums">{ago(row[0])}</span>+ <span className="shrink-0 font-medium">{eventName(String(row[1]))}</span>+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{detailLabel(row[2])}</span>+ </div>+ ))}+ </div>+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const CALLOUT = `import { CheckCircleIcon, InfoIcon, WarningCircleIcon } from "./icons";+import { type BlockProps, blockRoot } from "./runtime";++type CalloutProps = BlockProps & {+ tone?: "info" | "success" | "warning";+ title?: string;+ text?: string;+};++const TONES = {+ info: { icon: InfoIcon, className: "border-border bg-muted/40", iconClassName: "text-muted-foreground" },+ success: { icon: CheckCircleIcon, className: "border-emerald-500/25 bg-emerald-500/5", iconClassName: "text-emerald-600" },+ warning: { icon: WarningCircleIcon, className: "border-amber-500/30 bg-amber-500/5", iconClassName: "text-amber-600" },+};++export function Callout(props: CalloutProps) {+ const { tone = "info", title = "Worth knowing", text = "Add a short note for the people who read this canvas." } = props;+ const look = TONES[tone] ?? TONES.info;+ const Icon = look.icon;+ return (+ <div+ {...blockRoot("Callout", props, {+ params: {+ tone: {+ type: "select",+ label: "Tone",+ options: [+ { value: "info", label: "Note" },+ { value: "success", label: "Good" },+ { value: "warning", label: "Warning" },+ ],+ },+ title: { type: "text", label: "Title" },+ text: { type: "longtext", label: "Text" },+ },+ })}+ className={"flex shrink-0 gap-3 rounded-xl border px-4 py-3 " + look.className}+ >+ <Icon className={"mt-0.5 size-4 shrink-0 " + look.iconClassName} />+ <div className="flex min-w-0 flex-col gap-0.5">+ {title ? <div className="text-sm font-medium">{title}</div> : null}+ <div className="text-sm text-muted-foreground">{text}</div>+ </div>+ </div>+ );+}+`;++const INSIGHT = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import { Area, AreaChart, Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";+import {+ type BlockProps,+ BlockDescription,+ BlockState,+ CHART_COLORS,+ RetentionGrid,+ blockRoot,+ breakdownLabel,+ eventName,+ formatDay,+ formatNumber,+ rangeLabel,+ useBlockInsight,+ useCanvasFilters,+ ResultTable,+} from "./runtime";++type InsightProps = BlockProps & {+ shortId?: string;+ title?: string;+ followFilters?: boolean;+};++const LIST_DISPLAYS = new Set(["ActionsTable", "ActionsPie", "ActionsBarValue", "WorldMap"]);+const BAR_DISPLAYS = new Set(["ActionsBar", "ActionsStackedBar", "ActionsUnstackedBar"]);++function seriesName(row: any, index: number): string {+ if (row.breakdown_value !== undefined && row.breakdown_value !== null && row.breakdown_value !== "") return breakdownLabel(row.breakdown_value);+ return eventName(String(row.label ?? row.action?.name ?? "Series " + (index + 1)));+}++function TrendsBody({ rows, display }: { rows: any[]; display: string }) {+ if (display === "BoldNumber") {+ const total = Number(rows[0]?.aggregated_value ?? rows[0]?.count ?? Number.NaN);+ return <div className="py-4 text-4xl font-semibold tracking-tight tabular-nums">{formatNumber(total)}</div>;+ }+ if (LIST_DISPLAYS.has(display)) {+ const items = rows.map((row, index) => ({ label: seriesName(row, index), value: Number(row.aggregated_value ?? row.count ?? 0) }));+ const max = Math.max(1, ...items.map((item) => item.value));+ return (+ <div className="flex flex-col gap-1">+ {items.slice(0, 10).map((item, index) => (+ <div key={item.label + index} className="relative flex items-center justify-between gap-3 overflow-hidden rounded-md px-2 py-1.5 text-sm">+ <span className="absolute inset-y-0 left-0 bg-primary/10" style={{ width: (item.value / max) * 100 + "%" }} />+ <span className="relative min-w-0 truncate">{item.label}</span>+ <span className="relative tabular-nums">{formatNumber(item.value)}</span>+ </div>+ ))}+ </div>+ );+ }+ const days: string[] = rows[0]?.days ?? rows[0]?.labels ?? [];+ const data = days.map((day, index) => {+ const point: Record<string, number | string> = { day };+ rows.forEach((row, seriesIndex) => {+ point["s" + seriesIndex] = Number(row.data?.[index] ?? 0);+ });+ return point;+ });+ const Chart = BAR_DISPLAYS.has(display) ? BarChart : display === "ActionsAreaGraph" ? AreaChart : LineChart;+ return (+ <div className="h-56">+ <ResponsiveContainer width="100%" height="100%">+ <Chart data={data} margin={{ top: 4, right: 8, bottom: 0, left: -12 }}>+ <CartesianGrid stroke="currentColor" strokeOpacity={0.08} vertical={false} />+ <XAxis dataKey="day" tickFormatter={formatDay} tick={{ fontSize: 11 }} stroke="currentColor" strokeOpacity={0.4} minTickGap={24} />+ <YAxis tickFormatter={formatNumber} tick={{ fontSize: 11 }} stroke="currentColor" strokeOpacity={0.4} width={48} />+ <Tooltip labelFormatter={formatDay} formatter={(value: number) => formatNumber(value)} />+ {rows.map((row, index) => {+ const color = CHART_COLORS[index % CHART_COLORS.length];+ const key = "s" + index;+ if (Chart === BarChart) return <Bar key={key} dataKey={key} name={seriesName(row, index)} fill={color} radius={[3, 3, 0, 0]} isAnimationActive={false} />;+ if (Chart === AreaChart) return <Area key={key} dataKey={key} name={seriesName(row, index)} type="monotone" stroke={color} fill={color} fillOpacity={0.15} strokeWidth={2} isAnimationActive={false} />;+ return <Line key={key} dataKey={key} name={seriesName(row, index)} type="monotone" stroke={color} strokeWidth={2} dot={false} isAnimationActive={false} />;+ })}+ </Chart>+ </ResponsiveContainer>+ </div>+ );+}++function FunnelBody({ rows }: { rows: any[] }) {+ const steps: any[] = Array.isArray(rows[0]) ? rows[0] : rows;+ const first = Number(steps[0]?.count ?? 0);+ return (+ <div className="flex flex-col gap-2.5">+ {steps.map((step, index) => {+ const count = Number(step.count ?? 0);+ const share = first > 0 ? (count / first) * 100 : 0;+ return (+ <div key={index} className="flex flex-col gap-1">+ <div className="flex items-center justify-between text-sm">+ <span className="truncate">{index + 1}. {eventName(String(step.custom_name || step.name || "Step"))}</span>+ <span className="tabular-nums text-muted-foreground">{formatNumber(count)} · {Math.round(share)}%</span>+ </div>+ <div className="h-2 overflow-hidden rounded-full bg-muted">+ <div className="h-full rounded-full bg-primary" style={{ width: share + "%" }} />+ </div>+ </div>+ );+ })}+ </div>+ );+}++export function Insight(props: InsightProps) {+ const { shortId = "", title, followFilters = true } = props;+ const filters = useCanvasFilters();+ const result = useBlockInsight(shortId || null, followFilters ? filters.dateFrom : null);+ const meta = result.data?.insight;+ const rows = result.data?.results ?? [];+ const kind = meta?.kind ?? "";+ const name = title || meta?.name || "Saved insight";+ const body = () => {+ if (kind === "TrendsQuery" || kind === "StickinessQuery" || kind === "LifecycleQuery") return <TrendsBody rows={rows} display={meta?.display ?? ""} />;+ if (kind === "FunnelsQuery") return <FunnelBody rows={rows} />;+ if (kind === "RetentionQuery") return <RetentionGrid cohorts={rows} period="period" />;+ if (kind === "HogQLQuery" || kind === "DataVisualizationNode" || kind === "DataTableNode") return <ResultTable columns={result.data?.columns ?? []} rows={rows} />;+ return <div className="py-8 text-center text-sm text-muted-foreground">This insight type opens in PostHog. Ask the agent to rebuild it here.</div>;+ };+ return (+ <Card+ {...blockRoot("Insight", props, {+ params: {+ shortId: { type: "insight", label: "Insight" },+ title: { type: "text", label: "Title", description: "Leave empty to use the insight's own name." },+ followFilters: { type: "boolean", label: "Use canvas date range", description: "Turn off to keep the dates saved in the insight.", default: true },+ },+ })}+ className="group min-w-0 shrink-0"+ >+ <CardHeader className="flex flex-col gap-0.5">+ <CardTitle className="truncate">{name}</CardTitle>+ <BlockDescription text={props.description} />+ <div className="text-xs text-muted-foreground">Saved insight · {followFilters ? rangeLabel(filters.dateFrom) : "Its own dates"}</div>+ </CardHeader>+ <CardContent>+ {shortId ? (+ <BlockState loading={result.loading} error={result.error} empty={rows.length === 0} height={200}>+ {body()}+ </BlockState>+ ) : (+ <div className="flex h-40 items-center justify-center rounded-md border border-dashed border-border px-4 text-center text-sm text-muted-foreground">+ Pick a saved insight in the panel+ </div>+ )}+ </CardContent>+ </Card>+ );+}+`;++const RETENTION = `import { Card, CardContent, CardHeader, CardTitle } from "@posthog/quill";+import { type BlockProps, BlockDescription, BlockState, QueryButton, RetentionGrid, blockRoot, eventName, filterFields, scopeLabel, useBlockQuery, useCanvasFilters } from "./runtime";++type RetentionProps = BlockProps & {+ title?: string;+ startEvent?: string;+ returnEvent?: string;+ period?: "Day" | "Week" | "Month";+ intervals?: number;+ followFilters?: boolean;+};++export function Retention(props: RetentionProps) {+ const { title, startEvent = "$pageview", returnEvent = "$pageview", period = "Week", intervals = 8, followFilters = true, description } = props;+ const filters = useCanvasFilters();+ const query = {+ kind: "RetentionQuery",+ retentionFilter: {+ targetEntity: { id: startEvent, name: startEvent, type: "events" },+ returningEntity: { id: returnEvent, name: returnEvent, type: "events" },+ period,+ totalIntervals: Math.max(2, Math.min(16, intervals)),+ retentionType: "retention_first_time",+ },+ ...filterFields(filters, followFilters),+ };+ const result = useBlockQuery(query);+ const cohorts = result.data?.results ?? [];+ return (+ <Card+ {...blockRoot("Retention", props, {+ params: {+ title: { type: "text", label: "Title" },+ startEvent: { type: "event", label: "People who did" },+ returnEvent: { type: "event", label: "Came back to do" },+ period: { type: "select", label: "Period", options: ["Day", "Week", "Month"] },+ intervals: { type: "number", label: "Periods to show", min: 2, max: 16 },+ followFilters: { type: "boolean", label: "Use canvas filters", default: true },+ },+ })}+ className="group min-w-0 shrink-0"+ >+ <CardHeader className="flex flex-row items-start justify-between gap-2">+ <div className="flex min-w-0 flex-col gap-0.5">+ <CardTitle className="truncate">{title || "Retention"}</CardTitle>+ <BlockDescription text={props.description} />+ <div className="text-xs text-muted-foreground">+ {eventName(startEvent)} then {eventName(returnEvent)} · {scopeLabel(filters, followFilters)}+ </div>+ </div>+ <QueryButton query={query} hogql={result?.data?.hogql} />+ </CardHeader>+ <CardContent>+ <BlockState loading={result.loading} error={result.error} empty={cohorts.length === 0} height={200}>+ <RetentionGrid cohorts={cohorts} period={period} />+ </BlockState>+ </CardContent>+ </Card>+ );+}+`;++const COMPARE = `import { type BlockProps, blockRoot, setCanvasFilters, useCanvasFilters } from "./runtime";++export function Compare(props: BlockProps) {+ const filters = useCanvasFilters();+ const on = !!filters.compare;+ return (+ <button+ {...blockRoot("Compare", props)}+ type="button"+ aria-pressed={on}+ onClick={() => setCanvasFilters({ ...filters, compare: !on })}+ className={"inline-flex h-[34px] shrink-0 items-center gap-2 rounded-lg border px-3 text-sm shadow-xs transition-colors duration-150 " + (on ? "border-primary/40 bg-primary/10 text-primary" : "border-border bg-card text-foreground")}+ >+ <span className={"relative block h-3.5 w-6 shrink-0 rounded-full transition-colors duration-150 " + (on ? "bg-primary" : "bg-muted-foreground/30")}>+ <span+ className="absolute top-0.5 left-0.5 block size-2.5 rounded-full bg-white shadow-xs transition-transform duration-150"+ style={{ transform: on ? "translateX(10px)" : "translateX(0)", transitionTimingFunction: "cubic-bezier(0.23, 1, 0.32, 1)" }}+ />+ </span>+ Compare to previous+ </button>+ );+}+`;++const REFRESH = `import { useEffect, useRef, useState } from "react";+import { ArrowClockwiseIcon } from "./icons";+import { type BlockProps, blockRoot, refreshCanvasData, useLastUpdated } from "./runtime";++function sinceLabel(time: number | null, now: number): string {+ if (!time) return "Not loaded yet";+ const seconds = Math.max(0, Math.round((now - time) / 1000));+ if (seconds < 10) return "Updated just now";+ if (seconds < 60) return "Updated " + seconds + "s ago";+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return "Updated " + minutes + "m ago";+ return "Updated " + Math.round(minutes / 60) + "h ago";+}++export function Refresh(props: BlockProps) {+ const updated = useLastUpdated();+ const [now, setNow] = useState(() => Date.now());+ const icon = useRef<SVGSVGElement>(null);+ useEffect(() => {+ const timer = setInterval(() => setNow(Date.now()), 10000);+ return () => clearInterval(timer);+ }, []);+ const refresh = () => {+ refreshCanvasData();+ setNow(Date.now());+ if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ icon.current?.animate([{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }], { duration: 500, easing: "cubic-bezier(0.23, 1, 0.32, 1)" });+ }+ };+ return (+ <button+ {...blockRoot("Refresh", props)}+ type="button"+ onClick={refresh}+ className="inline-flex h-[34px] shrink-0 items-center gap-2 rounded-lg border border-border bg-card px-3 text-sm text-muted-foreground shadow-xs transition-colors duration-150 hover:text-foreground"+ >+ <ArrowClockwiseIcon ref={icon} className="size-3.5" />+ {sinceLabel(updated, now)}+ </button>+ );+}+`;++export const BLOCK_COMPONENT_SOURCES: Record<string, string> = {+ Metric: METRIC,+ Trend: TREND,+ TopList: TOP_LIST,+ Funnel: FUNNEL,+ SqlTable: SQL_TABLE,+ DateRange: DATE_RANGE,+ Interval: INTERVAL,+ PropertyFilter: PROPERTY_FILTER,+ Filters: FILTERS,+ Goal: GOAL,+ RecentEvents: RECENT_EVENTS,+ Callout: CALLOUT,+ Insight: INSIGHT,+ Retention: RETENTION,+ Compare: COMPARE,+ Refresh: REFRESH,+};diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/iconsSource.ts b/products/desktop/packages/core/src/canvas/blockLibrary/iconsSource.tsnew file mode 100644index 000000000000..93d42dab19f5--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/iconsSource.ts@@ -0,0 +1,24 @@+export const BLOCK_ICONS_SOURCE = `import type { SVGProps } from "react";++function icon(paths: string[]) {+ return function PhosphorIcon(props: SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 256 256" width="1em" height="1em" fill="currentColor" aria-hidden="true" {...props}>+ {paths.map((d) => (+ <path key={d} d={d} />+ ))}+ </svg>+ );+ };+}++export const CodeIcon = icon(["M69.12,94.15,28.5,128l40.62,33.85a8,8,0,1,1-10.24,12.29l-48-40a8,8,0,0,1,0-12.29l48-40a8,8,0,0,1,10.24,12.3Zm176,27.7-48-40a8,8,0,1,0-10.24,12.3L227.5,128l-40.62,33.85a8,8,0,1,0,10.24,12.29l48-40a8,8,0,0,0,0-12.29ZM162.73,32.48a8,8,0,0,0-10.25,4.79l-64,176a8,8,0,0,0,4.79,10.26A8.14,8.14,0,0,0,96,224a8,8,0,0,0,7.52-5.27l64-176A8,8,0,0,0,162.73,32.48Z"]);+export const FunnelIcon = icon(["M200,136a8,8,0,0,1-8,8H64a8,8,0,0,1,0-16H192A8,8,0,0,1,200,136Zm32-56H24a8,8,0,0,0,0,16H232a8,8,0,0,0,0-16Zm-80,96H104a8,8,0,0,0,0,16h48a8,8,0,0,0,0-16Z"]);+export const CaretLeftIcon = icon(["M165.66,202.34a8,8,0,0,1-11.32,11.32l-80-80a8,8,0,0,1,0-11.32l80-80a8,8,0,0,1,11.32,11.32L91.31,128Z"]);+export const PlusIcon = icon(["M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z"]);+export const XIcon = icon(["M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z"]);+export const InfoIcon = icon(["M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm16-40a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176ZM112,84a12,12,0,1,1,12,12A12,12,0,0,1,112,84Z"]);+export const CheckCircleIcon = icon(["M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z"]);+export const WarningCircleIcon = icon(["M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z"]);+export const ArrowClockwiseIcon = icon(["M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z"]);+`;diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/moveRange.test.ts b/products/desktop/packages/core/src/canvas/blockLibrary/moveRange.test.tsnew file mode 100644index 000000000000..acd02471e06b--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/moveRange.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { moveRange } from "./sourceEdits";++const FILE = "src/canvas.tsx";+const SOURCE = `<main>+ <section>+ <p>A</p>+ <p>B</p>+ </section>+</main>`;++function range(snippet: string) {+ const start = SOURCE.indexOf(snippet);+ return { file: FILE, start, end: start + snippet.length };+}++describe("moveRange", () => {+ it("moves a child out to just after its parent", () => {+ const section = SOURCE.slice(+ SOURCE.indexOf("<section>"),+ SOURCE.indexOf("</section>") + "</section>".length,+ );+ const moved = moveRange({ [FILE]: SOURCE }, range("<p>B</p>"), {+ ...range(section),+ place: "after",+ });+ expect(moved[FILE]?.replace(/\n\s*\n/g, "\n")).toBe(`<main>+ <section>+ <p>A</p>+ </section>+ <p>B</p>+</main>`);+ });+});diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/params.ts b/products/desktop/packages/core/src/canvas/blockLibrary/params.tsnew file mode 100644index 000000000000..4d9167a70afe--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/params.ts@@ -0,0 +1,100 @@+const PARAM_KINDS = [+ "text",+ "longtext",+ "number",+ "boolean",+ "select",+ "event",+ "events",+ "property",+ "insight",+ "color",+] as const;++export type ParamKind = (typeof PARAM_KINDS)[number];++export interface ParamOption {+ value: string;+ label: string;+}++export interface ParamSpec {+ kind: ParamKind;+ label: string;+ description: string | null;+ options: ParamOption[];+ min: number | null;+ max: number | null;+ step: number | null;+ fallback: unknown;+}++export type ParamSchema = Array<{ name: string; spec: ParamSpec }>;++const KINDS = new Set<string>(PARAM_KINDS);++export function componentLabel(name: string): string {+ const spaced = name+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/[_-]+/g, " ");+ return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();+}++function numberOrNull(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++function parseOptions(value: unknown): ParamOption[] {+ if (!Array.isArray(value)) return [];+ return value.flatMap((option): ParamOption[] => {+ if (typeof option === "string") return [{ value: option, label: option }];+ if (option && typeof option === "object" && "value" in option) {+ const record = option as { value: unknown; label?: unknown };+ const optionValue = String(record.value);+ return [+ {+ value: optionValue,+ label: typeof record.label === "string" ? record.label : optionValue,+ },+ ];+ }+ return [];+ });+}++function parseSpec(name: string, raw: unknown): ParamSpec | null {+ if (!raw || typeof raw !== "object") return null;+ const record = raw as Record<string, unknown>;+ const kind = (record.type ?? record.kind) as ParamKind;+ if (!KINDS.has(kind)) return null;+ return {+ kind,+ label:+ typeof record.label === "string" ? record.label : componentLabel(name),+ description:+ typeof record.description === "string" ? record.description : null,+ options: parseOptions(record.options),+ min: numberOrNull(record.min),+ max: numberOrNull(record.max),+ step: numberOrNull(record.step),+ fallback: record.default,+ };+}++export function parseParamSchema(raw: string | null): ParamSchema | null {+ if (!raw) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))+ return null;+ const schema = Object.entries(parsed as Record<string, unknown>).flatMap(+ ([name, spec]) => {+ const parsedSpec = parseSpec(name, spec);+ return parsedSpec ? [{ name, spec: parsedSpec }] : [];+ },+ );+ return schema.length > 0 ? schema : null;+ } catch {+ return null;+ }+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/placeableTarget.test.ts b/products/desktop/packages/core/src/canvas/blockLibrary/placeableTarget.test.tsnew file mode 100644index 000000000000..23deee4d4176--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/placeableTarget.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";+import type { DropPlace } from "./sourceEdits";+import { placeableTarget } from "./sourceEdits";++const FILE = "src/canvas.tsx";+const SOURCE = `function Game() {+ return (+ <div>+ <h2>Title</h2>+ </div>+ )+}++export default function Canvas() {+ return (+ <main>+ <Card title="A" />+ </main>+ )+}+`;+const ROOT = {+ file: FILE,+ start: SOURCE.indexOf("<main>"),+ end: SOURCE.indexOf("</main>") + "</main>".length,+};+const TITLE = {+ file: FILE,+ start: SOURCE.indexOf("<h2>"),+ end: SOURCE.indexOf("</h2>") + "</h2>".length,+};+const CARD = {+ file: FILE,+ start: SOURCE.indexOf("<Card"),+ end: SOURCE.indexOf("/>") + 2,+};++describe("placeableTarget", () => {+ it.each<[string, { start: number; end: number }, DropPlace, boolean]>([+ ["inside the root", ROOT, "inside", true],+ ["after the root", ROOT, "after", false],+ ["before the root", ROOT, "before", false],+ ["after a child of the root", CARD, "after", true],+ [+ "after an element of a component defined outside the root",+ TITLE,+ "after",+ true,+ ],+ [+ "at offsets that no longer point at JSX",+ { start: 0, end: 20 },+ "after",+ false,+ ],+ ])("%s", (_name, range, place, expected) => {+ expect(+ placeableTarget(+ { files: { [FILE]: SOURCE }, rootSource: ROOT },+ { file: FILE, ...range, place },+ ),+ ).toBe(expected);+ });+});diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/propertyNames.ts b/products/desktop/packages/core/src/canvas/blockLibrary/propertyNames.tsnew file mode 100644index 000000000000..585997d33b3a--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/propertyNames.ts@@ -0,0 +1,26 @@+const KNOWN_PROPERTIES: Record<string, string> = {+ $browser: "Browser",+ $browser_version: "Browser version",+ $os: "OS",+ $os_version: "OS version",+ $device_type: "Device type",+ $current_url: "URL",+ $pathname: "Path",+ $host: "Host",+ $referrer: "Referrer",+ $referring_domain: "Referring domain",+ $geoip_country_name: "Country",+ $geoip_city_name: "City",+ $screen_name: "Screen",+ $lib: "Library",+ utm_source: "UTM source",+ utm_medium: "UTM medium",+ utm_campaign: "UTM campaign",+};++export function propertyDisplayName(key: string): string {+ const known = KNOWN_PROPERTIES[key];+ if (known) return known;+ const text = key.replace(/^\$/, "").replace(/[_-]+/g, " ");+ return text.charAt(0).toUpperCase() + text.slice(1);+}diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/runtimeSource.ts b/products/desktop/packages/core/src/canvas/blockLibrary/runtimeSource.tsnew file mode 100644index 000000000000..c75995595259--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/runtimeSource.ts@@ -0,0 +1,641 @@+export const BLOCK_RUNTIME_SOURCE = `import { type ReactNode, useEffect, useRef, useState, useSyncExternalStore } from "react";+import { ph } from "@posthog/canvas-sdk";+import {+ Button,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@posthog/quill";+import { CodeIcon } from "./icons";++export type CanvasInterval = "hour" | "day" | "week" | "month";++export type FilterOperator = "exact" | "is_not" | "icontains" | "not_icontains" | "is_set" | "is_not_set" | "gt" | "lt";++export type CanvasPropertyFilter = {+ key: string;+ value: string;+ type: "event" | "person";+ operator?: FilterOperator;+};++export type CanvasFilters = {+ dateFrom: string;+ interval: CanvasInterval;+ properties: CanvasPropertyFilter[];+ compare?: boolean;+};++export type BlockProps = {+ blockId?: string;+ sql?: string;+ span?: "wide" | "full";+ description?: string;+ "data-ph-src"?: string;+};++const FILTERS_KEY = "blocks.filters";+const DEFAULT_FILTERS: CanvasFilters = { dateFrom: "-30d", interval: "day", properties: [] };+const listeners = new Set<() => void>();+let filters: CanvasFilters = DEFAULT_FILTERS;+let loaded = false;+let saveTimer: ReturnType<typeof setTimeout> | undefined;++function emit() {+ for (const listener of listeners) listener();+}++function loadFilters() {+ if (loaded) return;+ loaded = true;+ Promise.resolve(ph.state.get(FILTERS_KEY, { scope: "user" }))+ .then((stored: unknown) => {+ if (!stored || typeof stored !== "object") return;+ filters = { ...DEFAULT_FILTERS, ...(stored as Partial<CanvasFilters>) };+ emit();+ })+ .catch(() => undefined);+}++export function setCanvasFilters(next: CanvasFilters) {+ filters = next;+ emit();+ clearTimeout(saveTimer);+ saveTimer = setTimeout(() => {+ Promise.resolve(ph.state.set(FILTERS_KEY, next, { scope: "user" })).catch(() => undefined);+ }, 400);+}++export function useCanvasFilters(): CanvasFilters {+ loadFilters();+ return useSyncExternalStore(+ (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ () => filters,+ );+}++export type QueryResult = {+ columns: string[];+ results: any[];+ hogql?: string;+ insight?: { name: string | null; kind: string | null; display: string | null };+};++const MAX_PARALLEL_QUERIES = 6;+let runningQueries = 0;+const waitingQueries: Array<() => void> = [];++async function queued<T>(run: () => Promise<T>): Promise<T> {+ if (runningQueries >= MAX_PARALLEL_QUERIES) {+ await new Promise<void>((resolve) => waitingQueries.push(resolve));+ }+ runningQueries += 1;+ try {+ return await run();+ } finally {+ runningQueries -= 1;+ waitingQueries.shift()?.();+ }+}++async function withRetry(run: () => Promise<unknown>): Promise<QueryResult> {+ for (let attempt = 0; ; attempt += 1) {+ try {+ return (await queued(run)) as QueryResult;+ } catch (error) {+ const busy = String((error as Error)?.message ?? error).includes("runtime limits");+ if (!busy || attempt >= 3) throw error;+ await new Promise((resolve) => setTimeout(resolve, 300 * (attempt + 1)));+ }+ }+}++let refreshNonce = 0;+let lastUpdated: number | null = null;+const refreshListeners = new Set<() => void>();++function emitRefresh() {+ for (const listener of refreshListeners) listener();+}++function subscribeRefresh(listener: () => void) {+ refreshListeners.add(listener);+ return () => refreshListeners.delete(listener);+}++export function refreshCanvasData() {+ refreshNonce += 1;+ emitRefresh();+}++export function useRefreshNonce(): number {+ return useSyncExternalStore(subscribeRefresh, () => refreshNonce);+}++export function useLastUpdated(): number | null {+ return useSyncExternalStore(subscribeRefresh, () => lastUpdated);+}++function markUpdated() {+ lastUpdated = Date.now();+ emitRefresh();+}++const cache = new Map<string, Promise<QueryResult>>();+const resolved = new Map<string, QueryResult>();+const MAX_RESOLVED = 200;++function remember(key: string, data: QueryResult) {+ cache.delete(key);+ resolved.delete(key);+ resolved.set(key, data);+ while (resolved.size > MAX_RESOLVED) {+ const oldest = resolved.keys().next().value;+ if (oldest === undefined) break;+ resolved.delete(oldest);+ }+}++type RequestState = { data: QueryResult | null; error: string | null; loading: boolean };++function useCachedRequest(key: string | null, run: () => Promise<QueryResult>): RequestState {+ const [state, setState] = useState<RequestState>(() => ({+ data: key ? (resolved.get(key) ?? null) : null,+ error: null,+ loading: key !== null && !resolved.has(key),+ }));+ const latest = useRef(key);+ const runner = useRef(run);+ runner.current = run;+ useEffect(() => {+ latest.current = key;+ if (!key) return;+ const known = resolved.get(key);+ if (known) {+ setState({ data: known, error: null, loading: false });+ return;+ }+ setState((previous) => ({ ...previous, loading: true, error: null }));+ let request = cache.get(key);+ if (!request) {+ request = runner.current();+ cache.set(key, request);+ request.catch(() => cache.delete(key));+ }+ request+ .then((data) => {+ remember(key, data);+ markUpdated();+ if (latest.current === key) setState({ data, error: null, loading: false });+ })+ .catch((error: unknown) => {+ if (latest.current !== key) return;+ const message = error instanceof Error ? error.message : String(error);+ setState({ data: null, error: message, loading: false });+ });+ }, [key]);+ return state;+}++export function useBlockQuery(node: Record<string, unknown> | null, nonce = 0): RequestState {+ const refresh = useRefreshNonce();+ const key = node ? JSON.stringify(node) + "#" + nonce + "#" + refresh : null;+ return useCachedRequest(key, () => withRetry(() => Promise.resolve(ph.query(node as never))));+}++export function useBlockInsight(shortId: string | null, dateFrom: string | null): RequestState {+ const refresh = useRefreshNonce();+ const key = shortId ? "insight:" + shortId + "#" + (dateFrom ?? "saved") + "#" + refresh : null;+ return useCachedRequest(key, () =>+ withRetry(() => Promise.resolve(ph.loadInsight(shortId as string, dateFrom ? { dateRange: { date_from: dateFrom } } : {}))),+ );+}++type BlockRootOptions = {+ params?: Record<string, unknown>;+};++function serializableProps(props: Record<string, unknown>): Record<string, unknown> {+ const result: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(props)) {+ if (key === "children" || key === "data-ph-src" || typeof value === "function") continue;+ if (value !== null && typeof value === "object" && !Array.isArray(value)) continue;+ result[key] = value;+ }+ return result;+}++export function blockRoot(type: string, props: BlockProps & Record<string, unknown>, options: BlockRootOptions = {}) {+ return {+ "data-ph-block": type,+ "data-ph-block-id": props.blockId,+ "data-ph-props": JSON.stringify(serializableProps(props)),+ "data-ph-src": props["data-ph-src"],+ "data-ph-params": options.params ? JSON.stringify(options.params) : undefined,+ style: props.span === "full" ? { gridColumn: "1 / -1" } : props.span === "wide" ? { gridColumn: "span 2" } : undefined,+ };+}++export function sqlNode(sql: string, filters: CanvasFilters, followFilters = true) {+ return { kind: "HogQLQuery", query: sql, filters: filterFields(filters, followFilters) };+}++export function eventsNode(event: string, math = "total") {+ return { kind: "EventsNode", event, name: event, math };+}++export function filterFields(filters: CanvasFilters, followFilters = true) {+ return {+ dateRange: { date_from: filters.dateFrom },+ properties: followFilters+ ? filters.properties.map((property) => {+ const operator = property.operator ?? "exact";+ const presence = operator === "is_set" || operator === "is_not_set";+ return { key: property.key, value: presence ? operator : property.value, operator, type: property.type };+ })+ : [],+ };+}++export const CHART_COLORS = ["#1d4aff", "#f54e00", "#43827e", "#a621c8", "#f1a82c"];++const compact = new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 });+const whole = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });+const shortDate = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" });++export function formatNumber(value: number): string {+ if (!Number.isFinite(value)) return "0";+ return Math.abs(value) < 10000 ? whole.format(value) : compact.format(value);+}++export function formatPercent(value: number): string {+ return (value >= 10 ? Math.round(value) : value.toFixed(1)) + "%";+}++const RANGE_DAYS: Record<string, number> = { "-24h": 1, "-7d": 7, "-14d": 14, "-30d": 30, "-90d": 90, "-180d": 180, "-365d": 365 };+const DAY_MS = 86400000;++export function fillDateRows(xs: string[], rows: unknown[][], dateFrom: string): { xs: string[]; rows: unknown[][] } {+ const isDate = xs.length > 1 && xs.every((x) => /^[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(x));+ if (!isDate) return { xs, rows };+ const keys = xs.map((x) => x.slice(0, 10));+ const times = keys.map((key) => Date.parse(key + "T00:00:00Z"));+ const gaps = times.slice(1).map((time, index) => Math.round((time - times[index]) / DAY_MS)).filter((gap) => gap > 0);+ const step = Math.min(...gaps);+ if (step !== 1 && step !== 7) return { xs, rows };+ const byKey = new Map(keys.map((key, index) => [key, rows[index]]));+ const today = new Date();+ const end = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());+ const span = RANGE_DAYS[dateFrom];+ const start = span ? Math.min(times[0], end - span * DAY_MS) : times[0];+ const width = rows[0]?.length ?? 2;+ const filledXs: string[] = [];+ const filledRows: unknown[][] = [];+ const anchor = times[0];+ const first = anchor - Math.floor((anchor - start) / (step * DAY_MS)) * step * DAY_MS;+ for (let time = first; time <= end; time += step * DAY_MS) {+ const key = new Date(time).toISOString().slice(0, 10);+ filledXs.push(key);+ filledRows.push(byKey.get(key) ?? [key, ...Array.from({ length: width - 1 }, () => 0)]);+ }+ return { xs: filledXs, rows: filledRows };+}++export function previousSqlNode(sql: string, filters: CanvasFilters, followFilters = true) {+ const span = RANGE_DAYS[filters.dateFrom];+ if (!span || span < 7) return null;+ const node = sqlNode(sql, filters, followFilters);+ return { ...node, filters: { ...node.filters, dateRange: { date_from: "-" + span * 2 + "d", date_to: "-" + span + "d" } } };+}++export function previousRowsByDay(xs: string[], rows: unknown[][], dateFrom: string): Map<string, unknown[]> {+ const span = RANGE_DAYS[dateFrom] ?? 0;+ const times = xs.map((x) => Date.parse(x.slice(0, 10) + "T00:00:00Z"));+ const gaps = times.slice(1).map((time, index) => Math.round((time - times[index]) / DAY_MS)).filter((gap) => gap > 0);+ const step = gaps.length > 0 ? Math.min(...gaps) : 1;+ const shift = Math.round(span / step) * step * DAY_MS;+ const byDay = new Map<string, unknown[]>();+ times.forEach((time, index) => {+ if (!Number.isNaN(time)) byDay.set(new Date(time + shift).toISOString().slice(0, 10), rows[index]);+ });+ return byDay;+}++export function formatDay(value: string): string {+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? value : shortDate.format(date);+}++export const DATE_RANGES = [+ { value: "-7d", label: "7D" },+ { value: "-30d", label: "30D" },+ { value: "-90d", label: "90D" },+ { value: "-180d", label: "6M" },+ { value: "-365d", label: "12M" },+];++export function rangeLabel(value: string): string {+ const labels: Record<string, string> = {+ "-24h": "Last 24 hours",+ "-7d": "Last 7 days",+ "-14d": "Last 14 days",+ "-30d": "Last 30 days",+ "-90d": "Last 90 days",+ "-180d": "Last 6 months",+ "-365d": "Last 12 months",+ };+ return labels[value] ?? value;+}++export function breakdownLabel(value: unknown): string {+ if (value === null || value === undefined || value === "") return "Unknown";+ const text = String(value);+ if (text === "$$_posthog_breakdown_other_$$") return "Other";+ if (text === "$$_posthog_breakdown_null_$$") return "Unknown";+ if (text === "$direct") return "Direct";+ return text;+}++export const FILTER_OPERATORS: Array<{ value: FilterOperator; label: string }> = [+ { value: "exact", label: "is" },+ { value: "is_not", label: "is not" },+ { value: "icontains", label: "contains" },+ { value: "not_icontains", label: "does not contain" },+ { value: "is_set", label: "is set" },+ { value: "is_not_set", label: "is not set" },+];++export function propertyLabel(key: string): string {+ const known: Record<string, string> = {+ $browser: "Browser",+ $os: "OS",+ $device_type: "Device type",+ $current_url: "URL",+ $pathname: "Path",+ $referring_domain: "Referring domain",+ $geoip_country_name: "Country",+ $geoip_city_name: "City",+ };+ if (known[key]) return known[key];+ const text = key.replace(/^\\$/, "").replace(/[_-]+/g, " ");+ return text.charAt(0).toUpperCase() + text.slice(1);+}++export function filterLabel(filter: CanvasPropertyFilter): string {+ const operator = filter.operator ?? "exact";+ const verb = FILTER_OPERATORS.find((option) => option.value === operator)?.label ?? "is";+ const subject = (filter.type === "person" ? "Person " : "") + propertyLabel(filter.key);+ const presence = operator === "is_set" || operator === "is_not_set";+ return presence ? subject + " " + verb : subject + " " + verb + " " + filter.value;+}++export function scopeLabel(filters: CanvasFilters, followFilters = true): string {+ const values = followFilters+ ? filters.properties.map((property) => ((property.operator ?? "exact") === "exact" ? String(property.value) : filterLabel(property)))+ : [];+ return [rangeLabel(filters.dateFrom), ...values].join(" · ");+}++export function eventName(event: string): string {+ const known: Record<string, string> = { $pageview: "Pageview", $autocapture: "Autocapture", $pageleave: "Pageleave", $web_vitals: "Web vitals", $feature_flag_called: "Feature flag called", $groupidentify: "Group identify", $set: "Set person properties" };+ if (known[event]) return known[event];+ if (!event.startsWith("$")) return event;+ const words = event.slice(1).split("_").join(" ");+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function changeTone(value: number): string {+ if (Math.abs(value) < 0.05) return "bg-muted text-muted-foreground";+ return value > 0 ? "bg-emerald-500/10 text-emerald-600" : "bg-red-500/10 text-red-600";+}++export function ChangeBadge({ value }: { value: number }) {+ return (+ <span className={"rounded-full px-1.5 py-0.5 text-xs font-medium tabular-nums " + changeTone(value)} title="Change from the previous period">+ {(value > 0 ? "+" : "") + formatPercent(value)}+ </span>+ );+}++const MATH_LABELS: Record<string, string> = {+ total: "Count of",+ dau: "Unique users who did",+ weekly_active: "Weekly active users who did",+ monthly_active: "Monthly active users who did",+};++type QueryNode = {+ kind?: string;+ query?: string;+ series?: Array<{ event?: string; math?: string }>;+ interval?: string;+ dateRange?: { date_from?: string };+ compareFilter?: { compare?: boolean };+ breakdownFilter?: { breakdown?: string };+ trendsFilter?: { display?: string };+ properties?: Array<{ key?: string; value?: unknown; type?: string; operator?: string }>;+};++export function summarizeQuery(query: unknown): string {+ const node = (query ?? {}) as QueryNode;+ if (node.kind === "HogQLQuery") return "A custom HogQL query.";+ const series = (node.series ?? [])+ .map((item) => (MATH_LABELS[item.math ?? "total"] ?? "Count of") + " " + eventName(item.event ?? "events"))+ .join(" and ");+ const parts = [series || "Events"];+ if (node.breakdownFilter?.breakdown) parts.push("broken down by " + node.breakdownFilter.breakdown);+ const single = node.trendsFilter?.display === "BoldNumber" || node.trendsFilter?.display === "ActionsTable";+ if (!single && node.interval) parts.push("per " + node.interval);+ if (node.dateRange?.date_from) parts.push(rangeLabel(node.dateRange.date_from).toLowerCase());+ if (node.compareFilter?.compare) parts.push("compared with the previous period");+ const filters = (node.properties ?? []).map((item) =>+ filterLabel({+ key: String(item.key),+ value: String(item.value),+ type: item.type === "person" ? "person" : "event",+ operator: item.operator as FilterOperator | undefined,+ }),+ );+ if (filters.length > 0) parts.push("where " + filters.join(" and "));+ return parts.join(", ") + ".";+}++export function QueryButton({ query, hogql, className = "" }: { query: unknown; hogql?: string; className?: string }) {+ const node = (query ?? {}) as QueryNode;+ const inline = node.kind === "HogQLQuery" && node.query ? node.query : null;+ const text = inline ?? hogql ?? JSON.stringify(query, null, 2);+ const isSql = inline !== null || !!hogql;+ return (+ <span className={className + " opacity-0 transition-opacity group-hover:opacity-100"}>+ <Dialog>+ <DialogTrigger+ render={+ <Button variant="outline" size="sm" aria-label="Show query">+ <CodeIcon className="size-3.5" />+ </Button>+ }+ />+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>Query behind this block</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-3 px-4 pb-4">+ <p className="text-sm">{summarizeQuery(query)}</p>+ <pre className="max-h-[50vh] overflow-auto rounded-md bg-muted p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap break-words">{text}</pre>+ <p className="text-xs text-muted-foreground">+ {isSql ? "This HogQL runs with your access each time the canvas loads." : "The query definition. It runs with your access each time the canvas loads."}+ </p>+ </div>+ </DialogContent>+ </Dialog>+ </span>+ );+}++function tableCell(value: unknown): string {+ if (value === null || value === undefined) return "null";+ if (typeof value === "number") return formatNumber(value);+ return String(value);+}++export function ResultTable({ columns, rows }: { columns: string[]; rows: unknown[] }) {+ return (+ <div className="max-h-80 overflow-auto">+ <table className="w-full text-sm">+ <thead>+ <tr>+ {columns.map((column) => (+ <th key={column} className="border-b border-border py-1.5 pr-3 text-left text-xs font-normal text-muted-foreground">{column}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.slice(0, 100).map((row, rowIndex) => {+ const cells = Array.isArray(row) ? row : [row];+ return (+ <tr key={rowIndex} className="border-b border-border last:border-b-0">+ {columns.map((column, columnIndex) => (+ <td key={column} className="max-w-60 truncate py-1.5 pr-3 tabular-nums">{tableCell(cells[columnIndex])}</td>+ ))}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++function isPreviewDenial(error: string): boolean {+ return error.includes("capability manifest is unavailable") || error.includes("preview has no data access");+}++export function BlockState({ loading, error, empty, height = 160, children }: {+ loading: boolean;+ error: string | null;+ empty: boolean;+ height?: number;+ children: ReactNode;+}) {+ if (error && isPreviewDenial(error)) {+ return <div className="rounded-md bg-muted/60" style={{ height }} />;+ }+ if (error) {+ return (+ <div className="flex flex-col items-center justify-center gap-1 rounded-md bg-muted/40 px-4 text-center" style={{ minHeight: height }}>+ <span className="text-sm text-foreground">Couldn't load this data</span>+ <span className="line-clamp-2 text-xs text-muted-foreground">{error}</span>+ </div>+ );+ }+ if (loading && empty) {+ return <div className="animate-pulse rounded-md bg-muted/60" style={{ height }} />;+ }+ if (empty) {+ return (+ <div className="flex items-center justify-center rounded-md bg-muted/40 text-sm text-muted-foreground" style={{ minHeight: height }}>+ No data for this range+ </div>+ );+ }+ return <div className={loading ? "opacity-60 transition-opacity" : "transition-opacity"}>{children}</div>;+}++export type RetentionCohort = { date?: string; label?: string; values?: Array<{ count?: number }> };++export function RetentionGrid({ cohorts, period }: { cohorts: RetentionCohort[]; period: string }) {+ const columns = Math.max(0, ...cohorts.map((cohort) => cohort.values?.length ?? 0));+ const unit = period.toLowerCase();+ return (+ <div className="overflow-x-auto">+ <table className="w-full border-separate border-spacing-0.5 text-xs">+ <thead>+ <tr className="text-muted-foreground">+ <th colSpan={2} />+ <th colSpan={columns} className="pb-0.5 text-left font-normal">{unit.charAt(0).toUpperCase() + unit.slice(1)}s later</th>+ </tr>+ <tr className="text-muted-foreground">+ <th className="py-1 pr-3 text-left font-normal">Cohort</th>+ <th className="py-1 pr-3 text-right font-normal">People</th>+ {Array.from({ length: columns }, (_, index) => (+ <th key={index} className="min-w-9 py-1 text-center font-normal tabular-nums">+ {index}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {cohorts.map((cohort, row) => {+ const size = Number(cohort.values?.[0]?.count ?? 0);+ return (+ <tr key={(cohort.date ?? cohort.label ?? "") + row}>+ <td className="whitespace-nowrap py-1 pr-3 text-muted-foreground">{cohort.date ? formatDay(cohort.date) : cohort.label}</td>+ <td className="py-1 pr-3 text-right tabular-nums">{formatNumber(size)}</td>+ {Array.from({ length: columns }, (_, index) => {+ const value = cohort.values?.[index];+ if (!value) return <td key={index} />;+ if (size === 0) return <td key={index} className="rounded bg-muted/40 py-1.5 text-center text-muted-foreground">–</td>;+ const share = size > 0 ? Number(value.count ?? 0) / size : 0;+ return (+ <td+ key={index}+ className="rounded py-1.5 text-center tabular-nums"+ style={{ background: "color-mix(in srgb, var(--primary) " + Math.round(8 + share * 72) + "%, transparent)", color: share > 0.55 ? "white" : undefined }}+ >+ {Math.round(share * 100)}%+ </td>+ );+ })}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++export function BlockDescription({ text }: { text?: string }) {+ if (!text) return null;+ return <p className="text-xs text-muted-foreground">{text}</p>;+}++export function formatValue(value: number, format = "number"): string {+ if (!Number.isFinite(value)) return "–";+ if (format === "percent") return (Math.abs(value) >= 10 ? value.toFixed(0) : value.toFixed(1)) + "%";+ if (format === "currency") return "$" + formatNumber(value);+ if (format === "duration") {+ const seconds = Math.round(value);+ if (seconds < 60) return seconds + "s";+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return minutes + "m " + (seconds % 60) + "s";+ return Math.floor(minutes / 60) + "h " + (minutes % 60) + "m";+ }+ return formatNumber(value);+}+`;diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.test.ts b/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.test.tsnew file mode 100644index 000000000000..3364e78994a4--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import { setJsxAttributes } from "./sourceEdits";++const FILE = "src/canvas.tsx";++function edit(+ source: string,+ values: Record<string, string | number | boolean | string[] | undefined>,+): string {+ const start = source.indexOf("<Panel");+ const end = source.lastIndexOf(">") + 1;+ return (+ setJsxAttributes({ [FILE]: source }, { file: FILE, start, end }, values)[+ FILE+ ] ?? ""+ );+}++describe("setJsxAttributes", () => {+ it.each([+ {+ name: "replaces a string prop and keeps expression props",+ source:+ '<Panel title="Old" range={dateRange} onPick={(v) => set({ v })} />',+ values: { title: "New" },+ expected:+ '<Panel title="New" range={dateRange} onPick={(v) => set({ v })} />',+ },+ {+ name: "adds a prop to a self-closing tag",+ source: "<Panel {...shared} />",+ values: { limit: 5 },+ expected: "<Panel {...shared} limit={5} />",+ },+ {+ name: "removes a prop",+ source: '<Panel title="A" breakdown="$browser" />',+ values: { breakdown: undefined },+ expected: '<Panel title="A" />',+ },+ {+ name: "edits only the opening tag of an element with children",+ source: '<Panel title="A">\n <Child title="B" />\n</Panel>',+ values: { title: "C", steps: ["a", "b"] },+ expected:+ '<Panel title="C" steps={["a","b"]}>\n <Child title="B" />\n</Panel>',+ },+ {+ name: "keeps a string with quotes valid",+ source: '<Panel title="A" />',+ values: { title: 'Say "hi"' },+ expected: '<Panel title={"Say \\"hi\\""} />',+ },+ ])("$name", ({ source, values, expected }) => {+ expect(edit(source, values)).toBe(expected);+ });+});diff --git a/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.ts b/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.tsnew file mode 100644index 000000000000..6486e0ba1b4a--- /dev/null+++ b/products/desktop/packages/core/src/canvas/blockLibrary/sourceEdits.ts@@ -0,0 +1,549 @@+import {+ BLOCK_DEFINITIONS,+ BLOCK_ICONS_PATH,+ BLOCK_RUNTIME_PATH,+ type BlockDefinition,+ type BlockGroup,+ type BlockPropsRecord,+ type BlockPropValue,+ componentPath,+} from "./blockDefinitions";+import { withLibraryFile } from "./blockLibrarySync";+import { BLOCK_COMPONENT_SOURCES } from "./componentSources";++export type SourceFiles = Record<string, string>;++export interface SourceRange {+ file: string;+ start: number;+ end: number;+}++export type DropPlace = "before" | "after" | "left" | "right" | "inside";++export interface GridGrowth extends SourceRange {+ columns: number;+}++export interface SourceDropTarget extends SourceRange {+ place: DropPlace;+ grow?: GridGrowth;+}++const MAX_GRID_COLUMNS = 4;++const ROW_CLASS = "grid gap-4 sm:grid-cols-2";++export function newBlockId(): string {+ return `b-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;+}++function jsxString(value: string): string {+ if (/["{}<>\n\\]/.test(value)) return `{${JSON.stringify(value)}}`;+ return `"${value}"`;+}++function jsxAttribute(name: string, value: BlockPropValue): string | null {+ if (value === undefined || value === "") return null;+ if (value === true) return name;+ if (typeof value === "string") return `${name}=${jsxString(value)}`;+ return `${name}={${JSON.stringify(value)}}`;+}++export function componentJsx(+ component: string,+ blockId: string,+ props: BlockPropsRecord,+): string {+ const attributes = [+ `blockId="${blockId}"`,+ ...Object.entries(props)+ .filter(([name]) => name !== "blockId")+ .map(([name, value]) => jsxAttribute(name, value)),+ ].filter((attribute): attribute is string => attribute !== null);+ return `<${component} ${attributes.join(" ")} />`;+}++export function blockJsx(+ definition: BlockDefinition,+ blockId: string,+ props: BlockPropsRecord,+): string {+ if (definition.component) {+ return componentJsx(definition.component, blockId, props);+ }+ return definition.element ?? "";+}++function lineStart(source: string, offset: number): number {+ return source.lastIndexOf("\n", offset - 1) + 1;+}++function indentAt(source: string, offset: number): string {+ const start = lineStart(source, offset);+ const match = /^[ \t]*/.exec(source.slice(start, offset));+ return match ? match[0] : "";+}++function relativeImport(fromFile: string, toFile: string): string {+ const from = fromFile.split("/").slice(0, -1);+ const to = toFile.replace(/\.(tsx|ts|jsx|js)$/, "").split("/");+ let shared = 0;+ while (shared < from.length && from[shared] === to[shared]) shared += 1;+ const up = from.length - shared;+ const rest = to.slice(shared).join("/");+ return up === 0 ? `./${rest}` : `${"../".repeat(up)}${rest}`;+}++function importEnd(source: string): number {+ const pattern =+ /^import[\s\S]*?from\s+["'][^"']+["'];?[^\n]*\n|^import\s+["'][^"']+["'];?[^\n]*\n/gm;+ let end = 0;+ for (const match of source.matchAll(pattern)) {+ const before = source.slice(0, match.index ?? 0);+ const onlyImports = before.replace(pattern, "").trim().length === 0;+ if (!onlyImports) break;+ end = (match.index ?? 0) + match[0].length;+ }+ return end;+}++export function withImport(+ source: string,+ name: string,+ specifier: string,+): string {+ const existing = new RegExp(+ `import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*["']${specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']`,+ );+ if (existing.test(source)) return source;+ const at = importEnd(source);+ const line = `import { ${name} } from "${specifier}";\n`;+ return source.slice(0, at) + line + source.slice(at);+}++function withBlockFiles(files: SourceFiles, component: string): SourceFiles {+ const shared = withLibraryFile(+ withLibraryFile(files, BLOCK_RUNTIME_PATH),+ BLOCK_ICONS_PATH,+ );+ return withLibraryFile(shared, componentPath(component));+}++function withComponentImport(+ files: SourceFiles,+ file: string,+ component: string,+): SourceFiles {+ const source = files[file];+ if (source === undefined) return files;+ const specifier = relativeImport(file, componentPath(component));+ return { ...files, [file]: withImport(source, component, specifier) };+}++function insertInside(+ source: string,+ target: SourceDropTarget,+ snippet: string,+): string {+ const element = source.slice(target.start, target.end);+ const close = element.lastIndexOf("</");+ if (close === -1)+ return insertText(source, { ...target, place: "after" }, snippet);+ const at = target.start + close;+ const outer = indentAt(source, target.start);+ const closeLine = lineStart(source, at);+ if (source.slice(closeLine, at).trim().length === 0) {+ return `${source.slice(0, closeLine)}${outer} ${snippet}\n${source.slice(closeLine)}`;+ }+ return `${source.slice(0, at)}\n${outer} ${snippet}\n${outer}${source.slice(at)}`;+}++function isExpressionRoot(source: string, start: number): boolean {+ const before = source.slice(Math.max(0, start - 200), start).trimEnd();+ return (+ /(?:\breturn|=>|\?|:|&&|\|\|)\s*\(?$/.test(before) &&+ !/[{,]\s*$/.test(before)+ );+}++function wrapPair(+ source: string,+ target: SourceDropTarget,+ snippet: string,+ open: string,+ close: string,+): string {+ const indent = indentAt(source, target.start);+ const inner = `${indent} `;+ const existing = source+ .slice(target.start, target.end)+ .replace(/\n/g, "\n ");+ const snippetFirst = target.place === "before" || target.place === "left";+ const children = snippetFirst+ ? `${inner}${snippet}\n${inner}${existing}`+ : `${inner}${existing}\n${inner}${snippet}`;+ return `${source.slice(0, target.start)}${open}\n${children}\n${indent}${close}${source.slice(target.end)}`;+}++function insertText(+ source: string,+ target: SourceDropTarget,+ snippet: string,+): string {+ if (target.place === "inside") return insertInside(source, target, snippet);+ const rootPosition =+ (target.place === "before" || target.place === "after") &&+ isExpressionRoot(source, target.start);+ if (rootPosition) return wrapPair(source, target, snippet, "<>", "</>");+ const indent = indentAt(source, target.start);+ if (target.place === "before") {+ const at = lineStart(source, target.start);+ const leading =+ source.slice(at, target.start).trim().length === 0 ? at : target.start;+ return `${source.slice(0, leading)}${indent}${snippet}\n${source.slice(leading)}`;+ }+ if (target.place === "after") {+ return `${source.slice(0, target.end)}\n${indent}${snippet}${source.slice(target.end)}`;+ }+ return wrapPair(+ source,+ target,+ snippet,+ `<div className="${ROW_CLASS}">`,+ "</div>",+ );+}++export function insertBlock(+ files: SourceFiles,+ target: SourceDropTarget,+ definition: BlockDefinition,+ props: BlockPropsRecord,+ blockId: string,+): SourceFiles {+ const source = files[target.file];+ if (source === undefined) return files;+ const snippet = blockJsx(definition, blockId, props);+ let next: SourceFiles = {+ ...files,+ [target.file]: insertText(source, target, snippet),+ };+ if (target.grow) next = growGrid(next, target.grow);+ if (definition.component) {+ next = withBlockFiles(next, definition.component);+ next = withComponentImport(next, target.file, definition.component);+ }+ return next;+}++function growGrid(files: SourceFiles, grid: GridGrowth): SourceFiles {+ const source = files[grid.file];+ if (source === undefined || grid.columns >= MAX_GRID_COLUMNS) return files;+ const tagEnd = source.indexOf(">", grid.start);+ if (tagEnd === -1 || tagEnd > grid.end) return files;+ const openingTag = source.slice(grid.start, tagEnd);+ const pattern = new RegExp(+ `((?:^|[\\s"'\`])(?:[a-z0-9@]+:)*grid-cols-)${grid.columns}(?![0-9])`,+ "g",+ );+ if (!pattern.test(openingTag)) return files;+ const grown = openingTag.replace(pattern, `$1${grid.columns + 1}`);+ return {+ ...files,+ [grid.file]: source.slice(0, grid.start) + grown + source.slice(tagEnd),+ };+}++function removeText(source: string, range: SourceRange): string {+ const start = lineStart(source, range.start);+ const ownLine = source.slice(start, range.start).trim().length === 0;+ const lineEnd = source.indexOf("\n", range.end);+ const restOfLine = source.slice(+ range.end,+ lineEnd === -1 ? source.length : lineEnd,+ );+ if (ownLine && restOfLine.trim().length === 0) {+ return (+ source.slice(0, start) ++ source.slice(lineEnd === -1 ? source.length : lineEnd + 1)+ );+ }+ return source.slice(0, range.start) + source.slice(range.end);+}++export function removeRange(+ files: SourceFiles,+ range: SourceRange,+): SourceFiles {+ const source = files[range.file];+ if (source === undefined) return files;+ return { ...files, [range.file]: removeText(source, range) };+}++export function rangeText(files: SourceFiles, range: SourceRange): string {+ return files[range.file]?.slice(range.start, range.end) ?? "";+}++export function replaceRange(+ files: SourceFiles,+ range: SourceRange,+ text: string,+): SourceFiles {+ const source = files[range.file];+ if (source === undefined) return files;+ return {+ ...files,+ [range.file]: source.slice(0, range.start) + text + source.slice(range.end),+ };+}++function shiftTarget(+ target: SourceDropTarget,+ removed: SourceRange,+ removedLength: number,+): SourceDropTarget {+ if (target.file !== removed.file) return target;+ if (target.start >= removed.end) {+ return {+ ...target,+ start: target.start - removedLength,+ end: target.end - removedLength,+ };+ }+ if (target.start <= removed.start && target.end >= removed.end) {+ return { ...target, end: target.end - removedLength };+ }+ return target;+}++export function moveRange(+ files: SourceFiles,+ range: SourceRange,+ target: SourceDropTarget,+): SourceFiles {+ const text = rangeText(files, range);+ const inside =+ target.file === range.file &&+ target.start >= range.start &&+ target.end <= range.end;+ if (!text || inside) return files;+ const before = files[range.file] ?? "";+ const afterRemoval = removeRange(files, range);+ const removedLength = before.length - (afterRemoval[range.file] ?? "").length;+ const shifted = shiftTarget(target, range, removedLength);+ const source = afterRemoval[shifted.file];+ if (source === undefined) return files;+ let next: SourceFiles = {+ ...afterRemoval,+ [shifted.file]: insertText(source, shifted, text.trim()),+ };+ const component = /^<([A-Z][A-Za-z0-9]*)/.exec(text.trim())?.[1];+ if (+ component &&+ shifted.file !== range.file &&+ BLOCK_COMPONENT_SOURCES[component]+ ) {+ next = withComponentImport(next, shifted.file, component);+ }+ return next;+}++export function duplicateRange(+ files: SourceFiles,+ range: SourceRange,+ blockId: string,+): SourceFiles {+ const text = rangeText(files, range).replace(+ /blockId="[^"]*"/,+ `blockId="${blockId}"`,+ );+ const source = files[range.file];+ if (!text || source === undefined) return files;+ return {+ ...files,+ [range.file]: insertText(source, { ...range, place: "after" }, text),+ };+}++interface JsxAttribute {+ name: string | null;+ start: number;+ end: number;+}++interface OpeningTag {+ attributes: JsxAttribute[];+ insertAt: number;+}++function skipQuoted(source: string, from: number, quote: string): number {+ let index = from + 1;+ while (index < source.length && source[index] !== quote) {+ if (source[index] === "\\") index += 1;+ index += 1;+ }+ return index + 1;+}++function skipBraces(source: string, from: number): number {+ let depth = 0;+ let index = from;+ while (index < source.length) {+ const char = source[index];+ if (char === '"' || char === "'" || char === "`") {+ index = skipQuoted(source, index, char);+ continue;+ }+ if (char === "{") depth += 1;+ if (char === "}") {+ depth -= 1;+ if (depth === 0) return index + 1;+ }+ index += 1;+ }+ return index;+}++function scanOpeningTag(source: string, start: number): OpeningTag | null {+ const head = /^<[A-Za-z][\w.]*/.exec(source.slice(start));+ if (!head) return null;+ const attributes: JsxAttribute[] = [];+ let index = start + head[0].length;+ while (index < source.length) {+ while (/\s/.test(source[index] ?? "")) index += 1;+ const char = source[index];+ if (char === ">") return { attributes, insertAt: index };+ if (char === "/" && source[index + 1] === ">")+ return { attributes, insertAt: index };+ if (char === "{") {+ const end = skipBraces(source, index);+ attributes.push({ name: null, start: index, end });+ index = end;+ continue;+ }+ const name = /^[A-Za-z_$][\w:.-]*/.exec(source.slice(index));+ if (!name) return null;+ const attributeStart = index;+ index += name[0].length;+ if (source[index] === "=") {+ index += 1;+ const value = source[index];+ if (value === '"' || value === "'")+ index = skipQuoted(source, index, value);+ else if (value === "{") index = skipBraces(source, index);+ else return null;+ }+ attributes.push({ name: name[0], start: attributeStart, end: index });+ }+ return null;+}++export function setJsxAttributes(+ files: SourceFiles,+ range: SourceRange,+ values: BlockPropsRecord,+): SourceFiles {+ const source = files[range.file];+ if (source === undefined) return files;+ const tag = scanOpeningTag(source, range.start);+ if (!tag || tag.insertAt > range.end) return files;+ const edits: Array<{ start: number; end: number; text: string }> = [];+ const appended: string[] = [];+ for (const [name, value] of Object.entries(values)) {+ const existing = tag.attributes.find(+ (attribute) => attribute.name === name,+ );+ if (value === undefined) {+ if (!existing) continue;+ let start = existing.start;+ while (start > 0 && /[ \t]/.test(source[start - 1] ?? "")) start -= 1;+ edits.push({ start, end: existing.end, text: "" });+ continue;+ }+ const text = jsxAttribute(name, value) ?? `${name}=""`;+ if (existing)+ edits.push({ start: existing.start, end: existing.end, text });+ else appended.push(text);+ }+ if (appended.length > 0) {+ const before = source[tag.insertAt - 1] ?? "";+ const lead = /\s/.test(before) ? "" : " ";+ const tail = source[tag.insertAt] === "/" ? " " : "";+ edits.push({+ start: tag.insertAt,+ end: tag.insertAt,+ text: `${lead}${appended.join(" ")}${tail}`,+ });+ }+ if (edits.length === 0) return files;+ let next = source;+ for (const edit of edits.sort((a, b) => b.start - a.start)) {+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);+ }+ return { ...files, [range.file]: next };+}++export function updateBlockProps(+ files: SourceFiles,+ range: SourceRange,+ previous: Record<string, unknown>,+ props: BlockPropsRecord,+): SourceFiles {+ const values: BlockPropsRecord = { ...props };+ for (const name of Object.keys(previous)) {+ if (name !== "blockId" && !(name in props)) values[name] = undefined;+ }+ return setJsxAttributes(files, range, values);+}++export function replaceElementText(+ files: SourceFiles,+ range: SourceRange,+ text: string,+): SourceFiles {+ const current = rangeText(files, range);+ const match = /^(<[a-z][a-z0-9]*\b[^>]*>)([^<{}]*)(<\/[a-z][a-z0-9]*>)$/.exec(+ current,+ );+ if (!match) return files;+ const safe = text.replace(/[{}<>]/g, "");+ return replaceRange(files, range, `${match[1]}${safe}${match[3]}`);+}++export function blockRanges(+ files: SourceFiles,+ file: string,+ group: BlockGroup,+): SourceRange[] {+ const source = files[file];+ const components = BLOCK_DEFINITIONS.flatMap((definition) =>+ definition.group === group && definition.component+ ? [definition.component]+ : [],+ );+ if (source === undefined || components.length === 0) return [];+ const element = new RegExp(`<(?:${components.join("|")})\\b[^>]*/>`, "g");+ return Array.from(source.matchAll(element), (match) => ({+ file,+ start: match.index,+ end: match.index + match[0].length,+ }));+}++export function isJsxRange(files: SourceFiles, range: SourceRange): boolean {+ const text = rangeText(files, range);+ return text.startsWith("<") && text.endsWith(">");+}++export function placeableTarget(+ entry: { files: SourceFiles; rootSource: SourceRange | null },+ target: SourceDropTarget,+): boolean {+ if (!isJsxRange(entry.files, target)) return false;+ const root = entry.rootSource;+ if (!root || root.file !== target.file) return true;+ if (target.start === root.start && target.end === root.end)+ return target.place === "inside";+ return !(target.start <= root.start && target.end >= root.end);+}diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts b/products/desktop/packages/core/src/canvas/canvasDataService.test.tsindex 74de573fa3e2..22450594aab8 100644--- a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts+++ b/products/desktop/packages/core/src/canvas/canvasDataService.test.ts@@ -27,6 +27,9 @@ function makeService() {function insight(partial: Partial<InsightFetchResult>): InsightFetchResult {return {shortId: "abc123",+ name: null,+ sourceKind: "TrendsQuery",+ display: null,queryKind: "TrendsQuery",columns: [],results: [],diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.ts b/products/desktop/packages/core/src/canvas/canvasDataService.tsindex 987bd8791a7c..a2d46038d113 100644--- a/products/desktop/packages/core/src/canvas/canvasDataService.ts+++ b/products/desktop/packages/core/src/canvas/canvasDataService.ts@@ -13,10 +13,12 @@ import type {CanvasDataQueryInput,CanvasDataResult,CanvasLoadInsightInput,+ SavedInsight,} from "./freeformSchemas";import {fetchCurrentUser,fetchInsightByShortId,+ listSavedInsights,readCachedQuery,runQuery,} from "./posthogApi";@@ -124,10 +126,16 @@ export class CanvasDataService {});}}- const { columns, results } = await runQuery(this.authService, node, {- refresh: "blocking",+ const { columns, results, hogql } = await runQuery(+ this.authService,+ node,+ { refresh: "blocking" },+ );+ return boundedResult({+ columns,+ results: shaped(results),+ ...(hogql ? { hogql } : {}),});- return boundedResult({ columns, results: shaped(results) });} catch (err) {this.log.warn("Canvas query failed", {error: err instanceof Error ? err.message : String(err),@@ -156,6 +164,10 @@ export class CanvasDataService {);}+ listSavedInsights(search?: string): Promise<SavedInsight[]> {+ return listSavedInsights(this.authService, search);+ }+async loadInsight(input: CanvasLoadInsightInput): Promise<CanvasDataResult> {try {const insight = await fetchInsightByShortId(@@ -172,6 +184,11 @@ export class CanvasDataService {return boundedResult({columns: insight.columns,results: isRows ? normalizeHogQLRows(insight.results) : insight.results,+ insight: {+ name: insight.name,+ kind: insight.sourceKind,+ display: insight.display,+ },});} catch (err) {this.log.warn("Canvas loadInsight failed", {diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.tsindex c9f6689019a4..6f038aa0b701 100644--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts@@ -293,3 +293,20 @@ export const canvasConnectorCallResultSchema = z.object({export type CanvasConnectorCallResult = z.infer<typeof canvasConnectorCallResultSchema>;++export const publishProjectInput = z.object({+ id: z.string().min(1),+ project: canvasSourceProjectSchema,+ expectedCurrentVersionId: z.string().nullable(),+ prompt: z.string().optional(),+});+export type PublishProjectInput = z.infer<typeof publishProjectInput>;++export const publishProjectResultSchema = z.discriminatedUnion("status", [+ z.object({ status: z.literal("saved"), currentVersionId: z.string() }),+ z.object({+ status: z.literal("conflict"),+ currentVersionId: z.string().nullable(),+ }),+]);+export type PublishProjectResult = z.infer<typeof publishProjectResultSchema>;diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.tsindex 508c4a0300d2..bfd30e4a8c95 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts@@ -19,6 +19,8 @@ import {type CanvasView,canvasSourceProjectSchema,type DashboardRecord,+ type PublishProjectInput,+ type PublishProjectResult,} from "./dashboardSchemas";import {type CanvasAgentRequestResult,@@ -569,6 +571,54 @@ export class DashboardsService {return this.patch(input.id, { name: input.name }, "rename canvas");}+ async publishProject(+ input: PublishProjectInput,+ ): Promise<PublishProjectResult> {+ const res = await this.api.fetch(+ `canvases/${encodeURIComponent(input.id)}/publish/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ project: input.project,+ prompt: input.prompt ?? "Edited blocks",+ expected_current_version_id: input.expectedCurrentVersionId,+ }),+ },+ );+ const body = (await res.json().catch(() => ({}))) as {+ detail?: string;+ attr?: string | null;+ current_version_id?: string | null;+ diagnostics?: Array<{+ severity?: string;+ message?: string;+ path?: string;+ }>;+ };+ if (res.status === 409) {+ return {+ status: "conflict",+ currentVersionId: body.current_version_id ?? null,+ };+ }+ if (!res.ok || !body.current_version_id) {+ const firstError = body.diagnostics?.find(+ (diagnostic) => diagnostic.severity === "error" && diagnostic.message,+ );+ const reason = firstError+ ? `${firstError.path ? `${firstError.path}: ` : ""}${firstError.message}`+ : body.attr+ ? `${body.attr}: ${body.detail}`+ : body.detail;+ throw new ProjectApiError(+ reason ?? `Failed to save the canvas (${res.status})`,+ res.status,+ );+ }+ return { status: "saved", currentVersionId: body.current_version_id };+ }+// Read the canvas's source project — the head, or a historical version.async getSource(input: {id: string;diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex 3e50c89dd137..c6ebb596d18c 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -55,6 +55,14 @@ export const canvasDataResultSchema = z.object({// through untouched so the canvas reads the native trends shape.// Hence `unknown` per element rather than `unknown[]`.results: z.array(z.unknown()),+ hogql: z.string().optional(),+ insight: z+ .object({+ name: z.string().nullable(),+ kind: z.string().nullable(),+ display: z.string().nullable(),+ })+ .optional(),});export type CanvasDataResult = z.infer<typeof canvasDataResultSchema>;@@ -87,6 +95,12 @@ export const canvasLoadInsightInput = z.object({});export type CanvasLoadInsightInput = z.infer<typeof canvasLoadInsightInput>;+export const savedInsightSchema = z.object({+ shortId: z.string(),+ name: z.string(),+});+export type SavedInsight = z.infer<typeof savedInsightSchema>;+// Capture (write) avenue behind the `ph.capture` shim. The host sends the event// to the project using its PUBLIC project key (phc_…, safe to be client-side) —// the private read token still never enters the iframe. `distinctId` is who thediff --git a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts b/products/desktop/packages/core/src/canvas/freeformWhitelist.tsindex 50c090973228..5d2542b28bd4 100644--- a/products/desktop/packages/core/src/canvas/freeformWhitelist.ts+++ b/products/desktop/packages/core/src/canvas/freeformWhitelist.ts@@ -71,7 +71,7 @@ export const FREEFORM_WHITELIST: WhitelistEntry[] = [{name: "framer-motion",version: "12.23.12",- esm: `${ESM}/[email protected]?external=react,react-dom`,},{ name: "zod", version: "3.25.76", esm: `${ESM}/[email protected]` },{diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.ts b/products/desktop/packages/core/src/canvas/generationPrompt.tsindex 8f8e30e47f9e..186da004c2cd 100644--- a/products/desktop/packages/core/src/canvas/generationPrompt.ts+++ b/products/desktop/packages/core/src/canvas/generationPrompt.ts@@ -86,6 +86,8 @@ export function buildCanvasGenerationPrompt(input: {<${CANVAS_INSTRUCTIONS_TAG}>Invoke the \`building-canvases\` skill and follow it completely.+If the canvas source has \`src/blocks/runtime.tsx\`, read the skill's \`references/blocks.md\` before you edit, and keep the canvas's blocks.+Expose the values a person may want to change as params with \`editable()\`, as the skill's "Params" section describes.Target:- canvas id: "${escapeXmlAttr(input.dashboardId)}"diff --git a/products/desktop/packages/core/src/canvas/posthogApi.ts b/products/desktop/packages/core/src/canvas/posthogApi.tsindex fe239e23ce4e..3252ce679679 100644--- a/products/desktop/packages/core/src/canvas/posthogApi.ts+++ b/products/desktop/packages/core/src/canvas/posthogApi.ts@@ -1,4 +1,5 @@import type { AuthService } from "@posthog/core/auth/auth";+import type { SavedInsight } from "@posthog/core/canvas/freeformSchemas";// Thin authenticated helpers over the PostHog HTTP API, shared by the canvas// services so the HogQL-query and current-user round-trips aren't duplicated.@@ -10,6 +11,7 @@ interface HogQLResponse {columns?: string[];error?: string | null;last_refresh?: string | null;+ hogql?: string | null;}export interface HogQLResult {@@ -19,6 +21,7 @@ export interface HogQLResult {/** ISO time the returned result was computed, when the endpoint reports it —* what callers judge cached-result freshness by. */lastRefresh: string | null;+ hogql?: string;}/**@@ -41,6 +44,7 @@ export async function runQuery(results: Array.isArray(body.results) ? body.results : [],lastRefresh:typeof body.last_refresh === "string" ? body.last_refresh : null,+ ...(typeof body.hogql === "string" ? { hogql: body.hogql } : {}),};}@@ -83,7 +87,14 @@ async function postQuery(},);if (!response.ok) {- throw new Error(`Query failed (${response.status})`);+ const detail = await response+ .json()+ .then((error: unknown) => {+ const errorDetail = (error as { detail?: unknown } | null)?.detail;+ return typeof errorDetail === "string" ? errorDetail : null;+ })+ .catch(() => null);+ throw new Error(detail ?? `Query failed (${response.status})`);}const body = (await response.json()) as HogQLResponse;if (body.error) throw new Error(body.error);@@ -93,6 +104,9 @@ async function postQuery(/** A saved insight's stored result, fetched by short id. */export interface InsightFetchResult {shortId: string;+ name: string | null;+ sourceKind: string | null;+ display: string | null;/** `insight.query.kind` — drives result-shape coercion (HogQLQuery → rows). */queryKind: string | null;columns: string[];@@ -155,6 +169,36 @@ function buildVariablesOverride();}+interface InsightRow {+ short_id?: string;+ name?: string | null;+ derived_name?: string | null;+ query?: InsightQueryNode | null;+ columns?: string[] | null;+ result?: unknown;+}++async function fetchInsights(+ authService: AuthService,+ params: URLSearchParams,+ action: string,+): Promise<InsightRow[]> {+ const { apiHost } = await authService.getValidAccessToken();+ const projectId = authService.getState().currentProjectId;+ if (projectId == null) {+ throw new Error("No PostHog project selected");+ }+ const response = await authService.authenticatedFetch(+ fetch,+ `${apiHost}/api/projects/${projectId}/insights/?${params.toString()}`,+ );+ if (!response.ok) {+ throw new Error(`${action} failed (${response.status})`);+ }+ const body = (await response.json()) as { results?: InsightRow[] };+ return body.results ?? [];+}+/*** Fetch a SAVED insight by `short_id` and return its STORED result straight from* the insights endpoint (`/insights/?short_id=…&refresh=blocking`) — the same@@ -184,12 +228,6 @@ export async function fetchInsightByShortId(variables?: Record<string, unknown>;},): Promise<InsightFetchResult> {- const { apiHost } = await authService.getValidAccessToken();- const projectId = authService.getState().currentProjectId;- if (projectId == null) {- throw new Error("No PostHog project selected");- }-const params = new URLSearchParams({short_id: shortId,refresh: "blocking",@@ -204,29 +242,22 @@ export async function fetchInsightByShortId();}- const response = await authService.authenticatedFetch(- fetch,- `${apiHost}/api/projects/${projectId}/insights/?${params.toString()}`,- );- if (!response.ok) {- throw new Error(`Insight load failed (${response.status})`);- }-- const body = (await response.json()) as {- results?: Array<{- short_id?: string;- query?: InsightQueryNode | null;- columns?: string[] | null;- result?: unknown;- }>;- };- const insight = body.results?.[0];+ const [insight] = await fetchInsights(authService, params, "Insight load");if (!insight) {throw new Error(`Insight "${shortId}" not found`);}+ const source = (insight.query as { source?: Record<string, unknown> } | null)+ ?.source;+ const trendsFilter = source?.trendsFilter as { display?: string } | undefined;return {shortId,+ name: insight.name || insight.derived_name || null,+ sourceKind:+ (typeof source?.kind === "string" ? source.kind : null) ??+ insight.query?.kind ??+ null,+ display: trendsFilter?.display ?? null,queryKind: insight.query?.kind ?? null,columns: Array.isArray(insight.columns) ? insight.columns.map(String) : [],results: Array.isArray(insight.result) ? insight.result : [],@@ -273,3 +304,30 @@ export async function fetchCurrentUser(return null;}}++export async function listSavedInsights(+ authService: AuthService,+ search = "",+): Promise<SavedInsight[]> {+ const params = new URLSearchParams({+ saved: "true",+ basic: "true",+ limit: "200",+ order: "-last_modified_at",+ });+ if (search.trim()) params.set("search", search.trim());+ const insights = await fetchInsights(authService, params, "Insight list");+ return insights.flatMap((insight) =>+ insight.short_id+ ? [+ {+ shortId: insight.short_id,+ name:+ insight.name?.trim() ||+ insight.derived_name?.trim() ||+ "Untitled insight",+ },+ ]+ : [],+ );+}diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.tsindex cab7c44861ad..e16930d4e06e 100644--- a/products/desktop/packages/core/src/canvas/services.ts+++ b/products/desktop/packages/core/src/canvas/services.ts@@ -15,6 +15,8 @@ import type {CanvasVersion,CanvasView,DashboardRecord,+ PublishProjectInput,+ PublishProjectResult,} from "./dashboardSchemas";import type {CanvasAgentRequestResult,@@ -24,6 +26,7 @@ import type {CanvasDataQueryInput,CanvasDataResult,CanvasLoadInsightInput,+ SavedInsight,} from "./freeformSchemas";import type {CanvasLayout,@@ -46,6 +49,7 @@ export interface IDashboardsService {listComponents(input: { search?: string }): Promise<DashboardRecord[]>;listAll(): Promise<DashboardRecord[]>;get(id: string): Promise<DashboardRecord | null>;+ publishProject(input: PublishProjectInput): Promise<PublishProjectResult>;// Everything needed to open a canvas, in one round trip.view(id: string): Promise<CanvasView>;create(input: {@@ -149,6 +153,7 @@ export interface IDashboardsService {export interface ICanvasDataService {query(input: CanvasDataQueryInput): Promise<CanvasDataResult>;loadInsight(input: CanvasLoadInsightInput): Promise<CanvasDataResult>;+ listSavedInsights(search?: string): Promise<SavedInsight[]>;capture(input: CanvasCaptureInput): Promise<CanvasCaptureResult>;captureConfig(): Promise<CanvasCaptureConfig>;}diff --git a/products/desktop/packages/host-router/src/routers/canvas-data.router.ts b/products/desktop/packages/host-router/src/routers/canvas-data.router.tsindex b1b5c213d1ba..2fb0fa5c5023 100644--- a/products/desktop/packages/host-router/src/routers/canvas-data.router.ts+++ b/products/desktop/packages/host-router/src/routers/canvas-data.router.ts@@ -3,10 +3,12 @@ import {canvasCaptureInput,canvasDataQueryInput,canvasLoadInsightInput,+ savedInsightSchema,} from "@posthog/core/canvas/freeformSchemas";import { CANVAS_DATA_SERVICE } from "@posthog/core/canvas/identifiers";import type { ICanvasDataService } from "@posthog/core/canvas/services";import { publicProcedure, router } from "@posthog/host-trpc/trpc";+import { z } from "zod";// The data avenue behind a freeform canvas's `ph.*` shims. One-line forwards to// CanvasDataService, which injects the PostHog credentials host-side.@@ -23,6 +25,14 @@ export const canvasDataRouter = router({.get<ICanvasDataService>(CANVAS_DATA_SERVICE).loadInsight(input),),+ savedInsights: publicProcedure+ .input(z.object({ search: z.string().max(200).optional() }).optional())+ .output(z.array(savedInsightSchema))+ .query(({ ctx, input }) =>+ ctx.container+ .get<ICanvasDataService>(CANVAS_DATA_SERVICE)+ .listSavedInsights(input?.search),+ ),capture: publicProcedure.input(canvasCaptureInput).mutation(({ ctx, input }) =>diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.tsindex 296b3b3b1a8e..c97ce94ba5d3 100644--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts@@ -25,6 +25,8 @@ import {listComponentsInput,listDashboardsInput,promoteCanvasInput,+ publishProjectInput,+ publishProjectResultSchema,renameDashboardInput,reportCanvasErrorInput,requestCanvasAgentInput,@@ -109,6 +111,14 @@ export const dashboardsRouter = router({.get<IDashboardsService>(DASHBOARDS_SERVICE).patchLayout(input),),+ publishProject: publicProcedure+ .input(publishProjectInput)+ .output(publishProjectResultSchema)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .publishProject(input),+ ),source: publicProcedure.input(canvasSourceInput).output(canvasSourceSchema)diff --git a/products/desktop/packages/shared/src/canvas-platform.ts b/products/desktop/packages/shared/src/canvas-platform.tsindex 59d3e34eccb6..731957e9b5f9 100644--- a/products/desktop/packages/shared/src/canvas-platform.ts+++ b/products/desktop/packages/shared/src/canvas-platform.ts@@ -35,7 +35,7 @@ export const CANVAS_PLATFORM_MANIFEST = {three: { version: "0.179.1", url: "https://esm.sh/[email protected]" },"framer-motion": {version: "12.23.12",- url: "https://esm.sh/[email protected]?external=react,react-dom",+ url: "https://esm.sh/[email protected]?external=react,react-dom&[email protected],[email protected]",},zod: { version: "3.25.76", url: "https://esm.sh/[email protected]" },"@tanstack/react-table": {@@ -108,4 +108,31 @@ export const CANVAS_SDK_SPECIFIER = "@posthog/canvas-sdk";// its own build image and cannot reach this workspace.export const CANVAS_SDK_MODULE_SOURCE = `export const ph = globalThis.phexport default globalThis.ph++export function editable(name, props, params) {+ const schema = params || {}+ const values = {}+ for (const key of Object.keys(schema)) {+ const value = props ? props[key] : undefined+ if (value === undefined || typeof value === 'function') {+ continue+ }+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {+ continue+ }+ values[key] = value+ }+ const attributes = {+ 'data-ph-block': name,+ 'data-ph-params': JSON.stringify(schema),+ 'data-ph-props': JSON.stringify(values),+ }+ if (props && props['data-ph-src']) {+ attributes['data-ph-src'] = props['data-ph-src']+ }+ if (props && props.blockId) {+ attributes['data-ph-block-id'] = props.blockId+ }+ return attributes+}`;diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocks.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocks.tsxnew file mode 100644index 000000000000..9e268e29f625--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocks.tsx@@ -0,0 +1,89 @@+import { ChartLineUp, type Icon, SquaresFour } from "@phosphor-icons/react";+import {+ CANVAS_STARTERS,+ type CanvasStarter,+} from "@posthog/core/canvas/blockLibrary/blockProject";+import { isPlaceholderCanvasName } from "@posthog/core/canvas/canvasNaming";+import {+ useCanvasSourceAutosave,+ useStartCanvasFromStarter,+} from "@posthog/ui/features/canvas/blocks/canvasSourceHooks";+import {+ useDashboard,+ useDashboardMutations,+} from "@posthog/ui/features/canvas/hooks/useDashboards";+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import { useDashboardEditStore } from "@posthog/ui/features/canvas/stores/dashboardEditStore";++const STARTER_LOOKS: Record<string, { icon: Icon; color: string }> = {+ blank: { icon: SquaresFour, color: "blue" },+ "product-overview": { icon: ChartLineUp, color: "orange" },+};++const NAMED_STARTERS = new Set(["product-overview"]);++export function CanvasSourceAutosave({ canvasId }: { canvasId: string }) {+ useCanvasSourceAutosave(canvasId);+ return null;+}++export function CanvasBlocksStarter({ canvasId }: { canvasId: string }) {+ const start = useStartCanvasFromStarter(canvasId);+ const setTab = useCanvasChatPanelStore((state) => state.setTab);+ const setEditing = useDashboardEditStore((state) => state.setEditing);+ const { dashboard } = useDashboard(canvasId);+ const { renameDashboard } = useDashboardMutations();++ const pick = (starter: CanvasStarter) => {+ setTab("blocks");+ setEditing(canvasId, true);+ start(starter);+ if (!NAMED_STARTERS.has(starter.id)) return;+ if (!dashboard || !isPlaceholderCanvasName(dashboard.name)) return;+ void renameDashboard(canvasId, starter.name).catch(() => undefined);+ };++ return (+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {CANVAS_STARTERS.map((starter) => {+ const look = STARTER_LOOKS[starter.id] ?? {+ icon: SquaresFour,+ color: "blue",+ };+ const StarterIcon = look.icon;+ return (+ <button+ key={starter.id}+ type="button"+ onClick={() => pick(starter)}+ className="flex w-full cursor-pointer items-start gap-2.5 rounded-xl border border-(--gray-a3) bg-(--color-panel-solid) px-2.5 py-2 text-left shadow-[0_1px_3px_rgba(0,0,0,0.04),0_1px_2px_rgba(0,0,0,0.02)] transition-[border-color,box-shadow] hover:border-(--card-hover-border) hover:shadow-[0_2px_8px_rgba(0,0,0,0.06),0_1px_3px_rgba(0,0,0,0.04)]"+ style={+ {+ "--card-hover-border": `var(--${look.color}-6)`,+ } as React.CSSProperties+ }+ >+ <span+ className="flex size-6 shrink-0 items-center justify-center rounded-md"+ style={{ backgroundColor: `var(--${look.color}-3)` }}+ >+ <StarterIcon+ size={14}+ weight="duotone"+ color={`var(--${look.color}-9)`}+ />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="min-w-0 truncate font-medium text-foreground text-xs">+ {starter.name}+ </span>+ <span className="line-clamp-1 text-muted-foreground text-xs leading-normal">+ {starter.description}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocksPanel.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocksPanel.tsxnew file mode 100644index 000000000000..6fce97b012f2--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasBlocksPanel.tsx@@ -0,0 +1,414 @@+import {+ CaretLeft,+ CheckCircle,+ Sparkle,+ WarningCircle,+} from "@phosphor-icons/react";+import { Button } from "@posthog/quill";+import {+ isRootSelection,+ isSourceDirty,+ useCanvasEditSelection,+ useCanvasLibraryOpen,+ useCanvasSourceEntry,+ useCanvasSourceStore,+} from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import { SourceInspector } from "@posthog/ui/features/canvas/blocks/inspector/SourceInspector";+import {+ LIBRARY,+ LIBRARY_GROUPS,+ type LibraryEntry,+ libraryIcon,+ libraryLabel,+} from "@posthog/ui/features/canvas/blocks/libraryCatalog";+import { beginSourceDrag } from "@posthog/ui/features/canvas/blocks/sourceDrag";+import { useCanvasSourceActions } from "@posthog/ui/features/canvas/blocks/useCanvasSourceActions";+import { SearchInput } from "@posthog/ui/primitives/SearchInput";+import { Spinner } from "@posthog/ui/primitives/Spinner";+import { type ReactNode, useMemo, useState } from "react";++interface SaveStatus {+ saving: boolean;+ dirty: boolean;+ error: string | null;+}++function SaveIndicator({ status }: { status: SaveStatus }) {+ if (status.error) {+ return (+ <span className="flex items-center gap-1 text-[11px] text-destructive">+ <WarningCircle size={12} />+ Not saved+ </span>+ );+ }+ if (status.saving || status.dirty) {+ return (+ <span className="flex items-center gap-1 text-[11px] text-muted-foreground">+ <Spinner size="xs" aria-hidden="true" />+ Saving+ </span>+ );+ }+ return (+ <span className="flex items-center gap-1 text-[11px] text-muted-foreground">+ <CheckCircle size={12} />+ Saved+ </span>+ );+}++function LibraryItem({+ entry,+ onPointerDown,+ onActivate,+}: {+ entry: LibraryEntry;+ onPointerDown: (event: React.PointerEvent, entry: LibraryEntry) => void;+ onActivate: (entry: LibraryEntry) => void;+}) {+ const Icon = entry.icon;+ return (+ <button+ type="button"+ aria-label={`Add ${entry.label}`}+ data-blocks-library-item={entry.type}+ onPointerDown={(event) => onPointerDown(event, entry)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onActivate(entry);+ }+ }}+ className="group/item flex w-full cursor-grab select-none items-center gap-2.5 rounded-md px-2 py-1.5 text-left outline-none transition-[background-color,scale] duration-150 ease-out hover:bg-fill-hover focus-visible:bg-fill-hover active:scale-[0.98] active:cursor-grabbing motion-reduce:active:scale-100"+ >+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-[color,border-color] duration-150 group-hover/item:border-accent-8 group-hover/item:text-accent-11">+ <Icon size={16} />+ </div>+ <div className="min-w-0">+ <div className="truncate font-medium text-foreground text-xs">+ {entry.label}+ </div>+ <div className="line-clamp-2 text-[11px] text-muted-foreground leading-snug">+ {entry.description}+ </div>+ </div>+ </button>+ );+}++function AskAgentCard({+ onAskAgent,+}: {+ onAskAgent: (message: string) => void;+}) {+ return (+ <button+ type="button"+ onClick={() =>+ onAskAgent(+ "Improve this canvas. Keep the blocks I placed, and make the layout clear and consistent.",+ )+ }+ className="mx-2 mt-4 flex w-[calc(100%-1rem)] items-start gap-2.5 rounded-md border border-border border-dashed px-2.5 py-2 text-left transition-colors hover:border-accent-8 hover:bg-fill-hover"+ >+ <Sparkle size={14} className="mt-px shrink-0 text-accent-11" />+ <span className="min-w-0">+ <span className="block font-medium text-foreground text-xs">+ Ask the agent+ </span>+ <span className="block text-[11px] text-muted-foreground leading-snug">+ Blocks are code in this canvas. The agent can change them, or build+ what no block covers.+ </span>+ </span>+ </button>+ );+}++function Library({+ addsAfter,+ onPointerDown,+ onActivate,+ onAskAgent,+}: {+ addsAfter: string | null;+ onPointerDown: (event: React.PointerEvent, entry: LibraryEntry) => void;+ onActivate: (entry: LibraryEntry) => void;+ onAskAgent: (message: string) => void;+}) {+ const [search, setSearch] = useState("");+ const groups = useMemo(() => {+ const needle = search.trim().toLowerCase();+ const matches = (entry: LibraryEntry) =>+ !needle ||+ entry.label.toLowerCase().includes(needle) ||+ entry.description.toLowerCase().includes(needle);+ return LIBRARY_GROUPS.flatMap((group) => {+ const entries = LIBRARY.filter(+ (entry) => entry.group === group && matches(entry),+ );+ return entries.length > 0 ? [{ group, entries }] : [];+ });+ }, [search]);+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="px-3 pt-3 pb-2">+ <SearchInput+ value={search}+ onValueChange={setSearch}+ placeholder="Search blocks"+ className="w-full"+ />+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-1.5 pb-4">+ {groups.map(({ group, entries }) => (+ <div key={group} className="mt-2">+ <div className="px-2 pb-1 font-medium text-[10.5px] text-muted-foreground uppercase tracking-wide">+ {group}+ </div>+ {entries.map((entry) => (+ <LibraryItem+ key={entry.type}+ entry={entry}+ onPointerDown={onPointerDown}+ onActivate={onActivate}+ />+ ))}+ </div>+ ))}+ {groups.length === 0 ? (+ <div className="px-3 py-6 text-center text-muted-foreground text-xs">+ No blocks match “{search}”+ </div>+ ) : null}+ <div className="mx-2 mt-4 rounded-md bg-muted/50 px-2.5 py-2 text-[11px] text-muted-foreground leading-snug">+ {addsAfter+ ? `Click a block to add it after the selected ${addsAfter.toLowerCase()}, or drag it anywhere in the canvas.`+ : "Click a block to add it at the end, or drag it anywhere in the canvas."}+ </div>+ <AskAgentCard onAskAgent={onAskAgent} />+ </div>+ </div>+ );+}++const NOTICE_TONES = {+ error: { surface: "bg-destructive/5", icon: "text-destructive" },+ warning: { surface: "bg-muted/40", icon: "text-warning-foreground" },+};++function PanelNotice({+ tone,+ title,+ detail,+ children,+}: {+ tone: keyof typeof NOTICE_TONES;+ title: string;+ detail: string;+ children: ReactNode;+}) {+ return (+ <div+ className={`flex flex-col gap-2 border-border border-b px-3 py-2.5 ${NOTICE_TONES[tone].surface}`}+ >+ <div className="flex items-start gap-2">+ <WarningCircle+ size={14}+ className={`mt-px shrink-0 ${NOTICE_TONES[tone].icon}`}+ />+ <div className="min-w-0 text-[11.5px] leading-snug">+ <div className="font-medium text-foreground">{title}</div>+ <div className="break-words text-muted-foreground">{detail}</div>+ </div>+ </div>+ <div className="flex gap-1.5 pl-5">{children}</div>+ </div>+ );+}++export function CanvasBlocksPanel({+ canvasId,+ onAskAgent,+}: {+ canvasId: string;+ onAskAgent: (message: string) => void;+}) {+ const entry = useCanvasSourceEntry(canvasId);+ const selection = useCanvasEditSelection(canvasId);+ const libraryOpen = useCanvasLibraryOpen(canvasId);+ const actions = useCanvasSourceActions(canvasId);++ if (!entry) {+ return (+ <div className="p-3 text-muted-foreground text-xs">+ Blocks load with the canvas.+ </div>+ );+ }+ const store = useCanvasSourceStore.getState();+ const status: SaveStatus = {+ saving: entry.saving,+ dirty: isSourceDirty(entry),+ error:+ entry.saveError ??+ (entry.conflict ? "This canvas changed somewhere else" : null),+ };+ const isRoot = isRootSelection(entry, selection);+ const SelectedIcon = libraryIcon(selection?.blockType ?? null);+ const inspecting = !!selection && !libraryOpen;+ const addsAfter =+ selection && !isRoot+ ? libraryLabel(selection.blockType, selection.tag)+ : null;++ const addFromLibrary = (blockType: string) => {+ store.setLibraryOpen(canvasId, true);+ actions.addAfterSelection(blockType);+ };++ const onLibraryPointerDown = (+ event: React.PointerEvent,+ item: LibraryEntry,+ ) => {+ if (event.button !== 0) return;+ event.preventDefault();+ beginSourceDrag({+ source: { kind: "new", blockType: item.type },+ startX: event.clientX,+ startY: event.clientY,+ onDrop: (source, hit) => {+ store.setLibraryOpen(canvasId, true);+ actions.drop(source, hit);+ },+ onClick: () => addFromLibrary(item.type),+ });+ };++ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex h-9 shrink-0 items-center gap-1.5 border-border border-b px-3">+ {inspecting ? (+ <Button+ variant="default"+ size="xs"+ onClick={() => store.setLibraryOpen(canvasId, true)}+ >+ <CaretLeft size={11} />+ All blocks+ </Button>+ ) : (+ <span className="font-medium text-[11px] text-muted-foreground">+ Library+ </span>+ )}+ <div className="flex-1" />+ <SaveIndicator status={status} />+ </div>+ {entry.saveError ? (+ <PanelNotice+ tone="error"+ title="Your changes are not saved"+ detail={entry.saveError}+ >+ <Button+ variant="outline"+ size="xs"+ onClick={() => store.setSaving(canvasId, false, null)}+ >+ Try again+ </Button>+ <Button+ variant="default"+ size="xs"+ onClick={() =>+ onAskAgent(+ `Saving this canvas fails with: "${entry.saveError}". Fix the canvas source so it passes validation.`,+ )+ }+ >+ <Sparkle size={11} />+ Ask the agent to fix+ </Button>+ </PanelNotice>+ ) : null}+ {entry.conflict ? (+ <PanelNotice+ tone="warning"+ title="This canvas changed somewhere else"+ detail="A newer version was saved while you edited. Load it and drop your unsaved edits, or keep your edits and replace it."+ >+ <Button+ variant="outline"+ size="xs"+ onClick={() => store.resolveConflict(canvasId, false)}+ >+ Load the latest+ </Button>+ <Button+ variant="default"+ size="xs"+ onClick={() => store.resolveConflict(canvasId, true)}+ >+ Keep my edits+ </Button>+ </PanelNotice>+ ) : null}+ {inspecting && selection ? (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="flex items-center gap-2.5 border-border border-b px-3 py-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-accent-3 text-accent-11">+ <SelectedIcon size={14} />+ </div>+ <div className="min-w-0">+ <div className="font-medium text-foreground text-xs">+ {isRoot+ ? "Canvas"+ : libraryLabel(selection.blockType, selection.tag)}+ </div>+ <div className="truncate font-mono text-[10.5px] text-muted-foreground">+ {selection.source?.file ?? ""}+ </div>+ </div>+ </div>+ <SourceInspector+ key={+ selection.blockId ??+ `${selection.source?.file}:${selection.source?.start}`+ }+ selection={selection}+ isRoot={isRoot}+ onProps={(props) => actions.updateProps(selection, props)}+ onText={(text) => actions.setText(selection, text)}+ onDuplicate={() => actions.duplicate(selection)}+ onRemove={() => actions.remove(selection)}+ />+ {isRoot ? null : (+ <div className="px-3 pb-3">+ <Button+ variant="outline"+ size="sm"+ onClick={() =>+ onAskAgent(+ `Change the ${libraryLabel(selection.blockType, selection.tag).toLowerCase()} at ${selection.source?.file ?? "the canvas"}${selection.blockId ? ` (blockId ${selection.blockId})` : ""}: `,+ )+ }+ >+ <Sparkle size={12} />+ Ask the agent about this+ </Button>+ </div>+ )}+ </div>+ ) : (+ <Library+ addsAfter={addsAfter}+ onPointerDown={onLibraryPointerDown}+ onActivate={(item) => addFromLibrary(item.type)}+ onAskAgent={onAskAgent}+ />+ )}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsxnew file mode 100644index 000000000000..db7c3e9cf449--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsx@@ -0,0 +1,287 @@+import "./blocks.css";+import { CANVAS_ENTRY_PATH } from "@posthog/core/canvas/blockLibrary/blockProject";+import { parseParamSchema } from "@posthog/core/canvas/blockLibrary/params";+import type { SourceRange } from "@posthog/core/canvas/blockLibrary/sourceEdits";+import {+ type CanvasNavIntent,+ canvasToHostMessageSchema,+} from "@posthog/core/canvas/freeformSchemas";+import {+ type CanvasEditSelection,+ useCanvasSourceEntry,+ useCanvasSourceStore,+} from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import {+ CANVAS_EDITOR_CHANNEL,+ postToCanvasEditor,+} from "@posthog/ui/features/canvas/blocks/editorFrame";+import { SourceDragOverlay } from "@posthog/ui/features/canvas/blocks/SourceDragOverlay";+import {+ activeSourceDrag,+ beginSourceDrag,+ type SourceDropHit,+} from "@posthog/ui/features/canvas/blocks/sourceDrag";+import { useCanvasSourceActions } from "@posthog/ui/features/canvas/blocks/useCanvasSourceActions";+import { createCanvasHostMessageRouter } from "@posthog/ui/features/canvas/freeform/canvasHostMessageRouter";+import { buildSandboxDocument } from "@posthog/ui/features/canvas/freeform/sandboxRuntime";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";+import { useThemeStore } from "@posthog/ui/shell/themeStore";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+} from "react";++interface EditElementMessage extends Omit<CanvasEditSelection, "params"> {+ params: string | null;+}++function isTypingTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) return false;+ if (target.isContentEditable) return true;+ return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);+}++function toSelection(+ element: EditElementMessage | null,+): CanvasEditSelection | null {+ return element+ ? { ...element, params: parseParamSchema(element.params) }+ : null;+}++export function CanvasSourceEditor({+ canvasId,+ onDataRequest,+ onError,+ onRendered,+ onNavigate,+}: {+ canvasId: string;+ onDataRequest: (method: string, payload: unknown) => Promise<unknown>;+ onError?: (message: string, stack?: string) => void;+ onRendered?: () => void;+ onNavigate?: (intent: CanvasNavIntent) => void;+}) {+ const entry = useCanvasSourceEntry(canvasId);+ const actions = useCanvasSourceActions(canvasId);+ const iframeRef = useRef<HTMLIFrameElement>(null);+ const readyRef = useRef(false);+ const theme = useThemeStore((state) => (state.isDarkMode ? "dark" : "light"));+ const srcDoc = useMemo(() => buildSandboxDocument(), []);+ const latest = useRef({+ onDataRequest,+ onError,+ onRendered,+ onNavigate,+ theme,+ actions,+ });+ useLayoutEffect(() => {+ latest.current = {+ onDataRequest,+ onError,+ onRendered,+ onNavigate,+ theme,+ actions,+ };+ });++ const sendInit = useCallback(() => {+ const snapshot = useCanvasSourceStore.getState().entries[canvasId];+ if (!snapshot || !readyRef.current) return;+ postToCanvasEditor({+ type: "init",+ files: snapshot.files,+ entry: CANVAS_ENTRY_PATH,+ editing: true,+ rev: snapshot.rev,+ focusBlockId: snapshot.focusBlockId,+ focusSource: snapshot.focusSource,+ theme: latest.current.theme,+ highlights: [],+ });+ }, [canvasId]);++ const rev = entry?.rev;+ useEffect(() => {+ if (rev !== undefined) sendInit();+ }, [rev, sendInit]);++ useEffect(() => {+ postToCanvasEditor({ type: "set-theme", theme });+ }, [theme]);++ const handleEdit = useCallback(+ (data: Record<string, unknown>) => {+ const store = useCanvasSourceStore.getState();+ const frameRect = iframeRef.current?.getBoundingClientRect();+ const offsetX = frameRect?.left ?? 0;+ const offsetY = frameRect?.top ?? 0;+ switch (data.type) {+ case "canvas-edit-select":+ if (data.byPointer === true) store.setLibraryOpen(canvasId, false);+ latest.current.actions.select(+ toSelection((data.element as EditElementMessage | null) ?? null),+ );+ return;+ case "canvas-edit-root":+ store.setMounted(+ canvasId,+ Number(data.rev),+ (data.root as SourceRange | null) ?? null,+ );+ return;+ case "canvas-edit-drop-target":+ activeSourceDrag()?.hit((data.hit as SourceDropHit | null) ?? null);+ return;+ case "canvas-edit-drag-start": {+ const element = toSelection(data.element as EditElementMessage);+ if (!element) return;+ beginSourceDrag({+ source: { kind: "move", selection: element },+ startX: offsetX + Number(data.x),+ startY: offsetY + Number(data.y),+ onDrop: latest.current.actions.drop,+ });+ return;+ }+ case "canvas-edit-pointer":+ activeSourceDrag()?.move(+ offsetX + Number(data.x),+ offsetY + Number(data.y),+ );+ return;+ case "canvas-edit-pointer-up":+ activeSourceDrag()?.end(true);+ return;+ case "canvas-edit-pointer-cancel":+ activeSourceDrag()?.end(false);+ return;+ case "canvas-edit-key":+ handleKey(canvasId, data, latest.current.actions);+ return;+ case "canvas-edit-text": {+ const element = toSelection(data.element as EditElementMessage);+ if (element && typeof data.text === "string")+ latest.current.actions.setText(element, data.text);+ return;+ }+ }+ },+ [canvasId],+ );++ useLayoutEffect(() => {+ const route = createCanvasHostMessageRouter({+ post: (message) =>+ iframeRef.current?.contentWindow?.postMessage(message, "*"),+ callbacks: () => ({+ onReady: () => {+ readyRef.current = true;+ sendInit();+ },+ onDataRequest: latest.current.onDataRequest,+ onError: (message, stack) => latest.current.onError?.(message, stack),+ onRendered: () => latest.current.onRendered?.(),+ onNavigate: (intent) => latest.current.onNavigate?.(intent),+ onTextSelection: () => undefined,+ onCommentActivate: () => undefined,+ }),+ hasUserActivation: () => navigator.userActivation?.isActive === true,+ openExternal: openExternalUrl,+ onExternalOpenBlocked: () => undefined,+ });+ const onMessage = (event: MessageEvent) => {+ if (event.source !== iframeRef.current?.contentWindow) return;+ const data = event.data as Record<string, unknown> | null;+ if (!data || data.channel !== CANVAS_EDITOR_CHANNEL) return;+ if (+ typeof data.type === "string" &&+ data.type.startsWith("canvas-edit-")+ ) {+ handleEdit(data);+ return;+ }+ const parsed = canvasToHostMessageSchema.safeParse(data);+ if (parsed.success) void route(parsed.data);+ };+ window.addEventListener("message", onMessage);+ return () => window.removeEventListener("message", onMessage);+ }, [handleEdit, sendInit]);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (isTypingTarget(event.target)) return;+ const shortcut = event.metaKey || event.ctrlKey;+ if (!shortcut && event.target !== document.body) return;+ handleKey(+ canvasId,+ {+ key: event.key,+ metaKey: event.metaKey,+ ctrlKey: event.ctrlKey,+ shiftKey: event.shiftKey,+ },+ latest.current.actions,+ () => event.preventDefault(),+ );+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [canvasId]);++ return (+ <div className="relative h-full w-full">+ <iframe+ ref={iframeRef}+ title="Canvas editor"+ data-canvas-source-editor=""+ srcDoc={srcDoc}+ sandbox="allow-scripts"+ className="h-full w-full border-0 bg-transparent"+ />+ <SourceDragOverlay />+ </div>+ );+}++function handleKey(+ canvasId: string,+ data: Record<string, unknown>,+ actions: ReturnType<typeof useCanvasSourceActions>,+ prevent?: () => void,+): void {+ const store = useCanvasSourceStore.getState();+ const selection = store.selection[canvasId] ?? null;+ const key = String(data.key ?? "");+ const mod = data.metaKey === true || data.ctrlKey === true;+ if (key === "Escape") {+ const drag = activeSourceDrag();+ if (drag) drag.end(false);+ else {+ actions.select(null);+ postToCanvasEditor({ type: "canvas-edit-deselect" });+ }+ return;+ }+ if (mod && key.toLowerCase() === "z") {+ prevent?.();+ if (data.shiftKey === true) store.redo(canvasId);+ else store.undo(canvasId);+ return;+ }+ if (!selection) return;+ if (key === "Backspace" || key === "Delete") {+ prevent?.();+ actions.remove(selection);+ return;+ }+ if (mod && key.toLowerCase() === "d") {+ prevent?.();+ actions.duplicate(selection);+ }+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/SourceDragOverlay.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/SourceDragOverlay.tsxnew file mode 100644index 000000000000..be3f822cd9dc--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/SourceDragOverlay.tsx@@ -0,0 +1,43 @@+import { libraryIcon } from "@posthog/ui/features/canvas/blocks/libraryCatalog";+import { useSourceDragStore } from "@posthog/ui/features/canvas/blocks/sourceDrag";+import { createPortal } from "react-dom";++const GHOST_OFFSET_X = 14;+const GHOST_OFFSET_Y = 10;++export function SourceDragOverlay() {+ const ghost = useSourceDragStore((state) => state.ghost);+ if (!ghost) return null;+ const Icon = libraryIcon(ghost.blockType);+ const x = ghost.x + GHOST_OFFSET_X;+ const y = ghost.y + GHOST_OFFSET_Y;+ return createPortal(+ <>+ {ghost.phase === "drag" ? (+ <div className="blocks-pointer-shield cursor-grabbing" />+ ) : null}+ <div+ className="blocks-drag-ghost"+ data-phase={ghost.phase}+ style={{+ transform: `translate3d(${x}px, ${y}px, 0) rotate(${ghost.tilt.toFixed(2)}deg)`,+ }}+ >+ <div className="blocks-drag-ghost-card flex w-[220px] items-center gap-2.5 rounded-lg border border-border bg-card px-3 py-2.5">+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-accent-3 text-accent-11">+ <Icon size={16} />+ </div>+ <div className="min-w-0">+ <div className="truncate font-medium text-[12.5px] text-foreground">+ {ghost.label}+ </div>+ <div className="truncate text-[11px] text-muted-foreground">+ {ghost.hint}+ </div>+ </div>+ </div>+ </div>+ </>,+ document.querySelector(".radix-themes") ?? document.body,+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/blocks.css b/products/desktop/packages/ui/src/features/canvas/blocks/blocks.cssnew file mode 100644index 000000000000..1e897e4df453--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/blocks.css@@ -0,0 +1,69 @@+.blocks-pointer-shield {+ position: fixed;+ inset: 0;+ z-index: 998;+ user-select: none;+}++.blocks-drag-ghost {+ --blocks-ease-out: cubic-bezier(0.23, 1, 0.32, 1);+ pointer-events: none;+ position: fixed;+ z-index: 1000;+ top: 0;+ left: 0;+ transform-origin: 24px 20px;+ will-change: transform;+}++.blocks-drag-ghost[data-phase="drop"] {+ opacity: 0;+ scale: 0.98;+ transition:+ opacity 140ms var(--blocks-ease-out),+ scale 140ms var(--blocks-ease-out);+}++.blocks-drag-ghost[data-phase="return"] {+ opacity: 0;+ transition:+ transform 280ms var(--blocks-ease-out),+ opacity 180ms ease-out 100ms;+}++.blocks-drag-ghost-card {+ animation: blocks-ghost-lift 180ms var(--blocks-ease-out) both;+ box-shadow:+ 0 0 0 1px rgb(0 0 0 / 0.04),+ 0 2px 4px -1px rgb(0 0 0 / 0.06),+ 0 12px 28px -10px rgb(0 0 0 / 0.22);+}++@keyframes blocks-ghost-lift {+ from {+ opacity: 0;+ scale: 0.97;+ }+ to {+ opacity: 1;+ scale: 1;+ }+}++@media (prefers-reduced-motion: reduce) {+ .blocks-drag-ghost-card {+ animation-name: blocks-ghost-fade;+ }+ .blocks-drag-ghost[data-phase="return"] {+ transition: opacity 140ms ease-out;+ }+}++@keyframes blocks-ghost-fade {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.tsnew file mode 100644index 000000000000..8d86d6a111c5--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts@@ -0,0 +1,941 @@+interface BabelLike {+ transform: (+ code: string,+ options: Record<string, unknown>,+ ) => { code?: string | null };+}++interface BabelTypes {+ jsxAttribute: (name: unknown, value: unknown) => unknown;+ jsxIdentifier: (name: string) => unknown;+ stringLiteral: (value: string) => unknown;+}++interface JsxElementPath {+ node: {+ start?: number | null;+ end?: number | null;+ openingElement: {+ name: { type: string; name?: string; property?: { name?: string } };+ attributes: unknown[];+ };+ };+ findParent: (test: (parent: ParentPath) => boolean) => unknown;+}++interface ParentPath {+ isCallExpression: () => boolean;+ node: { callee: { type: string; property?: { name?: string } } };+}++interface ModulePath {+ node: { source?: { value: unknown } | null };+}++interface CompileOptions {+ editing: boolean;+ basePlugins: unknown[];+ cache: Map<string, string>;+}++export function compileCanvasProject(+ Babel: BabelLike,+ files: Record<string, string>,+ entry: string,+ options: CompileOptions,+): string {+ const urls = new Map<string, string>();+ const extensions = [+ "",+ ".tsx",+ ".ts",+ ".jsx",+ ".js",+ "/index.tsx",+ "/index.ts",+ ];++ const normalize = (parts: string[]): string => {+ const out: string[] = [];+ for (const part of parts) {+ if (part === "" || part === ".") continue;+ if (part === "..") out.pop();+ else out.push(part);+ }+ return out.join("/");+ };++ const resolve = (from: string, specifier: string): string | null => {+ const base = from.split("/").slice(0, -1);+ const joined = normalize([...base, ...specifier.split("/")]);+ for (const extension of extensions) {+ const candidate = joined + extension;+ if (candidate in files) return candidate;+ }+ return null;+ };++ const blobUrl = (code: string): string => {+ const cached = options.cache.get(code);+ if (cached) return cached;+ const url = URL.createObjectURL(+ new Blob([code], { type: "text/javascript" }),+ );+ options.cache.set(code, url);+ return url;+ };++ const styleModule = (css: string): string => {+ const style = document.createElement("style");+ style.setAttribute("data-canvas-style", "");+ style.textContent = css;+ document.head.appendChild(style);+ return blobUrl("export default null;");+ };++ const sourceRangePlugin =+ (file: string) =>+ ({ types: t }: { types: BabelTypes }) => ({+ visitor: {+ JSXElement(path: JsxElementPath) {+ const node = path.node;+ if (typeof node.start !== "number" || typeof node.end !== "number")+ return;+ const name = node.openingElement.name;+ const tag =+ name.type === "JSXIdentifier" ? name.name : name.property?.name;+ if (tag === "Fragment") return;+ const repeated = !!path.findParent(+ (parent: ParentPath) =>+ parent.isCallExpression() &&+ parent.node.callee.type === "MemberExpression" &&+ parent.node.callee.property?.name === "map",+ );+ const value = `${file}|${node.start}|${node.end}${repeated ? "|r" : ""}`;+ node.openingElement.attributes.unshift(+ t.jsxAttribute(+ t.jsxIdentifier("data-ph-src"),+ t.stringLiteral(value),+ ),+ );+ },+ },+ });++ const build = (path: string, stack: string[]): string => {+ const known = urls.get(path);+ if (known) return known;+ if (stack.includes(path))+ throw new Error(`Circular import: ${[...stack, path].join(" -> ")}`);+ const source = files[path] ?? "";+ if (path.endsWith(".css")) {+ const url = styleModule(source);+ urls.set(path, url);+ return url;+ }+ if (path.endsWith(".json")) {+ const url = blobUrl(`export default ${source.trim() || "null"};`);+ urls.set(path, url);+ return url;+ }+ const rewriteImports = () => ({+ visitor: {+ "ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration"(+ nodePath: ModulePath,+ ) {+ const sourceNode = nodePath.node.source;+ if (!sourceNode || typeof sourceNode.value !== "string") return;+ if (!sourceNode.value.startsWith(".")) return;+ const resolved = resolve(path, sourceNode.value);+ if (!resolved)+ throw new Error(+ `Cannot find "${sourceNode.value}" imported from ${path}`,+ );+ sourceNode.value = build(resolved, [...stack, path]);+ },+ },+ });+ const plugins = [+ ...options.basePlugins,+ rewriteImports,+ ...(options.editing && !path.startsWith("src/blocks/")+ ? [sourceRangePlugin(path)]+ : []),+ ];+ const out = Babel.transform(source, {+ filename: path.split("/").pop(),+ plugins,+ presets: [+ ["react", { runtime: "automatic" }],+ [+ "typescript",+ { isTSX: true, allExtensions: true, onlyRemoveTypeImports: true },+ ],+ ],+ }).code;+ const url = blobUrl(out ?? "");+ urls.set(path, url);+ return url;+ };++ for (const style of Array.from(+ document.querySelectorAll("style[data-canvas-style]"),+ )) {+ style.remove();+ }+ return build(entry, []);+}++type Post = (message: Record<string, unknown>) => void;++export function installCanvasEditing(+ post: Post,+ labels: Record<string, string>,+) {+ const PRIMARY = "#f54e00";+ let enabled = false;+ let rev = 0;+ let hovered: HTMLElement | null = null;+ let selected: HTMLElement | null = null;+ let selectedBlockId: string | null = null;+ let selectedSource: { key: string; block: string | null } | null = null;+ let dragOrigin: { x: number; y: number; element: HTMLElement } | null = null;+ let frame = 0;++ const EASE_OUT = "cubic-bezier(0.23, 1, 0.32, 1)";+ const EASE_IN_OUT = "cubic-bezier(0.77, 0, 0.175, 1)";+ const reduceMotion = () =>+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const layer = document.createElement("div");+ layer.style.cssText =+ "position:fixed;inset:0;pointer-events:none;z-index:2147483646;";+ const hoverBox = document.createElement("div");+ const selectBox = document.createElement("div");+ const label = document.createElement("div");+ const line = document.createElement("div");+ hoverBox.style.cssText = `position:fixed;left:0;top:0;border:1px solid rgba(245,78,0,.45);border-radius:8px;opacity:0;transition:opacity 100ms ease;`;+ selectBox.style.cssText = `position:fixed;left:0;top:0;border:1.5px solid ${PRIMARY};border-radius:10px;opacity:0;box-shadow:0 0 0 3px rgba(245,78,0,.08);transition:opacity 120ms ease;`;+ label.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};color:#fff;font:600 10.5px/18px system-ui,sans-serif;padding:0 7px;border-radius:5px 5px 0 0;opacity:0;white-space:nowrap;transition:opacity 120ms ease;`;+ line.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};border-radius:99px;opacity:0;transition:opacity 120ms ease,transform 110ms ${EASE_OUT};`;+ const emptyHint = document.createElement("div");+ emptyHint.textContent = "Drop blocks here, or click one in the panel";+ emptyHint.style.cssText =+ "position:fixed;display:flex;align-items:center;justify-content:center;border:1.5px dashed rgba(128,128,128,.35);border-radius:12px;color:rgba(128,128,128,.95);font:500 13px/1.4 system-ui,sans-serif;opacity:0;transition:opacity 160ms;";+ layer.append(emptyHint, hoverBox, selectBox, label, line);++ const parseSource = (element: Element) => {+ const raw = element.getAttribute("data-ph-src");+ if (!raw) return null;+ const [file, start, end, flag] = raw.split("|");+ if (!file) return null;+ return {+ file,+ start: Number(start),+ end: Number(end),+ repeated: flag === "r",+ };+ };++ let openBlock: Element | null = null;++ const candidateOf = (start: Element | null): HTMLElement | null => {+ let element: Element | null = start;+ while (element && element !== document.body) {+ const blockRoot = element.closest("[data-ph-block]");+ if (+ blockRoot instanceof HTMLElement &&+ blockRoot !== openBlock &&+ blockRoot.hasAttribute("data-ph-src")+ )+ return blockRoot;+ const source = parseSource(element);+ const rect = element.getBoundingClientRect();+ if (source && !source.repeated && rect.width >= 24 && rect.height >= 12) {+ return element as HTMLElement;+ }+ element = element.parentElement;+ }+ return null;+ };++ const gridSourceOf = (element: HTMLElement) => {+ const parent = element.parentElement;+ if (!parent || !getComputedStyle(parent).display.includes("grid"))+ return null;+ const source = parseSource(parent);+ if (!source || source.repeated) return null;+ return { file: source.file, start: source.start, end: source.end };+ };++ const fullGridRow = (element: HTMLElement) => {+ const grid = gridSourceOf(element);+ const parent = element.parentElement;+ if (!grid || !parent) return null;+ const columns = getComputedStyle(parent)+ .gridTemplateColumns.split(" ")+ .filter(Boolean).length;+ if (columns < 2 || columns >= 4 || parent.children.length !== columns)+ return null;+ return { ...grid, columns };+ };++ const describe = (element: HTMLElement) => {+ const source = parseSource(element);+ const blockType = element.getAttribute("data-ph-block");+ let props: Record<string, unknown> = {};+ try {+ props = JSON.parse(element.getAttribute("data-ph-props") ?? "{}");+ } catch {+ props = {};+ }+ const onlyText =+ element.children.length === 0 ? (element.textContent ?? "") : null;+ return {+ rev,+ source: source+ ? { file: source.file, start: source.start, end: source.end }+ : null,+ blockType,+ blockId: element.getAttribute("data-ph-block-id"),+ props,+ tag: element.tagName.toLowerCase(),+ text: onlyText,+ params: element.getAttribute("data-ph-params"),+ layout: {+ inGrid:+ !!element.parentElement &&+ getComputedStyle(element.parentElement).display.includes("grid"),+ grow: fullGridRow(element),+ grid: gridSourceOf(element),+ },+ };+ };++ const place = (box: HTMLElement, element: HTMLElement | null, inset = 0) => {+ if (!element || !element.isConnected) {+ box.style.opacity = "0";+ return;+ }+ const rect = element.getBoundingClientRect();+ box.style.transform = `translate3d(${rect.left - inset}px, ${rect.top - inset}px, 0)`;+ box.style.width = `${rect.width + inset * 2}px`;+ box.style.height = `${rect.height + inset * 2}px`;+ box.style.opacity = "1";+ };++ const labelFor = (element: HTMLElement): string => {+ const block = element.getAttribute("data-ph-block");+ if (!block) return labels[element.tagName.toLowerCase()] ?? "Element";+ const spaced = block.replace(/([a-z0-9])([A-Z])/g, "$1 $2");+ return labels[block] ?? spaced.charAt(0) + spaced.slice(1).toLowerCase();+ };++ const paintEmptyHint = () => {+ const rootElement = document.getElementById("root")+ ?.firstElementChild as HTMLElement | null;+ const last = rootElement?.lastElementChild;+ const empty = enabled && !!rootElement && rootElement.children.length <= 1;+ if (!empty || !rootElement) {+ emptyHint.style.opacity = "0";+ return;+ }+ const style = getComputedStyle(rootElement);+ const box = rootElement.getBoundingClientRect();+ const left = box.left + Number.parseFloat(style.paddingLeft);+ const width =+ box.width -+ Number.parseFloat(style.paddingLeft) -+ Number.parseFloat(style.paddingRight);+ const top = (last ? last.getBoundingClientRect().bottom : box.top) + 24;+ emptyHint.style.left = `${left}px`;+ emptyHint.style.top = `${top}px`;+ emptyHint.style.width = `${width}px`;+ emptyHint.style.height = "180px";+ emptyHint.style.opacity = "1";+ };++ const paint = () => {+ place(hoverBox, hovered && hovered !== selected ? hovered : null, 3);+ place(selectBox, selected, 4);+ if (selected?.isConnected) {+ const rect = selected.getBoundingClientRect();+ label.textContent = labelFor(selected);+ label.style.transform = `translate3d(${rect.left - 4}px, ${rect.top - 22}px, 0)`;+ label.style.opacity = "1";+ } else {+ label.style.opacity = "0";+ }+ paintEmptyHint();+ frame = requestAnimationFrame(paint);+ };++ const remember = (element: HTMLElement | null) => {+ selected = element;+ selectedBlockId = element?.getAttribute("data-ph-block-id") ?? null;+ const source = element ? parseSource(element) : null;+ selectedSource = source+ ? {+ key: `${source.file}|${source.start}`,+ block: element?.getAttribute("data-ph-block") ?? null,+ }+ : null;+ };++ const select = (element: HTMLElement | null) => {+ remember(element);+ post({+ type: "canvas-edit-select",+ element: element ? describe(element) : null,+ byPointer: true,+ });+ };++ const axisOf = (element: HTMLElement): "row" | "column" => {+ const parent = element.parentElement;+ if (!parent) return "column";+ const style = getComputedStyle(parent);+ if (style.display.includes("flex"))+ return style.flexDirection.startsWith("row") ? "row" : "column";+ if (style.display.includes("grid")) {+ const top = element.getBoundingClientRect().top;+ const siblings = Array.from(parent.children).filter(+ (child) => child !== element,+ );+ const sameRow = siblings.some(+ (sibling) => Math.abs(sibling.getBoundingClientRect().top - top) < 6,+ );+ return sameRow ? "row" : "column";+ }+ return "column";+ };++ const nearestChild = (+ container: HTMLElement,+ x: number,+ y: number,+ ): HTMLElement | null => {+ let best: HTMLElement | null = null;+ let bestDistance = Number.POSITIVE_INFINITY;+ for (const child of Array.from(container.children)) {+ const candidate = candidateOf(child);+ if (+ !candidate ||+ candidate === container ||+ !container.contains(candidate)+ )+ continue;+ const rect = candidate.getBoundingClientRect();+ const dx = Math.max(rect.left - x, 0, x - rect.right);+ const dy = Math.max(rect.top - y, 0, y - rect.bottom);+ const distance = Math.hypot(dx, dy);+ if (distance < bestDistance) {+ best = candidate;+ bestDistance = distance;+ }+ }+ return best;+ };++ const isBox = (element: HTMLElement) => {+ const style = getComputedStyle(element);+ const bordered =+ Number.parseFloat(style.borderTopWidth) > 0 &&+ Number.parseFloat(style.borderBottomWidth) > 0;+ const filled =+ style.backgroundColor !== "rgba(0, 0, 0, 0)" &&+ style.backgroundColor !== "transparent";+ return (+ (bordered || filled) && Number.parseFloat(style.borderTopLeftRadius) > 0+ );+ };++ const coarseTarget = (element: HTMLElement, root: HTMLElement | null) => {+ let current: HTMLElement | null = element;+ while (current && current !== root) {+ const tall = current.getBoundingClientRect().height >= 100;+ if (current.hasAttribute("data-ph-block") || (tall && isBox(current)))+ return current;+ const parent = candidateOf(current.parentElement);+ if (!parent || parent === current) break;+ current = parent;+ }+ let fallback: HTMLElement = element;+ while (fallback !== root && fallback.getBoundingClientRect().height < 100) {+ const parent = candidateOf(fallback.parentElement);+ if (!parent || parent === fallback) break;+ fallback = parent;+ }+ return fallback;+ };++ const findDropTarget = (+ x: number,+ y: number,+ exclude: string | null,+ coarse: boolean,+ ) => {+ let target = candidateOf(document.elementFromPoint(x, y));+ const root = candidateOf(+ document.getElementById("root")?.firstElementChild ?? null,+ );+ if (!target) target = root;+ if (!target) return null;+ if (coarse) target = coarseTarget(target, root);+ const rect = target.getBoundingClientRect();+ const layout = getComputedStyle(target).display;+ const arrangesChildren =+ layout.includes("grid") || layout.includes("flex") || rect.height > 160;+ const atomic = coarse && target !== root && isBox(target);+ const isContainer =+ target === root ||+ (!atomic &&+ target.children.length > 1 &&+ !target.hasAttribute("data-ph-block") &&+ arrangesChildren);+ if (isContainer) {+ const child = nearestChild(target, x, y);+ if (child) target = child;+ }+ const source = parseSource(target);+ if (!source) return null;+ if (exclude) {+ const [file, start, end] = exclude.split("|");+ if (+ source.file === file &&+ source.start >= Number(start) &&+ source.end <= Number(end)+ )+ return null;+ }+ const box = target.getBoundingClientRect();+ const axis = axisOf(target);+ let position: "before" | "after" | "left" | "right";+ let indicator: { left: number; top: number; width: number; height: number };+ const edge = Math.min(64, box.width * 0.2);+ if (axis === "column" && box.width > 240 && x < box.left + edge)+ position = "left";+ else if (axis === "column" && box.width > 240 && x > box.right - edge)+ position = "right";+ else if (axis === "row")+ position = x < box.left + box.width / 2 ? "before" : "after";+ else position = y < box.top + box.height / 2 ? "before" : "after";+ const vertical =+ axis === "row" || position === "left" || position === "right";+ if (vertical) {+ const atStart = position === "before" || position === "left";+ indicator = {+ left: atStart ? box.left - 9 : box.right + 7,+ top: box.top,+ width: 2,+ height: box.height,+ };+ } else {+ indicator = {+ left: box.left,+ top: position === "before" ? box.top - 9 : box.bottom + 7,+ width: box.width,+ height: 2,+ };+ }+ const grow =+ position === "before" || position === "after"+ ? fullGridRow(target)+ : null;+ return {+ rev,+ target: {+ file: source.file,+ start: source.start,+ end: source.end,+ place: position,+ ...(grow ? { grow } : {}),+ },+ indicator,+ };+ };++ const dropTarget = (+ x: number,+ y: number,+ exclude: string | null,+ coarse: boolean,+ ) => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ openBlock = rootElement?.hasAttribute("data-ph-block") ? rootElement : null;+ try {+ return findDropTarget(x, y, exclude, coarse);+ } finally {+ openBlock = null;+ }+ };++ const showLine = (+ indicator: {+ left: number;+ top: number;+ width: number;+ height: number;+ } | null,+ ) => {+ if (!indicator) {+ line.style.opacity = "0";+ return;+ }+ const wasHidden = line.style.opacity !== "1";+ if (wasHidden) line.style.transition = "none";+ line.style.transform = `translate3d(${indicator.left}px, ${indicator.top}px, 0)`;+ line.style.width = `${indicator.width}px`;+ line.style.height = `${indicator.height}px`;+ if (wasHidden) {+ void line.offsetWidth;+ line.style.transition = `opacity 120ms ease, transform 110ms ${EASE_OUT}`;+ }+ line.style.opacity = "1";+ };++ let forwarding = false;+ let lifted: HTMLElement | null = null;+ const drop = () => {+ if (!lifted) return;+ lifted.style.removeProperty("opacity");+ lifted.style.removeProperty("transition");+ lifted = null;+ };++ const onMove = (event: MouseEvent) => {+ if (!enabled) return;+ const pressed = (event.buttons & 1) === 1;+ if (forwarding) {+ if (!pressed) {+ forwarding = false;+ drop();+ post({ type: "canvas-edit-pointer-cancel" });+ return;+ }+ post({ type: "canvas-edit-pointer", x: event.clientX, y: event.clientY });+ return;+ }+ if (dragOrigin && !pressed) dragOrigin = null;+ hovered = candidateOf(event.target as Element);+ if (+ dragOrigin &&+ Math.hypot(event.clientX - dragOrigin.x, event.clientY - dragOrigin.y) > 5+ ) {+ const described = describe(dragOrigin.element);+ lifted = dragOrigin.element;+ lifted.style.transition = "opacity 120ms";+ lifted.style.opacity = "0.35";+ dragOrigin = null;+ forwarding = true;+ hovered = null;+ post({+ type: "canvas-edit-drag-start",+ element: described,+ x: event.clientX,+ y: event.clientY,+ });+ }+ };++ const TEXT_TAGS = [+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "p",+ "span",+ "li",+ "small",+ "strong",+ "em",+ "label",+ "td",+ "th",+ "blockquote",+ "figcaption",+ ];+ let editingText: { element: HTMLElement; original: string } | null = null;++ const finishText = (commit: boolean) => {+ const current = editingText;+ if (!current) return;+ editingText = null;+ const { element, original } = current;+ const text = (element.textContent ?? "").replace(/\s+/g, " ").trim();+ element.removeAttribute("contenteditable");+ element.style.removeProperty("outline");+ element.style.removeProperty("cursor");+ if (!commit || !text || text === original.trim()) {+ element.textContent = original;+ return;+ }+ post({ type: "canvas-edit-text", element: describe(element), text });+ };++ const startText = (element: HTMLElement) => {+ const plain =+ !element.hasAttribute("data-ph-block") &&+ element.children.length === 0 &&+ TEXT_TAGS.includes(element.tagName.toLowerCase());+ if (!plain) return false;+ editingText = { element, original: element.textContent ?? "" };+ element.setAttribute("contenteditable", "plaintext-only");+ element.style.outline = "none";+ element.style.cursor = "text";+ element.focus();+ const range = document.createRange();+ range.selectNodeContents(element);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ element.addEventListener("blur", () => finishText(true), { once: true });+ element.addEventListener("keydown", (event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ element.blur();+ }+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ finishText(false);+ element.blur();+ }+ });+ return true;+ };++ const onDouble = (event: MouseEvent) => {+ if (!enabled) return;+ event.preventDefault();+ event.stopPropagation();+ const element = candidateOf(event.target as Element);+ if (element && element !== editingText?.element) startText(element);+ };++ const onDown = (event: MouseEvent) => {+ forwarding = false;+ if (!enabled || event.button !== 0) return;+ if (editingText?.element.contains(event.target as Node)) return;+ const element = candidateOf(event.target as Element);+ event.preventDefault();+ event.stopPropagation();+ if (!element) {+ select(null);+ return;+ }+ select(element);+ const isRoot =+ element ===+ candidateOf(document.getElementById("root")?.firstElementChild ?? null);+ if (!isRoot) dragOrigin = { x: event.clientX, y: event.clientY, element };+ };++ const swallow = (event: Event) => {+ if (!enabled) return;+ event.preventDefault();+ event.stopPropagation();+ };++ const onUp = (_event: MouseEvent) => {+ dragOrigin = null;+ if (!forwarding) return;+ forwarding = false;+ post({+ type: "canvas-edit-pointer-up",+ });+ };++ const onKey = (event: KeyboardEvent) => {+ if (!enabled) return;+ const target = event.target as HTMLElement | null;+ if (+ target &&+ (target.isContentEditable ||+ ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName))+ )+ return;+ if (+ ["Backspace", "Delete", "Escape"].includes(event.key) ||+ ((event.metaKey || event.ctrlKey) &&+ ["d", "z"].includes(event.key.toLowerCase()))+ ) {+ event.preventDefault();+ post({+ type: "canvas-edit-key",+ key: event.key,+ metaKey: event.metaKey,+ ctrlKey: event.ctrlKey,+ shiftKey: event.shiftKey,+ });+ }+ };++ const land = (element: HTMLElement) => {+ const keyframes = reduceMotion()+ ? [{ opacity: 0 }, { opacity: 1 }]+ : [+ { opacity: 0, transform: "scale(0.985)" },+ { opacity: 1, transform: "none" },+ ];+ element.animate(keyframes, { duration: 240, easing: EASE_OUT });+ };++ let captured = new Map<string, DOMRect>();++ const capture = () => {+ captured = new Map();+ for (const element of Array.from(+ document.querySelectorAll<HTMLElement>("[data-ph-block-id]"),+ )) {+ const id = element.getAttribute("data-ph-block-id");+ if (id) captured.set(id, element.getBoundingClientRect());+ }+ };++ const slideIntoPlace = (): Map<string, DOMRect> => {+ const before = captured;+ captured = new Map();+ if (reduceMotion() || before.size === 0) return before;+ for (const element of Array.from(+ document.querySelectorAll<HTMLElement>("[data-ph-block-id]"),+ )) {+ const id = element.getAttribute("data-ph-block-id");+ const previous = id ? before.get(id) : undefined;+ if (!previous) continue;+ const now = element.getBoundingClientRect();+ const dx = previous.left - now.left;+ const dy = previous.top - now.top;+ const resized =+ Math.abs(previous.width - now.width) > 2 ||+ Math.abs(previous.height - now.height) > 2;+ if (resized || (Math.abs(dx) < 1 && Math.abs(dy) < 1)) continue;+ element.animate(+ [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }],+ { duration: 300, easing: EASE_IN_OUT },+ );+ }+ return before;+ };++ const afterMount = (+ nextRev: number,+ focusBlockId: string | null,+ focusSource: string | null,+ attempt = 0,+ ) => {+ rev = nextRev;+ hovered = null;+ const rootElement = candidateOf(+ document.getElementById("root")?.firstElementChild ?? null,+ );+ if (!rootElement && attempt < 120) {+ requestAnimationFrame(() => {+ if (rev === nextRev)+ afterMount(nextRev, focusBlockId, focusSource, attempt + 1);+ });+ return;+ }+ const previousRects = slideIntoPlace();+ const rootSource = rootElement ? parseSource(rootElement) : null;+ post({+ type: "canvas-edit-root",+ rev,+ root: rootSource+ ? {+ file: rootSource.file,+ start: rootSource.start,+ end: rootSource.end,+ }+ : null,+ });+ const id = focusBlockId ?? selectedBlockId;+ const sourceAt = (key: string) =>+ document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);+ const previous = selectedSource ? sourceAt(selectedSource.key) : null;+ const sameBlock =+ previous?.getAttribute("data-ph-block") === selectedSource?.block;+ const bySource = focusSource+ ? sourceAt(focusSource)+ : sameBlock+ ? previous+ : null;+ const element = id+ ? document.querySelector(`[data-ph-block-id="${CSS.escape(id)}"]`)+ : bySource;+ if (element instanceof HTMLElement) {+ remember(element);+ post({ type: "canvas-edit-select", element: describe(element) });+ const arrived =+ !!focusBlockId && !focusSource && !previousRects.has(focusBlockId);+ if (arrived) land(element);+ } else {+ remember(null);+ post({ type: "canvas-edit-select", element: null });+ }+ };++ const setEnabled = (next: boolean) => {+ if (next === enabled) return;+ enabled = next;+ if (enabled) {+ document.body.appendChild(layer);+ document.documentElement.style.cursor = "default";+ frame = requestAnimationFrame(paint);+ } else {+ layer.remove();+ cancelAnimationFrame(frame);+ selected = null;+ hovered = null;+ }+ };++ window.addEventListener("mousemove", onMove, true);+ window.addEventListener("mousedown", onDown, true);+ window.addEventListener("mouseup", onUp, true);+ window.addEventListener("click", swallow, true);+ window.addEventListener("dblclick", onDouble, true);+ window.addEventListener("keydown", onKey, true);+ document.addEventListener("mouseleave", () => {+ hovered = null;+ });++ return {+ capture,+ setEnabled,+ afterMount,+ handle(message: Record<string, unknown>) {+ if (message.type === "canvas-edit-drag-move") {+ const hit = enabled+ ? dropTarget(+ Number(message.x),+ Number(message.y),+ (message.exclude as string | null) ?? null,+ message.coarse === true,+ )+ : null;+ showLine(hit?.indicator ?? null);+ post({+ type: "canvas-edit-drop-target",+ hit: hit ? { rev: hit.rev, target: hit.target } : null,+ });+ return true;+ }+ if (message.type === "canvas-edit-drag-end") {+ if (message.final === true) {+ forwarding = false;+ dragOrigin = null;+ drop();+ }+ showLine(null);+ return true;+ }+ if (message.type === "canvas-edit-deselect") {+ remember(null);+ return true;+ }+ return false;+ },+ };+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceHooks.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceHooks.tsnew file mode 100644index 000000000000..d96128bc8cd3--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceHooks.ts@@ -0,0 +1,139 @@+import {+ CANVAS_ENTRY_PATH,+ type CanvasStarter,+ canvasCapabilities,+ starterProject,+} from "@posthog/core/canvas/blockLibrary/blockProject";+import { useHostTRPC } from "@posthog/host-router/react";+import {+ describeChanges,+ isSourceDirty,+ useCanvasSourceEntry,+ useCanvasSourceStore,+} from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import { invalidateCanvasLifecycle } from "@posthog/ui/features/canvas/hooks/invalidateCanvasLifecycle";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useCallback, useEffect } from "react";++const SOURCE_POLL_MS = 4_000;+const SAVE_DEBOUNCE_MS = 700;++export type CanvasSourceLoad = "loading" | "ready" | "empty";++export function useCanvasSourceSync(+ canvasId: string,+ enabled: boolean,+): CanvasSourceLoad {+ const trpc = useHostTRPC();+ const entry = useCanvasSourceEntry(canvasId);+ const { data, isLoading } = useQuery(+ trpc.dashboards.source.queryOptions(+ { id: canvasId },+ {+ enabled,+ refetchInterval: enabled ? SOURCE_POLL_MS : false,+ staleTime: 1_000,+ },+ ),+ );+ const remoteVersionId = data?.currentVersionId ?? null;+ const remoteHasCode = !!data?.project.files[CANVAS_ENTRY_PATH]?.trim();++ const hasEntry = !!entry;+ const idle = !isSourceDirty(entry) && !entry?.saving;+ useEffect(() => {+ if (!data || !remoteHasCode) return;+ const existing = useCanvasSourceStore.getState().entries[canvasId];+ const missing = !hasEntry && !existing;+ const stale =+ !!existing && existing.baseVersionId !== remoteVersionId && idle;+ if (missing || stale) {+ useCanvasSourceStore+ .getState()+ .load(canvasId, data.project, remoteVersionId);+ }+ }, [data, remoteHasCode, remoteVersionId, canvasId, hasEntry, idle]);++ if (entry) return "ready";+ if (isLoading || !data) return "loading";+ return remoteHasCode ? "loading" : "empty";+}++export function useStartCanvasFromStarter(+ canvasId: string,+): (starter: CanvasStarter) => void {+ return useCallback(+ (starter: CanvasStarter) => {+ const project = starterProject(starter);+ const store = useCanvasSourceStore.getState();+ store.load(canvasId, { ...project, files: {} }, null);+ store.apply(canvasId, project.files);+ },+ [canvasId],+ );+}++export function useCanvasSourceAutosave(canvasId: string): void {+ const trpc = useHostTRPC();+ const queryClient = useQueryClient();+ const entry = useCanvasSourceEntry(canvasId);+ const { mutateAsync } = useMutation(+ trpc.dashboards.publishProject.mutationOptions(),+ );+ const dirty = isSourceDirty(entry);+ const files = entry?.files;+ const saving = entry?.saving ?? false;+ const blocked = entry?.saveError != null || entry?.conflict != null;++ useEffect(() => {+ if (!dirty || saving || blocked || !files) return;+ const timer = setTimeout(() => {+ const store = useCanvasSourceStore.getState();+ const snapshot = store.entries[canvasId];+ if (!snapshot) return;+ store.setSaving(canvasId, true);+ const project = {+ ...snapshot.project,+ files: snapshot.files,+ capabilities: canvasCapabilities(+ snapshot.project.capabilities,+ snapshot.files,+ ),+ };+ mutateAsync({+ id: canvasId,+ project,+ expectedCurrentVersionId: snapshot.baseVersionId,+ prompt: describeChanges(snapshot.changes),+ })+ .then((result) => {+ const latest = useCanvasSourceStore.getState();+ if (result.status === "conflict") {+ latest.setConflict(canvasId, result.currentVersionId);+ return;+ }+ queryClient.setQueryData(+ trpc.dashboards.source.queryKey({ id: canvasId }),+ { project, currentVersionId: result.currentVersionId },+ );+ latest.markSaved(+ canvasId,+ snapshot.files,+ result.currentVersionId,+ snapshot.changes.length,+ );+ void invalidateCanvasLifecycle(queryClient, trpc, canvasId);+ })+ .catch((error: unknown) => {+ useCanvasSourceStore+ .getState()+ .setSaving(+ canvasId,+ false,+ error instanceof Error ? error.message : String(error),+ );+ });+ }, SAVE_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ }, [dirty, saving, blocked, files, canvasId, mutateAsync, queryClient, trpc]);+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.test.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.test.tsnew file mode 100644index 000000000000..56419797bc4e--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.test.ts@@ -0,0 +1,55 @@+import type { CanvasSourceProject } from "@posthog/core/canvas/dashboardSchemas";+import { beforeEach, describe, expect, it } from "vitest";+import { isSourceDirty, useCanvasSourceStore } from "./canvasSourceStore";++const CANVAS = "canvas-1";+const PROJECT = {+ schemaVersion: 1,+ entryHtml: "index.html",+ files: { "src/canvas.tsx": "saved" },+ dependencies: {},+} as unknown as CanvasSourceProject;++function entry() {+ const current = useCanvasSourceStore.getState().entries[CANVAS];+ if (!current) throw new Error("missing entry");+ return current;+}++describe("canvasSourceStore conflicts", () => {+ beforeEach(() => {+ const store = useCanvasSourceStore.getState();+ store.load(CANVAS, PROJECT, "v1");+ store.apply(CANVAS, { "src/canvas.tsx": "local edit" });+ store.setConflict(CANVAS, "v2");+ });++ it.each([+ {+ keepLocal: true,+ base: "v2",+ files: { "src/canvas.tsx": "local edit" },+ dirty: true,+ },+ {+ keepLocal: false,+ base: "v1",+ files: { "src/canvas.tsx": "saved" },+ dirty: false,+ },+ ])(+ "keepLocal=$keepLocal publishes over v2 only when chosen",+ ({ keepLocal, base, files, dirty }) => {+ useCanvasSourceStore.getState().resolveConflict(CANVAS, keepLocal);+ expect(entry().conflict).toBeNull();+ expect(entry().baseVersionId).toBe(base);+ expect(entry().files).toEqual(files);+ expect(isSourceDirty(entry())).toBe(dirty);+ },+ );++ it("drops undo history when a newer version loads", () => {+ useCanvasSourceStore.getState().load(CANVAS, PROJECT, "v2");+ expect(entry().past).toEqual([]);+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.tsnew file mode 100644index 000000000000..a4d98ff532be--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasSourceStore.ts@@ -0,0 +1,275 @@+import type { ParamSchema } from "@posthog/core/canvas/blockLibrary/params";+import type {+ GridGrowth,+ SourceFiles,+ SourceRange,+} from "@posthog/core/canvas/blockLibrary/sourceEdits";+import type { CanvasSourceProject } from "@posthog/core/canvas/dashboardSchemas";+import { create } from "zustand";++const HISTORY_LIMIT = 80;+const MAX_NOTED_CHANGES = 20;++export interface CanvasEditSelection {+ rev: number;+ source: SourceRange | null;+ blockType: string | null;+ blockId: string | null;+ props: Record<string, unknown>;+ tag: string;+ text: string | null;+ layout: {+ inGrid: boolean;+ grow: GridGrowth | null;+ grid: SourceRange | null;+ };+ params: ParamSchema | null;+}++export interface CanvasSourceEntry {+ project: CanvasSourceProject;+ files: SourceFiles;+ savedFiles: SourceFiles;+ baseVersionId: string | null;+ saving: boolean;+ saveError: string | null;+ conflict: { versionId: string | null } | null;+ past: SourceFiles[];+ future: SourceFiles[];+ rev: number;+ focusBlockId: string | null;+ focusSource: string | null;+ rootSource: SourceRange | null;+ mountedRev: number;+ changes: string[];+}++interface CanvasSourceState {+ entries: Record<string, CanvasSourceEntry>;+ selection: Record<string, CanvasEditSelection | null>;+ libraryOpen: Record<string, boolean>;+ setLibraryOpen: (canvasId: string, open: boolean) => void;+ load: (+ canvasId: string,+ project: CanvasSourceProject,+ versionId: string | null,+ ) => void;+ apply: (+ canvasId: string,+ files: SourceFiles,+ focusBlockId?: string | null,+ focusSource?: string | null,+ ) => void;+ undo: (canvasId: string) => void;+ redo: (canvasId: string) => void;+ setSaving: (canvasId: string, saving: boolean, error?: string | null) => void;+ markSaved: (+ canvasId: string,+ files: SourceFiles,+ versionId: string,+ noted: number,+ ) => void;+ noteChange: (canvasId: string, label: string) => void;+ setConflict: (canvasId: string, versionId: string | null) => void;+ resolveConflict: (canvasId: string, keepLocal: boolean) => void;+ setSelection: (+ canvasId: string,+ selection: CanvasEditSelection | null,+ ) => void;+ setMounted: (+ canvasId: string,+ rev: number,+ rootSource: SourceRange | null,+ ) => void;+}++function patch(+ state: CanvasSourceState,+ canvasId: string,+ update: (entry: CanvasSourceEntry) => Partial<CanvasSourceEntry>,+): Partial<CanvasSourceState> {+ const entry = state.entries[canvasId];+ if (!entry) return {};+ return {+ entries: { ...state.entries, [canvasId]: { ...entry, ...update(entry) } },+ };+}++export const useCanvasSourceStore = create<CanvasSourceState>((set) => ({+ entries: {},+ selection: {},+ libraryOpen: {},+ load: (canvasId, project, versionId) =>+ set((state) => {+ const previous = state.entries[canvasId];+ return {+ entries: {+ ...state.entries,+ [canvasId]: {+ project,+ files: project.files,+ savedFiles: project.files,+ baseVersionId: versionId,+ saving: false,+ saveError: null,+ conflict: null,+ past: [],+ future: [],+ rev: (previous?.rev ?? 0) + 1,+ focusBlockId: null,+ focusSource: null,+ rootSource: previous?.rootSource ?? null,+ mountedRev: previous?.mountedRev ?? 0,+ changes: [],+ },+ },+ };+ }),+ apply: (canvasId, files, focusBlockId = null, focusSource = null) =>+ set((state) =>+ patch(state, canvasId, (entry) => ({+ files,+ past: [...entry.past, entry.files].slice(-HISTORY_LIMIT),+ future: [],+ rev: entry.rev + 1,+ focusBlockId,+ focusSource,+ })),+ ),+ undo: (canvasId) =>+ set((state) =>+ patch(state, canvasId, (entry) => {+ const previous = entry.past[entry.past.length - 1];+ if (!previous) return {};+ return {+ files: previous,+ past: entry.past.slice(0, -1),+ future: [entry.files, ...entry.future],+ rev: entry.rev + 1,+ changes: [...entry.changes, "Undid a change"],+ focusBlockId: null,+ focusSource: null,+ };+ }),+ ),+ redo: (canvasId) =>+ set((state) =>+ patch(state, canvasId, (entry) => {+ const [next, ...rest] = entry.future;+ if (!next) return {};+ return {+ files: next,+ past: [...entry.past, entry.files],+ future: rest,+ rev: entry.rev + 1,+ changes: [...entry.changes, "Redid a change"],+ focusBlockId: null,+ focusSource: null,+ };+ }),+ ),+ setSaving: (canvasId, saving, error = null) =>+ set((state) =>+ patch(state, canvasId, () => ({ saving, saveError: error })),+ ),+ markSaved: (canvasId, files, versionId, noted) =>+ set((state) =>+ patch(state, canvasId, (entry) => ({+ savedFiles: files,+ baseVersionId: versionId,+ saving: false,+ saveError: null,+ changes: entry.changes.slice(noted),+ })),+ ),+ noteChange: (canvasId, label) =>+ set((state) =>+ patch(state, canvasId, (entry) => ({+ changes:+ entry.changes[entry.changes.length - 1] === label+ ? entry.changes+ : [...entry.changes, label].slice(-MAX_NOTED_CHANGES),+ })),+ ),+ setConflict: (canvasId, versionId) =>+ set((state) =>+ patch(state, canvasId, () => ({+ saving: false,+ saveError: null,+ conflict: { versionId },+ })),+ ),+ resolveConflict: (canvasId, keepLocal) =>+ set((state) =>+ patch(state, canvasId, (entry) =>+ keepLocal+ ? {+ baseVersionId: entry.conflict?.versionId ?? entry.baseVersionId,+ conflict: null,+ }+ : {+ files: entry.savedFiles,+ past: [],+ future: [],+ rev: entry.rev + 1,+ changes: [],+ conflict: null,+ },+ ),+ ),+ setLibraryOpen: (canvasId, open) =>+ set((state) => ({+ libraryOpen: { ...state.libraryOpen, [canvasId]: open },+ })),+ setSelection: (canvasId, selection) =>+ set((state) => ({+ selection: { ...state.selection, [canvasId]: selection },+ })),+ setMounted: (canvasId, rev, rootSource) =>+ set((state) =>+ patch(state, canvasId, () => ({ mountedRev: rev, rootSource })),+ ),+}));++export function isRootSelection(+ entry: CanvasSourceEntry,+ selection: CanvasEditSelection | null | undefined,+): boolean {+ const root = entry.rootSource;+ return (+ !!selection?.source &&+ !!root &&+ selection.source.file === root.file &&+ selection.source.start === root.start+ );+}++export function isSourceDirty(entry: CanvasSourceEntry | undefined): boolean {+ return !!entry && entry.files !== entry.savedFiles;+}++export function useCanvasSourceEntry(+ canvasId: string,+): CanvasSourceEntry | undefined {+ return useCanvasSourceStore((state) => state.entries[canvasId]);+}++export function useCanvasLibraryOpen(canvasId: string): boolean {+ return useCanvasSourceStore((state) => state.libraryOpen[canvasId] ?? false);+}++export function useCanvasEditSelection(+ canvasId: string,+): CanvasEditSelection | null {+ return useCanvasSourceStore((state) => state.selection[canvasId] ?? null);+}++export function describeChanges(changes: string[]): string {+ const unique = Array.from(new Set(changes));+ if (unique.length === 0) return "Edited the canvas";+ if (unique.length === 1) return unique[0] ?? "Edited the canvas";+ if (unique.length <= 3) {+ return `${unique.slice(0, -1).join(", ")} and ${unique[unique.length - 1]?.toLowerCase()}`;+ }+ return `${unique.slice(0, 2).join(", ")} and ${unique.length - 2} more changes`;+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/editorFrame.ts b/products/desktop/packages/ui/src/features/canvas/blocks/editorFrame.tsnew file mode 100644index 000000000000..60c4adb57074--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/editorFrame.ts@@ -0,0 +1,14 @@+export const CANVAS_EDITOR_CHANNEL = "posthog-canvas";++export function canvasEditorFrame(): HTMLIFrameElement | null {+ return document.querySelector<HTMLIFrameElement>(+ "iframe[data-canvas-source-editor]",+ );+}++export function postToCanvasEditor(message: Record<string, unknown>): void {+ canvasEditorFrame()?.contentWindow?.postMessage(+ { channel: CANVAS_EDITOR_CHANNEL, ...message },+ "*",+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/inspector/Pickers.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/Pickers.tsxnew file mode 100644index 000000000000..48353a49bc0e--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/Pickers.tsx@@ -0,0 +1,301 @@+import { CaretDown, Lightning } from "@phosphor-icons/react";+import { propertyDisplayName } from "@posthog/core/canvas/blockLibrary/propertyNames";+import {+ Button,+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+} from "@posthog/quill";+import {+ TOP_EVENT_PROPERTIES_HOGQL,+ TOP_EVENTS_HOGQL,+ useSavedInsights,+ useTopValues,+} from "@posthog/ui/features/canvas/blocks/pickerQueries";+import { useDebouncedValue } from "@posthog/ui/primitives/hooks/useDebouncedValue";+import { useCallback, useMemo, useRef, useState } from "react";++const CUSTOM_PREFIX = "__custom__:";+const NONE_VALUE = "__none__";++function eventLabel(event: string): string {+ const known: Record<string, string> = {+ $pageview: "Pageview",+ $pageleave: "Pageleave",+ $autocapture: "Autocapture",+ $screen: "Screen",+ $identify: "Identify",+ $exception: "Exception",+ $web_vitals: "Web vitals",+ $feature_flag_called: "Feature flag called",+ $groupidentify: "Group identify",+ $set: "Set person properties",+ };+ if (known[event]) return known[event];+ if (!event.startsWith("$")) return event;+ const words = event.slice(1).replaceAll("_", " ");+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function sameText(value: string): string {+ return value;+}++interface SearchPickerProps {+ value: string | null;+ onChange: (value: string | null) => void;+ options: string[];+ loading: boolean;+ placeholder: string;+ searchPlaceholder: string;+ ariaLabel: string;+ allowNone?: boolean;+ noneLabel?: string;+ format?: (value: string) => string;+ onSearchChange?: (search: string) => void;+}++function SearchPicker({+ value,+ onChange,+ options,+ loading,+ placeholder,+ searchPlaceholder,+ ariaLabel,+ allowNone,+ noneLabel = "None",+ format = sameText,+ onSearchChange,+}: SearchPickerProps) {+ const [open, setOpen] = useState(false);+ const [search, setSearchState] = useState("");+ const setSearch = (next: string) => {+ setSearchState(next);+ onSearchChange?.(next);+ };+ const anchorRef = useRef<HTMLDivElement>(null);+ const items = useMemo(() => {+ const needle = search.trim().toLowerCase();+ const base =+ value && !options.includes(value) ? [value, ...options] : options;+ const matches = needle+ ? base.filter(+ (option) =>+ option.toLowerCase().includes(needle) ||+ format(option).toLowerCase().includes(needle),+ )+ : base;+ const exact = base.some((option) => option.toLowerCase() === needle);+ const custom = needle && !exact ? [`${CUSTOM_PREFIX}${search.trim()}`] : [];+ return [+ ...(allowNone && !needle ? [NONE_VALUE] : []),+ ...matches.slice(0, 150),+ ...custom,+ ];+ }, [search, options, value, allowNone, format]);++ const choose = (next: string | null) => {+ setOpen(false);+ setSearch("");+ if (next === null) return;+ if (next === NONE_VALUE) {+ onChange(null);+ return;+ }+ onChange(+ next.startsWith(CUSTOM_PREFIX) ? next.slice(CUSTOM_PREFIX.length) : next,+ );+ };++ return (+ <div ref={anchorRef} className="w-full">+ <Combobox+ items={items}+ filter={null}+ value={value ?? NONE_VALUE}+ onValueChange={(next) => choose(next as string | null)}+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) setSearch("");+ }}+ inputValue={search}+ onInputValueChange={(next) => setSearch(next ?? "")}+ modal={false}+ >+ <ComboboxTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className="w-full min-w-0 justify-between"+ aria-label={ariaLabel}+ >+ <span className="min-w-0 truncate">+ {value ? format(value) : allowNone ? noneLabel : placeholder}+ </span>+ <CaretDown+ size={10}+ weight="bold"+ className="shrink-0 opacity-60"+ />+ </Button>+ }+ />+ <ComboboxContent+ anchor={anchorRef}+ side="bottom"+ align="start"+ sideOffset={4}+ className="w-[260px]"+ >+ <ComboboxInput placeholder={searchPlaceholder} showTrigger={false} />+ <ComboboxEmpty>+ {loading ? "Loading…" : "Nothing found"}+ </ComboboxEmpty>+ <ComboboxList className="max-h-[280px]">+ {(item: string) => {+ if (item === NONE_VALUE) {+ return (+ <ComboboxItem key={item} value={item}>+ <span className="text-muted-foreground">{noneLabel}</span>+ </ComboboxItem>+ );+ }+ if (item.startsWith(CUSTOM_PREFIX)) {+ const raw = item.slice(CUSTOM_PREFIX.length);+ return (+ <ComboboxItem key={item} value={item}>+ <Lightning size={12} className="shrink-0" />+ <span className="min-w-0 truncate">Use “{raw}”</span>+ </ComboboxItem>+ );+ }+ return (+ <ComboboxItem key={item} value={item} title={item}>+ <span className="min-w-0 flex-1 truncate">+ {format(item)}+ </span>+ {format(item) !== item ? (+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">+ {item}+ </span>+ ) : null}+ </ComboboxItem>+ );+ }}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </div>+ );+}++export function EventPicker({+ value,+ onChange,+}: {+ value: string;+ onChange: (value: string) => void;+}) {+ const { data: options = [], isLoading } = useTopValues(TOP_EVENTS_HOGQL);+ return (+ <SearchPicker+ value={value}+ onChange={(next) => {+ if (next) onChange(next);+ }}+ options={options}+ loading={isLoading}+ placeholder="Pick an event"+ searchPlaceholder="Search events…"+ ariaLabel="Event"+ format={eventLabel}+ />+ );+}++export function PropertyPicker({+ value,+ onChange,+ allowNone,+ noneLabel,+}: {+ value: string | null;+ onChange: (value: string | null) => void;+ allowNone?: boolean;+ noneLabel?: string;+}) {+ const { data: options = [], isLoading } = useTopValues(+ TOP_EVENT_PROPERTIES_HOGQL,+ );+ return (+ <SearchPicker+ value={value}+ onChange={onChange}+ options={options}+ loading={isLoading}+ placeholder="Pick a property"+ searchPlaceholder="Search properties…"+ ariaLabel="Property"+ format={propertyDisplayName}+ allowNone={allowNone}+ noneLabel={noneLabel}+ />+ );+}++export function InsightPicker({+ value,+ onChange,+}: {+ value: string | null;+ onChange: (value: string | null) => void;+}) {+ const [search, setSearch] = useState("");+ const [picked, setPicked] = useState<{ shortId: string; name: string }>();+ const { data, isLoading } = useSavedInsights(+ useDebouncedValue(search, 250).debounced,+ );+ const names = useMemo(+ () =>+ new Map([+ ...(picked ? [[picked.shortId, picked.name] as const] : []),+ ...(data ?? []).map(+ (insight) => [insight.shortId, insight.name] as const,+ ),+ ]),+ [data, picked],+ );+ const options = useMemo(+ () => (data ?? []).map((insight) => insight.shortId),+ [data],+ );+ const format = useCallback(+ (shortId: string) => names.get(shortId) ?? shortId,+ [names],+ );+ const choose = (next: string | null) => {+ const name = next ? names.get(next) : undefined;+ if (next && name) setPicked({ shortId: next, name });+ onChange(next);+ };+ return (+ <SearchPicker+ value={value}+ onChange={choose}+ options={options}+ loading={isLoading}+ placeholder="Pick a saved insight"+ searchPlaceholder="Search insights…"+ ariaLabel="Insight"+ format={format}+ onSearchChange={setSearch}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/inspector/SourceInspector.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/SourceInspector.tsxnew file mode 100644index 000000000000..3afe19382a66--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/SourceInspector.tsx@@ -0,0 +1,900 @@+import {+ CopySimple,+ Play,+ Plus,+ Sparkle,+ Trash,+ X,+} from "@phosphor-icons/react";+import {+ type BlockPropsRecord,+ type BlockPropValue,+ blockDefinition,+} from "@posthog/core/canvas/blockLibrary/blockDefinitions";+import {+ builderSql,+ SQL_BLOCK_TYPES,+ SQL_COLUMN_HINTS,+} from "@posthog/core/canvas/blockLibrary/blockSql";+import type {+ ParamSchema,+ ParamSpec,+} from "@posthog/core/canvas/blockLibrary/params";+import { Button, Slider } from "@posthog/quill";+import type { CanvasEditSelection } from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import {+ ControlNote,+ DraftInput,+ DraftTextarea,+ InspectorField,+ InspectorSwitch,+ MathSelect,+ type MathValue,+ OptionSelect,+ Segmented,+} from "@posthog/ui/features/canvas/blocks/inspector/fields";+import {+ EventPicker,+ InsightPicker,+ PropertyPicker,+} from "@posthog/ui/features/canvas/blocks/inspector/Pickers";+import { SqlEditor } from "@posthog/ui/features/canvas/components/context/SqlEditor";+import { type ReactNode, useEffect, useState } from "react";++type Change = (props: BlockPropsRecord) => void;++function asString(value: unknown, fallback = ""): string {+ return typeof value === "string" ? value : fallback;+}++function asStrings(value: unknown, fallback: string[]): string[] {+ return Array.isArray(value) && value.every((item) => typeof item === "string")+ ? value+ : fallback;+}++function asNumber(value: unknown, fallback: number): number {+ return typeof value === "number" ? value : fallback;+}++function asBoolean(value: unknown, fallback: boolean): boolean {+ return typeof value === "boolean" ? value : fallback;+}++function cleanProps(props: Record<string, unknown>): BlockPropsRecord {+ const result: BlockPropsRecord = {};+ for (const [key, value] of Object.entries(props)) {+ if (key === "blockId") continue;+ result[key] = value as BlockPropValue;+ }+ return result;+}++function TitleField({+ props,+ onChange,+}: {+ props: BlockPropsRecord;+ onChange: Change;+}) {+ return (+ <InspectorField label="Title">+ <DraftInput+ value={asString(props.title)}+ ariaLabel="Title"+ placeholder="Leave empty for a default title"+ onCommit={(title) => onChange({ ...props, title: title || undefined })}+ />+ </InspectorField>+ );+}++function FollowFilters({+ props,+ onChange,+}: {+ props: BlockPropsRecord;+ onChange: Change;+}) {+ return (+ <InspectorSwitch+ label="Use canvas filters"+ hint="When off, the date range still applies, but property filters do not."+ checked={asBoolean(props.followFilters, true)}+ onChange={(followFilters) =>+ onChange({ ...props, followFilters: followFilters ? undefined : false })+ }+ />+ );+}++function StepList({+ label,+ values,+ min,+ max,+ onChange,+}: {+ label: string;+ values: string[];+ min: number;+ max: number;+ onChange: (values: string[]) => void;+}) {+ const seen = new Map<string, number>();+ return (+ <InspectorField label={label}>+ <div className="flex flex-col gap-1.5">+ {values.map((item, index) => {+ const count = seen.get(item) ?? 0;+ seen.set(item, count + 1);+ return (+ <div+ key={count ? `${item}#${count}` : item}+ className="flex items-center gap-1.5"+ >+ <span className="w-4 shrink-0 text-center text-[11px] text-muted-foreground tabular-nums">+ {index + 1}+ </span>+ <div className="min-w-0 flex-1">+ <EventPicker+ value={item}+ onChange={(event) =>+ onChange(+ values.map((current, i) =>+ i === index ? event : current,+ ),+ )+ }+ />+ </div>+ <Button+ variant="default"+ size="icon-sm"+ aria-label="Remove"+ disabled={values.length <= min}+ onClick={() => onChange(values.filter((_, i) => i !== index))}+ >+ <X size={12} />+ </Button>+ </div>+ );+ })}+ {values.length < max ? (+ <Button+ variant="outline"+ size="sm"+ onClick={() => onChange([...values, "$pageview"])}+ >+ <Plus size={12} />+ Add+ </Button>+ ) : null}+ </div>+ </InspectorField>+ );+}++const NUMBER_FORMATS = [+ { value: "number", label: "Number" },+ { value: "percent", label: "Percent" },+ { value: "currency", label: "Currency" },+ { value: "duration", label: "Duration" },+];++const WIDTHS = [+ { value: "normal", label: "Normal" },+ { value: "wide", label: "Wide" },+ { value: "full", label: "Full" },+];++function CommonFields({+ selection,+ props,+ onChange,+}: {+ selection: CanvasEditSelection;+ props: BlockPropsRecord;+ onChange: Change;+}): ReactNode {+ const definition = selection.blockType+ ? blockDefinition(selection.blockType)+ : undefined;+ if (!definition) return null;+ const describable = definition.group === "Data";+ const sizable = selection.layout.inGrid;+ if (!describable && !sizable) return null;+ return (+ <>+ {describable ? (+ <InspectorField label="Description">+ <DraftTextarea+ value={asString(props.description)}+ ariaLabel="Description"+ rows={2}+ placeholder="What should readers take from this?"+ onCommit={(description) =>+ onChange({+ ...props,+ description: description.trim() ? description : undefined,+ })+ }+ />+ </InspectorField>+ ) : null}+ {sizable ? (+ <InspectorField label="Width">+ <Segmented+ value={asString(props.span, "normal")}+ ariaLabel="Width"+ options={WIDTHS}+ onChange={(span) =>+ onChange({+ ...props,+ span: span === "normal" ? undefined : span,+ })+ }+ />+ </InspectorField>+ ) : null}+ </>+ );+}++function MeasureField({+ label,+ props,+ onChange,+}: {+ label: string;+ props: BlockPropsRecord;+ onChange: Change;+}) {+ return (+ <InspectorField label={label}>+ <div className="flex flex-col gap-1.5">+ <EventPicker+ value={asString(props.event, "$pageview")}+ onChange={(event) => onChange({ ...props, event })}+ />+ <MathSelect+ value={asString(props.math, "total") as MathValue}+ onChange={(math) => onChange({ ...props, math })}+ />+ </div>+ </InspectorField>+ );+}++function ComponentFields({+ type,+ props,+ onChange,+}: {+ type: string;+ props: BlockPropsRecord;+ onChange: Change;+}): ReactNode {+ switch (type) {+ case "Metric":+ return (+ <>+ <TitleField props={props} onChange={onChange} />+ <MeasureField label="Measure" props={props} onChange={onChange} />+ <InspectorField label="Number format">+ <OptionSelect+ value={asString(props.format, "number")}+ ariaLabel="Number format"+ options={NUMBER_FORMATS}+ onChange={(format) =>+ onChange({+ ...props,+ format: format === "number" ? undefined : format,+ })+ }+ />+ </InspectorField>+ <InspectorSwitch+ label="Compare with previous period"+ checked={asBoolean(props.compare, true)}+ onChange={(compare) =>+ onChange({ ...props, compare: compare ? undefined : false })+ }+ />+ <FollowFilters props={props} onChange={onChange} />+ </>+ );+ case "Trend":+ return (+ <>+ <TitleField props={props} onChange={onChange} />+ <InspectorField label="Chart">+ <Segmented+ value={asString(props.display, "line") as "line" | "bar" | "area"}+ ariaLabel="Chart type"+ options={[+ { value: "line", label: "Line" },+ { value: "bar", label: "Bar" },+ { value: "area", label: "Area" },+ ]}+ onChange={(display) => onChange({ ...props, display })}+ />+ </InspectorField>+ <StepList+ label="Events"+ values={asStrings(props.events, ["$pageview"])}+ min={1}+ max={5}+ onChange={(events) => onChange({ ...props, events })}+ />+ <InspectorField label="Measure">+ <MathSelect+ value={asString(props.math, "total") as MathValue}+ onChange={(math) => onChange({ ...props, math })}+ />+ </InspectorField>+ <InspectorField label="Break down by">+ <PropertyPicker+ value={asString(props.breakdown) || null}+ allowNone+ noneLabel="No breakdown"+ onChange={(breakdown) =>+ onChange({ ...props, breakdown: breakdown ?? undefined })+ }+ />+ </InspectorField>+ <FollowFilters props={props} onChange={onChange} />+ </>+ );+ case "TopList":+ return (+ <>+ <TitleField props={props} onChange={onChange} />+ <InspectorField label="Rank values of">+ <PropertyPicker+ value={asString(props.breakdown, "$pathname")}+ onChange={(breakdown) => {+ if (breakdown) onChange({ ...props, breakdown });+ }}+ />+ </InspectorField>+ <MeasureField label="By" props={props} onChange={onChange} />+ <InspectorField label="Rows">+ <Segmented+ value={String(asNumber(props.limit, 8))}+ ariaLabel="Rows"+ options={[+ { value: "5", label: "5" },+ { value: "8", label: "8" },+ { value: "12", label: "12" },+ ]}+ onChange={(limit) => onChange({ ...props, limit: Number(limit) })}+ />+ </InspectorField>+ <FollowFilters props={props} onChange={onChange} />+ </>+ );+ case "Funnel":+ return (+ <>+ <TitleField props={props} onChange={onChange} />+ <StepList+ label="Steps"+ values={asStrings(props.steps, ["$pageview", "$autocapture"])}+ min={2}+ max={8}+ onChange={(steps) => onChange({ ...props, steps })}+ />+ <InspectorField label="Conversion window">+ <Segmented+ value={String(asNumber(props.windowDays, 14))}+ ariaLabel="Conversion window"+ options={[+ { value: "1", label: "1 day" },+ { value: "7", label: "7 days" },+ { value: "14", label: "14 days" },+ { value: "30", label: "30 days" },+ ]}+ onChange={(windowDays) =>+ onChange({ ...props, windowDays: Number(windowDays) })+ }+ />+ </InspectorField>+ <FollowFilters props={props} onChange={onChange} />+ </>+ );+ case "SqlTable":+ return (+ <>+ <TitleField props={props} onChange={onChange} />+ <SqlField+ type="SqlTable"+ sql={asString(props.query)}+ onCommit={(query) => onChange({ ...props, query })}+ />+ </>+ );+ case "PropertyFilter":+ return (+ <>+ <InspectorField label="Label">+ <DraftInput+ value={asString(props.label)}+ ariaLabel="Label"+ placeholder={asString(props.property, "$browser")}+ onCommit={(label) =>+ onChange({ ...props, label: label || undefined })+ }+ />+ </InspectorField>+ <InspectorField+ label="Property"+ hint="Every data block that uses canvas filters shows only matching events."+ >+ <PropertyPicker+ value={asString(props.property, "$browser")}+ onChange={(property) => {+ if (property) onChange({ ...props, property });+ }}+ />+ </InspectorField>+ </>+ );+ case "DateRange":+ return (+ <ControlNote>+ Sets the date range for every data block on this canvas. Each viewer+ can change it for themselves.+ </ControlNote>+ );+ case "Interval":+ return (+ <ControlNote>+ Groups every chart on this canvas by day, week or month.+ </ControlNote>+ );+ default:+ return (+ <ControlNote>+ This block has no settings here. Ask the agent to change it.+ </ControlNote>+ );+ }+}++const SEGMENTED_OPTION_LIMIT = 4;+const HEX_COLOR = /^#[0-9a-f]{6}$/i;++function clampNumber(value: number, spec: ParamSpec): number {+ const low = spec.min ?? Number.NEGATIVE_INFINITY;+ const high = spec.max ?? Number.POSITIVE_INFINITY;+ return Math.min(high, Math.max(low, value));+}++function stepOf(spec: ParamSpec): number {+ if (spec.step !== null) return spec.step;+ const range = (spec.max ?? 1) - (spec.min ?? 0);+ return Number.isInteger(spec.min) && Number.isInteger(spec.max) && range >= 2+ ? 1+ : range / 100;+}++function firstValue(next: number | readonly number[]): number | undefined {+ return Array.isArray(next) ? next[0] : (next as number);+}++function ParamSlider({+ value,+ spec,+ onCommit,+}: {+ value: number;+ spec: ParamSpec;+ onCommit: (value: number) => void;+}) {+ const [draft, setDraft] = useState(value);+ useEffect(() => setDraft(value), [value]);+ const step = stepOf(spec);+ const decimals =+ step < 1 ? Math.min(2, String(step).split(".")[1]?.length ?? 1) : 0;+ return (+ <div className="flex items-center gap-3">+ <Slider+ aria-label={spec.label}+ value={[draft]}+ min={spec.min ?? 0}+ max={spec.max ?? 100}+ step={step}+ className="min-w-0 flex-1"+ onValueChange={(next: number | readonly number[]) => {+ const raw = firstValue(next);+ if (typeof raw === "number") setDraft(raw);+ }}+ onValueCommitted={(next: number | readonly number[]) => {+ const raw = firstValue(next);+ if (typeof raw === "number" && raw !== value)+ onCommit(Number(raw.toFixed(decimals)));+ }}+ />+ <span className="w-9 shrink-0 text-right text-muted-foreground text-xs tabular-nums">+ {draft.toFixed(decimals)}+ </span>+ </div>+ );+}++function ParamField({+ name,+ spec,+ value,+ onChange,+}: {+ name: string;+ spec: ParamSpec;+ value: unknown;+ onChange: (value: BlockPropValue) => void;+}): ReactNode {+ const hint = spec.description ?? undefined;+ switch (spec.kind) {+ case "boolean":+ return (+ <InspectorSwitch+ label={spec.label}+ hint={hint}+ checked={asBoolean(value, false)}+ onChange={onChange}+ />+ );+ case "longtext":+ return (+ <InspectorField label={spec.label} hint={hint}>+ <DraftTextarea+ value={asString(value)}+ ariaLabel={spec.label}+ rows={3}+ onCommit={onChange}+ />+ </InspectorField>+ );+ case "number":+ if (spec.min !== null && spec.max !== null) {+ return (+ <InspectorField label={spec.label} hint={hint}>+ <ParamSlider+ value={asNumber(value, spec.min)}+ spec={spec}+ onCommit={onChange}+ />+ </InspectorField>+ );+ }+ return (+ <InspectorField label={spec.label} hint={hint}>+ <DraftInput+ value={String(asNumber(value, spec.min ?? 0))}+ ariaLabel={spec.label}+ onCommit={(next) => {+ const parsed = Number(next);+ if (Number.isFinite(parsed)) onChange(clampNumber(parsed, spec));+ }}+ />+ </InspectorField>+ );+ case "select": {+ const current = asString(value, spec.options[0]?.value ?? "");+ return (+ <InspectorField label={spec.label} hint={hint}>+ {spec.options.length <= SEGMENTED_OPTION_LIMIT ? (+ <Segmented+ value={current}+ options={spec.options}+ ariaLabel={spec.label}+ onChange={onChange}+ />+ ) : (+ <OptionSelect+ value={current}+ options={spec.options}+ ariaLabel={spec.label}+ onChange={onChange}+ />+ )}+ </InspectorField>+ );+ }+ case "event":+ return (+ <InspectorField label={spec.label} hint={hint}>+ <EventPicker+ value={asString(value, "$pageview")}+ onChange={onChange}+ />+ </InspectorField>+ );+ case "events":+ return (+ <StepList+ label={spec.label}+ values={asStrings(value, ["$pageview"])}+ min={1}+ max={8}+ onChange={onChange}+ />+ );+ case "property":+ return (+ <InspectorField label={spec.label} hint={hint}>+ <PropertyPicker+ value={asString(value) || null}+ onChange={(next) => onChange(next ?? undefined)}+ />+ </InspectorField>+ );+ case "insight":+ return (+ <InspectorField label={spec.label} hint={hint}>+ <InsightPicker+ value={asString(value) || null}+ onChange={(next) => onChange(next ?? undefined)}+ />+ </InspectorField>+ );+ case "color": {+ const color = asString(value, "#f54e00");+ return (+ <InspectorField label={spec.label} hint={hint}>+ <div className="flex items-center gap-2">+ <label+ className="relative size-8 shrink-0 cursor-pointer overflow-hidden rounded-md border border-border"+ style={{ backgroundColor: color }}+ >+ <input+ type="color"+ aria-label={spec.label}+ value={HEX_COLOR.test(color) ? color : "#000000"}+ onChange={(event) => onChange(event.target.value)}+ className="absolute inset-0 size-full cursor-pointer opacity-0"+ />+ </label>+ <DraftInput+ value={color}+ ariaLabel={`${spec.label} hex`}+ onCommit={onChange}+ />+ </div>+ </InspectorField>+ );+ }+ default:+ return (+ <InspectorField label={spec.label} hint={hint}>+ <DraftInput+ value={asString(value)}+ ariaLabel={spec.label || name}+ onCommit={onChange}+ />+ </InspectorField>+ );+ }+}++function ParamsForm({+ schema,+ props,+ onChange,+}: {+ schema: ParamSchema;+ props: BlockPropsRecord;+ onChange: Change;+}) {+ return (+ <>+ {schema.map(({ name, spec }) => (+ <ParamField+ key={name}+ name={name}+ spec={spec}+ value={props[name] ?? spec.fallback}+ onChange={(value) => onChange({ ...props, [name]: value })}+ />+ ))}+ </>+ );+}++function BlockFields({+ selection,+ props,+ onChange,+}: {+ selection: CanvasEditSelection;+ props: BlockPropsRecord;+ onChange: Change;+}): ReactNode {+ if (selection.params) {+ return (+ <ParamsForm schema={selection.params} props={props} onChange={onChange} />+ );+ }+ if (!selection.blockType) return null;+ return (+ <ComponentFields+ type={selection.blockType}+ props={props}+ onChange={onChange}+ />+ );+}++function SqlField({+ type,+ sql,+ onCommit,+}: {+ type: string;+ sql: string;+ onCommit: (sql: string) => void;+}) {+ const [draft, setDraft] = useState(sql);+ useEffect(() => setDraft(sql), [sql]);+ const changed = draft.trim() !== sql.trim();+ return (+ <InspectorField+ label="HogQL"+ hint={+ <>+ {SQL_COLUMN_HINTS[type]} Keep{" "}+ <code className="font-mono">{"{filters}"}</code> in the WHERE clause+ so the canvas date range and filters apply.+ </>+ }+ >+ <div className="overflow-hidden rounded-md border border-border bg-card">+ <SqlEditor+ key={sql}+ initialValue={sql}+ onChange={setDraft}+ onRun={onCommit}+ />+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[11px] text-muted-foreground">⌘↵ to run</span>+ <Button+ variant="primary"+ size="sm"+ disabled={!changed}+ onClick={() => onCommit(draft)}+ >+ <Play size={12} weight="fill" />+ Run query+ </Button>+ </div>+ </InspectorField>+ );+}++function QueryModeFields({+ type,+ props,+ onChange,+ children,+}: {+ type: string;+ props: BlockPropsRecord;+ onChange: Change;+ children: ReactNode;+}) {+ const sql = typeof props.sql === "string" ? props.sql : null;+ return (+ <>+ <InspectorField label="Data">+ <Segmented+ value={sql === null ? "builder" : "sql"}+ ariaLabel="Data"+ options={[+ { value: "builder", label: "Builder" },+ { value: "sql", label: "SQL" },+ ]}+ onChange={(mode) =>+ onChange(+ mode === "sql"+ ? { ...props, sql: builderSql(type, props) }+ : { ...props, sql: undefined },+ )+ }+ />+ </InspectorField>+ {sql === null ? (+ children+ ) : (+ <>+ <TitleField props={props} onChange={onChange} />+ <SqlField+ type={type}+ sql={sql}+ onCommit={(next) => onChange({ ...props, sql: next })}+ />+ </>+ )}+ </>+ );+}++export function SourceInspector({+ selection,+ isRoot,+ onProps,+ onText,+ onDuplicate,+ onRemove,+}: {+ selection: CanvasEditSelection;+ isRoot: boolean;+ onProps: (props: BlockPropsRecord) => void;+ onText: (text: string) => void;+ onDuplicate: () => void;+ onRemove: () => void;+}) {+ const props = cleanProps(selection.props);+ return (+ <div className="flex flex-col gap-4 p-3">+ {selection.params &&+ selection.blockType &&+ !blockDefinition(selection.blockType) ? (+ <div className="flex gap-2.5 rounded-lg border border-border bg-muted/40 px-3 py-2.5">+ <Sparkle size={14} className="mt-0.5 shrink-0 text-accent-11" />+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="font-medium text-foreground text-xs">+ Set up by the agent+ </span>+ <span className="text-[11.5px] text-muted-foreground leading-snug">+ These fields come from the component's code, so you can change+ them without a prompt.+ </span>+ </div>+ </div>+ ) : null}+ {selection.blockType && SQL_BLOCK_TYPES.has(selection.blockType) ? (+ <QueryModeFields+ type={selection.blockType}+ props={props}+ onChange={onProps}+ >+ <BlockFields selection={selection} props={props} onChange={onProps} />+ </QueryModeFields>+ ) : (+ <BlockFields selection={selection} props={props} onChange={onProps} />+ )}+ <CommonFields selection={selection} props={props} onChange={onProps} />+ {!selection.blockType && selection.text !== null ? (+ <InspectorField label="Text">+ <DraftTextarea+ value={selection.text}+ ariaLabel="Text"+ rows={3}+ onCommit={onText}+ />+ </InspectorField>+ ) : null}+ {!selection.blockType && selection.text === null ? (+ <ControlNote>+ {isRoot+ ? "This is the whole canvas. Drag blocks into it from the panel."+ : "Move this element by dragging it on the canvas, or ask the agent to change it."}+ </ControlNote>+ ) : null}+ {isRoot ? null : (+ <div className="flex gap-1.5">+ <Button variant="outline" size="sm" onClick={onDuplicate}>+ <CopySimple size={12} />+ Duplicate+ </Button>+ <Button variant="outline" size="sm" onClick={onRemove}>+ <Trash size={12} />+ Delete+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/inspector/fields.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/fields.tsxnew file mode 100644index 000000000000..f5cd0172c3f8--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/inspector/fields.tsx@@ -0,0 +1,253 @@+import {+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+ Textarea,+ ToggleGroup,+ ToggleGroupItem,+} from "@posthog/quill";+import { settingsToggleItemClassName } from "@posthog/ui/features/settings/components/SettingsSegmented";+import { type ReactNode, useEffect, useId, useState } from "react";++export type MathValue = "total" | "dau" | "weekly_active" | "monthly_active";++const MATH_OPTIONS: Array<{ value: MathValue; label: string }> = [+ { value: "total", label: "Total count" },+ { value: "dau", label: "Unique users" },+ { value: "weekly_active", label: "Weekly active users" },+ { value: "monthly_active", label: "Monthly active users" },+];++function mathLabel(value: MathValue): string {+ return MATH_OPTIONS.find((option) => option.value === value)?.label ?? value;+}++export function InspectorField({+ label,+ hint,+ children,+}: {+ label: string;+ hint?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="flex flex-col gap-1.5">+ <div className="font-medium text-[11px] text-muted-foreground">+ {label}+ </div>+ {children}+ {hint ? (+ <div className="text-[11px] text-muted-foreground/80 leading-snug">+ {hint}+ </div>+ ) : null}+ </div>+ );+}++export function InspectorSwitch({+ label,+ hint,+ checked,+ onChange,+}: {+ label: string;+ hint?: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ const id = useId();+ return (+ <div className="flex items-start justify-between gap-3">+ <label htmlFor={id} className="min-w-0 cursor-pointer">+ <span className="block text-foreground text-xs">{label}</span>+ {hint ? (+ <span className="block text-[11px] text-muted-foreground/80 leading-snug">+ {hint}+ </span>+ ) : null}+ </label>+ <Switch id={id} checked={checked} onCheckedChange={onChange} size="sm" />+ </div>+ );+}++export function DraftInput({+ value,+ onCommit,+ placeholder,+ ariaLabel,+}: {+ value: string;+ onCommit: (value: string) => void;+ placeholder?: string;+ ariaLabel: string;+}) {+ const [draft, setDraft] = useState(value);+ useEffect(() => setDraft(value), [value]);+ const commit = () => {+ if (draft !== value) onCommit(draft);+ };+ return (+ <Input+ value={draft}+ placeholder={placeholder}+ aria-label={ariaLabel}+ className="h-8"+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={(event) => {+ if (event.key === "Enter") commit();+ }}+ />+ );+}++export function DraftTextarea({+ value,+ onCommit,+ ariaLabel,+ mono,+ rows = 6,+ placeholder,+}: {+ value: string;+ onCommit: (value: string) => void;+ ariaLabel: string;+ mono?: boolean;+ rows?: number;+ placeholder?: string;+}) {+ const [draft, setDraft] = useState(value);+ useEffect(() => setDraft(value), [value]);+ return (+ <Textarea+ value={draft}+ rows={rows}+ placeholder={placeholder}+ aria-label={ariaLabel}+ className={mono ? "font-mono text-[11.5px] leading-relaxed" : "text-xs"}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => {+ if (draft !== value) onCommit(draft);+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ if (draft !== value) onCommit(draft);+ }+ }}+ />+ );+}++export function MathSelect({+ value,+ onChange,+}: {+ value: MathValue;+ onChange: (value: MathValue) => void;+}) {+ return (+ <Select+ value={value}+ onValueChange={(next: MathValue | null) => {+ if (next) onChange(next);+ }}+ >+ <SelectTrigger aria-label="Measure" size="sm" className="w-full">+ <SelectValue>+ {(selected: MathValue) => mathLabel(selected)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start" side="bottom" sideOffset={4}>+ {MATH_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++export function OptionSelect({+ value,+ options,+ onChange,+ ariaLabel,+}: {+ value: string;+ options: Array<{ value: string; label: string }>;+ onChange: (value: string) => void;+ ariaLabel: string;+}) {+ const labelOf = (selected: string) =>+ options.find((option) => option.value === selected)?.label ?? selected;+ return (+ <Select+ value={value}+ onValueChange={(next: string | null) => {+ if (next) onChange(next);+ }}+ >+ <SelectTrigger aria-label={ariaLabel} size="sm" className="w-full">+ <SelectValue>{(selected: string) => labelOf(selected)}</SelectValue>+ </SelectTrigger>+ <SelectContent align="start" side="bottom" sideOffset={4}>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++export function Segmented<T extends string>({+ value,+ options,+ onChange,+ ariaLabel,+}: {+ value: T;+ options: Array<{ value: T; label: string }>;+ onChange: (value: T) => void;+ ariaLabel: string;+}) {+ return (+ <ToggleGroup+ value={[value]}+ onValueChange={(next: string[]) => {+ const selected = next[0] as T | undefined;+ if (selected && selected !== value) onChange(selected);+ }}+ aria-label={ariaLabel}+ >+ {options.map((option) => (+ <ToggleGroupItem+ key={option.value}+ value={option.value}+ size="sm"+ variant="outline"+ className={settingsToggleItemClassName}+ >+ {option.label}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ );+}++export function ControlNote({ children }: { children: ReactNode }) {+ return (+ <div className="rounded-md bg-muted/50 px-2.5 py-2 text-[11.5px] text-muted-foreground leading-snug">+ {children}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/libraryCatalog.ts b/products/desktop/packages/ui/src/features/canvas/blocks/libraryCatalog.tsnew file mode 100644index 000000000000..330ce06627ea--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/libraryCatalog.ts@@ -0,0 +1,92 @@+import {+ ArrowClockwise,+ ArrowsLeftRight,+ CalendarBlank,+ ChartBar,+ ChartLine,+ Clock,+ Code,+ Cube,+ FadersHorizontal,+ Funnel,+ GridFour,+ type Icon,+ Info,+ ListNumbers,+ Minus,+ NumberSquareOne,+ Paragraph,+ Pulse,+ SlidersHorizontal,+ Target,+ TextH,+} from "@phosphor-icons/react";+import {+ BLOCK_DEFINITIONS,+ type BlockDefinition,+ type BlockGroup,+ blockDefinition,+} from "@posthog/core/canvas/blockLibrary/blockDefinitions";+import { componentLabel } from "@posthog/core/canvas/blockLibrary/params";++const ICONS: Record<string, Icon> = {+ Metric: NumberSquareOne,+ Trend: ChartLine,+ TopList: ListNumbers,+ Funnel,+ SqlTable: Code,+ DateRange: CalendarBlank,+ Interval: Clock,+ PropertyFilter: SlidersHorizontal,+ Filters: FadersHorizontal,+ Goal: Target,+ RecentEvents: Pulse,+ Callout: Info,+ Insight: ChartBar,+ Retention: GridFour,+ Compare: ArrowsLeftRight,+ Refresh: ArrowClockwise,+ Heading: TextH,+ Paragraph,+ Divider: Minus,+};++export const LIBRARY_GROUPS: BlockGroup[] = ["Data", "Controls", "Content"];++export interface LibraryEntry extends BlockDefinition {+ icon: Icon;+}++export const LIBRARY: LibraryEntry[] = BLOCK_DEFINITIONS.map((definition) => ({+ ...definition,+ icon: ICONS[definition.type] ?? Cube,+}));++const ELEMENT_LABELS: Record<string, string> = {+ h1: "Heading",+ h2: "Heading",+ h3: "Heading",+ p: "Text",+ hr: "Divider",+ header: "Header",+ main: "Page",+ section: "Section",+};++export const EDIT_LABELS: Record<string, string> = {+ ...ELEMENT_LABELS,+ ...Object.fromEntries(+ BLOCK_DEFINITIONS.map((definition) => [definition.type, definition.label]),+ ),+};++export function libraryLabel(blockType: string | null, tag?: string): string {+ if (blockType) {+ return blockDefinition(blockType)?.label ?? componentLabel(blockType);+ }+ return (tag && ELEMENT_LABELS[tag]) || "Element";+}++export function libraryIcon(blockType: string | null): Icon {+ return (blockType && ICONS[blockType]) || Cube;+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/pickerQueries.ts b/products/desktop/packages/ui/src/features/canvas/blocks/pickerQueries.tsnew file mode 100644index 000000000000..89116d00cdaf--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/pickerQueries.ts@@ -0,0 +1,30 @@+import { hostClient } from "@posthog/ui/features/canvas/hostClient";+import { keepPreviousData, useQuery } from "@tanstack/react-query";++export const TOP_EVENTS_HOGQL =+ "SELECT event, count() AS c FROM events WHERE timestamp > now() - INTERVAL 30 DAY GROUP BY event ORDER BY c DESC LIMIT 300";++export const TOP_EVENT_PROPERTIES_HOGQL =+ "SELECT k, count() AS c FROM (SELECT arrayJoin(JSONExtractKeys(properties)) AS k FROM events WHERE timestamp > now() - INTERVAL 7 DAY LIMIT 20000) GROUP BY k ORDER BY c DESC LIMIT 200";++export function useTopValues(hogql: string) {+ return useQuery({+ queryKey: ["canvas-block-hogql", hogql],+ queryFn: async (): Promise<string[]> => {+ const result = await hostClient().canvasData.query.mutate({ hogql });+ return (result.results as unknown[][]).map((row) => String(row[0]));+ },+ staleTime: 10 * 60_000,+ retry: false,+ });+}++export function useSavedInsights(search: string) {+ return useQuery({+ queryKey: ["canvas-block-saved-insights", search],+ queryFn: () => hostClient().canvasData.savedInsights.query({ search }),+ placeholderData: keepPreviousData,+ staleTime: 60_000,+ retry: false,+ });+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/sourceDrag.ts b/products/desktop/packages/ui/src/features/canvas/blocks/sourceDrag.tsnew file mode 100644index 000000000000..0893885f2b39--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/sourceDrag.ts@@ -0,0 +1,225 @@+import { blockDefinition } from "@posthog/core/canvas/blockLibrary/blockDefinitions";+import type { SourceDropTarget } from "@posthog/core/canvas/blockLibrary/sourceEdits";+import type { CanvasEditSelection } from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import {+ canvasEditorFrame,+ postToCanvasEditor,+} from "@posthog/ui/features/canvas/blocks/editorFrame";+import { libraryLabel } from "@posthog/ui/features/canvas/blocks/libraryCatalog";+import { create } from "zustand";++export type SourceDragSource =+ | { kind: "new"; blockType: string }+ | { kind: "move"; selection: CanvasEditSelection };++export interface SourceDropHit {+ rev: number;+ target: SourceDropTarget;+}++interface GhostState {+ label: string;+ blockType: string | null;+ x: number;+ y: number;+ tilt: number;+ hint: string | null;+ phase: GhostPhase;+}++export type GhostPhase = "drag" | "drop" | "return";++interface SourceDragStore {+ ghost: GhostState | null;+ setGhost: (ghost: GhostState | null) => void;+}++export const useSourceDragStore = create<SourceDragStore>((set) => ({+ ghost: null,+ setGhost: (ghost) => set({ ghost }),+}));++const ACTIVATION_DISTANCE = 4;+const MAX_TILT = 3;+const TILT_GAIN = 0.3;+const TILT_EASE = 0.18;+const DROP_EXIT_MS = 140;+const RETURN_EXIT_MS = 280;++let exitTimer: ReturnType<typeof setTimeout> | null = null;++function prefersReducedMotion(): boolean {+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;+}++function leaveGhost(ghost: GhostState, duration: number): void {+ const { setGhost } = useSourceDragStore.getState();+ if (exitTimer) clearTimeout(exitTimer);+ setGhost(ghost);+ exitTimer = setTimeout(() => {+ exitTimer = null;+ if (useSourceDragStore.getState().ghost?.phase !== "drag") setGhost(null);+ }, duration);+}++export interface SourceDragController {+ move: (clientX: number, clientY: number) => void;+ hit: (hit: SourceDropHit | null) => void;+ end: (commit: boolean) => void;+}++let active: SourceDragController | null = null;++export function activeSourceDrag(): SourceDragController | null {+ return active;+}++function hintFor(hit: SourceDropHit | null): string {+ if (!hit) return "Drop on the canvas";+ if (hit.target.place === "left" || hit.target.place === "right")+ return "Place side by side";+ if (hit.target.place === "inside") return "Add at the end";+ return "Place here";+}++function isDataBlock(blockType: string | null): boolean {+ return !!blockType && blockDefinition(blockType)?.group === "Data";+}++export function beginSourceDrag(options: {+ source: SourceDragSource;+ startX: number;+ startY: number;+ onDrop: (source: SourceDragSource, hit: SourceDropHit) => void;+ onClick?: () => void;+}): void {+ const { setGhost } = useSourceDragStore.getState();+ const { source } = options;+ const blockType =+ source.kind === "new" ? source.blockType : source.selection.blockType;+ const label = libraryLabel(+ blockType,+ source.kind === "move" ? source.selection.tag : undefined,+ );+ let started = source.kind === "move";+ let lastX = options.startX;+ let tilt = 0;+ let latestHit: SourceDropHit | null = null;+ const coarse = isDataBlock(blockType);+ const reduceMotion = prefersReducedMotion();+ let lastGhost: GhostState | null = null;+ const exclude =+ source.kind === "move" && source.selection.source+ ? `${source.selection.source.file}|${source.selection.source.start}|${source.selection.source.end}`+ : null;++ const render = (x: number, y: number) => {+ const velocity = x - lastX;+ lastX = x;+ const wanted = Math.max(+ -MAX_TILT,+ Math.min(MAX_TILT, velocity * TILT_GAIN),+ );+ tilt += (wanted - tilt) * TILT_EASE;+ if (exitTimer) {+ clearTimeout(exitTimer);+ exitTimer = null;+ }+ const ghost: GhostState = {+ label,+ blockType,+ x,+ y,+ tilt: reduceMotion ? 0 : tilt,+ hint: hintFor(latestHit),+ phase: "drag",+ };+ lastGhost = ghost;+ setGhost(ghost);+ };++ const forward = (x: number, y: number) => {+ const frame = canvasEditorFrame();+ const rect = frame?.getBoundingClientRect();+ const inside =+ !!rect &&+ x >= rect.left &&+ x <= rect.right &&+ y >= rect.top &&+ y <= rect.bottom;+ if (!rect || !inside) {+ latestHit = null;+ postToCanvasEditor({ type: "canvas-edit-drag-end" });+ return;+ }+ postToCanvasEditor({+ type: "canvas-edit-drag-move",+ x: x - rect.left,+ y: y - rect.top,+ exclude,+ coarse,+ });+ };++ const controller: SourceDragController = {+ move(x, y) {+ if (!started) {+ if (+ Math.hypot(x - options.startX, y - options.startY) <+ ACTIVATION_DISTANCE+ )+ return;+ started = true;+ }+ render(x, y);+ forward(x, y);+ },+ hit(hit) {+ latestHit = hit;+ },+ end(commit) {+ window.removeEventListener("pointermove", onMove, true);+ window.removeEventListener("pointerup", onUp, true);+ window.removeEventListener("keydown", onKey, true);+ postToCanvasEditor({ type: "canvas-edit-drag-end", final: true });+ active = null;+ if (!started || !lastGhost) {+ setGhost(null);+ if (commit && !started) options.onClick?.();+ return;+ }+ const dropped = commit && !!latestHit;+ if (dropped && latestHit) {+ leaveGhost({ ...lastGhost, phase: "drop" }, DROP_EXIT_MS);+ options.onDrop(source, latestHit);+ return;+ }+ leaveGhost(+ {+ ...lastGhost,+ x: options.startX,+ y: options.startY,+ tilt: 0,+ phase: "return",+ },+ reduceMotion ? DROP_EXIT_MS : RETURN_EXIT_MS,+ );+ },+ };++ const onMove = (event: PointerEvent) =>+ controller.move(event.clientX, event.clientY);+ const onUp = () => controller.end(true);+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ controller.end(false);+ };++ window.addEventListener("pointermove", onMove, true);+ window.addEventListener("pointerup", onUp, true);+ window.addEventListener("keydown", onKey, true);+ active = controller;+ if (started) render(options.startX, options.startY);+}diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/useCanvasSourceActions.ts b/products/desktop/packages/ui/src/features/canvas/blocks/useCanvasSourceActions.tsnew file mode 100644index 000000000000..22215ae52f43--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/blocks/useCanvasSourceActions.ts@@ -0,0 +1,255 @@+import {+ type BlockPropsRecord,+ blockDefinition,+ freshBlockProps,+} from "@posthog/core/canvas/blockLibrary/blockDefinitions";+import { syncBlockLibrary } from "@posthog/core/canvas/blockLibrary/blockLibrarySync";+import {+ blockRanges,+ duplicateRange,+ insertBlock,+ isJsxRange,+ moveRange,+ newBlockId,+ placeableTarget,+ removeRange,+ replaceElementText,+ type SourceDropTarget,+ type SourceFiles,+ type SourceRange,+ updateBlockProps,+} from "@posthog/core/canvas/blockLibrary/sourceEdits";+import {+ type CanvasEditSelection,+ isRootSelection,+ useCanvasSourceStore,+} from "@posthog/ui/features/canvas/blocks/canvasSourceStore";+import { libraryLabel } from "@posthog/ui/features/canvas/blocks/libraryCatalog";+import type {+ SourceDragSource,+ SourceDropHit,+} from "@posthog/ui/features/canvas/blocks/sourceDrag";+import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import { useMemo } from "react";++export interface CanvasSourceActions {+ insert: (blockType: string, target: SourceDropTarget) => void;+ addAfterSelection: (blockType: string) => void;+ drop: (source: SourceDragSource, hit: SourceDropHit) => void;+ remove: (selection: CanvasEditSelection) => void;+ duplicate: (selection: CanvasEditSelection) => void;+ updateProps: (+ selection: CanvasEditSelection,+ props: BlockPropsRecord,+ ) => void;+ setText: (selection: CanvasEditSelection, text: string) => void;+ select: (selection: CanvasEditSelection | null) => void;+}++function current(canvasId: string) {+ return useCanvasSourceStore.getState().entries[canvasId];+}++function isFresh(canvasId: string, rev: number): boolean {+ const entry = current(canvasId);+ return !!entry && entry.mountedRev === entry.rev && rev === entry.rev;+}++const SIDE_BY_SIDE_BLOCKS = new Set(["Metric", "TopList", "Funnel"]);++function besideSelection(+ selection: CanvasEditSelection,+ blockType: string,+): SourceDropTarget {+ const source = selection.source as SourceRange;+ const pairs =+ selection.blockType === blockType && SIDE_BY_SIDE_BLOCKS.has(blockType);+ const grid = selection.layout.grid;+ if (!pairs && grid) return { ...grid, place: "after" };+ if (!pairs) return { ...source, place: "after" };+ if (!selection.layout.inGrid) return { ...source, place: "right" };+ const grow = selection.layout.grow;+ return grow+ ? { ...source, place: "after", grow }+ : { ...source, place: "after" };+}++export function useCanvasSourceActions(canvasId: string): CanvasSourceActions {+ const setTab = useCanvasChatPanelStore((state) => state.setTab);+ return useMemo(() => {+ const store = () => useCanvasSourceStore.getState();+ const apply = (+ files: SourceFiles,+ focusBlockId: string | null = null,+ focusSource: string | null = null,+ ) =>+ store().apply(+ canvasId,+ syncBlockLibrary(files),+ focusBlockId,+ focusSource,+ );+ const note = (verb: string, selection: CanvasEditSelection) =>+ store().noteChange(+ canvasId,+ `${verb} ${libraryLabel(selection.blockType, selection.tag).toLowerCase()}`,+ );++ const insert = (blockType: string, target: SourceDropTarget) => {+ const entry = current(canvasId);+ const definition = blockDefinition(blockType);+ if (!entry || !definition) return;+ const blockId = newBlockId();+ const files = insertBlock(+ entry.files,+ target,+ definition,+ freshBlockProps(definition, entry.files),+ blockId,+ );+ if (files === entry.files) return;+ store().noteChange(canvasId, `Added ${definition.label.toLowerCase()}`);+ apply(files, definition.component ? blockId : null);+ if (definition.needsSetup) store().setLibraryOpen(canvasId, false);+ setTab("blocks");+ };++ const addAfterSelection = (blockType: string) => {+ const entry = current(canvasId);+ if (!entry) return;+ const selection = store().selection[canvasId];+ const root = entry.rootSource;+ const group = blockDefinition(blockType)?.group;+ const control =+ group === "Controls" && root+ ? blockRanges(entry.files, root.file, "Controls").at(-1)+ : undefined;+ if (control) {+ insert(blockType, { ...control, place: "after" });+ return;+ }+ const controlSelected =+ !!selection?.blockType &&+ blockDefinition(selection.blockType)?.group === "Controls";+ const besideAllowed = group === "Controls" || !controlSelected;+ if (+ selection?.source &&+ !isRootSelection(entry, selection) &&+ besideAllowed &&+ isFresh(canvasId, selection.rev)+ ) {+ insert(blockType, besideSelection(selection, blockType));+ return;+ }+ const firstData =+ group === "Data" && root+ ? blockRanges(entry.files, root.file, "Data")[0]+ : undefined;+ if (firstData) {+ insert(blockType, { ...firstData, place: "before" });+ return;+ }+ if (!root || entry.mountedRev !== entry.rev) return;+ const inRoot: SourceDropTarget = { ...root, place: "inside" };+ if (placeableTarget(entry, inRoot)) insert(blockType, inRoot);+ };++ const drop = (dragged: SourceDragSource, hit: SourceDropHit) => {+ const entry = current(canvasId);+ if (!entry || !isFresh(canvasId, hit.rev)) return;+ if (!placeableTarget(entry, hit.target)) return;+ if (dragged.kind === "new") {+ insert(dragged.blockType, hit.target);+ return;+ }+ const range = dragged.selection.source;+ if (!range || !isFresh(canvasId, dragged.selection.rev)) return;+ if (!isJsxRange(entry.files, range)) return;+ const files = moveRange(entry.files, range, hit.target);+ if (files !== entry.files) note("Moved", dragged.selection);+ apply(files, dragged.selection.blockId);+ };++ const remove = (selection: CanvasEditSelection) => {+ const entry = current(canvasId);+ if (!entry || !selection.source || !isFresh(canvasId, selection.rev))+ return;+ if (isRootSelection(entry, selection)) return;+ note("Removed", selection);+ apply(removeRange(entry.files, selection.source));+ store().setSelection(canvasId, null);+ };++ const duplicate = (selection: CanvasEditSelection) => {+ const entry = current(canvasId);+ if (!entry || !selection.source || !isFresh(canvasId, selection.rev))+ return;+ const blockId = newBlockId();+ note("Duplicated", selection);+ apply(+ duplicateRange(entry.files, selection.source, blockId),+ selection.blockId ? blockId : null,+ );+ };++ const updateProps = (+ selection: CanvasEditSelection,+ props: BlockPropsRecord,+ ) => {+ const entry = current(canvasId);+ if (+ !entry ||+ !selection.source ||+ !selection.blockType ||+ !isFresh(canvasId, selection.rev)+ )+ return;+ const files = updateBlockProps(+ entry.files,+ selection.source,+ selection.props,+ props,+ );+ if (files === entry.files) return;+ note("Changed", selection);+ apply(+ files,+ selection.blockId,+ selection.blockId+ ? null+ : `${selection.source.file}|${selection.source.start}`,+ );+ store().setSelection(canvasId, { ...selection, props });+ };++ const setText = (selection: CanvasEditSelection, text: string) => {+ const entry = current(canvasId);+ if (!entry || !selection.source || !isFresh(canvasId, selection.rev))+ return;+ const files = replaceElementText(entry.files, selection.source, text);+ if (files === entry.files) return;+ store().noteChange(canvasId, "Edited text");+ apply(+ files,+ selection.blockId,+ `${selection.source.file}|${selection.source.start}`,+ );+ };++ const select = (selection: CanvasEditSelection | null) => {+ store().setSelection(canvasId, selection);+ if (selection) setTab("blocks");+ };++ return {+ insert,+ addAfterSelection,+ drop,+ remove,+ duplicate,+ updateProps,+ setText,+ select,+ };+ }, [canvasId, setTab]);+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsxindex e9d78fce2ad6..5bb616c8153c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx@@ -3,6 +3,7 @@ import {FileTextIcon,HashIcon,PlusIcon,+ SquaresFourIcon,} from "@phosphor-icons/react";import {Button,@@ -19,6 +20,8 @@ import {import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";+import { useCreateAndOpenDashboard } from "@posthog/ui/features/canvas/hooks/useDashboards";+import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import {formatHotkey,SHORTCUTS,@@ -50,6 +53,8 @@ export function ChannelsFab({const inRail = placement === "rail";const { iconSize: railIconSize } = useNavRailMetrics();const [modalOpen, setModalOpen] = useState(false);+ const { personalChannel } = useTaskChannels();+ const createAndOpen = useCreateAndOpenDashboard(channelId);const hasDraft = useDraftStore((state) =>Object.entries(state.drafts).some(([sessionId, draft]) =>@@ -79,9 +84,17 @@ export function ChannelsFab({</DropdownMenuItem>);- // Inside a space on the layout, the menu held one item, so the button is that- // item: a click starts the task instead of asking which kind to start.- const newTaskOnly = channelsLayout && !!channelId;+ const canvasChannelId = channelId ?? personalChannel?.id;+ const newCanvas = () => {+ if (!canvasChannelId) return;+ void createAndOpen({ channelId: canvasChannelId });+ };+ const newCanvasItem = (+ <DropdownMenuItem onClick={newCanvas} disabled={!canvasChannelId}>+ <SquaresFourIcon size={14} className="text-gray-9" />+ New canvas+ </DropdownMenuItem>+ );const draftDot = channelsLayout && hasDraft && (<span@@ -90,7 +103,7 @@ export function ChannelsFab({/>);- const label = newTaskOnly ? "New task" : "Create";+ const label = "Create";const trigger = (<Button@@ -102,7 +115,6 @@ export function ChannelsFab({? "shrink-0 rounded-full": "absolute right-3 bottom-3 z-10 rounded-full"}- onClick={newTaskOnly ? newTask : undefined}><PlusIcon size={inRail ? railIconSize : 20} weight="bold" />{draftDot}@@ -124,17 +136,6 @@ export function ChannelsFab({</TooltipContent>);- if (newTaskOnly) {- return (- <div className="flex h-12 w-full items-center justify-center">- <Tooltip>- <TooltipTrigger render={trigger} />- {tooltip}- </Tooltip>- </div>- );- }-return (<><DropdownMenu>@@ -154,6 +155,7 @@ export function ChannelsFab({<FileTextIcon size={14} className="text-gray-9" />New task</DropdownMenuItem>+ {newCanvasItem}{/* Inside a space the menu is about filling that space; makinganother one belongs to the list this button also serves. */}{channelsLayout && !channelId && (diff --git a/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.tsx b/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.tsxindex 8d0f3bf1f61f..56b748942d64 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ShellLayout.tsx@@ -93,7 +93,9 @@ function FreeformEditControls({const editing = useIsDashboardEditing(dashboardId);const setEditing = useDashboardEditStore((s) => s.setEditing);const openChat = useCanvasChatPanelStore((state) => state.openChat);+ const openBlocks = useCanvasChatPanelStore((state) => state.openBlocks);const { dashboard } = useDashboard(dashboardId);+ const builtByAgent = !!dashboard?.generationTaskId;const { setPinned, invalidateDashboards } = useDashboardMutations();const isPinned = dashboard?.pinnedAt != null;// "Delete…" opens a confirmation rather than deleting inline — the canvas and@@ -250,7 +252,8 @@ function FreeformEditControls({dashboard_id: dashboardId,editing: !editing,});- if (!editing) openChat();+ if (!editing && builtByAgent) openChat();+ if (!editing && !builtByAgent) openBlocks();setEditing(dashboardId, !editing);}}>diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasGenerateHero.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasGenerateHero.tsxindex 862a2b536e21..0729c7ac3dbc 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasGenerateHero.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasGenerateHero.tsx@@ -1,10 +1,10 @@import { ShapesIcon } from "@phosphor-icons/react";+import { CanvasBlocksStarter } from "@posthog/ui/features/canvas/blocks/CanvasBlocks";import { CANVAS_GENERATE_SUGGESTIONS } from "@posthog/ui/features/canvas/freeform/canvasGenerateSuggestions";import { FreeformGenerateBar } from "@posthog/ui/features/canvas/freeform/FreeformGenerateBar";import type { EditorHandle } from "@posthog/ui/features/message-editor/types";import { SuggestedPromptCard } from "@posthog/ui/features/task-detail/components/SuggestedPromptCard";import { DotPatternBackground } from "@posthog/ui/primitives/DotPatternBackground";-import { Flex, Text } from "@radix-ui/themes";import { useRef } from "react";// The empty-canvas landing state: a centered composer with starter-prompt@@ -30,29 +30,18 @@ export function CanvasGenerateHero({const editorRef = useRef<EditorHandle>(null);return (- <Flex- direction="column"- align="center"- justify="center"- className="relative h-full w-full overflow-y-auto px-4 py-10"- >+ <div className="relative flex h-full w-full flex-col items-center justify-center overflow-y-auto px-4 py-10"><DotPatternBackground className="h-full" />- <Flex direction="column" gap="5" className="z-[1] w-full max-w-[620px]">- <Flex direction="column" align="center" gap="2" className="text-center">- <Flex- align="center"- justify="center"- className="size-10 rounded-xl bg-accent-3 text-accent-9"- >+ <div className="z-[1] flex w-full max-w-[620px] flex-col gap-5">+ <div className="flex flex-col items-center gap-2 text-center">+ <div className="flex size-10 items-center justify-center rounded-xl bg-accent-3 text-accent-9"><ShapesIcon size={20} weight="duotone" />- </Flex>- <Text size="5" weight="bold" className="text-gray-12">- Build a canvas- </Text>- <Text size="2" className="text-gray-10">- Describe what you want and an agent builds it.- </Text>- </Flex>+ </div>+ <h2 className="font-bold text-foreground text-xl">Build a canvas</h2>+ <p className="text-muted-foreground text-sm">+ Describe it and an agent builds it, or drop in blocks yourself.+ </p>+ </div><FreeformGenerateBarref={editorRef}@@ -65,10 +54,10 @@ export function CanvasGenerateHero({onStarted={onStarted}/>- <Flex direction="column" gap="2">- <Text size="1" weight="medium" className="px-1 text-gray-11">+ <div className="flex flex-col gap-2">+ <span className="px-1 font-medium text-muted-foreground text-xs">Suggestions- </Text>+ </span><div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{CANVAS_GENERATE_SUGGESTIONS.map((suggestion) => (<SuggestedPromptCard@@ -81,8 +70,15 @@ export function CanvasGenerateHero({/>))}</div>- </Flex>- </Flex>- </Flex>+ </div>++ <div className="flex flex-col gap-2">+ <span className="px-1 font-medium text-muted-foreground text-xs">+ Build it yourself+ </span>+ <CanvasBlocksStarter canvasId={dashboardId} />+ </div>+ </div>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsxindex dc0a22b35b78..4adba608a2a9 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx@@ -48,13 +48,15 @@ describe("CanvasSidePanel", () => {channelName="General"name="Launch canvas"displayedVersionId="version-2"+ liveVersionId="version-2"+ onAskAgent={vi.fn()}commentVersionLabel={(versionId) => versionId}onCommentOpen={vi.fn()}/>,);expect(screen.getByTestId("task-chat")).toBeInTheDocument();- fireEvent.click(screen.getByText("Comments"));+ fireEvent.click(screen.getByLabelText("Comments"));expect(screen.getByTestId("task-comments")).toHaveTextContent("task-1:canvas-1",);@@ -71,6 +73,8 @@ describe("CanvasSidePanel", () => {channelName: "General",name: "Launch canvas",displayedVersionId: "version-2",+ liveVersionId: "version-2",+ onAskAgent: vi.fn(),commentVersionLabel: (versionId: string) => versionId,onCommentOpen: vi.fn(),};@@ -78,7 +82,7 @@ describe("CanvasSidePanel", () => {<CanvasSidePanel {...props} chatTaskId="task-1" />,);- fireEvent.click(screen.getByText("Chat"));+ fireEvent.click(screen.getByLabelText("Chat"));expect(screen.getByTestId("task-chat")).toBeInTheDocument();rerender(<CanvasSidePanel {...props} chatTaskId={null} />);@@ -104,6 +108,8 @@ describe("CanvasSidePanel", () => {channelName="General"name="Launch canvas"displayedVersionId="version-2"+ liveVersionId="version-2"+ onAskAgent={vi.fn()}commentVersionLabel={(versionId) => versionId}onCommentOpen={vi.fn()}/>,diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsxindex 1bbc750df0b8..db22a27e3d0a 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx@@ -1,4 +1,11 @@-import { ChatCircleIcon, SidebarSimpleIcon } from "@phosphor-icons/react";+import {+ ChatCircleIcon,+ ChatTeardropTextIcon,+ type Icon,+ PulseIcon,+ SidebarSimpleIcon,+ SquaresFourIcon,+} from "@phosphor-icons/react";import {Button,Empty,@@ -6,16 +13,19 @@ import {EmptyHeader,EmptyMedia,EmptyTitle,- Tabs,- TabsList,- TabsTrigger,Tooltip,TooltipContent,+ TooltipProvider,TooltipTrigger,} from "@posthog/quill";+import { CanvasBlocksPanel } from "@posthog/ui/features/canvas/blocks/CanvasBlocksPanel";import { TaskCommentsList } from "@posthog/ui/features/canvas/components/TaskCommentsList";+import { CanvasTimeline } from "@posthog/ui/features/canvas/freeform/CanvasTimeline";import { FreeformGenerateBar } from "@posthog/ui/features/canvas/freeform/FreeformGenerateBar";-import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";+import {+ type CanvasPanelTab,+ useCanvasChatPanelStore,+} from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";import type { EditorHandle } from "@posthog/ui/features/message-editor/types";import { EmbeddedSessionView } from "@posthog/ui/features/sessions/components/EmbeddedSessionView";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";@@ -24,6 +34,55 @@ import { LoadingState } from "@posthog/ui/primitives/LoadingState";import { useQuery } from "@tanstack/react-query";import { type Ref, useEffect, useRef } from "react";+const PANEL_TABS: Record<CanvasPanelTab, { label: string; Icon: Icon }> = {+ chat: { label: "Chat", Icon: ChatTeardropTextIcon },+ blocks: { label: "Blocks", Icon: SquaresFourIcon },+ comments: { label: "Comments", Icon: ChatCircleIcon },+ timeline: { label: "Timeline", Icon: PulseIcon },+};++const TAB_ORDER: readonly CanvasPanelTab[] = [+ "chat",+ "blocks",+ "comments",+ "timeline",+];++function PanelTabButton({+ tab,+ active,+ disabled,+ onSelect,+}: {+ tab: CanvasPanelTab;+ active: boolean;+ disabled: boolean;+ onSelect: (tab: CanvasPanelTab) => void;+}) {+ const { label, Icon } = PANEL_TABS[tab];+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="default"+ size="icon-sm"+ aria-label={label}+ aria-pressed={active}+ data-selected={active || undefined}+ disabled={disabled}+ onClick={() => onSelect(tab)}+ className="text-muted-foreground data-selected:bg-fill-selected data-selected:text-foreground"+ >+ <Icon size={16} />+ </Button>+ }+ />+ <TooltipContent side="bottom">{label}</TooltipContent>+ </Tooltip>+ );+}+// The canvas's right-hand dock. It shows the chat of this person's run on the// canvas (steering/queue included) when they have one; otherwise it shows the// edit composer, which starts their first run. Header carries a minimize@@ -38,12 +97,14 @@ export function CanvasSidePanel({channelName,name,displayedVersionId,+ liveVersionId,commentVersionLabel,onCommentOpen,templateId,isEdit,editorRef,onStarted,+ onAskAgent,}: {/** The run whose chat the panel shows: the current person's own run on this* canvas, or null when they have none. Another person's run never shows@@ -59,6 +120,7 @@ export function CanvasSidePanel({channelName: string;name: string;displayedVersionId: string | null;+ liveVersionId: string | null;commentVersionLabel: (versionId: string) => string | null;onCommentOpen: (versionId: string | null) => void;templateId?: string;@@ -68,6 +130,7 @@ export function CanvasSidePanel({// Exposes the edit composer's editor so self-repair can prefill it.editorRef?: Ref<EditorHandle>;onStarted?: (taskId: string) => void;+ onAskAgent: (message: string) => void;}) {const tab = useCanvasChatPanelStore((state) => state.tab);const setTab = useCanvasChatPanelStore((state) => state.setTab);@@ -80,49 +143,69 @@ export function CanvasSidePanel({previousTaskId.current = chatTaskId;}, [chatTaskId, setTab]);+ const firstBuildRunning = !!chatTaskId && !isEdit;+ const visibleTab: CanvasPanelTab =+ tab === "blocks" && (!interactive || firstBuildRunning) ? "chat" : tab;+return (<div className="flex h-full min-w-0 flex-col bg-gray-1"><ChromeBarclassName="bg-chrome"actions={- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon"- variant="default"- aria-label="Minimize panel"- onClick={onMinimize}- >- <SidebarSimpleIcon size={16} />- </Button>- }- />- <TooltipContent>Minimize panel</TooltipContent>- </Tooltip>+ <TooltipProvider delay={400}>+ <div className="flex items-center gap-0.5">+ {TAB_ORDER.filter(+ (option) => option !== "blocks" || interactive,+ ).map((option) => (+ <PanelTabButton+ key={option}+ tab={option}+ active={visibleTab === option}+ disabled={+ (option === "comments" && !commentTaskId) ||+ (option === "blocks" && firstBuildRunning)+ }+ onSelect={setTab}+ />+ ))}+ <span aria-hidden className="mx-1 h-4 w-px bg-border" />+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-sm"+ variant="default"+ aria-label="Minimize panel"+ onClick={onMinimize}+ className="text-muted-foreground"+ >+ <SidebarSimpleIcon size={16} />+ </Button>+ }+ />+ <TooltipContent side="bottom">Minimize panel</TooltipContent>+ </Tooltip>+ </div>+ </TooltipProvider>}>- <Tabs- value={tab}- onValueChange={(value) => setTab(value as "chat" | "comments")}- >- <TabsList variant="line" className="h-10 gap-1 p-0">- <TabsTrigger value="chat" className="px-2.5">- Chat- </TabsTrigger>- <TabsTrigger- value="comments"- disabled={!commentTaskId}- className="px-2.5"- >- Comments- </TabsTrigger>- </TabsList>- </Tabs>+ <span className="min-w-0 flex-1 truncate font-medium text-[13px]">+ {PANEL_TABS[visibleTab].label}+ </span></ChromeBar><div className="min-h-0 flex-1">- {tab === "comments" && commentTaskId ? (+ {visibleTab === "blocks" ? (+ <CanvasBlocksPanel canvasId={dashboardId} onAskAgent={onAskAgent} />+ ) : visibleTab === "timeline" ? (+ <CanvasTimeline+ dashboardId={dashboardId}+ liveVersionId={liveVersionId}+ viewingVersionId={displayedVersionId}+ versionLabel={commentVersionLabel}+ onOpen={onCommentOpen}+ />+ ) : visibleTab === "comments" && commentTaskId ? (<CanvasCommentstaskId={commentTaskId}dashboardId={dashboardId}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasTimeline.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasTimeline.tsxnew file mode 100644index 000000000000..06a33930502a--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasTimeline.tsx@@ -0,0 +1,136 @@+import { PulseIcon, Sparkle } from "@phosphor-icons/react";+import type { CanvasVersion } from "@posthog/core/canvas/dashboardSchemas";+import {+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@posthog/quill";+import { formatRelativeAge } from "@posthog/shared";+import { useCanvasVersions } from "@posthog/ui/features/canvas/hooks/useDashboards";+import { LoadingState } from "@posthog/ui/primitives/LoadingState";++function versionTitle(version: CanvasVersion): string {+ const prompt = version.prompt?.trim();+ if (prompt) return prompt;+ return version.parentVersionId ? "Published a change" : "Created the canvas";+}++function TimelineRow({+ version,+ label,+ live,+ viewing,+ last,+ onOpen,+}: {+ version: CanvasVersion;+ label: string | null;+ live: boolean;+ viewing: boolean;+ last: boolean;+ onOpen: () => void;+}) {+ const byAgent = !!version.taskId;+ return (+ <li className="relative flex gap-3 pl-1">+ {last ? null : (+ <span+ aria-hidden+ className="absolute top-5 bottom-0 left-[9px] w-px bg-border"+ />+ )}+ <span+ aria-hidden+ className={`relative mt-1.5 flex size-3 shrink-0 items-center justify-center rounded-full border ${live ? "border-primary bg-primary" : "border-border bg-background"}`}+ />+ <button+ type="button"+ onClick={onOpen}+ data-selected={viewing || undefined}+ className="mb-1 flex min-w-0 flex-1 flex-col gap-0.5 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-fill-hover data-selected:bg-fill-selected"+ >+ <span className="line-clamp-2 text-foreground text-xs">+ {versionTitle(version)}+ </span>+ <span className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground">+ {byAgent ? (+ <span className="flex items-center gap-1">+ <Sparkle size={11} />+ Agent+ </span>+ ) : (+ <span className="truncate">{version.createdBy ?? "Someone"}</span>+ )}+ <span aria-hidden>·</span>+ <span className="shrink-0">+ {formatRelativeAge(version.createdAt)}+ </span>+ {label ? (+ <>+ <span aria-hidden>·</span>+ <span className="shrink-0">{label}</span>+ </>+ ) : null}+ {live ? (+ <span className="ml-auto shrink-0 font-medium text-primary">+ Live+ </span>+ ) : null}+ </span>+ </button>+ </li>+ );+}++export function CanvasTimeline({+ dashboardId,+ liveVersionId,+ viewingVersionId,+ versionLabel,+ onOpen,+}: {+ dashboardId: string;+ liveVersionId: string | null;+ viewingVersionId: string | null;+ versionLabel: (versionId: string) => string | null;+ onOpen: (versionId: string | null) => void;+}) {+ const { versions, isLoading } = useCanvasVersions(dashboardId);+ if (isLoading) return <LoadingState />;+ if (versions.length === 0) {+ return (+ <Empty className="h-full border-0">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <PulseIcon size={24} />+ </EmptyMedia>+ <EmptyTitle>No changes yet</EmptyTitle>+ <EmptyDescription>+ Every edit to this canvas, by you or an agent, shows here.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );+ }+ const ordered = versions.toSorted((a, b) => b.createdAt - a.createdAt);+ const viewing = viewingVersionId ?? liveVersionId;+ return (+ <div className="h-full overflow-y-auto px-3 py-3">+ <ol className="flex flex-col">+ {ordered.map((version, index) => (+ <TimelineRow+ key={version.id}+ version={version}+ label={versionLabel(version.id)}+ live={version.id === liveVersionId}+ viewing={version.id === viewing}+ last={index === ordered.length - 1}+ onOpen={() => onOpen(version.id)}+ />+ ))}+ </ol>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex 5968111a463e..10b4b62fb913 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -55,6 +55,13 @@ import { CANVAS_COMPONENT_PATH, formatRelativeAge } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import { CanvasSourceAutosave } from "@posthog/ui/features/canvas/blocks/CanvasBlocks";+import { CanvasSourceEditor } from "@posthog/ui/features/canvas/blocks/CanvasSourceEditor";+import { useCanvasSourceSync } from "@posthog/ui/features/canvas/blocks/canvasSourceHooks";+import {+ useCanvasSourceEntry,+ useCanvasSourceStore,+} from "@posthog/ui/features/canvas/blocks/canvasSourceStore";import {isCanvasGenerating,isCanvasGenerationRunning,@@ -433,12 +440,27 @@ export function FreeformCanvasView({browseVersionId: browsing ? browseVersionId : null,});const { currentIndex } = nav;- const canUndo = !isGenerating && nav.canUndo;- const canRedo = !isGenerating && nav.canRedo;+ const sourceEntry = useCanvasSourceEntry(dashboardId);+ const sourceEnabled = interactive && !embedded;+ const sourceEditing = sourceEnabled && !browsing && !!sourceEntry;+ const versionCanUndo = !isGenerating && nav.canUndo;+ const versionCanRedo = !isGenerating && nav.canRedo;+ const canUndo = sourceEditing ? sourceEntry.past.length > 0 : versionCanUndo;+ const canRedo = sourceEditing+ ? sourceEntry.future.length > 0+ : versionCanRedo;const onUndo = () => {+ if (sourceEditing) {+ useCanvasSourceStore.getState().undo(dashboardId);+ return;+ }if (nav.undoTargetId) setBrowseVersion(threadId, nav.undoTargetId);};const onRedo = () => {+ if (sourceEditing) {+ useCanvasSourceStore.getState().redo(dashboardId);+ return;+ }// A null target means stepping onto (or past) the head — back to live.setBrowseVersion(threadId, nav.redoTargetId);};@@ -789,7 +811,8 @@ export function FreeformCanvasView({// published — the record is the always-available signal, so a canvas with// content never flashes the empty state while source/builds load.const hasSource = !!headVersionId || !!headCode?.trim();- const hasContent = hasSource || !!pinnedArtifact;+ const sourceLoad = useCanvasSourceSync(dashboardId, sourceEnabled);+ const hasContent = hasSource || !!pinnedArtifact || !!sourceEntry;// `isGenerating` keys off the effective task (the optimistic bridge right after// submit, then the polled record) and short-circuits on a terminal run — so a// failed/cancelled run can't strand the canvas body on the spinner.@@ -843,8 +866,42 @@ export function FreeformCanvasView({latestFinishedCanvasBuild(lifecycle)?.buildStatus === "failed");const showToolbar = !embedded && (interactive || hasBuildSignal);+ const liveAppElement = pinnedArtifact ? (+ <BuiltCanvas+ key={`${pinnedArtifact.buildId}:${artifactRefreshKey}`}+ artifactUrl={pinnedArtifact.url}+ capabilities={publishedBuild?.manifest?.capabilities}+ onDataRequest={onDataRequest}+ onError={onError}+ onReady={onArtifactReady}+ onRendered={onRendered}+ onNavigate={onNavigate}+ onTextSelection={setTextSelection}+ onCommentActivate={activateComment}+ commentHighlights={commentHighlights}+ clearTextSelectionKey={clearTextSelectionKey}+ />+ ) : headCode ? (+ <CanvasFramePlaceholder+ dashboardId={dashboardId}+ code={headCode}+ analytics={analytics}+ onDataRequest={onDataRequest}+ onError={onError}+ onRendered={onRendered}+ onNavigate={onNavigate}+ onTextSelection={setTextSelection}+ onCommentActivate={activateComment}+ commentHighlights={commentHighlights}+ clearTextSelectionKey={clearTextSelectionKey}+ />+ ) : null;+ const sourcePending =+ sourceEnabled && !sourceEntry && sourceLoad === "loading" && hasSource;+return (<Flex height="100%" overflow="hidden" position="relative">+ {sourceEnabled ? <CanvasSourceAutosave canvasId={dashboardId} /> : null}<CanvasAgentRequestDialogprompt={agentRequest?.prompt ?? null}loading={agentRequest?.submitting ?? false}@@ -1219,43 +1276,18 @@ export function FreeformCanvasView({</Empty></ScrollArea>)- ) : pinnedArtifact ? (- <Box className="h-full w-full">- <BuiltCanvas- key={`${pinnedArtifact.buildId}:${artifactRefreshKey}`}- artifactUrl={pinnedArtifact.url}- capabilities={publishedBuild?.manifest?.capabilities}- onDataRequest={onDataRequest}- onError={onError}- onReady={onArtifactReady}- onRendered={onRendered}- onNavigate={onNavigate}- onTextSelection={setTextSelection}- onCommentActivate={activateComment}- commentHighlights={commentHighlights}- clearTextSelectionKey={clearTextSelectionKey}- />- </Box>- ) : headCode ? (- // The iframe lives in the persistent warm-frame pool- // (CanvasFrameHost); this placeholder just reserves the viewport- // box and owns scroll via the host's overlay, so the canvas- // survives navigation without a reload.- <Box className="h-full w-full">- <CanvasFramePlaceholder- dashboardId={dashboardId}- code={headCode}- analytics={analytics}- onDataRequest={onDataRequest}- onError={onError}- onRendered={onRendered}- onNavigate={onNavigate}- onTextSelection={setTextSelection}- onCommentActivate={activateComment}- commentHighlights={commentHighlights}- clearTextSelectionKey={clearTextSelectionKey}- />- </Box>+ ) : sourceEditing ? (+ <CanvasSourceEditor+ canvasId={dashboardId}+ onDataRequest={onDataRequest}+ onError={onError}+ onRendered={onRendered}+ onNavigate={onNavigate}+ />+ ) : sourcePending ? (+ <LoadingState label="Loading canvas" />+ ) : liveAppElement ? (+ <Box className="h-full w-full">{liveAppElement}</Box>) : (<ScrollArea className="h-full">{isGenerating ? (@@ -1327,6 +1359,7 @@ export function FreeformCanvasView({channelName={channelName}name={dashboard?.name ?? "Canvas"}displayedVersionId={displayedVersionId}+ liveVersionId={headVersionId}commentVersionLabel={commentVersionLabel}onCommentOpen={(versionId) => {setBrowseVersion(@@ -1338,6 +1371,7 @@ export function FreeformCanvasView({isEdit={hasSource}editorRef={editorRef}onStarted={setStartedTaskId}+ onAskAgent={prefillComposer}/></ResizableSidebar>)}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex 3dd86a9b0bc4..b00ecad4a839 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -10,6 +10,11 @@ import {CANVAS_SDK_MODULE_SOURCE,CANVAS_SDK_SPECIFIER,} from "@posthog/shared";+import {+ compileCanvasProject,+ installCanvasEditing,+} from "@posthog/ui/features/canvas/blocks/canvasEditRuntime";+import { EDIT_LABELS } from "@posthog/ui/features/canvas/blocks/libraryCatalog";import {commentActionAnchorRect,installSelectionSettleGate,@@ -585,6 +590,11 @@ export function buildSandboxDocument(},});+ const compileCanvasProject = ${compileCanvasProject.toString()};+ const installCanvasEditing = ${installCanvasEditing.toString()};+ const editing = installCanvasEditing(post, ${JSON.stringify(EDIT_LABELS)});+ const moduleCache = new Map();+let root = null;// mount() is async and is called once per streamed code snapshot, so several// runs overlap on their awaits. Without ordering, a slower EARLIER (partial,@@ -593,25 +603,25 @@ export function buildSandboxDocument(// A monotonic sequence makes only the newest mount commit its render/error;// superseded runs bail out after each await.let mountSeq = 0;- const mount = async (code) => {+ const mount = async (input) => {const seq = ++mountSeq;try {- const out = Babel.transform(code, {- filename: "canvas.tsx",- plugins: [jsxUnicodeEscapesPlugin],- presets: [- ["react", { runtime: "automatic" }],- ["typescript", { isTSX: true, allExtensions: true, onlyRemoveTypeImports: true }],- ],- }).code;- const url = URL.createObjectURL(- new Blob([out], { type: "text/javascript" }),+ const revoke = !input.files;+ const url = compileCanvasProject(+ Babel,+ input.files || { "canvas.tsx": input.code },+ input.files ? input.entry || "src/canvas.tsx" : "canvas.tsx",+ {+ editing: !!input.editing,+ basePlugins: [jsxUnicodeEscapesPlugin],+ cache: revoke ? new Map() : moduleCache,+ },);let mod;try {mod = await import(url);} finally {- URL.revokeObjectURL(url);+ if (revoke) URL.revokeObjectURL(url);}if (seq !== mountSeq) return; // a newer snapshot superseded this oneconst Comp = mod.default;@@ -631,19 +641,34 @@ export function buildSandboxDocument(static getDerivedStateFromError(error) { return { error }; }componentDidCatch(error) { reportError(error.message, error.stack); }render() {- if (this.state.error) return null;+ if (this.state.error) return React.createElement(Committed, { key: "failed", failed: true });return this.props.children;}}+ if (input.editing) editing.capture();+ const afterCommit = (failed) => {+ requestAnimationFrame(() => {+ if (seq !== mountSeq) return;+ renderCommentHighlights(currentCommentHighlights);+ editing.setEnabled(!!input.editing);+ if (input.editing) editing.afterMount(input.rev || 0, input.focusBlockId || null, input.focusSource || null);+ if (!failed) post({ type: "rendered" });+ });+ };+ function Committed(props) {+ React.useLayoutEffect(() => {+ afterCommit(!!props.failed);+ }, []);+ return null;+ }root.render(- React.createElement(Boundary, null, React.createElement(Comp)),+ React.createElement(+ Boundary,+ null,+ React.createElement(Comp),+ React.createElement(Committed, { key: seq }),+ ),);- // Let layout settle, then report success.- requestAnimationFrame(() => {- if (seq !== mountSeq) return;- renderCommentHighlights(currentCommentHighlights);- post({ type: "rendered" });- });} catch (err) {// Only the latest snapshot reports — a superseded partial's parse error// must not surface as the canvas's error or flicker the host banner.@@ -663,11 +688,12 @@ export function buildSandboxDocument(window.addEventListener("message", (e) => {const d = e.data;if (!d || d.channel !== CHANNEL) return;+ if (editing.handle(d)) return;if (d.type === "init") {applyTheme(d.theme);currentCommentHighlights = d.highlights || [];if (d.analytics) void bootAnalytics(d.analytics);- void mount(d.code);+ void mount(d);} else if (d.type === "set-theme") {// Re-theme in place — no mount(), so the app keeps all its state.applyTheme(d.theme);diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/usePinnedArtifact.ts b/products/desktop/packages/ui/src/features/canvas/freeform/usePinnedArtifact.tsindex e435a15b2ece..1d914058b355 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/usePinnedArtifact.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/usePinnedArtifact.ts@@ -25,6 +25,27 @@ export interface PinnedArtifact {* the pin's mint time (otherwise the expiry timer would keep firing on a URL* that's already been recovered). */refreshKey: number;+ contentKey: string | null;+}++function artifactContentKey(build: CanvasBuildRecord): string | null {+ const manifest = build.manifest;+ if (!manifest) return null;+ const assets = manifest.assets+ .map((asset) => `${asset.path}:${asset.contentHash}`)+ .sort()+ .join("|");+ return `${manifest.entryHtml}#${assets}#${JSON.stringify(manifest.capabilities)}`;+}++function sameArtifactBytes(+ pinned: PinnedArtifact,+ build: CanvasBuildRecord,+): boolean {+ const next = artifactContentKey(build);+ return (+ pinned.contentKey !== null && next !== null && pinned.contentKey === next+ );}/**@@ -74,9 +95,13 @@ export function usePinnedArtifact({// path when the pinned URL expired.const [refreshKey, setRefreshKey] = useState(0);if (publishedBuild?.artifactUrl) {+ const buildChanged =+ !!pinnedArtifact &&+ pinnedArtifact.buildId !== publishedBuild.id &&+ !sameArtifactBytes(pinnedArtifact, publishedBuild);const adoptFresh =!pinnedArtifact ||- pinnedArtifact.buildId !== publishedBuild.id ||+ buildChanged ||pinnedArtifact.refreshKey !== refreshKey;if (adoptFresh) {setPinnedArtifact({@@ -84,6 +109,7 @@ export function usePinnedArtifact({url: publishedBuild.artifactUrl,mintedAt: mintedAt || Date.now(),refreshKey,+ contentKey: artifactContentKey(publishedBuild),});}} else if (lifecycle && pinnedArtifact) {diff --git a/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.tsindex 2f153c7a8e16..e75ed391bfe3 100644--- a/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts+++ b/products/desktop/packages/ui/src/features/canvas/stores/canvasChatPanelStore.ts@@ -7,7 +7,7 @@ import { persist } from "zustand/middleware";// Collapse and width are global user preferences (persisted) so the panel keeps// its shape across canvases and navigation.const DEFAULT_PANEL_WIDTH = 420;-type CanvasPanelTab = "chat" | "comments";+export type CanvasPanelTab = "chat" | "blocks" | "comments" | "timeline";interface CanvasChatPanelState {collapsed: boolean;@@ -21,6 +21,7 @@ interface CanvasChatPanelState {setWidth: (width: number) => void;setTab: (tab: CanvasPanelTab) => void;openChat: () => void;+ openBlocks: () => void;openComments: () => void;}@@ -38,6 +39,8 @@ export const useCanvasChatPanelStore = create<CanvasChatPanelState>()(setWidth: (width) => set({ width }),setTab: (tab) => set({ tab }),openChat: () => set({ collapsed: false, tab: "chat", viewOpen: false }),+ openBlocks: () =>+ set({ collapsed: false, tab: "blocks", viewOpen: false }),openComments: () =>set({ collapsed: false, tab: "comments", viewOpen: true }),}),