Skip to content

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

feat(canvas): add manual canvas editing to web (#109203)

Peter Kirkham3f1ced856bb3
diff --git a/frontend/src/layout/navigation-3000/sidepanel/SidePanel.tsx b/frontend/src/layout/navigation-3000/sidepanel/SidePanel.tsx
index d8a61c449b9d..2a2e82f38485 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/SidePanel.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/SidePanel.tsx
@@ -3,7 +3,7 @@ import './SidePanel.scss'
import { useActions, useValues } from 'kea'
import { Suspense, useEffect, useRef } from 'react'
-import { IconChat, IconComment, IconLock, IconLogomark, IconNotebook, IconPulse } from '@posthog/icons'
+import { IconApps, IconChat, IconComment, IconLock, IconLogomark, IconNotebook, IconPulse } from '@posthog/icons'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
@@ -108,6 +108,11 @@ export const SIDE_PANEL_TABS: Record<SidePanelTab, { label: string; Icon: any; C
Icon: IconChat,
Content: CanvasSidePanel,
},
+ [SidePanelTab.CanvasBlocks]: {
+ label: 'Blocks',
+ Icon: IconApps,
+ Content: CanvasSidePanel,
+ },
[SidePanelTab.CanvasComments]: {
label: 'Comments',
Icon: IconComment,
diff --git a/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.tsx
index 1d11f757d36a..1cfa72184fa8 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/sidePanelLogic.tsx
@@ -36,6 +36,7 @@ export const TABS_PERSISTED_ACROSS_NAVIGATION = [SidePanelTab.Max, SidePanelTab.
/** The tabs a canvas scene shows instead of the general ones, in order. */
export const CANVAS_SIDE_PANEL_TABS = [
SidePanelTab.CanvasChat,
+ SidePanelTab.CanvasBlocks,
SidePanelTab.CanvasComments,
SidePanelTab.CanvasTimeline,
]
@@ -177,7 +178,9 @@ export const sidePanelLogic = kea<sidePanelLogicType>([
if (sceneSidePanelContext.canvas_id && currentTeam) {
// Support stays openable from the help menu, but the canvas tabs take the bar.
return [
- ...CANVAS_SIDE_PANEL_TABS,
+ ...CANVAS_SIDE_PANEL_TABS.filter(
+ (tab) => tab !== SidePanelTab.CanvasBlocks || sceneSidePanelContext.canvas_blocks
+ ),
SidePanelTab.Exports,
...(isCloudOrDev ? [SidePanelTab.Support] : []),
]
diff --git a/frontend/src/layout/navigation-3000/sidepanel/types.ts b/frontend/src/layout/navigation-3000/sidepanel/types.ts
index 4614ab432eda..48017e11fcea 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/types.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/types.ts
@@ -13,5 +13,7 @@ export type SidePanelSceneContext = {
discussions_disabled?: boolean
/** The canvas on screen. Its panel tabs replace the general ones. */
canvas_id?: string
+ /** Whether the canvas on screen is being edited by hand, which adds its Blocks tab. */
+ canvas_blocks?: boolean
}
export const SIDE_PANEL_CONTEXT_KEY = 'sidePanelContext'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 4a9932b1e483..47094cd5fbc4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7170,6 +7170,7 @@ export enum SidePanelTab {
Info = 'info',
// A canvas scene replaces the general tabs with its own panel tabs.
CanvasChat = 'canvas-chat',
+ CanvasBlocks = 'canvas-blocks',
CanvasComments = 'canvas-comments',
CanvasTimeline = 'canvas-timeline',
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2c26d5a1a718..9d03effe0d66 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2770,6 +2770,9 @@ importers:
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ '@types/react-dom':
+ specifier: 18.3.7
+ version: 18.3.7(@types/[email protected])
kea:
specifier: 'catalog:'
version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
diff --git a/products/canvas/backend/sandbox/sandbox_document.html b/products/canvas/backend/sandbox/sandbox_document.html
index a90b88e4e274..1cb4b268e94f 100644
--- a/products/canvas/backend/sandbox/sandbox_document.html
+++ b/products/canvas/backend/sandbox/sandbox_document.html
@@ -84,6 +84,7 @@
const portOnly = new URLSearchParams(location.hash.slice(1)).get("bridge") === "port";
let bridgePort = null;
let sendToHost = null;
+ let disconnectBridge = null;
const post = (msg) => {
const message = { channel: CHANNEL, ...msg };
if (sendToHost) sendToHost(message);
@@ -1116,7 +1117,7 @@
lifted = null;
};
const onMove = (event) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
const pressed = (event.buttons & 1) === 1;
if (forwarding) {
if (!pressed) {
@@ -1205,29 +1206,31 @@
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 onTextKey = (event) => {
+ if (!event.isTrusted || !editingText || event.target !== editingText.element) return;
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ finishText(true);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ finishText(false);
+ }
+ };
+ const onTextBlur = (event) => {
+ if (event.isTrusted && event.target === editingText?.element) finishText(true);
+ };
const onDouble = (event) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
event.preventDefault();
event.stopPropagation();
const element = candidateOf(event.target);
if (element && element !== editingText?.element) startText(element);
};
const onDown = (event) => {
+ if (!event.isTrusted) return;
forwarding = false;
if (!enabled || event.button !== 0) return;
if (editingText?.element.contains(event.target)) return;
@@ -1247,18 +1250,19 @@
};
};
const swallow = (event) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
event.preventDefault();
event.stopPropagation();
};
- const onUp = (_event) => {
+ const onUp = (event) => {
+ if (!event.isTrusted) return;
dragOrigin = null;
if (!forwarding) return;
forwarding = false;
post({ type: "canvas-edit-pointer-up" });
};
const onKey = (event) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
const target = event.target;
if (target && (target.isContentEditable || [
"INPUT",
@@ -1383,6 +1387,8 @@
window.addEventListener("mouseup", onUp, true);
window.addEventListener("click", swallow, true);
window.addEventListener("dblclick", onDouble, true);
+ window.addEventListener("keydown", onTextKey, true);
+ window.addEventListener("blur", onTextBlur, true);
window.addEventListener("keydown", onKey, true);
document.addEventListener("mouseleave", () => {
hovered = null;
@@ -1543,13 +1549,14 @@
if (e.data?.channel === CHANNEL && e.data.type === "connect" && e.ports[0] && !bridgePort) {
bridgePort = e.ports[0];
sendToHost = bridgePort.postMessage.bind(bridgePort);
+ disconnectBridge = bridgePort.close.bind(bridgePort);
bridgePort.onmessage = (event) => receive(event.data);
post({ type: "ready" });
} else if (!portOnly && !bridgePort) {
receive(e.data);
}
});
- window.addEventListener("pagehide", () => bridgePort?.close());
+ window.addEventListener("pagehide", () => disconnectBridge?.());
post({ type: "ready" });
</script>
diff --git a/products/canvas/frontend/canvasAnalytics.ts b/products/canvas/frontend/canvasAnalytics.ts
index 245588d23286..1a22a7ade094 100644
--- a/products/canvas/frontend/canvasAnalytics.ts
+++ b/products/canvas/frontend/canvasAnalytics.ts
@@ -12,10 +12,22 @@ export const CANVAS_EVENTS = {
// pinned: `surface` values, shared with PostHog Desktop
export type CanvasSurface = 'web_new_canvas_page' | 'web_canvas_scene' | 'web_canvas_side_panel'
-// pinned: `action_type` values of the Dashboard action event. "revert" is shared with PostHog
-// Desktop. The rest name web actions Desktop does not track yet, so Desktop should reuse them.
+// pinned: `action_type` values of the Dashboard action event. "revert" and "edit_toggle" are shared
+// with PostHog Desktop. The rest name web actions Desktop does not track yet, so Desktop should reuse them.
export type CanvasDashboardActionType =
| 'revert'
+ | 'edit_toggle'
+ | 'block_insert'
+ | 'block_move'
+ | 'block_edit'
+ | 'block_remove'
+ | 'block_duplicate'
+ | 'text_edit'
+ | 'edit_undo'
+ | 'edit_redo'
+ | 'edit_save'
+ | 'edit_conflict'
+ | 'edit_conflict_resolve'
| 'promote_draft'
| 'panel_tab_change'
| 'panel_toggle'
@@ -28,7 +40,7 @@ export type CanvasDashboardActionType =
| 'build_unpin'
| 'fix_request'
-/** Captures a canvas action from the scene or its side panel. Never pass prompt or comment text. */
+/** Captures a canvas action from the scene or its side panel. Never pass prompt, comment, or source text. */
export function captureCanvasAction(
actionType: CanvasDashboardActionType,
properties: {
@@ -40,6 +52,14 @@ export function captureCanvasAction(
open?: boolean
origin?: 'build' | 'runtime'
outcome?: string
+ /** edit_toggle: the state being entered. */
+ editing?: boolean
+ /** A library block type, "custom" for a component the agent wrote, or "element" for plain markup. */
+ block_type?: string
+ /** block_insert: whether the block was clicked in or dragged in. */
+ method?: 'click' | 'drag'
+ /** edit_conflict_resolve: whether the author kept their edits over the newer version. */
+ keep_local?: boolean
}
): void {
posthog.capture(CANVAS_EVENTS.dashboardAction, {
diff --git a/products/canvas/frontend/editing/CanvasEditSaveStatus.tsx b/products/canvas/frontend/editing/CanvasEditSaveStatus.tsx
new file mode 100644
index 000000000000..d173509d15a5
--- /dev/null
+++ b/products/canvas/frontend/editing/CanvasEditSaveStatus.tsx
@@ -0,0 +1,105 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheckCircle } from '@posthog/icons'
+import { Button, Spinner, Text } from '@posthog/quill'
+
+import { CanvasStatusIssue } from '../scene/CanvasStatusIssue'
+import { canvasEditLogic } from './canvasEditLogic'
+
+/**
+ * Whether the author's edits are published yet, in the canvas header while editing. A failed save
+ * or a newer version from somewhere else opens what went wrong and the ways out of it.
+ */
+export function CanvasEditSaveStatus(): JSX.Element | null {
+ const { sourceEditing, entry, saveStatus } = useValues(canvasEditLogic)
+ const { retrySave, resolveConflict, askAgent } = useActions(canvasEditLogic)
+
+ if (!sourceEditing || !entry || !saveStatus) {
+ return null
+ }
+ if (entry.conflict) {
+ return (
+ <div className="flex items-center" data-attr="canvas-save-status">
+ <CanvasStatusIssue
+ label="Save conflict"
+ title="This canvas changed somewhere else"
+ description="A newer version was saved while you edited. Load it and drop your unsaved edits, or keep your edits and replace it."
+ details={[]}
+ dataAttr="canvas-save-conflict-details"
+ actions={
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => resolveConflict(false)}
+ data-attr="canvas-conflict-load-latest"
+ >
+ Load the latest
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={() => resolveConflict(true)}
+ data-attr="canvas-conflict-keep-mine"
+ >
+ Keep my edits
+ </Button>
+ </>
+ }
+ />
+ </div>
+ )
+ }
+ if (entry.saveError) {
+ const saveError = entry.saveError
+ return (
+ <div className="flex items-center" data-attr="canvas-save-status">
+ <CanvasStatusIssue
+ label="Not saved"
+ title="Your changes are not saved"
+ description="Your last change didn't publish. Try again, or ask the agent to fix the source if the error points to it."
+ details={[saveError]}
+ dataAttr="canvas-save-error-details"
+ actions={
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => retrySave()}
+ data-attr="canvas-save-retry"
+ >
+ Try again
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={() =>
+ askAgent(
+ `Saving this canvas fails with: "${saveError}". Fix the canvas source so it passes validation.`
+ )
+ }
+ data-attr="canvas-save-ask-agent"
+ >
+ Ask agent to fix
+ </Button>
+ </>
+ }
+ />
+ </div>
+ )
+ }
+ const saving = saveStatus.saving || saveStatus.dirty
+ return (
+ <Text
+ render={<span />}
+ size="xs"
+ variant="muted"
+ className="flex items-center gap-1 px-1"
+ aria-live="polite"
+ data-attr="canvas-save-status"
+ >
+ {saving ? <Spinner aria-hidden="true" /> : <IconCheckCircle aria-hidden="true" />}
+ <span>{saving ? 'Saving…' : 'Saved'}</span>
+ </Text>
+ )
+}
diff --git a/products/canvas/frontend/editing/CanvasEditToggle.tsx b/products/canvas/frontend/editing/CanvasEditToggle.tsx
new file mode 100644
index 000000000000..4adde38dafa2
--- /dev/null
+++ b/products/canvas/frontend/editing/CanvasEditToggle.tsx
@@ -0,0 +1,44 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheck, IconPencil } from '@posthog/icons'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { canvasEditLogic } from './canvasEditLogic'
+
+/** Enters edit mode, where the canvas's blocks can be selected, moved and changed by hand, and leaves it. */
+export function CanvasEditToggle(): JSX.Element {
+ const { editing, editUnavailableReason, entry } = useValues(canvasEditLogic)
+ const { setEditing, finishEditing } = useActions(canvasEditLogic)
+
+ if (editing) {
+ return (
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={finishEditing}
+ loading={entry?.saving}
+ data-attr="canvas-edit-done"
+ >
+ <IconCheck />
+ Done
+ </Button>
+ )
+ }
+ return (
+ <Tooltip>
+ <TooltipTrigger delay={0} render={<span className="inline-flex" />}>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!!editUnavailableReason}
+ onClick={() => setEditing(true)}
+ data-attr="canvas-edit-toggle"
+ >
+ <IconPencil />
+ Edit
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{editUnavailableReason ?? 'Select, move, and change blocks by hand'}</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/products/canvas/frontend/editing/CanvasEditorRenderer.tsx b/products/canvas/frontend/editing/CanvasEditorRenderer.tsx
new file mode 100644
index 000000000000..4a68fcd2169f
--- /dev/null
+++ b/products/canvas/frontend/editing/CanvasEditorRenderer.tsx
@@ -0,0 +1,68 @@
+import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
+import { useCallback } from 'react'
+
+import { themeLogic } from 'lib/logic/themeLogic'
+
+import {
+ CanvasHostLogicProps,
+ canvasHasUserActivation,
+ canvasHostLogic,
+ handleCanvasDataRequest,
+} from '../host/canvasHostLogic'
+import { CanvasHostPromptDialog } from '../host/CanvasHostPromptDialog'
+import { canvasSceneLogic } from '../scene/canvasSceneLogic'
+import { canvasEditLogic } from './canvasEditLogic'
+import { CanvasSourceEditor } from './CanvasSourceEditor'
+
+function EditorFrame({
+ hostProps,
+ documentUrl,
+}: {
+ hostProps: CanvasHostLogicProps
+ documentUrl: string
+}): JSX.Element {
+ const hostLogic = useMountedLogic(canvasHostLogic(hostProps))
+ const { navigate, openExternal, canvasErrored } = useActions(hostLogic)
+ const { setRuntimeError } = useActions(canvasSceneLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+ const onDataRequest = useCallback(
+ (method: string, payload: unknown) => handleCanvasDataRequest(hostLogic, method, payload),
+ [hostLogic]
+ )
+ return (
+ <CanvasSourceEditor
+ documentUrl={documentUrl}
+ theme={isDarkModeOn ? 'dark' : 'light'}
+ hasUserActivation={canvasHasUserActivation}
+ onOpenExternal={openExternal}
+ onDataRequest={onDataRequest}
+ onNavigate={navigate}
+ // Each edit remounts the source, so a clean render clears the last error.
+ onRendered={() => setRuntimeError(null)}
+ onError={(message) => {
+ setRuntimeError(message)
+ canvasErrored(message, null)
+ }}
+ />
+ )
+}
+
+/** The canvas body in edit mode: the head source in the editable sandbox, wired to the host bridge. */
+export function CanvasEditorRenderer(): JSX.Element | null {
+ const { canvas, sandboxDocumentUrl } = useValues(canvasSceneLogic)
+ const { entry } = useValues(canvasEditLogic)
+ if (!canvas || !sandboxDocumentUrl || !entry) {
+ return null
+ }
+ const hostProps: CanvasHostLogicProps = {
+ canvasId: canvas.id,
+ spaceId: canvas.channel,
+ sourceVersionId: entry.baseVersionId,
+ }
+ return (
+ <BindLogic logic={canvasHostLogic} props={hostProps}>
+ <EditorFrame hostProps={hostProps} documentUrl={sandboxDocumentUrl} />
+ <CanvasHostPromptDialog />
+ </BindLogic>
+ )
+}
diff --git a/products/canvas/frontend/editing/CanvasSourceEditor.test.tsx b/products/canvas/frontend/editing/CanvasSourceEditor.test.tsx
new file mode 100644
index 000000000000..ceb39c444ba7
--- /dev/null
+++ b/products/canvas/frontend/editing/CanvasSourceEditor.test.tsx
@@ -0,0 +1,64 @@
+import { render, waitFor } from '@testing-library/react'
+
+import type { CanvasCapabilitiesApi } from '../generated/api.schemas'
+import { CanvasDocumentBridge } from '../host/canvasDocumentBridge'
+import { BLOCK_RUNTIME_PATH } from './blockLibrary/blockDefinitions'
+import { CanvasSourceEditor } from './CanvasSourceEditor'
+import { CanvasSourceEntry, applySourceFiles, loadSourceEntry } from './canvasSourceSnapshots'
+
+let mockEntry: CanvasSourceEntry
+jest.mock('kea', () => ({
+ ...jest.requireActual('kea'),
+ useValues: () => ({ entry: mockEntry }),
+ useActions: () => ({}),
+}))
+jest.mock('./canvasEditLogic', () => ({ canvasEditLogic: {} }))
+jest.mock('./SourceDragOverlay', () => ({ SourceDragOverlay: () => null }))
+jest.mock('../host/canvasDocumentBridge', () => ({
+ CanvasDocumentBridge: jest.fn().mockImplementation(() => ({ post: jest.fn(), close: jest.fn() })),
+}))
+
+describe('CanvasSourceEditor capabilities', () => {
+ test.each(['missing', 'denied', 'allowed', 'existing blocks', 'added blocks'])(
+ 'enforces query permissions with %s',
+ async (state) => {
+ jest.mocked(CanvasDocumentBridge).mockClear()
+ const capabilities: CanvasCapabilitiesApi = {
+ posthog: { insights: [], inlineQueries: state === 'allowed', captureEvents: [] },
+ network: { origins: [] },
+ }
+ mockEntry = loadSourceEntry(
+ null,
+ {
+ schemaVersion: 1,
+ entryHtml: 'index.html',
+ files: state === 'existing blocks' ? { [BLOCK_RUNTIME_PATH]: '' } : {},
+ capabilities: state === 'missing' ? undefined : capabilities,
+ },
+ 'v1'
+ )
+ if (state === 'added blocks') {
+ mockEntry = applySourceFiles(mockEntry, { [BLOCK_RUNTIME_PATH]: '' })
+ }
+ const onDataRequest = jest.fn(async () => ({ results: [] }))
+ render(
+ <CanvasSourceEditor
+ documentUrl="https://example.com/sandbox"
+ theme="light"
+ hasUserActivation={() => false}
+ onOpenExternal={jest.fn()}
+ onDataRequest={onDataRequest}
+ />
+ )
+ const onMessage = jest.mocked(CanvasDocumentBridge).mock.calls[0][1]
+ const bridge = jest.mocked(CanvasDocumentBridge).mock.results[0].value
+ onMessage({ channel: 'posthog-canvas', type: 'data-request', id: 'q1', method: 'query', payload: {} })
+
+ const allowed = state === 'allowed' || state === 'added blocks'
+ await waitFor(() =>
+ expect(bridge.post).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1', ok: allowed }))
+ )
+ expect(onDataRequest).toHaveBeenCalledTimes(allowed ? 1 : 0)
+ }
+ )
+})
diff --git a/products/canvas/frontend/editing/CanvasSourceEditor.tsx b/products/canvas/frontend/editing/CanvasSourceEditor.tsx
new file mode 100644
index 000000000000..b2fd2af6c2d1
--- /dev/null
+++ b/products/canvas/frontend/editing/CanvasSourceEditor.tsx
@@ -0,0 +1,261 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useLayoutEffect, useRef } from 'react'
+
+import { assertCanvasCapability } from '../host/canvasCapabilities'
+import { CanvasDocumentBridge } from '../host/canvasDocumentBridge'
+import { CanvasHostCallbacks, createCanvasHostMessageRouter } from '../host/canvasHostMessageRouter'
+import {
+ CanvasTheme,
+ CanvasEditMessage,
+ canvasEditMessageSchema,
+ canvasToHostMessageSchema,
+} from '../host/canvasProtocol'
+import { CANVAS_ENTRY_PATH } from './blockLibrary/blockProject'
+import { parseParamSchema } from './blockLibrary/params'
+import type { SourceRange } from './blockLibrary/sourceEdits'
+import { CanvasEditKey, canvasEditLogic } from './canvasEditLogic'
+import { connectCanvasEditor, postToCanvasEditor } from './canvasEditorFrame'
+import type { CanvasEditSelection } from './canvasSourceSnapshots'
+import { SourceDropHit, activeSourceDrag, beginSourceDrag } from './sourceDrag'
+import { SourceDragOverlay } from './SourceDragOverlay'
+
+export interface CanvasSourceEditorProps extends CanvasHostCallbacks {
+ /** The sandbox bootstrap document on the artifact origin. It carries the edit runtime. */
+ documentUrl: string
+ theme: CanvasTheme
+ hasUserActivation: () => boolean
+ onOpenExternal: (url: string) => void
+}
+
+/** The frame reports the param schema as the raw JSON the component declared. */
+interface EditElementMessage extends Omit<CanvasEditSelection, 'params'> {
+ params: string | null
+}
+
+function toSelection(element: EditElementMessage | null | undefined): CanvasEditSelection | null {
+ return element ? { ...element, params: parseParamSchema(element.params) } : null
+}
+
+function isTypingTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) {
+ return false
+ }
+ return target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName)
+}
+
+/**
+ * The canvas in edit mode: the head source runs in the sandbox with the edit runtime on, which
+ * outlines the element under the pointer and reports selection, drags and text edits back here.
+ * Every local change sends a fresh init with the files, so the frame remounts the new source.
+ */
+export function CanvasSourceEditor({
+ documentUrl,
+ theme,
+ hasUserActivation,
+ onOpenExternal,
+ ...callbacks
+}: CanvasSourceEditorProps): JSX.Element {
+ const { entry } = useValues(canvasEditLogic)
+ const { select, frameMounted, dropBlock, setText, editKey } = useActions(canvasEditLogic)
+ const iframeRef = useRef<HTMLIFrameElement>(null)
+ const readyRef = useRef(false)
+ const latest = useRef({ entry, theme, callbacks, hasUserActivation, onOpenExternal })
+ latest.current = { entry, theme, callbacks, hasUserActivation, onOpenExternal }
+
+ const sendInit = (): void => {
+ const snapshot = latest.current.entry
+ 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: [],
+ })
+ }
+
+ const handleKey = (key: CanvasEditKey, prevent?: () => void): void => {
+ const mod = key.metaKey || key.ctrlKey
+ if (key.key === 'Escape') {
+ const drag = activeSourceDrag()
+ if (drag) {
+ drag.end(false)
+ } else {
+ select(null)
+ postToCanvasEditor({ type: 'canvas-edit-deselect' })
+ }
+ return
+ }
+ if ((mod && ['z', 'd'].includes(key.key.toLowerCase())) || key.key === 'Backspace' || key.key === 'Delete') {
+ prevent?.()
+ editKey(key)
+ }
+ }
+
+ const handleEdit = (data: CanvasEditMessage): void => {
+ const rect = iframeRef.current?.getBoundingClientRect()
+ const offsetX = rect?.left ?? 0
+ const offsetY = rect?.top ?? 0
+ switch (data.type) {
+ case 'canvas-edit-select':
+ select(toSelection(data.element as EditElementMessage | null), data.byPointer === true)
+ return
+ case 'canvas-edit-root':
+ frameMounted(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) {
+ beginSourceDrag({
+ source: { kind: 'move', selection: element },
+ startX: offsetX + Number(data.x),
+ startY: offsetY + Number(data.y),
+ onDrop: dropBlock,
+ })
+ }
+ 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({
+ key: String(data.key ?? ''),
+ metaKey: data.metaKey === true,
+ ctrlKey: data.ctrlKey === true,
+ shiftKey: data.shiftKey === true,
+ })
+ return
+ case 'canvas-edit-text': {
+ const element = toSelection(data.element as EditElementMessage)
+ if (element && typeof data.text === 'string') {
+ setText(element, data.text)
+ }
+ return
+ }
+ }
+ }
+ const latestHandlers = useRef({ handleEdit, handleKey, sendInit })
+ latestHandlers.current = { handleEdit, handleKey, sendInit }
+
+ // A layout effect attaches the listener during commit, before the frame's one-shot "ready" can arrive.
+ useLayoutEffect(() => {
+ readyRef.current = false
+ const route = createCanvasHostMessageRouter({
+ post: (message) => bridge.post(message),
+ callbacks: () => ({
+ ...latest.current.callbacks,
+ onDataRequest: async (method, payload) => {
+ assertCanvasCapability(latest.current.entry?.project.capabilities, method, payload)
+ if (!latest.current.callbacks.onDataRequest) {
+ throw new Error('Canvas data bridge is unavailable')
+ }
+ return latest.current.callbacks.onDataRequest(method, payload)
+ },
+ onReady: () => {
+ if (readyRef.current) {
+ return
+ }
+ readyRef.current = true
+ latestHandlers.current.sendInit()
+ latest.current.callbacks.onReady?.()
+ },
+ // Text selection is for comments, and edit mode takes the pointer for itself.
+ onTextSelection: undefined,
+ onCommentActivate: undefined,
+ }),
+ hasUserActivation: () => latest.current.hasUserActivation(),
+ openExternal: (url) => latest.current.onOpenExternal(url),
+ })
+ const bridge = new CanvasDocumentBridge(
+ iframeRef.current!,
+ (data) => {
+ const edit = canvasEditMessageSchema.safeParse(data)
+ if (edit.success) {
+ latestHandlers.current.handleEdit(edit.data)
+ return
+ }
+ const parsed = canvasToHostMessageSchema.safeParse(data)
+ if (parsed.success) {
+ void route(parsed.data)
+ }
+ },
+ () => {}
+ )
+ const disconnect = connectCanvasEditor(iframeRef.current!, bridge.post)
+ return () => {
+ readyRef.current = false
+ activeSourceDrag()?.end(false)
+ disconnect()
+ bridge.close()
+ }
+ }, [documentUrl])
+
+ const rev = entry?.rev
+ useEffect(() => {
+ if (rev !== undefined) {
+ latestHandlers.current.sendInit()
+ }
+ }, [rev])
+
+ useEffect(() => {
+ if (readyRef.current) {
+ postToCanvasEditor({ type: 'set-theme', theme })
+ }
+ }, [theme])
+
+ // Shortcuts pressed while the host has focus. The frame forwards its own through canvas-edit-key.
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent): void => {
+ if (!event.isTrusted || isTypingTarget(event.target)) {
+ return
+ }
+ const shortcut = event.metaKey || event.ctrlKey
+ if (!shortcut && event.target !== document.body) {
+ return
+ }
+ latestHandlers.current.handleKey(
+ { key: event.key, metaKey: event.metaKey, ctrlKey: event.ctrlKey, shiftKey: event.shiftKey },
+ () => event.preventDefault()
+ )
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [])
+
+ return (
+ <div className="relative h-full w-full">
+ <iframe
+ ref={iframeRef}
+ title="Canvas editor"
+ data-canvas-source-editor=""
+ // allow-scripts without allow-same-origin keeps the sandbox in an opaque origin.
+ // Do not add allow-popups or allow-same-origin.
+ sandbox="allow-scripts"
+ key={documentUrl}
+ src={`${documentUrl}#bridge=port`}
+ referrerPolicy="no-referrer"
+ // Without a matching color-scheme the browser paints the frame white before init lands.
+ style={{ colorScheme: theme }}
+ className="h-full w-full border-0 bg-background"
+ data-attr="canvas-source-editor"
+ />
+ <SourceDragOverlay />
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/editing/SourceDragOverlay.scss b/products/canvas/frontend/editing/SourceDragOverlay.scss
new file mode 100644
index 000000000000..af94374a615d
--- /dev/null
+++ b/products/canvas/frontend/editing/SourceDragOverlay.scss
@@ -0,0 +1,69 @@
+.CanvasSourceDrag__shield {
+ position: fixed;
+ inset: 0;
+ z-index: 998;
+ user-select: none;
+}
+
+.CanvasSourceDrag__ghost {
+ --canvas-source-drag-ease-out: cubic-bezier(0.23, 1, 0.32, 1);
+
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 1000;
+ pointer-events: none;
+ transform-origin: 24px 20px;
+ will-change: transform;
+
+ &[data-phase='drop'] {
+ opacity: 0;
+ transition:
+ opacity 140ms var(--canvas-source-drag-ease-out),
+ scale 140ms var(--canvas-source-drag-ease-out);
+ scale: 0.98;
+ }
+
+ &[data-phase='return'] {
+ opacity: 0;
+ transition:
+ transform 280ms var(--canvas-source-drag-ease-out),
+ opacity 180ms ease-out 100ms;
+ }
+}
+
+.CanvasSourceDrag__card {
+ animation: CanvasSourceDrag__Lift 180ms var(--canvas-source-drag-ease-out) both;
+}
+
+@keyframes CanvasSourceDrag__Lift {
+ from {
+ opacity: 0;
+ scale: 0.97;
+ }
+
+ to {
+ opacity: 1;
+ scale: 1;
+ }
+}
+
+@keyframes CanvasSourceDrag__Fade {
+ from {
+ opacity: 0;
+ }
+
+ to {
+ opacity: 1;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .CanvasSourceDrag__card {
+ animation-name: CanvasSourceDrag__Fade;
+ }
+
+ .CanvasSourceDrag__ghost[data-phase='return'] {
+ transition: opacity 140ms ease-out;
+ }
+}
diff --git a/products/canvas/frontend/editing/SourceDragOverlay.tsx b/products/canvas/frontend/editing/SourceDragOverlay.tsx
new file mode 100644
index 000000000000..617e41858140
--- /dev/null
+++ b/products/canvas/frontend/editing/SourceDragOverlay.tsx
@@ -0,0 +1,46 @@
+import './SourceDragOverlay.scss'
+
+import { useValues } from 'kea'
+import { createPortal } from 'react-dom'
+
+import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@posthog/quill'
+
+import { canvasSourceDragLogic } from './canvasSourceDragLogic'
+import { libraryIcon } from './libraryCatalog'
+
+// The card sits just below and right of the pointer, so it never covers the drop line.
+const GHOST_OFFSET_X = 14
+const GHOST_OFFSET_Y = 10
+
+/** The card that follows the pointer while a block is dragged onto or across the canvas. */
+export function SourceDragOverlay(): JSX.Element | null {
+ const { ghost } = useValues(canvasSourceDragLogic)
+ 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(
+ <div data-quill>
+ {/* Covers the frame while dragging, so the host keeps receiving pointer events. */}
+ {ghost.phase === 'drag' ? <div className="CanvasSourceDrag__shield cursor-grabbing" /> : null}
+ <div
+ className="CanvasSourceDrag__ghost"
+ data-phase={ghost.phase}
+ style={{ transform: `translate3d(${x}px, ${y}px, 0) rotate(${ghost.tilt.toFixed(2)}deg)` }}
+ >
+ <Item variant="outline" size="xs" className="CanvasSourceDrag__card w-56 bg-card shadow-lg">
+ <ItemMedia variant="icon" aria-hidden>
+ <Icon />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle className="truncate">{ghost.label}</ItemTitle>
+ <ItemDescription className="truncate">{ghost.hint}</ItemDescription>
+ </ItemContent>
+ </Item>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/products/canvas/frontend/editing/blockLibrary/blockDefinitions.ts b/products/canvas/frontend/editing/blockLibrary/blockDefinitions.ts
new file mode 100644
index 000000000000..9393d29e61da
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockDefinitions.ts
@@ -0,0 +1,269 @@
+import { jsxOpeningTags, jsxStringAttribute } from './jsxOpeningTags'
+
+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`
+}
+
+export function freshBlockProps(definition: BlockDefinition, files: Record<string, string>): BlockPropsRecord {
+ const presets = definition.presets ?? [{}]
+ const source = Object.values(files).join('\n')
+ const tags = definition.component ? jsxOpeningTags(source, definition.component) : []
+ const used = (preset: BlockPropsRecord): boolean =>
+ tags.some(({ tag }) => jsxStringAttribute(source, tag, 'title') === String(preset.title ?? ''))
+ return presets.find((preset) => !used(preset)) ?? presets[0]
+}
diff --git a/products/canvas/frontend/editing/blockLibrary/blockLibrarySync.test.ts b/products/canvas/frontend/editing/blockLibrary/blockLibrarySync.test.ts
new file mode 100644
index 000000000000..b9e68f586e10
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockLibrarySync.test.ts
@@ -0,0 +1,48 @@
+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,
+ runtime: undefined,
+ expected: BLOCK_COMPONENT_SOURCES.Metric,
+ },
+ {
+ name: 'keeps a copy someone changed',
+ current: `${OLD_COPY}// edited\n`,
+ runtime: undefined,
+ 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/canvas/frontend/editing/blockLibrary/blockLibrarySync.ts b/products/canvas/frontend/editing/blockLibrary/blockLibrarySync.ts
new file mode 100644
index 000000000000..e6a0be72f338
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockLibrarySync.ts
@@ -0,0 +1,93 @@
+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): boolean => 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
+ }
+ if (next === files) {
+ next = { ...files }
+ }
+ next[path] = latest
+ manifest[path] = hashText(latest)
+ changed = true
+ }
+ return changed ? writeManifest(next, manifest) : files
+}
diff --git a/products/canvas/frontend/editing/blockLibrary/blockProject.test.ts b/products/canvas/frontend/editing/blockLibrary/blockProject.test.ts
new file mode 100644
index 000000000000..6482ce10ddfd
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockProject.test.ts
@@ -0,0 +1,15 @@
+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 > 1"}\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/canvas/frontend/editing/blockLibrary/blockProject.ts b/products/canvas/frontend/editing/blockLibrary/blockProject.ts
new file mode 100644
index 000000000000..f3a361fb7069
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockProject.ts
@@ -0,0 +1,104 @@
+import { BLOCK_ICONS_PATH, BLOCK_RUNTIME_PATH, componentPath } from './blockDefinitions'
+import { withLibraryFile } from './blockLibrarySync'
+import { BLOCK_COMPONENT_SOURCES } from './componentSources'
+import { jsxOpeningTags, jsxStringAttribute } from './jsxOpeningTags'
+
+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>
+`
+
+// Matches PostHog Desktop's "Blank" starter, so a blank canvas edits the same way in both apps.
+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>
+ );
+}
+`
+
+interface Capabilities {
+ posthog?: {
+ insights?: string[]
+ inlineQueries?: boolean
+ captureEvents?: string[]
+ state?: string[]
+ actions?: string[]
+ agentRequests?: boolean
+ }
+ network?: { origins?: string[] }
+ connectors?: unknown[]
+}
+
+function insightBlockIds(files: Record<string, string>): string[] {
+ return Object.values(files).flatMap((source) =>
+ jsxOpeningTags(source, 'Insight').flatMap(({ tag }) => {
+ const id = jsxStringAttribute(source, tag, 'shortId')
+ return id ? [id] : []
+ })
+ )
+}
+
+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: [] },
+ }
+}
+
+function usedComponents(source: string): string[] {
+ return Array.from(source.matchAll(/from\s+["']\.\/blocks\/([A-Za-z]+)["']/g), (match) => match[1]).filter(
+ (name) => !!BLOCK_COMPONENT_SOURCES[name]
+ )
+}
+
+/** The files of a blank canvas built from blocks: a title, a date range, and the block library it needs. */
+export function blankCanvasFiles(): Record<string, string> {
+ let files = withLibraryFile({ 'index.html': ENTRY_HTML, [CANVAS_ENTRY_PATH]: BLANK_CANVAS }, BLOCK_RUNTIME_PATH)
+ files = withLibraryFile(files, BLOCK_ICONS_PATH)
+ for (const component of usedComponents(BLANK_CANVAS)) {
+ files = withLibraryFile(files, componentPath(component))
+ }
+ return files
+}
diff --git a/products/canvas/frontend/editing/blockLibrary/blockSql.ts b/products/canvas/frontend/editing/blockLibrary/blockSql.ts
new file mode 100644
index 000000000000..1644c6a66ab8
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/blockSql.ts
@@ -0,0 +1,122 @@
+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/canvas/frontend/editing/blockLibrary/componentSources.ts b/products/canvas/frontend/editing/blockLibrary/componentSources.ts
new file mode 100644
index 000000000000..b3294108a6b1
--- /dev/null
+++ b/products/canvas/frontend/editing/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-fill-hover">
+ <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-fill-hover " + (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-fill-hover"
+ >
+ <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-fill-hover 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-fill-hover/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-fill-hover/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-fill-hover">
+ <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-fill-hover/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-fill-hover">
+ <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-fill-hover-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/canvas/frontend/editing/blockLibrary/iconsSource.ts b/products/canvas/frontend/editing/blockLibrary/iconsSource.ts
new file mode 100644
index 000000000000..147fee0cf4dc
--- /dev/null
+++ b/products/canvas/frontend/editing/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/canvas/frontend/editing/blockLibrary/jsxOpeningTags.ts b/products/canvas/frontend/editing/blockLibrary/jsxOpeningTags.ts
new file mode 100644
index 000000000000..0a751772a9d4
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/jsxOpeningTags.ts
@@ -0,0 +1,119 @@
+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
+}
+
+export 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 jsxOpeningTags(source: string, component: string): { start: number; end: number; tag: OpeningTag }[] {
+ return Array.from(source.matchAll(/<([A-Za-z][\w.]*)\b/g)).flatMap((match) => {
+ if (match[1] !== component) {
+ return []
+ }
+ const tag = scanOpeningTag(source, match.index)
+ return tag ? [{ start: match.index, end: tag.insertAt + (source[tag.insertAt] === '/' ? 2 : 1), tag }] : []
+ })
+}
+
+export function jsxStringAttribute(source: string, tag: OpeningTag, name: string): string | null {
+ const attribute = tag.attributes.find((attribute) => attribute.name === name)
+ if (!attribute) {
+ return null
+ }
+ let value = source.slice(attribute.start, attribute.end).slice(name.length).trim().replace(/^=\s*/, '')
+ if (value.startsWith('{') && value.endsWith('}')) {
+ value = value.slice(1, -1).trim()
+ }
+ if (value.startsWith('"')) {
+ try {
+ return JSON.parse(value) as string
+ } catch {
+ return null
+ }
+ }
+ return value.startsWith("'") && value.endsWith("'") ? value.slice(1, -1) : null
+}
diff --git a/products/canvas/frontend/editing/blockLibrary/params.ts b/products/canvas/frontend/editing/blockLibrary/params.ts
new file mode 100644
index 000000000000..d2e17bb770a9
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/params.ts
@@ -0,0 +1,105 @@
+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/canvas/frontend/editing/blockLibrary/propertyNames.ts b/products/canvas/frontend/editing/blockLibrary/propertyNames.ts
new file mode 100644
index 000000000000..97fcc537da1e
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/propertyNames.ts
@@ -0,0 +1,28 @@
+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/canvas/frontend/editing/blockLibrary/runtimeSource.ts b/products/canvas/frontend/editing/blockLibrary/runtimeSource.ts
new file mode 100644
index 000000000000..2e1916a6bcae
--- /dev/null
+++ b/products/canvas/frontend/editing/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-fill-hover 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-fill-hover 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-fill-hover/60" style={{ height }} />;
+ }
+ if (error) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-1 rounded-md bg-fill-hover/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-fill-hover/60" style={{ height }} />;
+ }
+ if (empty) {
+ return (
+ <div className="flex items-center justify-center rounded-md bg-fill-hover/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-fill-hover/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/canvas/frontend/editing/blockLibrary/sourceEdits.test.ts b/products/canvas/frontend/editing/blockLibrary/sourceEdits.test.ts
new file mode 100644
index 000000000000..b73d75ad6a3e
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/sourceEdits.test.ts
@@ -0,0 +1,129 @@
+import { blockDefinition, freshBlockProps } from './blockDefinitions'
+import { blockRanges, DropPlace, moveRange, placeableTarget, 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] ?? ''
+}
+
+const NESTED = `<main>
+ <section>
+ <p>A</p>
+ <p>B</p>
+ </section>
+</main>`
+
+function nestedRange(snippet: string): { file: string; start: number; end: number } {
+ const start = NESTED.indexOf(snippet)
+ return { file: FILE, start, end: start + snippet.length }
+}
+
+const TWO_ROOTS = `function Game() {
+ return (
+ <div>
+ <h2>Title</h2>
+ </div>
+ )
+}
+
+export default function Canvas() {
+ return (
+ <main>
+ <Card title="A" />
+ </main>
+ )
+}
+`
+const ROOT = {
+ file: FILE,
+ start: TWO_ROOTS.indexOf('<main>'),
+ end: TWO_ROOTS.indexOf('</main>') + '</main>'.length,
+}
+const TITLE = {
+ file: FILE,
+ start: TWO_ROOTS.indexOf('<h2>'),
+ end: TWO_ROOTS.indexOf('</h2>') + '</h2>'.length,
+}
+const CARD = {
+ file: FILE,
+ start: TWO_ROOTS.indexOf('<Card'),
+ end: TWO_ROOTS.indexOf('/>') + 2,
+}
+
+describe('sourceEdits', () => {
+ 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\\""} />',
+ },
+ ])('setJsxAttributes $name', ({ source, values, expected }) => {
+ expect(edit(source, values)).toBe(expected)
+ })
+
+ it('moveRange moves a child out to just after its parent', () => {
+ const section = NESTED.slice(NESTED.indexOf('<section>'), NESTED.indexOf('</section>') + '</section>'.length)
+ const moved = moveRange({ [FILE]: NESTED }, nestedRange('<p>B</p>'), {
+ ...nestedRange(section),
+ place: 'after',
+ })
+ expect(moved[FILE]?.replace(/\n\s*\n/g, '\n')).toBe(`<main>
+ <section>
+ <p>A</p>
+ </section>
+ <p>B</p>
+</main>`)
+ })
+
+ 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],
+ ])('placeableTarget %s', (_name, range, place, expected) => {
+ expect(
+ placeableTarget({ files: { [FILE]: TWO_ROOTS }, rootSource: ROOT }, { file: FILE, ...range, place })
+ ).toBe(expected)
+ })
+})
+
+test('finds data blocks and used presets after comparison attributes', () => {
+ const definition = blockDefinition('Funnel')!
+ const title = String(definition.presets![0].title)
+ const source = `<Funnel sql={"SELECT 1 WHERE 2 >= 1"} title="${title}" />`
+ const files = { [FILE]: source }
+ expect(blockRanges(files, FILE, 'Data')).toEqual([{ file: FILE, start: 0, end: source.length }])
+ if (definition.presets!.length > 1) {
+ expect(freshBlockProps(definition, files)).toEqual(definition.presets![1])
+ }
+})
diff --git a/products/canvas/frontend/editing/blockLibrary/sourceEdits.ts b/products/canvas/frontend/editing/blockLibrary/sourceEdits.ts
new file mode 100644
index 000000000000..3f68ce43ddd3
--- /dev/null
+++ b/products/canvas/frontend/editing/blockLibrary/sourceEdits.ts
@@ -0,0 +1,441 @@
+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'
+import { jsxOpeningTags, scanOpeningTag } from './jsxOpeningTags'
+
+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),
+ }
+}
+
+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 []
+ }
+ return components
+ .flatMap((component) =>
+ jsxOpeningTags(source, component)
+ .filter(({ end }) => source.slice(end - 2, end) === '/>')
+ .map(({ start, end }) => ({ file, start, end }))
+ )
+ .sort((left, right) => left.start - right.start)
+}
+
+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/canvas/frontend/editing/canvasEditLogic.test.ts b/products/canvas/frontend/editing/canvasEditLogic.test.ts
new file mode 100644
index 000000000000..53b6cf8b64a4
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasEditLogic.test.ts
@@ -0,0 +1,118 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import * as api from '../generated/api'
+import type { CanvasSourcePublishResponseApi, CanvasSourceResponseApi } from '../generated/api.schemas'
+import { canvasSceneLogic } from '../scene/canvasSceneLogic'
+import { canvasEditLogic } from './canvasEditLogic'
+
+const source = {
+ project: { schemaVersion: 1, entryHtml: 'index.html', files: { 'src/canvas.tsx': '<main>Saved</main>' } },
+ current_version_id: 'v1',
+ canvas: { id: 'canvas' } as CanvasSourceResponseApi['canvas'],
+} as CanvasSourceResponseApi
+
+const published = (version: string): CanvasSourcePublishResponseApi =>
+ ({ current_version_id: version }) as CanvasSourcePublishResponseApi
+
+describe('canvasEditLogic saving', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/canvases/:id/view/': {
+ canvas: { id: 'canvas', channel: 'space', kind: 'freeform', generation_task_id: null },
+ current_version_id: 'v1',
+ published_build: null,
+ has_active_build: false,
+ },
+ '/api/projects/:team_id/canvases/:id/builds/': { builds: [], published_build_id: null },
+ '/api/projects/:team_id/canvases/:id/versions/': { results: [], next: null },
+ '/api/projects/:team_id/canvases/:id/drafts/': [],
+ '/api/projects/:team_id/task_channels/:id/': { id: 'space', name: 'Space' },
+ },
+ })
+ initKeaTests()
+ jest.spyOn(api, 'canvasesSourceRetrieve').mockResolvedValue(source)
+ })
+ afterEach(() => {
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
+
+ test.each(['loading', 'failed'])('Done exits when source is %s and no edits exist', async (state) => {
+ jest.mocked(api.canvasesSourceRetrieve).mockImplementation(() => new Promise(() => {}))
+ const publish = jest.spyOn(api, 'canvasesPublishCreate')
+ const logic = canvasEditLogic({ id: 'canvas' })
+ await expectLogic(canvasSceneLogic({ id: 'canvas' }), () => {
+ logic.mount()
+ }).toDispatchActions(['loadViewSuccess', 'loadSpaceSuccess'])
+ logic.actions.setEditing(true)
+ if (state === 'failed') {
+ logic.actions.sourceLoadFailed('Source is unavailable')
+ }
+ logic.actions.finishEditing()
+ expect(logic.values.editing).toBe(false)
+ expect(publish).not.toHaveBeenCalled()
+ })
+
+ test.each([409, 503])('Done keeps recovery controls open after save status %s', async (status) => {
+ jest.spyOn(api, 'canvasesPublishCreate').mockRejectedValue({ status, data: { current_version_id: 'v2' } })
+ const logic = canvasEditLogic({ id: 'canvas' })
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.setEditing(true)).toDispatchActions(['sourceLoaded'])
+ logic.actions.applyEdit({ 'src/canvas.tsx': '<main>Changed</main>' }, 'Edited text')
+ await expectLogic(logic, () => logic.actions.finishEditing()).toDispatchActions([
+ status === 409 ? 'conflictDetected' : 'saveFailed',
+ ])
+ expect(logic.values.editing).toBe(true)
+ expect(logic.values.entry?.saving).toBe(false)
+ })
+
+ test('saves a later edit after the in-flight save completes following unmount', async () => {
+ let complete!: (result: CanvasSourcePublishResponseApi) => void
+ const publish = jest
+ .spyOn(api, 'canvasesPublishCreate')
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ .mockResolvedValue(published('v3'))
+ const logic = canvasEditLogic({ id: 'canvas' })
+ const unmount = logic.mount()
+ logic.actions.sourceLoaded(source)
+ logic.actions.applyEdit({ 'src/canvas.tsx': '<main>First</main>' }, 'First edit')
+ logic.actions.save()
+ logic.actions.applyEdit({ 'src/canvas.tsx': '<main>Second</main>' }, 'Second edit')
+ unmount()
+ complete(published('v2'))
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(publish).toHaveBeenLastCalledWith(
+ expect.any(String),
+ 'canvas',
+ expect.objectContaining({
+ expected_current_version_id: 'v2',
+ project: expect.objectContaining({ files: { 'src/canvas.tsx': '<main>Second</main>' } }),
+ })
+ )
+ expect(publish).toHaveBeenCalledTimes(2)
+ })
+
+ test('autosaves while the document is hidden', async () => {
+ const publish = jest.spyOn(api, 'canvasesPublishCreate').mockResolvedValue(published('v2'))
+ const logic = canvasEditLogic({ id: 'canvas' })
+ logic.mount()
+ logic.actions.sourceLoaded(source)
+ jest.useFakeTimers()
+ logic.actions.applyEdit({ 'src/canvas.tsx': '<main>Changed</main>' }, 'Edited text')
+ const hidden = jest.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+ document.dispatchEvent(new Event('visibilitychange'))
+ await jest.advanceTimersByTimeAsync(700)
+ expect(publish).toHaveBeenCalledTimes(1)
+ hidden.mockRestore()
+ })
+})
diff --git a/products/canvas/frontend/editing/canvasEditLogic.ts b/products/canvas/frontend/editing/canvasEditLogic.ts
new file mode 100644
index 000000000000..7b9fd31a9d9c
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasEditLogic.ts
@@ -0,0 +1,876 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { beforeUnload } from 'kea-router'
+
+import { CanvasDashboardActionType, captureCanvasAction } from '../canvasAnalytics'
+import { canvasesPublishCreate, canvasesSourceRetrieve } from '../generated/api'
+import type {
+ CanvasApi,
+ CanvasCapabilitiesApi,
+ CanvasDiagnosticApi,
+ CanvasSourceResponseApi,
+ CanvasViewResponseApi,
+} from '../generated/api.schemas'
+import { canvasHistoryLogic } from '../history/canvasHistoryLogic'
+import { canvasNewLogic } from '../newCanvas/canvasNewLogic'
+import { canvasSceneLogic } from '../scene/canvasSceneLogic'
+import { CanvasPanelTab } from '../sidePanel/canvasPanelTabs'
+import { canvasSidePanelLogic } from '../sidePanel/canvasSidePanelLogic'
+import { canvasChatLogic } from '../sidePanel/chat/canvasChatLogic'
+import { BlockPropsRecord, blockDefinition, freshBlockProps } from './blockLibrary/blockDefinitions'
+import { syncBlockLibrary } from './blockLibrary/blockLibrarySync'
+import { CANVAS_ENTRY_PATH, canvasCapabilities } from './blockLibrary/blockProject'
+import {
+ SourceDropTarget,
+ SourceFiles,
+ SourceRange,
+ blockRanges,
+ duplicateRange,
+ insertBlock,
+ isJsxRange,
+ moveRange,
+ newBlockId,
+ placeableTarget,
+ removeRange,
+ replaceElementText,
+ updateBlockProps,
+} from './blockLibrary/sourceEdits'
+import {
+ CanvasEditSelection,
+ CanvasSourceEntry,
+ applySourceFiles,
+ describeChanges,
+ isFreshRev,
+ isRootSelection,
+ isSourceDirty,
+ loadSourceEntry,
+ markSourceSaved,
+ noteSourceChange,
+ redoSourceEntry,
+ resolveSourceConflict,
+ setSourceConflict,
+ setSourceMounted,
+ setSourceSaving,
+ undoSourceEntry,
+} from './canvasSourceSnapshots'
+import { analyticsBlockType, libraryLabel } from './libraryCatalog'
+import type { SourceDragSource, SourceDropHit } from './sourceDrag'
+
+// Matches PostHog Desktop: edits save shortly after the author stops, and the head is re-read
+// while editing so a publish from elsewhere loads when there is nothing local to lose.
+const SAVE_DEBOUNCE_MS = 700
+const SOURCE_POLL_MS = 4_000
+
+const SIDE_BY_SIDE_BLOCKS = new Set(['Metric', 'TopList', 'Funnel'])
+
+export interface CanvasEditLogicProps {
+ id: string
+}
+
+export interface CanvasEditKey {
+ key: string
+ metaKey: boolean
+ ctrlKey: boolean
+ shiftKey: boolean
+}
+
+export interface CanvasSaveStatus {
+ saving: boolean
+ dirty: boolean
+ error: string | null
+}
+
+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' }
+}
+
+function saveErrorMessage(error: unknown): string {
+ const data = (error as { data?: { detail?: string; diagnostics?: CanvasDiagnosticApi[] } } | null)?.data
+ const diagnostic = data?.diagnostics?.find((item) => item.severity === 'error')
+ if (diagnostic) {
+ return diagnostic.path ? `${diagnostic.path}: ${diagnostic.message}` : diagnostic.message
+ }
+ return data?.detail || (error instanceof Error ? error.message : String(error))
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasEditLogicValues {
+ browseVersionId: string | null // canvasHistoryLogic
+ editHandoff: string | null // canvasNewLogic
+ canvas: CanvasApi | null // canvasSceneLogic
+ currentProjectId: number | null // canvasSceneLogic
+ isGenerating: boolean // canvasSceneLogic
+ sandboxDocumentUrl: string | null // canvasSceneLogic
+ view: CanvasViewResponseApi | null // canvasSceneLogic
+ canRedoEdit: boolean
+ canUndoEdit: boolean
+ editUnavailableReason: string | null
+ editing: boolean
+ entry: CanvasSourceEntry | null
+ finishAfterSave: boolean
+ libraryOpen: boolean
+ saveStatus: CanvasSaveStatus | null
+ selection: CanvasEditSelection | null
+ sourceEditing: boolean
+ sourceError: string | null
+ sourceLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasEditLogicActions {
+ setDraft: (draft: string) => {
+ draft: string
+ } // canvasChatLogic
+ setBrowseVersion: (versionId: string | null) => {
+ versionId: string | null
+ } // canvasHistoryLogic
+ clearEditHandoff: () => {
+ value: true
+ } // canvasNewLogic
+ loadBuilds: () => any // canvasSceneLogic
+ loadView: () => any // canvasSceneLogic
+ loadViewSuccess: (
+ view: CanvasViewResponseApi | null,
+ payload?: any
+ ) => {
+ payload?: any
+ view: CanvasViewResponseApi | null
+ } // canvasSceneLogic
+ startPolling: () => {
+ value: true
+ } // canvasSceneLogic
+ openTab: (
+ tab: CanvasPanelTab,
+ canvasId: string
+ ) => {
+ canvasId: string
+ tab: CanvasPanelTab
+ } // canvasSidePanelLogic
+ setBlocksCanvasId: (canvasId: string | null) => {
+ canvasId: string | null
+ } // canvasSidePanelLogic
+ switchTab: (tab: CanvasPanelTab) => {
+ tab: CanvasPanelTab
+ } // canvasSidePanelLogic
+ addAfterSelection: (blockType: string) => {
+ blockType: string
+ }
+ applyEdit: (
+ files: SourceFiles,
+ label: string,
+ focusBlockId?: string | null,
+ focusSource?: string | null
+ ) => {
+ files: SourceFiles
+ focusBlockId: string | null
+ focusSource: string | null
+ label: string
+ }
+ askAgent: (message: string) => {
+ message: string
+ }
+ conflictDetected: (versionId: string | null) => {
+ versionId: string | null
+ }
+ dropBlock: (
+ source: SourceDragSource,
+ hit: SourceDropHit
+ ) => {
+ hit: SourceDropHit
+ source: SourceDragSource
+ }
+ duplicateSelection: (selection: CanvasEditSelection) => {
+ selection: CanvasEditSelection
+ }
+ editKey: (key: CanvasEditKey) => {
+ key: CanvasEditKey
+ }
+ finishEditing: () => {
+ value: true
+ }
+ frameMounted: (
+ rev: number,
+ root: SourceRange | null
+ ) => {
+ rev: number
+ root: SourceRange | null
+ }
+ insertBlock: (
+ blockType: string,
+ target: SourceDropTarget,
+ method: 'click' | 'drag'
+ ) => {
+ blockType: string
+ method: 'click' | 'drag'
+ target: SourceDropTarget
+ }
+ loadSource: () => {
+ value: true
+ }
+ redoEdit: () => {
+ value: true
+ }
+ removeSelection: (selection: CanvasEditSelection) => {
+ selection: CanvasEditSelection
+ }
+ resolveConflict: (keepLocal: boolean) => {
+ keepLocal: boolean
+ }
+ retrySave: () => {
+ value: true
+ }
+ save: () => {
+ value: true
+ }
+ saveFailed: (error: string) => {
+ error: string
+ }
+ saveStarted: () => {
+ value: true
+ }
+ saveSucceeded: (
+ files: SourceFiles,
+ versionId: string,
+ noted: number
+ ) => {
+ files: SourceFiles
+ noted: number
+ versionId: string
+ }
+ select: (
+ selection: CanvasEditSelection | null,
+ byPointer?: boolean
+ ) => {
+ byPointer: boolean
+ selection: CanvasEditSelection | null
+ }
+ setEditing: (editing: boolean) => {
+ editing: boolean
+ }
+ setLibraryOpen: (open: boolean) => {
+ open: boolean
+ }
+ setText: (
+ selection: CanvasEditSelection,
+ text: string
+ ) => {
+ selection: CanvasEditSelection
+ text: string
+ }
+ sourceLoadFailed: (error: string) => {
+ error: string
+ }
+ sourceLoaded: (source: CanvasSourceResponseApi) => {
+ source: CanvasSourceResponseApi
+ }
+ sourceUnchanged: () => {
+ value: true
+ }
+ undoEdit: () => {
+ value: true
+ }
+ updateProps: (
+ selection: CanvasEditSelection,
+ props: BlockPropsRecord
+ ) => {
+ props: BlockPropsRecord
+ selection: CanvasEditSelection
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasEditLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ sourceEditing: (editing: boolean, browseVersionId: string | null) => boolean
+ canUndoEdit: (entry: CanvasSourceEntry | null) => boolean
+ canRedoEdit: (entry: CanvasSourceEntry | null) => boolean
+ saveStatus: (entry: CanvasSourceEntry | null) => CanvasSaveStatus | null
+ editUnavailableReason: (
+ view: CanvasViewResponseApi | null,
+ sandboxDocumentUrl: string | null,
+ isGenerating: boolean
+ ) => string | null
+ }
+}
+
+export type canvasEditLogicType = MakeLogicType<
+ canvasEditLogicValues,
+ canvasEditLogicActions,
+ CanvasEditLogicProps,
+ canvasEditLogicMeta
+>
+
+/**
+ * Manual editing of a canvas, ported from PostHog Desktop's block editor. The author edits the head
+ * source in the draft sandbox: selecting, moving, inserting and changing blocks rewrites the files
+ * locally, a snapshot stack backs undo and redo, and every change publishes a new version shortly after.
+ */
+export const canvasEditLogic = kea<canvasEditLogicType>([
+ props({} as CanvasEditLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'canvas', 'frontend', 'editing', 'canvasEditLogic', key]),
+ connect((props: CanvasEditLogicProps) => ({
+ values: [
+ canvasSceneLogic({ id: props.id }),
+ ['currentProjectId', 'view', 'canvas', 'isGenerating', 'sandboxDocumentUrl'],
+ canvasHistoryLogic({ id: props.id }),
+ ['browseVersionId'],
+ canvasNewLogic,
+ ['editHandoff'],
+ ],
+ actions: [
+ canvasSceneLogic({ id: props.id }),
+ ['loadView', 'loadViewSuccess', 'loadBuilds', 'startPolling'],
+ canvasHistoryLogic({ id: props.id }),
+ ['setBrowseVersion'],
+ canvasSidePanelLogic,
+ ['openTab', 'setBlocksCanvasId', 'switchTab'],
+ canvasChatLogic({ id: props.id }),
+ ['setDraft'],
+ canvasNewLogic,
+ ['clearEditHandoff'],
+ ],
+ })),
+ actions({
+ setEditing: (editing: boolean) => ({ editing }),
+ finishEditing: true,
+ loadSource: true,
+ sourceLoaded: (source: CanvasSourceResponseApi) => ({ source }),
+ sourceLoadFailed: (error: string) => ({ error }),
+ sourceUnchanged: true,
+ /** The frame mounted a rev of the files, and reports where the canvas's root element is. */
+ frameMounted: (rev: number, root: SourceRange | null) => ({ rev, root }),
+ select: (selection: CanvasEditSelection | null, byPointer: boolean = false) => ({ selection, byPointer }),
+ setLibraryOpen: (open: boolean) => ({ open }),
+ applyEdit: (
+ files: SourceFiles,
+ label: string,
+ focusBlockId: string | null = null,
+ focusSource: string | null = null
+ ) => ({ files, label, focusBlockId, focusSource }),
+ insertBlock: (blockType: string, target: SourceDropTarget, method: 'click' | 'drag') => ({
+ blockType,
+ target,
+ method,
+ }),
+ addAfterSelection: (blockType: string) => ({ blockType }),
+ dropBlock: (source: SourceDragSource, hit: SourceDropHit) => ({ source, hit }),
+ removeSelection: (selection: CanvasEditSelection) => ({ selection }),
+ duplicateSelection: (selection: CanvasEditSelection) => ({ selection }),
+ updateProps: (selection: CanvasEditSelection, props: BlockPropsRecord) => ({ selection, props }),
+ setText: (selection: CanvasEditSelection, text: string) => ({ selection, text }),
+ editKey: (key: CanvasEditKey) => ({ key }),
+ undoEdit: true,
+ redoEdit: true,
+ save: true,
+ saveStarted: true,
+ saveSucceeded: (files: SourceFiles, versionId: string, noted: number) => ({ files, versionId, noted }),
+ saveFailed: (error: string) => ({ error }),
+ retrySave: true,
+ conflictDetected: (versionId: string | null) => ({ versionId }),
+ resolveConflict: (keepLocal: boolean) => ({ keepLocal }),
+ askAgent: (message: string) => ({ message }),
+ }),
+ reducers({
+ finishAfterSave: [false, { finishEditing: () => true, setEditing: () => false }],
+ editing: [
+ false,
+ {
+ setEditing: (_, { editing }) => editing,
+ },
+ ],
+ entry: [
+ null as CanvasSourceEntry | null,
+ {
+ sourceLoaded: (state, { source }) => loadSourceEntry(state, source.project, source.current_version_id),
+ frameMounted: (state, { rev, root }) => (state ? setSourceMounted(state, rev, root) : state),
+ applyEdit: (state, { files, label, focusBlockId, focusSource }) =>
+ state ? applySourceFiles(noteSourceChange(state, label), files, focusBlockId, focusSource) : state,
+ undoEdit: (state) => (state ? undoSourceEntry(state) : state),
+ redoEdit: (state) => (state ? redoSourceEntry(state) : state),
+ saveStarted: (state) => (state ? setSourceSaving(state, true) : state),
+ saveSucceeded: (state, { files, versionId, noted }) =>
+ state ? markSourceSaved(state, files, versionId, noted) : state,
+ saveFailed: (state, { error }) => (state ? setSourceSaving(state, false, error) : state),
+ retrySave: (state) => (state ? setSourceSaving(state, false, null) : state),
+ conflictDetected: (state, { versionId }) => (state ? setSourceConflict(state, versionId) : state),
+ resolveConflict: (state, { keepLocal }) => (state ? resolveSourceConflict(state, keepLocal) : state),
+ },
+ ],
+ sourceLoading: [
+ false,
+ {
+ loadSource: () => true,
+ sourceLoaded: () => false,
+ sourceLoadFailed: () => false,
+ sourceUnchanged: () => false,
+ },
+ ],
+ sourceError: [
+ null as string | null,
+ {
+ loadSource: () => null,
+ sourceLoadFailed: (_, { error }) => error,
+ },
+ ],
+ selection: [
+ null as CanvasEditSelection | null,
+ {
+ select: (_, { selection }) => selection,
+ setEditing: () => null,
+ },
+ ],
+ // The Blocks tab shows the library while this is on, and the inspector for a selection otherwise.
+ libraryOpen: [
+ false,
+ {
+ setLibraryOpen: (_, { open }) => open,
+ select: (state, { byPointer }) => (byPointer ? false : state),
+ },
+ ],
+ }),
+ selectors({
+ // A browsed version shows instead of the editor, like PostHog Desktop.
+ sourceEditing: [
+ (s) => [s.editing, s.browseVersionId],
+ (editing: boolean, browseVersionId: string | null): boolean => editing && !browseVersionId,
+ ],
+ canUndoEdit: [(s) => [s.entry], (entry: CanvasSourceEntry | null): boolean => (entry?.past.length ?? 0) > 0],
+ canRedoEdit: [(s) => [s.entry], (entry: CanvasSourceEntry | null): boolean => (entry?.future.length ?? 0) > 0],
+ saveStatus: [
+ (s) => [s.entry],
+ (entry: CanvasSourceEntry | null): CanvasSaveStatus | null =>
+ entry
+ ? {
+ saving: entry.saving,
+ dirty: isSourceDirty(entry),
+ error: entry.saveError ?? (entry.conflict ? 'This canvas changed somewhere else' : null),
+ }
+ : null,
+ ],
+ /** Why the Edit toggle is off, or null when the canvas can be edited. */
+ editUnavailableReason: [
+ (s) => [s.view, s.sandboxDocumentUrl, s.isGenerating],
+ (
+ view: CanvasViewResponseApi | null,
+ sandboxDocumentUrl: string | null,
+ isGenerating: boolean
+ ): string | null => {
+ if (!view?.current_version_id) {
+ return 'This canvas has no source to edit yet.'
+ }
+ if (!sandboxDocumentUrl) {
+ return "Editing needs a separate canvas origin, and this PostHog instance doesn't have one set up."
+ }
+ if (isGenerating) {
+ return 'The agent is changing the canvas. Wait for it to finish.'
+ }
+ return null
+ },
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => {
+ const track = (
+ actionType: CanvasDashboardActionType,
+ properties: Omit<Parameters<typeof captureCanvasAction>[1], 'dashboard_id'> = {}
+ ): void => {
+ captureCanvasAction(actionType, {
+ dashboard_id: props.id,
+ channel_id: values.canvas?.channel,
+ ...properties,
+ })
+ }
+ const blocked = (entry: CanvasSourceEntry): boolean => entry.saveError !== null || entry.conflict !== null
+ const idle = (entry: CanvasSourceEntry | null): boolean => !!entry && !isSourceDirty(entry) && !entry.saving
+ const scheduleSave = (): void => {
+ const entry = values.entry
+ if (!entry || !isSourceDirty(entry) || entry.saving || blocked(entry)) {
+ cache.disposables.dispose('autosave')
+ return
+ }
+ cache.disposables.add(
+ () => {
+ const timer = setTimeout(() => actions.save(), SAVE_DEBOUNCE_MS)
+ return () => clearTimeout(timer)
+ },
+ 'autosave',
+ { pauseOnPageHidden: false }
+ )
+ }
+ const note = (verb: string, selection: CanvasEditSelection): string =>
+ `${verb} ${libraryLabel(selection.blockType, selection.tag).toLowerCase()}`
+ const apply = (
+ files: SourceFiles,
+ label: string,
+ focusBlockId: string | null = null,
+ focusSource: string | null = null
+ ): void => actions.applyEdit(syncBlockLibrary(files), label, focusBlockId, focusSource)
+ const fresh = (rev: number): boolean => isFreshRev(values.entry, rev)
+
+ return {
+ finishEditing: () => {
+ if (!values.entry || idle(values.entry)) {
+ actions.setEditing(false)
+ } else {
+ actions.openTab('blocks', props.id)
+ actions.save()
+ }
+ },
+ setEditing: ({ editing }) => {
+ track('edit_toggle', { editing })
+ actions.setBlocksCanvasId(editing ? props.id : null)
+ if (editing) {
+ actions.setBrowseVersion(null)
+ actions.openTab(values.canvas?.generation_task_id ? 'chat' : 'blocks', props.id)
+ actions.loadSource()
+ cache.disposables.add(() => {
+ const timer = setInterval(() => {
+ if (idle(values.entry) && !values.sourceLoading) {
+ actions.loadSource()
+ }
+ }, SOURCE_POLL_MS)
+ return () => clearInterval(timer)
+ }, 'sourcePoll')
+ return
+ }
+ cache.disposables.dispose('sourcePoll')
+ // Done saves what is still pending instead of waiting for the debounce.
+ const entry = values.entry
+ if (entry && isSourceDirty(entry) && !entry.saving && !blocked(entry)) {
+ cache.disposables.dispose('autosave')
+ actions.save()
+ }
+ },
+ loadSource: async () => {
+ if (!values.currentProjectId) {
+ actions.sourceLoadFailed('Pick a project to edit this canvas.')
+ return
+ }
+ try {
+ const source = await canvasesSourceRetrieve(String(values.currentProjectId), props.id)
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ if (!source.project.files[CANVAS_ENTRY_PATH]?.trim()) {
+ actions.sourceLoadFailed('This canvas has no source to edit yet.')
+ return
+ }
+ const entry = values.entry
+ // Local edits are never replaced from here: a stale save conflicts instead.
+ if (!entry || (idle(entry) && entry.baseVersionId !== source.current_version_id)) {
+ actions.sourceLoaded(source)
+ } else {
+ actions.sourceUnchanged()
+ }
+ } catch (error) {
+ if (!cache.disposables.isDisposed) {
+ actions.sourceLoadFailed(error instanceof Error ? error.message : 'Try again in a moment.')
+ }
+ }
+ },
+ loadViewSuccess: ({ view }) => {
+ const entry = values.entry
+ if (values.editing && view && idle(entry) && entry?.baseVersionId !== view.current_version_id) {
+ actions.loadSource()
+ }
+ },
+ select: ({ selection }) => {
+ if (selection) {
+ actions.switchTab('blocks')
+ }
+ },
+ insertBlock: ({ blockType, target, method }) => {
+ const entry = values.entry
+ 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
+ }
+ apply(files, `Added ${definition.label.toLowerCase()}`, definition.component ? blockId : null)
+ if (definition.needsSetup) {
+ actions.setLibraryOpen(false)
+ }
+ actions.switchTab('blocks')
+ track('block_insert', { block_type: blockType, method })
+ },
+ addAfterSelection: ({ blockType }) => {
+ const entry = values.entry
+ if (!entry) {
+ return
+ }
+ const selection = values.selection
+ 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) {
+ actions.insertBlock(blockType, { ...control, place: 'after' }, 'click')
+ return
+ }
+ const controlSelected =
+ !!selection?.blockType && blockDefinition(selection.blockType)?.group === 'Controls'
+ const besideAllowed = group === 'Controls' || !controlSelected
+ if (selection?.source && !isRootSelection(entry, selection) && besideAllowed && fresh(selection.rev)) {
+ actions.insertBlock(blockType, besideSelection(selection, blockType), 'click')
+ return
+ }
+ const firstData = group === 'Data' && root ? blockRanges(entry.files, root.file, 'Data')[0] : undefined
+ if (firstData) {
+ actions.insertBlock(blockType, { ...firstData, place: 'before' }, 'click')
+ return
+ }
+ if (!root || entry.mountedRev !== entry.rev) {
+ return
+ }
+ const inRoot: SourceDropTarget = { ...root, place: 'inside' }
+ if (placeableTarget(entry, inRoot)) {
+ actions.insertBlock(blockType, inRoot, 'click')
+ }
+ },
+ dropBlock: ({ source, hit }) => {
+ const entry = values.entry
+ if (!entry || !fresh(hit.rev) || !placeableTarget(entry, hit.target)) {
+ return
+ }
+ if (source.kind === 'new') {
+ actions.insertBlock(source.blockType, hit.target, 'drag')
+ return
+ }
+ const range = source.selection.source
+ if (!range || !fresh(source.selection.rev) || !isJsxRange(entry.files, range)) {
+ return
+ }
+ const files = moveRange(entry.files, range, hit.target)
+ if (files === entry.files) {
+ return
+ }
+ apply(files, note('Moved', source.selection), source.selection.blockId)
+ track('block_move', { block_type: analyticsBlockType(source.selection.blockType) })
+ },
+ removeSelection: ({ selection }) => {
+ const entry = values.entry
+ if (!entry || !selection.source || !fresh(selection.rev) || isRootSelection(entry, selection)) {
+ return
+ }
+ apply(removeRange(entry.files, selection.source), note('Removed', selection))
+ actions.select(null)
+ track('block_remove', { block_type: analyticsBlockType(selection.blockType) })
+ },
+ duplicateSelection: ({ selection }) => {
+ const entry = values.entry
+ if (!entry || !selection.source || !fresh(selection.rev)) {
+ return
+ }
+ const blockId = newBlockId()
+ apply(
+ duplicateRange(entry.files, selection.source, blockId),
+ note('Duplicated', selection),
+ selection.blockId ? blockId : null
+ )
+ track('block_duplicate', { block_type: analyticsBlockType(selection.blockType) })
+ },
+ updateProps: ({ selection, props: blockProps }) => {
+ const entry = values.entry
+ if (!entry || !selection.source || !selection.blockType || !fresh(selection.rev)) {
+ return
+ }
+ const files = updateBlockProps(entry.files, selection.source, selection.props, blockProps)
+ if (files === entry.files) {
+ return
+ }
+ apply(
+ files,
+ note('Changed', selection),
+ selection.blockId,
+ selection.blockId ? null : `${selection.source.file}|${selection.source.start}`
+ )
+ actions.select({ ...selection, props: blockProps })
+ track('block_edit', { block_type: analyticsBlockType(selection.blockType) })
+ },
+ setText: ({ selection, text }) => {
+ const entry = values.entry
+ if (!entry || !selection.source || !fresh(selection.rev)) {
+ return
+ }
+ const files = replaceElementText(entry.files, selection.source, text)
+ if (files === entry.files) {
+ return
+ }
+ apply(files, 'Edited text', selection.blockId, `${selection.source.file}|${selection.source.start}`)
+ track('text_edit', { block_type: analyticsBlockType(selection.blockType) })
+ },
+ editKey: ({ key }) => {
+ const mod = key.metaKey || key.ctrlKey
+ const selection = values.selection
+ if (mod && key.key.toLowerCase() === 'z') {
+ if (key.shiftKey) {
+ actions.redoEdit()
+ } else {
+ actions.undoEdit()
+ }
+ return
+ }
+ if (!selection) {
+ return
+ }
+ if (key.key === 'Backspace' || key.key === 'Delete') {
+ actions.removeSelection(selection)
+ return
+ }
+ if (mod && key.key.toLowerCase() === 'd') {
+ actions.duplicateSelection(selection)
+ }
+ },
+ undoEdit: () => {
+ track('edit_undo')
+ scheduleSave()
+ },
+ redoEdit: () => {
+ track('edit_redo')
+ scheduleSave()
+ },
+ applyEdit: scheduleSave,
+ retrySave: scheduleSave,
+ saveSucceeded: () => {
+ scheduleSave()
+ if (values.finishAfterSave && idle(values.entry)) {
+ actions.setEditing(false)
+ }
+ },
+ resolveConflict: ({ keepLocal }) => {
+ track('edit_conflict_resolve', { keep_local: keepLocal })
+ if (keepLocal) {
+ scheduleSave()
+ } else {
+ actions.loadSource()
+ }
+ },
+ save: async () => {
+ let entry = values.entry
+ const projectId = values.currentProjectId
+ if (!entry || !projectId || !isSourceDirty(entry) || entry.saving || blocked(entry)) {
+ return
+ }
+ actions.saveStarted()
+ while (entry) {
+ const files = entry.files
+ const project = {
+ ...entry.project,
+ files,
+ capabilities: canvasCapabilities(entry.project.capabilities, files) as
+ | CanvasCapabilitiesApi
+ | undefined,
+ }
+ try {
+ const result = await canvasesPublishCreate(String(projectId), props.id, {
+ project,
+ prompt: describeChanges(entry.changes),
+ expected_current_version_id: entry.baseVersionId,
+ })
+ if (cache.disposables.isDisposed) {
+ entry = markSourceSaved(
+ cache.detachedEntry ?? entry,
+ files,
+ result.current_version_id,
+ entry.changes.length
+ )
+ cache.detachedEntry = entry
+ if (isSourceDirty(entry)) {
+ continue
+ }
+ return
+ }
+ actions.saveSucceeded(files, result.current_version_id, entry.changes.length)
+ track('edit_save', { success: true })
+ // The publish queued a build, so the header's build status and the timeline refresh.
+ actions.loadView()
+ actions.loadBuilds()
+ actions.startPolling()
+ return
+ } catch (error) {
+ if (cache.disposables.isDisposed) {
+ return
+ }
+ const status = (error as { status?: number } | null)?.status
+ if (status === 409) {
+ const data = (error as { data?: { current_version_id?: string | null } }).data
+ actions.conflictDetected(data?.current_version_id ?? null)
+ track('edit_conflict')
+ return
+ }
+ actions.saveFailed(saveErrorMessage(error))
+ track('edit_save', { success: false })
+ return
+ }
+ }
+ },
+ askAgent: ({ message }) => {
+ actions.setDraft(message)
+ actions.openTab('chat', props.id)
+ },
+ }
+ }),
+ beforeUnload(({ values }) => ({
+ enabled: () => !!values.entry && (isSourceDirty(values.entry) || values.entry.saving),
+ message: 'Your canvas has unsaved changes. Wait for the save to finish before you leave.',
+ })),
+ beforeUnmount(({ values, actions, cache }) => {
+ cache.detachedEntry = values.entry
+ if (
+ values.entry &&
+ isSourceDirty(values.entry) &&
+ !values.entry.saving &&
+ !values.entry.saveError &&
+ !values.entry.conflict
+ ) {
+ actions.save()
+ }
+ if (values.editing) {
+ actions.setBlocksCanvasId(null)
+ }
+ }),
+ afterMount(({ actions, values, props }) => {
+ // Start blank on the start page lands here to add the first blocks.
+ if (values.editHandoff === props.id) {
+ actions.clearEditHandoff()
+ actions.setEditing(true)
+ actions.openTab('blocks', props.id)
+ }
+ }),
+])
diff --git a/products/canvas/frontend/editing/canvasEditorFrame.ts b/products/canvas/frontend/editing/canvasEditorFrame.ts
new file mode 100644
index 000000000000..8799b70fecc4
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasEditorFrame.ts
@@ -0,0 +1,22 @@
+import { CANVAS_CHANNEL } from '../host/canvasProtocol'
+
+/** The frame of the canvas being edited. One canvas is edited at a time, so a document query finds it. */
+export function canvasEditorFrame(): HTMLIFrameElement | null {
+ return document.querySelector<HTMLIFrameElement>('iframe[data-canvas-source-editor]')
+}
+
+const bridges = new WeakMap<HTMLIFrameElement, (message: unknown) => void>()
+
+export function connectCanvasEditor(frame: HTMLIFrameElement, post: (message: unknown) => void): () => void {
+ bridges.set(frame, post)
+ return () => {
+ bridges.delete(frame)
+ }
+}
+
+export function postToCanvasEditor(message: Record<string, unknown>): void {
+ const frame = canvasEditorFrame()
+ if (frame) {
+ bridges.get(frame)?.({ channel: CANVAS_CHANNEL, ...message })
+ }
+}
diff --git a/products/canvas/frontend/editing/canvasSourceDragLogic.ts b/products/canvas/frontend/editing/canvasSourceDragLogic.ts
new file mode 100644
index 000000000000..e115c8fed9d3
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasSourceDragLogic.ts
@@ -0,0 +1,71 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+
+export type GhostPhase = 'drag' | 'drop' | 'return'
+
+/** The card that follows the pointer while a block is dragged. */
+export interface SourceDragGhost {
+ label: string
+ blockType: string | null
+ x: number
+ y: number
+ tilt: number
+ hint: string | null
+ phase: GhostPhase
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasSourceDragLogicValues {
+ ghost: SourceDragGhost | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasSourceDragLogicActions {
+ leaveGhost: (
+ ghost: SourceDragGhost,
+ duration: number
+ ) => {
+ duration: number
+ ghost: SourceDragGhost
+ }
+ setGhost: (ghost: SourceDragGhost | null) => {
+ ghost: SourceDragGhost | null
+ }
+}
+
+export type canvasSourceDragLogicType = MakeLogicType<canvasSourceDragLogicValues, canvasSourceDragLogicActions>
+
+/** The drag ghost of the block editor. A drag spans the host and the frame, so its state lives outside both. */
+export const canvasSourceDragLogic = kea<canvasSourceDragLogicType>([
+ path(['products', 'canvas', 'frontend', 'editing', 'canvasSourceDragLogic']),
+ actions({
+ setGhost: (ghost: SourceDragGhost | null) => ({ ghost }),
+ /** Plays the drop or return exit, then clears the ghost unless a new drag took over. */
+ leaveGhost: (ghost: SourceDragGhost, duration: number) => ({ ghost, duration }),
+ }),
+ reducers({
+ ghost: [
+ null as SourceDragGhost | null,
+ {
+ setGhost: (_, { ghost }) => ghost,
+ leaveGhost: (_, { ghost }) => ghost,
+ },
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ setGhost: ({ ghost }) => {
+ if (ghost?.phase === 'drag') {
+ cache.disposables.dispose('exit')
+ }
+ },
+ leaveGhost: ({ duration }) => {
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => {
+ if (values.ghost?.phase !== 'drag') {
+ actions.setGhost(null)
+ }
+ }, duration)
+ return () => clearTimeout(timer)
+ }, 'exit')
+ },
+ })),
+])
diff --git a/products/canvas/frontend/editing/canvasSourceSnapshots.test.ts b/products/canvas/frontend/editing/canvasSourceSnapshots.test.ts
new file mode 100644
index 000000000000..da498b8ed0c9
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasSourceSnapshots.test.ts
@@ -0,0 +1,50 @@
+import type { CanvasSourceProjectApi } from '../generated/api.schemas'
+import {
+ CanvasSourceEntry,
+ applySourceFiles,
+ isSourceDirty,
+ loadSourceEntry,
+ redoSourceEntry,
+ resolveSourceConflict,
+ setSourceConflict,
+ setSourceSaving,
+ undoSourceEntry,
+} from './canvasSourceSnapshots'
+
+const PROJECT: CanvasSourceProjectApi = {
+ schemaVersion: 1,
+ entryHtml: 'index.html',
+ files: { 'src/canvas.tsx': 'saved' },
+ dependencies: {},
+}
+
+function conflicted(): CanvasSourceEntry {
+ const loaded = loadSourceEntry(null, PROJECT, 'v1')
+ return setSourceConflict(setSourceSaving(applySourceFiles(loaded, { 'src/canvas.tsx': 'local edit' }), true), 'v2')
+}
+
+describe('canvasSourceSnapshots', () => {
+ 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 }) => {
+ const entry = resolveSourceConflict(conflicted(), keepLocal)
+ expect(entry.conflict).toBeNull()
+ expect(conflicted().saving).toBe(false)
+ expect(entry.baseVersionId).toBe(base)
+ expect(entry.files).toEqual(files)
+ expect(isSourceDirty(entry)).toBe(dirty)
+ })
+
+ it('drops undo history when a newer version loads', () => {
+ expect(loadSourceEntry(conflicted(), PROJECT, 'v2').past).toEqual([])
+ })
+
+ it('redoes an undone edit until a new edit replaces it', () => {
+ const edited = applySourceFiles(loadSourceEntry(null, PROJECT, 'v1'), { 'src/canvas.tsx': 'first' })
+ const undone = undoSourceEntry(edited)
+ expect(undone.files).toEqual({ 'src/canvas.tsx': 'saved' })
+ expect(redoSourceEntry(undone).files).toEqual({ 'src/canvas.tsx': 'first' })
+ expect(applySourceFiles(undone, { 'src/canvas.tsx': 'second' }).future).toEqual([])
+ })
+})
diff --git a/products/canvas/frontend/editing/canvasSourceSnapshots.ts b/products/canvas/frontend/editing/canvasSourceSnapshots.ts
new file mode 100644
index 000000000000..af9b4f796694
--- /dev/null
+++ b/products/canvas/frontend/editing/canvasSourceSnapshots.ts
@@ -0,0 +1,218 @@
+import type { CanvasCapabilitiesApi, CanvasSourceProjectApi } from '../generated/api.schemas'
+import { canvasCapabilities } from './blockLibrary/blockProject'
+import type { ParamSchema } from './blockLibrary/params'
+import type { GridGrowth, SourceFiles, SourceRange } from './blockLibrary/sourceEdits'
+
+// The local edit state of one canvas. Each
+// function returns a new entry, so the kea reducer that holds it stays a thin dispatch.
+
+const HISTORY_LIMIT = 80
+const MAX_NOTED_CHANGES = 20
+
+/** What the edit runtime in the frame reports about the element the author selected. */
+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: CanvasSourceProjectApi
+ files: SourceFiles
+ savedFiles: SourceFiles
+ baseVersionId: string | null
+ saving: boolean
+ saveError: string | null
+ conflict: { versionId: string | null } | null
+ past: SourceFiles[]
+ future: SourceFiles[]
+ /** Bumped on every change to the files, so the frame knows to remount. */
+ rev: number
+ focusBlockId: string | null
+ focusSource: string | null
+ rootSource: SourceRange | null
+ /** The rev the frame last mounted. Source ranges from an older mount point at stale offsets. */
+ mountedRev: number
+ changes: string[]
+}
+
+export function loadSourceEntry(
+ previous: CanvasSourceEntry | null,
+ project: CanvasSourceProjectApi,
+ versionId: string | null
+): CanvasSourceEntry {
+ return {
+ 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: [],
+ }
+}
+
+export function applySourceFiles(
+ entry: CanvasSourceEntry,
+ files: SourceFiles,
+ focusBlockId: string | null = null,
+ focusSource: string | null = null
+): CanvasSourceEntry {
+ return {
+ ...entry,
+ project: {
+ ...entry.project,
+ capabilities: canvasCapabilities(entry.project.capabilities, files) as CanvasCapabilitiesApi | undefined,
+ },
+ files,
+ past: [...entry.past, entry.files].slice(-HISTORY_LIMIT),
+ future: [],
+ rev: entry.rev + 1,
+ focusBlockId,
+ focusSource,
+ }
+}
+
+export function undoSourceEntry(entry: CanvasSourceEntry): CanvasSourceEntry {
+ const previous = entry.past[entry.past.length - 1]
+ if (!previous) {
+ return entry
+ }
+ return {
+ ...entry,
+ 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,
+ }
+}
+
+export function redoSourceEntry(entry: CanvasSourceEntry): CanvasSourceEntry {
+ const [next, ...rest] = entry.future
+ if (!next) {
+ return entry
+ }
+ return {
+ ...entry,
+ files: next,
+ past: [...entry.past, entry.files],
+ future: rest,
+ rev: entry.rev + 1,
+ changes: [...entry.changes, 'Redid a change'],
+ focusBlockId: null,
+ focusSource: null,
+ }
+}
+
+export function setSourceSaving(
+ entry: CanvasSourceEntry,
+ saving: boolean,
+ error: string | null = null
+): CanvasSourceEntry {
+ return { ...entry, saving, saveError: error }
+}
+
+export function markSourceSaved(
+ entry: CanvasSourceEntry,
+ files: SourceFiles,
+ versionId: string,
+ noted: number
+): CanvasSourceEntry {
+ return {
+ ...entry,
+ savedFiles: files,
+ baseVersionId: versionId,
+ saving: false,
+ saveError: null,
+ changes: entry.changes.slice(noted),
+ }
+}
+
+export function noteSourceChange(entry: CanvasSourceEntry, label: string): CanvasSourceEntry {
+ return {
+ ...entry,
+ changes:
+ entry.changes[entry.changes.length - 1] === label
+ ? entry.changes
+ : [...entry.changes, label].slice(-MAX_NOTED_CHANGES),
+ }
+}
+
+export function setSourceConflict(entry: CanvasSourceEntry, versionId: string | null): CanvasSourceEntry {
+ return { ...entry, saving: false, saveError: null, conflict: { versionId } }
+}
+
+export function resolveSourceConflict(entry: CanvasSourceEntry, keepLocal: boolean): CanvasSourceEntry {
+ return keepLocal
+ ? { ...entry, baseVersionId: entry.conflict?.versionId ?? entry.baseVersionId, conflict: null }
+ : {
+ ...entry,
+ files: entry.savedFiles,
+ past: [],
+ future: [],
+ rev: entry.rev + 1,
+ changes: [],
+ conflict: null,
+ }
+}
+
+export function setSourceMounted(
+ entry: CanvasSourceEntry,
+ rev: number,
+ rootSource: SourceRange | null
+): CanvasSourceEntry {
+ return { ...entry, mountedRev: rev, rootSource }
+}
+
+export function isRootSelection(
+ entry: CanvasSourceEntry | null,
+ 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 | null | undefined): boolean {
+ return !!entry && entry.files !== entry.savedFiles
+}
+
+/** Whether a selection or drop target still points at the files on screen. */
+export function isFreshRev(entry: CanvasSourceEntry | null, rev: number): boolean {
+ return !!entry && entry.mountedRev === entry.rev && rev === entry.rev
+}
+
+/** The version-history message for a save, built from the labels of the edits it carries. */
+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/canvas/frontend/editing/libraryCatalog.ts b/products/canvas/frontend/editing/libraryCatalog.ts
new file mode 100644
index 000000000000..61a5a1194a9a
--- /dev/null
+++ b/products/canvas/frontend/editing/libraryCatalog.ts
@@ -0,0 +1,89 @@
+import {
+ IconCalendar,
+ IconClock,
+ IconCode,
+ IconPuzzle,
+ IconFilter,
+ IconFunnels,
+ IconGraph,
+ IconInfo,
+ IconLetter,
+ IconLineGraph,
+ IconList,
+ IconLive,
+ IconMinus,
+ IconRefresh,
+ IconRetention,
+ IconTarget,
+ IconTextWidth,
+ IconTrending,
+ IconTrends,
+} from '@posthog/icons'
+
+import { BLOCK_DEFINITIONS, BlockDefinition, BlockGroup, blockDefinition } from './blockLibrary/blockDefinitions'
+import { componentLabel } from './blockLibrary/params'
+
+export type LibraryIcon = typeof IconPuzzle
+
+const ICONS: Record<string, LibraryIcon> = {
+ Metric: IconTrending,
+ Trend: IconLineGraph,
+ TopList: IconList,
+ Funnel: IconFunnels,
+ SqlTable: IconCode,
+ DateRange: IconCalendar,
+ Interval: IconClock,
+ PropertyFilter: IconFilter,
+ Filters: IconFilter,
+ Goal: IconTarget,
+ RecentEvents: IconLive,
+ Callout: IconInfo,
+ Insight: IconGraph,
+ Retention: IconRetention,
+ Compare: IconTrends,
+ Refresh: IconRefresh,
+ Heading: IconLetter,
+ Paragraph: IconTextWidth,
+ Divider: IconMinus,
+}
+
+export const LIBRARY_GROUPS: BlockGroup[] = ['Data', 'Controls', 'Content']
+
+export interface LibraryEntry extends BlockDefinition {
+ icon: LibraryIcon
+}
+
+export const LIBRARY: LibraryEntry[] = BLOCK_DEFINITIONS.map((definition) => ({
+ ...definition,
+ icon: ICONS[definition.type] ?? IconPuzzle,
+}))
+
+const ELEMENT_LABELS: Record<string, string> = {
+ h1: 'Heading',
+ h2: 'Heading',
+ h3: 'Heading',
+ p: 'Text',
+ hr: 'Divider',
+ header: 'Header',
+ main: 'Page',
+ section: 'Section',
+}
+
+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): LibraryIcon {
+ return (blockType && ICONS[blockType]) || IconPuzzle
+}
+
+/** The block type for analytics: a library block's type, never the name of a component the agent wrote. */
+export function analyticsBlockType(blockType: string | null): string {
+ if (!blockType) {
+ return 'element'
+ }
+ return blockDefinition(blockType) ? blockType : 'custom'
+}
diff --git a/products/canvas/frontend/editing/sourceDrag.ts b/products/canvas/frontend/editing/sourceDrag.ts
new file mode 100644
index 000000000000..db5178590637
--- /dev/null
+++ b/products/canvas/frontend/editing/sourceDrag.ts
@@ -0,0 +1,181 @@
+import { blockDefinition } from './blockLibrary/blockDefinitions'
+import type { SourceDropTarget } from './blockLibrary/sourceEdits'
+import { canvasEditorFrame, postToCanvasEditor } from './canvasEditorFrame'
+import { SourceDragGhost, canvasSourceDragLogic } from './canvasSourceDragLogic'
+import type { CanvasEditSelection } from './canvasSourceSnapshots'
+import { libraryLabel } from './libraryCatalog'
+
+// A drag starts in the host (a library item) or in the frame (a block on the canvas), and
+// the pointer crosses between them, so the host drives it. It forwards the pointer into the
+// frame, which answers with the drop target under it. Ported from PostHog Desktop's sourceDrag.
+
+export type SourceDragSource = { kind: 'new'; blockType: string } | { kind: 'move'; selection: CanvasEditSelection }
+
+export interface SourceDropHit {
+ rev: number
+ target: SourceDropTarget
+}
+
+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
+
+function prefersReducedMotion(): boolean {
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches
+}
+
+function setGhost(ghost: SourceDragGhost | null): void {
+ canvasSourceDragLogic.findMounted()?.actions.setGhost(ghost)
+}
+
+function leaveGhost(ghost: SourceDragGhost, duration: number): void {
+ canvasSourceDragLogic.findMounted()?.actions.leaveGhost(ghost, 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 {
+ active?.end(false)
+ 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: SourceDragGhost | 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): void => {
+ const velocity = x - lastX
+ lastX = x
+ const wanted = Math.max(-MAX_TILT, Math.min(MAX_TILT, velocity * TILT_GAIN))
+ tilt += (wanted - tilt) * TILT_EASE
+ const ghost: SourceDragGhost = {
+ label,
+ blockType,
+ x,
+ y,
+ tilt: reduceMotion ? 0 : tilt,
+ hint: hintFor(latestHit),
+ phase: 'drag',
+ }
+ lastGhost = ghost
+ setGhost(ghost)
+ }
+
+ const forward = (x: number, y: number): void => {
+ const rect = canvasEditorFrame()?.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('pointercancel', onCancel, true)
+ window.removeEventListener('blur', onCancel)
+ 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
+ }
+ if (commit && 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): void => controller.move(event.clientX, event.clientY)
+ const onUp = (): void => controller.end(true)
+ const onCancel = (): void => controller.end(false)
+ const onKey = (event: KeyboardEvent): void => {
+ if (event.key !== 'Escape') {
+ return
+ }
+ event.preventDefault()
+ event.stopPropagation()
+ controller.end(false)
+ }
+
+ window.addEventListener('pointermove', onMove, true)
+ window.addEventListener('pointerup', onUp, true)
+ window.addEventListener('pointercancel', onCancel, true)
+ window.addEventListener('blur', onCancel)
+ window.addEventListener('keydown', onKey, true)
+ active = controller
+ if (started) {
+ render(options.startX, options.startY)
+ }
+}
diff --git a/products/canvas/frontend/history/CanvasVersionControls.tsx b/products/canvas/frontend/history/CanvasVersionControls.tsx
index e29dce4762f5..405b2deb8598 100644
--- a/products/canvas/frontend/history/CanvasVersionControls.tsx
+++ b/products/canvas/frontend/history/CanvasVersionControls.tsx
@@ -16,6 +16,7 @@ import {
TooltipTrigger,
} from '@posthog/quill'
+import { canvasEditLogic } from '../editing/canvasEditLogic'
import {
canvasBuildStatusBadgeVariant,
canvasBuildStatusLabel,
@@ -60,7 +61,7 @@ function StepButton({
)
}
-/** Undo and redo through versions, and the version and draft pickers, in the canvas header. */
+/** Undo and redo through versions, and the version and draft pickers, in the canvas header. Undo and redo through local edits while editing. */
export function CanvasVersionControls(): JSX.Element | null {
const {
versions,
@@ -74,7 +75,37 @@ export function CanvasVersionControls(): JSX.Element | null {
isGenerating,
} = useValues(canvasHistoryLogic)
const { undo, redo, setBrowseVersion } = useActions(canvasHistoryLogic)
+ const { sourceEditing, canUndoEdit, canRedoEdit } = useValues(canvasEditLogic)
+ const { undoEdit, redoEdit } = useActions(canvasEditLogic)
+ // While editing, undo and redo step through local edits instead of published versions, like PostHog Desktop.
+ if (sourceEditing) {
+ return (
+ <div
+ role="group"
+ aria-label="Edits"
+ className="flex items-center gap-0.5"
+ data-attr="canvas-version-controls"
+ >
+ <StepButton
+ label="Undo"
+ disabledReason={canUndoEdit ? null : 'There is nothing to undo.'}
+ onClick={undoEdit}
+ dataAttr="canvas-edit-undo"
+ >
+ <IconUndo />
+ </StepButton>
+ <StepButton
+ label="Redo"
+ disabledReason={canRedoEdit ? null : 'There is nothing to redo.'}
+ onClick={redoEdit}
+ dataAttr="canvas-edit-redo"
+ >
+ <IconRedo />
+ </StepButton>
+ </div>
+ )
+ }
if (versions.length === 0 && drafts.length === 0) {
return null
}
diff --git a/products/canvas/frontend/host/canvasProtocol.test.ts b/products/canvas/frontend/host/canvasProtocol.test.ts
new file mode 100644
index 000000000000..0733cf993fb7
--- /dev/null
+++ b/products/canvas/frontend/host/canvasProtocol.test.ts
@@ -0,0 +1,13 @@
+import { CANVAS_CHANNEL, canvasEditMessageSchema } from './canvasProtocol'
+
+describe('canvas edit messages', () => {
+ test.each([
+ { type: 'canvas-edit-pointer', x: Infinity, y: 0 },
+ { type: 'canvas-edit-root', rev: 1.5, root: null },
+ { type: 'canvas-edit-root', rev: 1, root: { file: 'src/canvas.tsx', start: 20, end: 10 } },
+ { type: 'canvas-edit-key', key: 'Delete', metaKey: 'false', ctrlKey: false, shiftKey: false },
+ { type: 'canvas-edit-text', element: null, text: 'forged' },
+ ])('rejects malformed $type messages', (message) => {
+ expect(canvasEditMessageSchema.safeParse({ channel: CANVAS_CHANNEL, ...message }).success).toBe(false)
+ })
+})
diff --git a/products/canvas/frontend/host/canvasProtocol.ts b/products/canvas/frontend/host/canvasProtocol.ts
index 4e6e18a24e9e..abcd99d2e308 100644
--- a/products/canvas/frontend/host/canvasProtocol.ts
+++ b/products/canvas/frontend/host/canvasProtocol.ts
@@ -179,3 +179,74 @@ export type HostToCanvasMessage =
result?: unknown
error?: string
}
+
+const sourceRangeFields = {
+ file: z.string().min(1).max(1024),
+ start: z.number().int().min(0).max(10_000_000),
+ end: z.number().int().min(0).max(10_000_000),
+}
+const sourceRangeSchema = z.object(sourceRangeFields).refine(({ start, end }) => end > start)
+const gridGrowthSchema = z
+ .object({ ...sourceRangeFields, columns: z.number().int().min(1).max(4) })
+ .refine(({ start, end }) => end > start)
+const editElementSchema = z.object({
+ rev: z.number().int().nonnegative(),
+ source: sourceRangeSchema.nullable(),
+ blockType: z.string().max(128).nullable(),
+ blockId: z.string().max(128).nullable(),
+ props: z.record(z.string().max(128), z.unknown()),
+ tag: z.string().max(128),
+ text: z.string().max(100_000).nullable(),
+ params: z.string().max(100_000).nullable(),
+ layout: z.object({ inGrid: z.boolean(), grow: gridGrowthSchema.nullable(), grid: sourceRangeSchema.nullable() }),
+})
+const coordinates = { x: z.number().finite(), y: z.number().finite() }
+export const canvasEditMessageSchema = z.discriminatedUnion('type', [
+ z.object({
+ channel,
+ type: z.literal('canvas-edit-select'),
+ element: editElementSchema.nullable(),
+ byPointer: z.boolean().optional(),
+ }),
+ z.object({
+ channel,
+ type: z.literal('canvas-edit-root'),
+ rev: z.number().int().nonnegative(),
+ root: sourceRangeSchema.nullable(),
+ }),
+ z.object({
+ channel,
+ type: z.literal('canvas-edit-drop-target'),
+ hit: z
+ .object({
+ rev: z.number().int().nonnegative(),
+ target: z
+ .object({
+ ...sourceRangeFields,
+ place: z.enum(['before', 'after', 'left', 'right', 'inside']),
+ grow: gridGrowthSchema.optional(),
+ })
+ .refine(({ start, end }) => end > start),
+ })
+ .nullable(),
+ }),
+ z.object({ channel, type: z.literal('canvas-edit-drag-start'), element: editElementSchema, ...coordinates }),
+ z.object({ channel, type: z.literal('canvas-edit-pointer'), ...coordinates }),
+ z.object({ channel, type: z.literal('canvas-edit-pointer-up') }),
+ z.object({ channel, type: z.literal('canvas-edit-pointer-cancel') }),
+ z.object({
+ channel,
+ type: z.literal('canvas-edit-key'),
+ key: z.string().min(1).max(32),
+ metaKey: z.boolean(),
+ ctrlKey: z.boolean(),
+ shiftKey: z.boolean(),
+ }),
+ z.object({
+ channel,
+ type: z.literal('canvas-edit-text'),
+ element: editElementSchema,
+ text: z.string().max(100_000),
+ }),
+])
+export type CanvasEditMessage = z.infer<typeof canvasEditMessageSchema>
diff --git a/products/canvas/frontend/newCanvas/CanvasNewScene.tsx b/products/canvas/frontend/newCanvas/CanvasNewScene.tsx
index b33d283b5453..6e3902de29bb 100644
--- a/products/canvas/frontend/newCanvas/CanvasNewScene.tsx
+++ b/products/canvas/frontend/newCanvas/CanvasNewScene.tsx
@@ -1,6 +1,17 @@
import { useActions, useValues } from 'kea'
-import { Text } from '@posthog/quill'
+import { IconApps } from '@posthog/icons'
+import {
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+ Text,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
@@ -17,11 +28,13 @@ export const scene: SceneExport = {
logic: canvasNewLogic,
}
-/** The start page for a new canvas. Nothing is saved until the first prompt is sent. */
+/** The start page for a new canvas. Nothing is saved until the first prompt is sent, or until Start blank. */
export function CanvasNewScene(): JSX.Element {
const enabled = useFeatureFlag('TODAY_RAIL_NAV')
- const { instruction, sending, sendDisabledReason } = useValues(canvasNewLogic)
- const { setInstruction, send } = useActions(canvasNewLogic)
+ const { instruction, sending, sendDisabledReason, startingBlank, startBlankDisabledReason } =
+ useValues(canvasNewLogic)
+ const { setInstruction, send, startBlank } = useActions(canvasNewLogic)
+ const blankDisabledReason = startBlankDisabledReason ?? (sending ? 'Wait for the canvas to be created.' : null)
if (!enabled) {
return <NotFound object="page" />
@@ -34,15 +47,60 @@ export function CanvasNewScene(): JSX.Element {
</Text>
</CanvasToolbar>
<main className="min-h-0 flex-1">
- <CanvasStartHero description="Describe it and an agent builds it. The canvas is saved when you send.">
+ <CanvasStartHero description="Describe it and an agent builds it, or start blank and add blocks yourself.">
<CanvasComposer
instruction={instruction}
onInstructionChange={setInstruction}
onSubmit={send}
submitting={sending}
- disabledReason={sendDisabledReason}
+ disabledReason={startingBlank ? 'Wait for the canvas to be created.' : sendDisabledReason}
footerStart={<CanvasSpaceSelect />}
/>
+ <section aria-labelledby="canvas-build-yourself-label" className="flex flex-col gap-2">
+ <Text
+ id="canvas-build-yourself-label"
+ size="xs"
+ variant="muted"
+ weight="medium"
+ render={<h2 />}
+ >
+ Build it yourself
+ </Text>
+ <Tooltip>
+ {/* A disabled button gets no pointer events, so a span anchors the tooltip. */}
+ <TooltipTrigger delay={0} render={<span className="flex" />}>
+ <Item
+ variant="outline"
+ size="sm"
+ className="w-full flex-nowrap bg-card text-left hover:bg-fill-hover"
+ render={
+ <button
+ type="button"
+ disabled={!!blankDisabledReason || startingBlank}
+ aria-busy={startingBlank}
+ onClick={() => startBlank()}
+ data-attr="canvas-new-start-blank"
+ />
+ }
+ >
+ <ItemMedia aria-hidden>
+ <IconApps />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle className="truncate">
+ {startingBlank ? 'Creating the canvas…' : 'Blank'}
+ </ItemTitle>
+ <ItemDescription className="truncate">
+ A title and a date range. Add blocks by hand.
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ </TooltipTrigger>
+ <TooltipContent>
+ {blankDisabledReason ?? 'Create an empty canvas and add blocks by hand'}
+ </TooltipContent>
+ </Tooltip>
+ </section>
</CanvasStartHero>
</main>
</div>
diff --git a/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts b/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts
index 6066b447aa42..ca36c1a54db8 100644
--- a/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts
+++ b/products/canvas/frontend/newCanvas/canvasNewLogic.test.ts
@@ -7,7 +7,10 @@ import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { CANVAS_ENTRY_PATH } from '../editing/blockLibrary/blockProject'
+import { canvasEditLogic } from '../editing/canvasEditLogic'
import { canvasSceneLogic } from '../scene/canvasSceneLogic'
+import { canvasSidePanelLogic } from '../sidePanel/canvasSidePanelLogic'
import { canvasNewLogic } from './canvasNewLogic'
const CANVAS_ID = 'canvas-new-1'
@@ -19,12 +22,16 @@ describe('canvasNewLogic', () => {
let taskStatus = 201
let linkStatus = 200
let runCount = 0
+ let publishStatus = 201
+ let published: { project: { files: Record<string, string> }; expected_current_version_id: string | null } | null =
+ null
beforeEach(() => {
createdCanvas = null
createCount = 0
linkStatus = 200
runCount = 0
+ published = null
useMocks({
get: {
'/api/projects/:team_id/task_channels/': [
@@ -46,6 +53,20 @@ describe('canvasNewLogic', () => {
'/api/projects/:team_id/tasks/:id/': { id: 'task-1', title: 'Daily signups', latest_run: null },
'/api/projects/:team_id/canvases/:id/builds/': { builds: [], published_build_id: null },
'/api/projects/:team_id/task_channels/:id/': { id: 'space-growth', name: 'growth', system_role: null },
+ '/api/projects/:team_id/canvases/:id/source/': () => [
+ 200,
+ {
+ canvas: createdCanvas,
+ project: {
+ schemaVersion: 1,
+ entryHtml: 'index.html',
+ files: { 'index.html': '<div id="root"></div>', [CANVAS_ENTRY_PATH]: '' },
+ dependencies: { react: '19.0.0' },
+ canvasSdkVersion: '0.2.0',
+ },
+ current_version_id: null,
+ },
+ ],
},
post: {
'/api/projects/:team_id/tasks/:id/run/': async ({ request }) => {
@@ -73,6 +94,12 @@ describe('canvasNewLogic', () => {
? [201, { id: 'task-1', title: 'Daily signups', latest_run: null }]
: [403, { error: 'Agent-started task runs are not available for this project' }]
},
+ '/api/projects/:team_id/canvases/:id/publish/': async ({ request }) => {
+ published = (await request.json()) as typeof published
+ return publishStatus === 201
+ ? [201, { current_version_id: 'version-1' }]
+ : [400, { detail: 'Invalid project' }]
+ },
},
patch: {
'/api/projects/:team_id/canvases/:id/': async ({ request }) => {
@@ -122,4 +149,39 @@ describe('canvasNewLogic', () => {
expect(logic.values.startHandoff).toBeNull()
}
)
+
+ test.each([
+ ['publishes the blank starter and opens it in edit mode on the Blocks tab', 201, true],
+ ['lands on the empty canvas when the starter fails to publish', 400, false],
+ ])('Start blank %s', async (_, status, editing) => {
+ publishStatus = status
+ const logic = canvasNewLogic()
+ logic.mount()
+ router.actions.push(urls.canvasNew('space-growth'))
+ await expectLogic(logic).toDispatchActions(['loadSpacesSuccess'])
+
+ logic.actions.startBlank()
+ logic.actions.startBlank()
+ logic.actions.send()
+ await expectLogic(logic).toDispatchActions(['startBlankFinished'])
+
+ expect(createCount).toEqual(1)
+ expect(createdCanvas).toMatchObject({ id: CANVAS_ID, channel: 'space-growth' })
+ expect(published?.expected_current_version_id).toBeNull()
+ expect(published?.project.files[CANVAS_ENTRY_PATH]).toContain('<DateRange blockId="b-range" />')
+ expect(Object.keys(published?.project.files ?? {})).toEqual(
+ expect.arrayContaining(['src/blocks/runtime.tsx', 'src/blocks/DateRange.tsx', 'src/blocks/library.json'])
+ )
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.canvasDetail(CANVAS_ID))
+ expect(router.values.lastMethod).toEqual('REPLACE')
+
+ canvasSceneLogic({ id: CANVAS_ID }).mount()
+ const editLogic = canvasEditLogic({ id: CANVAS_ID })
+ editLogic.mount()
+ expect(editLogic.values.editing).toBe(editing)
+ expect(logic.values.editHandoff).toBeNull()
+ if (editing) {
+ expect(canvasSidePanelLogic.values).toMatchObject({ selectedTab: 'canvas-blocks', sidePanelOpen: true })
+ }
+ })
})
diff --git a/products/canvas/frontend/newCanvas/canvasNewLogic.ts b/products/canvas/frontend/newCanvas/canvasNewLogic.ts
index 3c56d4c2df3e..9b73f00c36c0 100644
--- a/products/canvas/frontend/newCanvas/canvasNewLogic.ts
+++ b/products/canvas/frontend/newCanvas/canvasNewLogic.ts
@@ -14,10 +14,14 @@ import { Breadcrumb } from '~/types'
import { CANVAS_EVENTS } from '../canvasAnalytics'
import { CanvasSpace, loadCanvasSpaces } from '../canvasTasksApi'
import { FREEFORM_TEMPLATE_ID, UNTITLED_CANVAS_NAME } from '../canvasTemplates'
-import { canvasesCreate } from '../generated/api'
-import type { CanvasApi } from '../generated/api.schemas'
+import { canvasCapabilities, blankCanvasFiles } from '../editing/blockLibrary/blockProject'
+import { canvasesCreate, canvasesPublishCreate, canvasesSourceRetrieve } from '../generated/api'
+import type { CanvasApi, CanvasCapabilitiesApi } from '../generated/api.schemas'
import { startCanvasGeneration } from '../startCanvasGeneration'
+// pinned: `starter_id` of the create event for a canvas started without a prompt, shared with PostHog Desktop's starters
+const BLANK_STARTER_ID = 'blank'
+
/** A prompt whose canvas exists but whose build did not start. The canvas page picks it up. */
export interface CanvasStartHandoff {
canvasId: string
@@ -48,6 +52,7 @@ export interface canvasNewLogicValues {
currentProjectId: number | null // projectLogic
breadcrumbs: Breadcrumb[]
chosenSpaceId: string | null
+ editHandoff: string | null
fromSuggestion: boolean
instruction: string
requestedSpaceId: string | null
@@ -58,14 +63,22 @@ export interface canvasNewLogicValues {
spaces: CanvasSpace[] | null
spacesLoading: boolean
spacesUnavailable: boolean
+ startBlankDisabledReason: string | null
startHandoff: CanvasStartHandoff | null
+ startingBlank: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasNewLogicActions {
+ clearEditHandoff: () => {
+ value: true
+ }
clearStartHandoff: () => {
value: true
}
+ handOffEdit: (canvasId: string) => {
+ canvasId: string
+ }
handOffStart: (handoff: CanvasStartHandoff) => {
handoff: CanvasStartHandoff
}
@@ -109,6 +122,15 @@ export interface canvasNewLogicActions {
setSelectedSpaceId: (spaceId: string) => {
spaceId: string
}
+ startBlank: () => {
+ value: true
+ }
+ startBlankFinished: () => {
+ value: true
+ }
+ startBlankStarted: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -120,12 +142,12 @@ export interface canvasNewLogicMeta {
requestedSpaceId: string | null
) => string | null
selectedSpace: (spaces: CanvasSpace[] | null, selectedSpaceId: string | null) => CanvasSpace | null
- sendDisabledReason: (
- instruction: string,
+ startBlankDisabledReason: (
spaces: CanvasSpace[] | null,
spacesUnavailable: boolean,
selectedSpaceId: string | null
) => string | null
+ sendDisabledReason: (startBlankDisabledReason: string | null, instruction: string) => string | null
}
}
@@ -139,6 +161,7 @@ export type canvasNewLogicType = MakeLogicType<
/**
* The new canvas start page: a prompt and a space. Sending creates the canvas, starts the
* agent that builds it, and replaces the page with the canvas, so Back skips the empty start page.
+ * Start blank creates the canvas from blocks instead and opens it in edit mode.
*/
export const canvasNewLogic = kea<canvasNewLogicType>([
path(['products', 'canvas', 'frontend', 'newCanvas', 'canvasNewLogic']),
@@ -155,6 +178,12 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
sent: true,
handOffStart: (handoff: CanvasStartHandoff) => ({ handoff }),
clearStartHandoff: true,
+ startBlank: true,
+ startBlankStarted: true,
+ startBlankFinished: true,
+ /** A blank canvas to open in edit mode. The canvas page picks it up. */
+ handOffEdit: (canvasId: string) => ({ canvasId }),
+ clearEditHandoff: true,
}),
loaders(({ values }) => ({
spaces: [
@@ -202,6 +231,20 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
sendFinished: () => false,
},
],
+ startingBlank: [
+ false,
+ {
+ startBlankStarted: () => true,
+ startBlankFinished: () => false,
+ },
+ ],
+ editHandoff: [
+ null as string | null,
+ {
+ handOffEdit: (_, { canvasId }) => canvasId,
+ clearEditHandoff: () => null,
+ },
+ ],
spacesUnavailable: [
false,
{
@@ -228,10 +271,9 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
(spaces: CanvasSpace[] | null, selectedSpaceId: string | null): CanvasSpace | null =>
spaces?.find((space) => space.id === selectedSpaceId) ?? null,
],
- sendDisabledReason: [
- (s) => [s.instruction, s.spaces, s.spacesUnavailable, s.selectedSpaceId],
+ startBlankDisabledReason: [
+ (s) => [s.spaces, s.spacesUnavailable, s.selectedSpaceId],
(
- instruction: string,
spaces: CanvasSpace[] | null,
spacesUnavailable: boolean,
selectedSpaceId: string | null
@@ -245,6 +287,15 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
if (!selectedSpaceId) {
return 'You don’t have a space to put a canvas in yet'
}
+ return null
+ },
+ ],
+ sendDisabledReason: [
+ (s) => [s.startBlankDisabledReason, s.instruction],
+ (startBlankDisabledReason: string | null, instruction: string): string | null => {
+ if (startBlankDisabledReason) {
+ return startBlankDisabledReason
+ }
if (!instruction.trim()) {
return 'Describe the canvas first'
}
@@ -259,69 +310,124 @@ export const canvasNewLogic = kea<canvasNewLogicType>([
],
],
}),
- listeners(({ actions, values }) => ({
- send: async () => {
- const projectId = values.currentProjectId ? String(values.currentProjectId) : null
- const space = values.selectedSpace
- const instruction = values.instruction.trim()
- const fromSuggestion = values.fromSuggestion
- if (values.sending || values.sendDisabledReason || !projectId || !space) {
- return
- }
- actions.sendStarted()
- const stillOnStartPage = (): boolean =>
- removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()
+ listeners(({ actions, values }) => {
+ const createCanvas = async (
+ projectId: string,
+ spaceId: string,
+ starterId?: string
+ ): Promise<CanvasApi | null> => {
try {
- let canvas: CanvasApi
- try {
- canvas = await canvasesCreate(projectId, {
- channel_id: space.id,
- name: UNTITLED_CANVAS_NAME,
- template_id: FREEFORM_TEMPLATE_ID,
- })
- } catch (error) {
- toast.error({
- title: "Couldn't create the canvas",
- description: error instanceof Error ? error.message : 'Try again in a moment.',
- })
- return
- }
+ const canvas = await canvasesCreate(projectId, {
+ channel_id: spaceId,
+ name: UNTITLED_CANVAS_NAME,
+ template_id: FREEFORM_TEMPLATE_ID,
+ })
posthog.capture(CANVAS_EVENTS.dashboardAction, {
action_type: 'create',
surface: 'web_new_canvas_page',
- channel_id: space.id,
+ channel_id: spaceId,
dashboard_id: canvas.id,
template_id: FREEFORM_TEMPLATE_ID,
+ ...(starterId ? { starter_id: starterId } : {}),
+ })
+ return canvas
+ } catch (error) {
+ toast.error({
+ title: "Couldn't create the canvas",
+ description: error instanceof Error ? error.message : 'Try again in a moment.',
})
+ return null
+ }
+ }
+ return {
+ send: async () => {
+ const projectId = values.currentProjectId ? String(values.currentProjectId) : null
+ const space = values.selectedSpace
+ const instruction = values.instruction.trim()
+ const fromSuggestion = values.fromSuggestion
+ if (values.sending || values.startingBlank || values.sendDisabledReason || !projectId || !space) {
+ return
+ }
+ actions.sendStarted()
+ const stillOnStartPage = (): boolean =>
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()
try {
- await startCanvasGeneration({
- projectId,
- canvas,
- spaceName: space.name,
- instruction,
- fromSuggestion,
- surface: 'web_new_canvas_page',
- })
- actions.sent()
- } catch (error) {
- // The canvas exists, so the person lands on it with the prompt kept, ready to send again.
- actions.handOffStart({ canvasId: canvas.id, instruction, fromSuggestion })
- toast.error({
- title: "Couldn't start building the canvas",
- description: error instanceof Error ? error.message : 'Try again in a moment.',
- })
+ const canvas = await createCanvas(projectId, space.id)
+ if (!canvas) {
+ return
+ }
+ try {
+ await startCanvasGeneration({
+ projectId,
+ canvas,
+ spaceName: space.name,
+ instruction,
+ fromSuggestion,
+ surface: 'web_new_canvas_page',
+ })
+ actions.sent()
+ } catch (error) {
+ // The canvas exists, so the person lands on it with the prompt kept, ready to send again.
+ actions.handOffStart({ canvasId: canvas.id, instruction, fromSuggestion })
+ toast.error({
+ title: "Couldn't start building the canvas",
+ description: error instanceof Error ? error.message : 'Try again in a moment.',
+ })
+ }
+ if (stillOnStartPage()) {
+ router.actions.replace(urls.canvasDetail(canvas.id))
+ }
+ } finally {
+ actions.sendFinished()
}
- if (stillOnStartPage()) {
- router.actions.replace(urls.canvasDetail(canvas.id))
+ },
+ startBlank: async () => {
+ const projectId = values.currentProjectId ? String(values.currentProjectId) : null
+ const space = values.selectedSpace
+ if (values.sending || values.startingBlank || values.startBlankDisabledReason || !projectId || !space) {
+ return
}
- } finally {
- actions.sendFinished()
- }
- },
- })),
+ actions.startBlankStarted()
+ try {
+ const canvas = await createCanvas(projectId, space.id, BLANK_STARTER_ID)
+ if (!canvas) {
+ return
+ }
+ try {
+ // The new canvas's source carries the platform's pinned dependencies, so only the files change.
+ const source = await canvasesSourceRetrieve(projectId, canvas.id)
+ const files = blankCanvasFiles()
+ await canvasesPublishCreate(projectId, canvas.id, {
+ project: {
+ ...source.project,
+ files,
+ capabilities: canvasCapabilities(source.project.capabilities, files) as
+ | CanvasCapabilitiesApi
+ | undefined,
+ },
+ prompt: 'Started a blank canvas',
+ expected_current_version_id: source.current_version_id,
+ })
+ actions.handOffEdit(canvas.id)
+ } catch {
+ // The canvas exists, so the person lands on it and can describe it to the agent instead.
+ toast.error({
+ title: "The canvas was created, but its blank layout didn't save",
+ description: 'Describe the canvas to have the agent build it.',
+ })
+ }
+ if (removeProjectIdIfPresent(router.values.location.pathname) === urls.canvasNew()) {
+ router.actions.replace(urls.canvasDetail(canvas.id))
+ }
+ } finally {
+ actions.startBlankFinished()
+ }
+ },
+ }
+ }),
urlToAction(({ actions, values }) => ({
[urls.canvasNew()]: (_, searchParams) => {
- if (values.sending) {
+ if (values.sending || values.startingBlank) {
return
}
actions.setRequestedSpaceId(typeof searchParams.space === 'string' ? searchParams.space : null)
diff --git a/products/canvas/frontend/scene/CanvasScene.tsx b/products/canvas/frontend/scene/CanvasScene.tsx
index 52776de5be4b..49c73ce736d2 100644
--- a/products/canvas/frontend/scene/CanvasScene.tsx
+++ b/products/canvas/frontend/scene/CanvasScene.tsx
@@ -16,6 +16,8 @@ import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { SceneExport } from 'scenes/sceneTypes'
+import { canvasEditLogic } from '../editing/canvasEditLogic'
+import { CanvasEditorRenderer } from '../editing/CanvasEditorRenderer'
import { CanvasBrowsedCanvas } from '../history/CanvasBrowsedCanvas'
import { CanvasHistoryConfirmDialog } from '../history/CanvasHistoryConfirmDialog'
import { canvasHistoryLogic } from '../history/canvasHistoryLogic'
@@ -33,14 +35,56 @@ export const scene: SceneExport<CanvasSceneLogicProps> = {
paramsToProps: ({ params: { id } }) => ({ id }),
}
+function CanvasEditBody(): JSX.Element {
+ const { entry, sourceError, sourceLoading } = useValues(canvasEditLogic)
+ const { loadSource, setEditing } = useActions(canvasEditLogic)
+
+ if (entry) {
+ return <CanvasEditorRenderer />
+ }
+ if (sourceError && !sourceLoading) {
+ return (
+ <Empty className="h-full border-0">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <IconWarning />
+ </EmptyMedia>
+ <EmptyTitle>This canvas can't be edited right now</EmptyTitle>
+ <EmptyDescription>{sourceError}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <div className="flex flex-wrap justify-center gap-2">
+ <Button variant="outline" onClick={() => loadSource()} data-attr="canvas-edit-load-retry">
+ Try again
+ </Button>
+ <Button variant="default" onClick={() => setEditing(false)} data-attr="canvas-edit-cancel">
+ Stop editing
+ </Button>
+ </div>
+ </EmptyContent>
+ </Empty>
+ )
+ }
+ return (
+ <div className="flex h-full flex-col gap-3 p-4" aria-label="Loading the canvas source">
+ <Skeleton className="h-4 w-1/3" />
+ <Skeleton className="h-full w-full" />
+ </div>
+ )
+}
+
function CanvasBody(): JSX.Element {
const { bodyState, viewLoading, liveRenderSource } = useValues(canvasSceneLogic)
const { loadView } = useActions(canvasSceneLogic)
const { browseVersionId } = useValues(canvasHistoryLogic)
+ const { editing } = useValues(canvasEditLogic)
if (browseVersionId && bodyState !== 'missing' && bodyState !== 'error') {
return <CanvasBrowsedCanvas />
}
+ if (editing && bodyState !== 'missing' && bodyState !== 'error') {
+ return <CanvasEditBody />
+ }
switch (bodyState) {
case 'loading':
return (
@@ -113,14 +157,16 @@ export function CanvasScene({ id }: CanvasSceneLogicProps): JSX.Element {
<BindLogic logic={canvasSceneLogic} props={{ id }}>
<BindLogic logic={canvasHistoryLogic} props={{ id }}>
<BindLogic logic={canvasCommentsLogic} props={{ id }}>
- <div data-quill className="flex h-full min-h-0 flex-col bg-background">
- <CanvasSceneHeader />
- <main className="relative min-h-0 flex-1">
- <CanvasBody />
- </main>
- <CanvasSelectionCommentAction />
- <CanvasHistoryConfirmDialog />
- </div>
+ <BindLogic logic={canvasEditLogic} props={{ id }}>
+ <div data-quill className="flex h-full min-h-0 flex-col bg-background">
+ <CanvasSceneHeader />
+ <main className="relative min-h-0 flex-1">
+ <CanvasBody />
+ </main>
+ <CanvasSelectionCommentAction />
+ <CanvasHistoryConfirmDialog />
+ </div>
+ </BindLogic>
</BindLogic>
</BindLogic>
</BindLogic>
diff --git a/products/canvas/frontend/scene/CanvasSceneHeader.tsx b/products/canvas/frontend/scene/CanvasSceneHeader.tsx
index 681bd895184e..333d869f7508 100644
--- a/products/canvas/frontend/scene/CanvasSceneHeader.tsx
+++ b/products/canvas/frontend/scene/CanvasSceneHeader.tsx
@@ -19,6 +19,8 @@ import { LinkPrimitive } from 'lib/lemon-ui/Link'
import { urls } from 'scenes/urls'
import { canvasSpaceLabel } from '../canvasTasksApi'
+import { CanvasEditSaveStatus } from '../editing/CanvasEditSaveStatus'
+import { CanvasEditToggle } from '../editing/CanvasEditToggle'
import { CanvasVersionControls } from '../history/CanvasVersionControls'
import { CanvasBuildStatus } from './CanvasBuildStatus'
import { CanvasGenerationIndicator } from './CanvasGenerationIndicator'
@@ -30,7 +32,7 @@ import { CanvasToolbar } from './CanvasToolbar'
/**
* The bar across the top of the canvas, laid out like PostHog Desktop's: the name and version history
- * at the start, then the canvas's status, the side panel, and the canvas menu at the end.
+ * at the start, then the canvas's status, editing, the side panel, and the canvas menu at the end.
*/
export function CanvasSceneHeader(): JSX.Element {
const { canvas, space } = useValues(canvasSceneLogic)
@@ -51,6 +53,8 @@ export function CanvasSceneHeader(): JSX.Element {
<CanvasGenerationIndicator />
<CanvasBuildStatus />
<CanvasRuntimeErrorNotice />
+ <CanvasEditSaveStatus />
+ <CanvasEditToggle />
<CanvasSidePanelToggle />
<DropdownMenu>
<Tooltip>
diff --git a/products/canvas/frontend/scene/canvasSceneLogic.ts b/products/canvas/frontend/scene/canvasSceneLogic.ts
index 5304224a502d..2cf4f960eae5 100644
--- a/products/canvas/frontend/scene/canvasSceneLogic.ts
+++ b/products/canvas/frontend/scene/canvasSceneLogic.ts
@@ -144,6 +144,7 @@ export function canvasBuildStatus(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasSceneLogicValues {
startHandoff: CanvasStartHandoff | null // canvasNewLogic
+ blocksCanvasId: string | null // canvasSidePanelLogic
currentProjectId: number | null // projectLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
@@ -377,7 +378,7 @@ export interface canvasSceneLogicMeta {
view: CanvasViewResponseApi | null
) => CanvasGenerationPhase | null
sidePanelAvailable: (bodyState: CanvasBodyState) => boolean
- sidePanelContext: (arg: string) => SidePanelSceneContext
+ sidePanelContext: (arg: string, blocksCanvasId: string | null) => SidePanelSceneContext
shouldPoll: (
view: CanvasViewResponseApi | null,
isGenerating: boolean,
@@ -407,6 +408,8 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
['startHandoff'],
sidePanelStateLogic,
['selectedTab', 'sidePanelOpen'],
+ canvasSidePanelLogic,
+ ['blocksCanvasId'],
],
// Connecting keeps the Views sidebar's logic mounted, so it knows this canvas's state when it opens.
actions: [
@@ -704,8 +707,11 @@ export const canvasSceneLogic = kea<canvasSceneLogicType>([
(bodyState: CanvasBodyState): boolean => !['loading', 'error', 'missing', 'empty'].includes(bodyState),
],
[SIDE_PANEL_CONTEXT_KEY]: [
- () => [(_, props: CanvasSceneLogicProps) => props.id],
- (canvasId: string): SidePanelSceneContext => ({ canvas_id: canvasId }),
+ (s) => [(_, props: CanvasSceneLogicProps) => props.id, s.blocksCanvasId],
+ (canvasId: string, blocksCanvasId: string | null): SidePanelSceneContext => ({
+ canvas_id: canvasId,
+ canvas_blocks: blocksCanvasId === canvasId,
+ }),
],
shouldPoll: [
(s) => [s.view, s.isGenerating, s.buildStatus],
diff --git a/products/canvas/frontend/sidePanel/CanvasSidePanelTabBody.tsx b/products/canvas/frontend/sidePanel/CanvasSidePanelTabBody.tsx
index ec3df9d864dd..b90f1346a747 100644
--- a/products/canvas/frontend/sidePanel/CanvasSidePanelTabBody.tsx
+++ b/products/canvas/frontend/sidePanel/CanvasSidePanelTabBody.tsx
@@ -1,3 +1,4 @@
+import { CanvasBlocksTab } from './blocks/CanvasBlocksTab'
import type { CanvasPanelTab } from './canvasPanelTabs'
import { CanvasChatTab } from './chat/CanvasChatTab'
import { CanvasCommentsTab } from './comments/CanvasCommentsTab'
@@ -8,6 +9,8 @@ export function CanvasSidePanelTabBody({ tab, canvasId }: { tab: CanvasPanelTab;
switch (tab) {
case 'chat':
return <CanvasChatTab canvasId={canvasId} />
+ case 'blocks':
+ return <CanvasBlocksTab canvasId={canvasId} />
case 'comments':
return <CanvasCommentsTab />
case 'timeline':
diff --git a/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibrary.tsx b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibrary.tsx
new file mode 100644
index 000000000000..2dcb02b914ff
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibrary.tsx
@@ -0,0 +1,143 @@
+import { ChangeEvent, PointerEvent, useMemo, useState } from 'react'
+
+import { IconSearch, IconSparkles } from '@posthog/icons'
+import {
+ Button,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+ Text,
+} from '@posthog/quill'
+
+import { LIBRARY, LIBRARY_GROUPS, LibraryEntry } from '../../editing/libraryCatalog'
+import { CanvasBlocksLibraryItem } from './CanvasBlocksLibraryItem'
+
+const IMPROVE_PROMPT = 'Improve this canvas. Keep the blocks I placed, and make the layout clear and consistent.'
+
+/** The block library: every block by group, searchable, with a way to hand the rest to the agent. */
+export function CanvasBlocksLibrary({
+ addsAfter,
+ onPointerDown,
+ onActivate,
+ onAskAgent,
+}: {
+ addsAfter: string | null
+ onPointerDown: (event: PointerEvent, entry: LibraryEntry) => void
+ onActivate: (entry: LibraryEntry) => void
+ onAskAgent: (message: string) => void
+}): JSX.Element {
+ const [search, setSearch] = useState('')
+ const groups = useMemo(() => {
+ const needle = search.trim().toLowerCase()
+ const matches = (entry: LibraryEntry): boolean =>
+ !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="flex flex-col gap-2 px-3 pt-3 pb-2">
+ <InputGroup>
+ <InputGroupAddon align="inline-start">
+ <InputGroupText>
+ <IconSearch />
+ </InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ type="search"
+ value={search}
+ placeholder="Search blocks"
+ aria-label="Search blocks"
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setSearch(event.target.value)}
+ data-attr="canvas-blocks-search"
+ />
+ </InputGroup>
+ <Text size="xs" variant="muted">
+ {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.'}
+ </Text>
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 pb-4">
+ {groups.length === 0 ? (
+ <Empty className="border-0 p-4">
+ <EmptyHeader>
+ <EmptyTitle>No blocks match your search</EmptyTitle>
+ <EmptyDescription>
+ Try another word, or ask the agent to build what you need.
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={() => setSearch('')}>
+ Clear search
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : (
+ groups.map(({ group, entries }) => (
+ <section
+ key={group}
+ aria-labelledby={`canvas-blocks-group-${group}`}
+ className="flex flex-col gap-1"
+ >
+ <Text
+ id={`canvas-blocks-group-${group}`}
+ size="xs"
+ variant="muted"
+ weight="medium"
+ render={<h3 />}
+ >
+ {group}
+ </Text>
+ <div className="flex flex-col">
+ {entries.map((entry) => (
+ <CanvasBlocksLibraryItem
+ key={entry.type}
+ entry={entry}
+ onPointerDown={onPointerDown}
+ onActivate={onActivate}
+ />
+ ))}
+ </div>
+ </section>
+ ))
+ )}
+ <Item
+ variant="outline"
+ size="xs"
+ className="w-full items-start text-left hover:bg-fill-button-tertiary-hover"
+ render={
+ <button
+ type="button"
+ onClick={() => onAskAgent(IMPROVE_PROMPT)}
+ data-attr="canvas-blocks-ask-agent"
+ />
+ }
+ >
+ <ItemMedia variant="icon" aria-hidden>
+ <IconSparkles />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>Ask the agent…</ItemTitle>
+ <ItemDescription>
+ Blocks are code in this canvas. The agent can change them, or build what no block covers.
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ </div>
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibraryItem.tsx b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibraryItem.tsx
new file mode 100644
index 000000000000..f64ed31b4773
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksLibraryItem.tsx
@@ -0,0 +1,52 @@
+import { KeyboardEvent, PointerEvent } from 'react'
+
+import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@posthog/quill'
+
+import type { LibraryEntry } from '../../editing/libraryCatalog'
+
+/** One block in the library. Clicking adds it, and dragging places it anywhere on the canvas. */
+export function CanvasBlocksLibraryItem({
+ entry,
+ onPointerDown,
+ onActivate,
+}: {
+ entry: LibraryEntry
+ onPointerDown: (event: PointerEvent, entry: LibraryEntry) => void
+ onActivate: (entry: LibraryEntry) => void
+}): JSX.Element {
+ const Icon = entry.icon
+ return (
+ <Item
+ size="xs"
+ // The app compiles fill tokens as plain classes only, so hover uses the tertiary button fill.
+ className="w-full cursor-grab items-start text-left select-none hover:bg-fill-button-tertiary-hover focus-visible:bg-fill-button-tertiary-hover active:cursor-grabbing"
+ render={
+ <button
+ type="button"
+ aria-label={`Add ${entry.label}`}
+ data-attr={`canvas-blocks-library-${entry.type}`}
+ onClick={(event) => {
+ if (event.detail === 0) {
+ onActivate(entry)
+ }
+ }}
+ onPointerDown={(event) => onPointerDown(event, entry)}
+ onKeyDown={(event: KeyboardEvent) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault()
+ onActivate(entry)
+ }
+ }}
+ />
+ }
+ >
+ <ItemMedia variant="icon" aria-hidden>
+ <Icon />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle className="truncate">{entry.label}</ItemTitle>
+ <ItemDescription className="line-clamp-2">{entry.description}</ItemDescription>
+ </ItemContent>
+ </Item>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/CanvasBlocksNotice.tsx b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksNotice.tsx
new file mode 100644
index 000000000000..058ea2445b3e
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksNotice.tsx
@@ -0,0 +1,44 @@
+import { ReactNode } from 'react'
+
+import { IconWarning } from '@posthog/icons'
+import { Item, ItemContent, ItemFooter, ItemMedia, ItemTitle, Text } from '@posthog/quill'
+
+/** A problem with saving, shown above the library or inspector with the actions that resolve it. */
+export function CanvasBlocksNotice({
+ tone,
+ title,
+ detail,
+ children,
+}: {
+ tone: 'destructive' | 'warning'
+ title: string
+ detail: string
+ children: ReactNode
+}): JSX.Element {
+ return (
+ // Item drops a role prop, so the alert role sits on the wrapper.
+ <div role="alert" className="shrink-0 px-3 pt-3">
+ <Item
+ variant="outline"
+ size="xs"
+ tone={tone}
+ className="items-start"
+ data-attr={`canvas-blocks-notice-${tone === 'destructive' ? 'error' : 'warning'}`}
+ >
+ <ItemMedia variant="icon" aria-hidden>
+ <IconWarning />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle>{title}</ItemTitle>
+ {/* ItemDescription clamps to two lines, and this detail must show in full. */}
+ <Text size="xs" variant="muted" className="break-words">
+ {detail}
+ </Text>
+ </ItemContent>
+ <ItemFooter className="justify-start">
+ <div className="flex flex-wrap gap-2">{children}</div>
+ </ItemFooter>
+ </Item>
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/CanvasBlocksTab.tsx b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksTab.tsx
new file mode 100644
index 000000000000..a5c6b8822f9f
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/CanvasBlocksTab.tsx
@@ -0,0 +1,186 @@
+import { useActions, useValues } from 'kea'
+import { PointerEvent } from 'react'
+
+import { IconChevronLeft, IconSparkles } from '@posthog/icons'
+import { Button, Item, ItemContent, ItemDescription, ItemMedia, ItemTitle, Skeleton } from '@posthog/quill'
+
+import { canvasEditLogic } from '../../editing/canvasEditLogic'
+import { isRootSelection } from '../../editing/canvasSourceSnapshots'
+import { LibraryEntry, libraryIcon, libraryLabel } from '../../editing/libraryCatalog'
+import { beginSourceDrag } from '../../editing/sourceDrag'
+import { CanvasBlocksLibrary } from './CanvasBlocksLibrary'
+import { CanvasBlocksNotice } from './CanvasBlocksNotice'
+import { CanvasSourceInspector } from './inspector/CanvasSourceInspector'
+
+/**
+ * The Blocks tab of an edited canvas: the library to add blocks from, or the inspector for the
+ * selected block, with any save problem on top. Like PostHog Desktop's Blocks panel.
+ * The save state itself shows in the canvas header.
+ */
+export function CanvasBlocksTab({ canvasId }: { canvasId: string }): JSX.Element {
+ const { entry, selection, libraryOpen } = useValues(canvasEditLogic({ id: canvasId }))
+ const {
+ setLibraryOpen,
+ addAfterSelection,
+ dropBlock,
+ updateProps,
+ setText,
+ duplicateSelection,
+ removeSelection,
+ retrySave,
+ resolveConflict,
+ askAgent,
+ } = useActions(canvasEditLogic({ id: canvasId }))
+
+ if (!entry) {
+ return (
+ <div className="flex flex-col gap-2 p-3" aria-label="Loading blocks">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-3 w-16" />
+ <Skeleton className="h-12 w-full" />
+ <Skeleton className="h-12 w-full" />
+ </div>
+ )
+ }
+ 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): void => {
+ setLibraryOpen(true)
+ addAfterSelection(blockType)
+ }
+ const onLibraryPointerDown = (event: PointerEvent, item: LibraryEntry): void => {
+ if (event.button !== 0) {
+ return
+ }
+ event.preventDefault()
+ beginSourceDrag({
+ source: { kind: 'new', blockType: item.type },
+ startX: event.clientX,
+ startY: event.clientY,
+ onDrop: (source, hit) => {
+ setLibraryOpen(true)
+ dropBlock(source, hit)
+ },
+ onClick: () => addFromLibrary(item.type),
+ })
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col" data-attr="canvas-blocks-tab">
+ {inspecting ? (
+ <div className="flex shrink-0 items-center border-b border-border px-2 py-1">
+ <Button
+ variant="default"
+ size="sm"
+ onClick={() => setLibraryOpen(true)}
+ data-attr="canvas-blocks-all"
+ >
+ <IconChevronLeft />
+ All blocks
+ </Button>
+ </div>
+ ) : null}
+ {entry.saveError ? (
+ <CanvasBlocksNotice tone="destructive" title="Your changes are not saved" detail={entry.saveError}>
+ <Button variant="outline" size="xs" onClick={() => retrySave()} data-attr="canvas-save-retry">
+ Try again
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() =>
+ askAgent(
+ `Saving this canvas fails with: "${entry.saveError}". Fix the canvas source so it passes validation.`
+ )
+ }
+ data-attr="canvas-save-ask-agent"
+ >
+ <IconSparkles />
+ Ask agent to fix
+ </Button>
+ </CanvasBlocksNotice>
+ ) : null}
+ {entry.conflict ? (
+ <CanvasBlocksNotice
+ tone="warning"
+ title="This canvas changed somewhere else"
+ detail="Edits stop saving until you choose. Load the latest and drop your unsaved edits, or keep your edits and replace it."
+ >
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => resolveConflict(false)}
+ data-attr="canvas-conflict-load-latest"
+ >
+ Load the latest
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => resolveConflict(true)}
+ data-attr="canvas-conflict-keep-mine"
+ >
+ Keep my edits
+ </Button>
+ </CanvasBlocksNotice>
+ ) : null}
+ {inspecting && selection ? (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="px-3 pt-3">
+ <Item variant="muted" size="xs">
+ <ItemMedia variant="icon" aria-hidden>
+ <SelectedIcon />
+ </ItemMedia>
+ <ItemContent className="min-w-0">
+ <ItemTitle>
+ {isRoot ? 'Canvas' : libraryLabel(selection.blockType, selection.tag)}
+ </ItemTitle>
+ {selection.source?.file ? (
+ <ItemDescription className="truncate font-mono" translate="no">
+ {selection.source.file}
+ </ItemDescription>
+ ) : null}
+ </ItemContent>
+ </Item>
+ </div>
+ <CanvasSourceInspector
+ key={selection.blockId ?? `${selection.source?.file}:${selection.source?.start}`}
+ selection={selection}
+ isRoot={isRoot}
+ onProps={(props) => updateProps(selection, props)}
+ onText={(text) => setText(selection, text)}
+ onDuplicate={() => duplicateSelection(selection)}
+ onRemove={() => removeSelection(selection)}
+ />
+ {isRoot ? null : (
+ <div className="px-3 pb-3">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ askAgent(
+ `Change the ${libraryLabel(selection.blockType, selection.tag).toLowerCase()} at ${selection.source?.file ?? 'the canvas'}${selection.blockId ? ` (blockId ${selection.blockId})` : ''}: `
+ )
+ }
+ data-attr="canvas-block-ask-agent"
+ >
+ <IconSparkles />
+ Ask the agent about this…
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <CanvasBlocksLibrary
+ addsAfter={addsAfter}
+ onPointerDown={onLibraryPointerDown}
+ onActivate={(item) => addFromLibrary(item.type)}
+ onAskAgent={askAgent}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/CanvasSourceInspector.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/CanvasSourceInspector.tsx
new file mode 100644
index 000000000000..1ae9b827a23c
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/CanvasSourceInspector.tsx
@@ -0,0 +1,112 @@
+import { IconCopy, IconSparkles, IconTrash } from '@posthog/icons'
+import { Button, Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from '@posthog/quill'
+
+import { BlockPropsRecord, blockDefinition } from '../../../editing/blockLibrary/blockDefinitions'
+import { SQL_BLOCK_TYPES } from '../../../editing/blockLibrary/blockSql'
+import type { CanvasEditSelection } from '../../../editing/canvasSourceSnapshots'
+import { CommonBlockFields } from './CommonBlockFields'
+import { ComponentFields } from './ComponentFields'
+import { ControlNote } from './ControlNote'
+import { DraftTextarea } from './DraftTextarea'
+import { InspectorField } from './InspectorField'
+import { BlockPropsChange, editableProps } from './inspectorValues'
+import { ParamField } from './ParamField'
+import { QueryModeFields } from './QueryModeFields'
+
+function BlockFields({
+ selection,
+ props,
+ onChange,
+}: {
+ selection: CanvasEditSelection
+ props: BlockPropsRecord
+ onChange: BlockPropsChange
+}): JSX.Element | null {
+ if (selection.params) {
+ return (
+ <>
+ {selection.params.map(({ name, spec }) => (
+ <ParamField
+ key={name}
+ name={name}
+ spec={spec}
+ value={props[name] ?? spec.fallback}
+ onChange={(value) => onChange({ ...props, [name]: value })}
+ />
+ ))}
+ </>
+ )
+ }
+ if (!selection.blockType) {
+ return null
+ }
+ return <ComponentFields type={selection.blockType} props={props} onChange={onChange} />
+}
+
+/** The settings of the selected block or element, and the actions on it. */
+export function CanvasSourceInspector({
+ selection,
+ isRoot,
+ onProps,
+ onText,
+ onDuplicate,
+ onRemove,
+}: {
+ selection: CanvasEditSelection
+ isRoot: boolean
+ onProps: (props: BlockPropsRecord) => void
+ onText: (text: string) => void
+ onDuplicate: () => void
+ onRemove: () => void
+}): JSX.Element {
+ const props = editableProps(selection.props)
+ return (
+ <div className="flex flex-col gap-4 p-3">
+ {selection.params && selection.blockType && !blockDefinition(selection.blockType) ? (
+ <Item variant="muted" size="xs" className="items-start">
+ <ItemMedia variant="icon" aria-hidden>
+ <IconSparkles />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>Set up by the agent</ItemTitle>
+ <ItemDescription>
+ These fields come from the component's code, so you can change them without a prompt.
+ </ItemDescription>
+ </ItemContent>
+ </Item>
+ ) : 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} />
+ )}
+ <CommonBlockFields 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 flex-wrap gap-2">
+ <Button variant="outline" size="sm" onClick={onDuplicate} data-attr="canvas-block-duplicate">
+ <IconCopy />
+ Duplicate
+ </Button>
+ <Button variant="outline" size="sm" onClick={onRemove} data-attr="canvas-block-delete">
+ <IconTrash />
+ Delete
+ </Button>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/CommonBlockFields.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/CommonBlockFields.tsx
new file mode 100644
index 000000000000..a0bfa024089b
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/CommonBlockFields.tsx
@@ -0,0 +1,55 @@
+import { BlockPropsRecord, blockDefinition } from '../../../editing/blockLibrary/blockDefinitions'
+import type { CanvasEditSelection } from '../../../editing/canvasSourceSnapshots'
+import { DraftTextarea } from './DraftTextarea'
+import { InspectorField } from './InspectorField'
+import { WIDTHS } from './inspectorOptions'
+import { BlockPropsChange, asString } from './inspectorValues'
+import { Segmented } from './Segmented'
+
+/** The description every data block takes, and the width of a block that sits in a grid. */
+export function CommonBlockFields({
+ selection,
+ props,
+ onChange,
+}: {
+ selection: CanvasEditSelection
+ props: BlockPropsRecord
+ onChange: BlockPropsChange
+}): JSX.Element | null {
+ 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}
+ </>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/ComponentFields.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/ComponentFields.tsx
new file mode 100644
index 000000000000..451ac5850428
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/ComponentFields.tsx
@@ -0,0 +1,237 @@
+import type { BlockPropsRecord } from '../../../editing/blockLibrary/blockDefinitions'
+import { ControlNote } from './ControlNote'
+import { DraftInput } from './DraftInput'
+import { EventPicker } from './EventPicker'
+import { EventStepList } from './EventStepList'
+import { InspectorField } from './InspectorField'
+import { MATH_OPTIONS, MathValue, NUMBER_FORMATS } from './inspectorOptions'
+import { InspectorSwitch } from './InspectorSwitch'
+import { BlockPropsChange, asBoolean, asNumber, asString, asStrings } from './inspectorValues'
+import { OptionSelect } from './OptionSelect'
+import { PropertyPicker } from './PropertyPicker'
+import { Segmented } from './Segmented'
+import { SqlField } from './SqlField'
+import { TitleField } from './TitleField'
+
+function FollowFilters({ props, onChange }: { props: BlockPropsRecord; onChange: BlockPropsChange }): JSX.Element {
+ 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 MeasureField({
+ label,
+ props,
+ onChange,
+}: {
+ label: string
+ props: BlockPropsRecord
+ onChange: BlockPropsChange
+}): JSX.Element {
+ return (
+ <InspectorField label={label}>
+ <div className="flex flex-col gap-2">
+ <EventPicker
+ value={asString(props.event, '$pageview')}
+ onChange={(event) => onChange({ ...props, event })}
+ />
+ <OptionSelect
+ value={asString(props.math, 'total') as MathValue}
+ options={MATH_OPTIONS}
+ ariaLabel="Measure"
+ onChange={(math) => onChange({ ...props, math })}
+ />
+ </div>
+ </InspectorField>
+ )
+}
+
+/** The settings of a library block that does not declare its own param schema. */
+export function ComponentFields({
+ type,
+ props,
+ onChange,
+}: {
+ type: string
+ props: BlockPropsRecord
+ onChange: BlockPropsChange
+}): JSX.Element {
+ 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')}
+ ariaLabel="Chart type"
+ options={[
+ { value: 'line', label: 'Line' },
+ { value: 'bar', label: 'Bar' },
+ { value: 'area', label: 'Area' },
+ ]}
+ onChange={(display) => onChange({ ...props, display })}
+ />
+ </InspectorField>
+ <EventStepList
+ label="Events"
+ itemLabel="event"
+ values={asStrings(props.events, ['$pageview'])}
+ min={1}
+ max={5}
+ onChange={(events) => onChange({ ...props, events })}
+ />
+ <InspectorField label="Measure">
+ <OptionSelect
+ value={asString(props.math, 'total') as MathValue}
+ options={MATH_OPTIONS}
+ ariaLabel="Measure"
+ 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} />
+ <EventStepList
+ label="Steps"
+ itemLabel="step"
+ 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>
+ }
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/ControlNote.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/ControlNote.tsx
new file mode 100644
index 000000000000..8913706093ca
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/ControlNote.tsx
@@ -0,0 +1,12 @@
+import { ReactNode } from 'react'
+
+import { Text } from '@posthog/quill'
+
+/** An explanation in place of settings, for blocks and elements the inspector cannot change. */
+export function ControlNote({ children }: { children: ReactNode }): JSX.Element {
+ return (
+ <Text size="xs" variant="muted">
+ {children}
+ </Text>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/DraftInput.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/DraftInput.tsx
new file mode 100644
index 000000000000..6566ae3de492
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/DraftInput.tsx
@@ -0,0 +1,38 @@
+import { ChangeEvent, KeyboardEvent, useEffect, useState } from 'react'
+
+import { Input } from '@posthog/quill'
+
+/** A text input that changes the source only on blur or Enter, so typing does not publish a version per key. */
+export function DraftInput({
+ value,
+ onCommit,
+ placeholder,
+ ariaLabel,
+}: {
+ value: string
+ onCommit: (value: string) => void
+ placeholder?: string
+ ariaLabel: string
+}): JSX.Element {
+ const [draft, setDraft] = useState(value)
+ useEffect(() => setDraft(value), [value])
+ const commit = (): void => {
+ if (draft !== value) {
+ onCommit(draft)
+ }
+ }
+ return (
+ <Input
+ value={draft}
+ placeholder={placeholder}
+ aria-label={ariaLabel}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ commit()
+ }
+ }}
+ />
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/DraftTextarea.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/DraftTextarea.tsx
new file mode 100644
index 000000000000..bce2b5a9dc58
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/DraftTextarea.tsx
@@ -0,0 +1,41 @@
+import { ChangeEvent, KeyboardEvent, useEffect, useState } from 'react'
+
+import { Textarea } from '@posthog/quill'
+
+/** A multi-line text field that changes the source on blur or Cmd+Enter. */
+export function DraftTextarea({
+ value,
+ onCommit,
+ ariaLabel,
+ rows = 6,
+ placeholder,
+}: {
+ value: string
+ onCommit: (value: string) => void
+ ariaLabel: string
+ rows?: number
+ placeholder?: string
+}): JSX.Element {
+ const [draft, setDraft] = useState(value)
+ useEffect(() => setDraft(value), [value])
+ const commit = (): void => {
+ if (draft !== value) {
+ onCommit(draft)
+ }
+ }
+ return (
+ <Textarea
+ value={draft}
+ rows={rows}
+ placeholder={placeholder}
+ aria-label={ariaLabel}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
+ commit()
+ }
+ }}
+ />
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/EventPicker.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/EventPicker.tsx
new file mode 100644
index 000000000000..96a8edaedc58
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/EventPicker.tsx
@@ -0,0 +1,29 @@
+import { useActions, useValues } from 'kea'
+
+import { canvasBlockPickersLogic } from './canvasBlockPickersLogic'
+import { eventLabel } from './pickerLabels'
+import { SearchPicker } from './SearchPicker'
+
+/** Picks one event, from the project's most common ones or typed in. */
+export function EventPicker({ value, onChange }: { value: string; onChange: (value: string) => void }): JSX.Element {
+ const { topEvents, topEventsLoading, topEventsError } = useValues(canvasBlockPickersLogic)
+ const { ensureTopEvents } = useActions(canvasBlockPickersLogic)
+ return (
+ <SearchPicker
+ value={value}
+ onChange={(next) => {
+ if (next) {
+ onChange(next)
+ }
+ }}
+ options={topEvents ?? []}
+ loading={topEventsLoading}
+ error={topEventsError ? 'Options did not load. Close and reopen this list to try again.' : null}
+ onOpen={ensureTopEvents}
+ placeholder="Pick an event"
+ searchPlaceholder="Search events…"
+ ariaLabel="Event"
+ format={eventLabel}
+ />
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/EventStepList.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/EventStepList.tsx
new file mode 100644
index 000000000000..783347517e03
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/EventStepList.tsx
@@ -0,0 +1,88 @@
+import { IconPlus, IconX } from '@posthog/icons'
+import { Button, Text, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
+
+import { EventPicker } from './EventPicker'
+import { InspectorField } from './InspectorField'
+
+/** An ordered list of events, like a trend's series or a funnel's steps. */
+export function EventStepList({
+ label,
+ itemLabel,
+ values,
+ min,
+ max,
+ onChange,
+}: {
+ label: string
+ /** One entry, for example "event" or "step". */
+ itemLabel: string
+ values: string[]
+ min: number
+ max: number
+ onChange: (values: string[]) => void
+}): JSX.Element {
+ const seen = new Map<string, number>()
+ return (
+ <InspectorField label={label}>
+ <div className="flex flex-col gap-2">
+ {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-2">
+ <Text
+ size="xs"
+ variant="muted"
+ render={<span />}
+ className="w-4 shrink-0 text-center tabular-nums"
+ translate="no"
+ >
+ {index + 1}
+ </Text>
+ <div className="min-w-0 flex-1">
+ <EventPicker
+ value={item}
+ onChange={(event) =>
+ onChange(values.map((current, i) => (i === index ? event : current)))
+ }
+ />
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label={`Remove ${itemLabel} ${index + 1}`}
+ disabled={values.length <= min}
+ onClick={() => onChange(values.filter((_, i) => i !== index))}
+ />
+ }
+ >
+ <IconX />
+ </TooltipTrigger>
+ <TooltipContent>
+ {values.length <= min
+ ? `Keep at least ${min} ${itemLabel}${min === 1 ? '' : 's'}`
+ : `Remove ${itemLabel}`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )
+ })}
+ {values.length < max ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={() => onChange([...values, '$pageview'])}
+ >
+ <IconPlus />
+ {`Add ${itemLabel}`}
+ </Button>
+ ) : null}
+ </div>
+ </InspectorField>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/InsightPicker.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/InsightPicker.tsx
new file mode 100644
index 000000000000..c1a306e70adf
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/InsightPicker.tsx
@@ -0,0 +1,49 @@
+import { useActions, useValues } from 'kea'
+import { useCallback, useMemo, useState } from 'react'
+
+import { CanvasSavedInsight, canvasBlockPickersLogic } from './canvasBlockPickersLogic'
+import { SearchPicker } from './SearchPicker'
+
+/** Picks one saved insight by name. The block stores its short id. */
+export function InsightPicker({
+ value,
+ onChange,
+}: {
+ value: string | null
+ onChange: (value: string | null) => void
+}): JSX.Element {
+ const { savedInsights, savedInsightsLoading } = useValues(canvasBlockPickersLogic)
+ const { setInsightSearch } = useActions(canvasBlockPickersLogic)
+ // Keeps the picked insight's name after a search narrows the list past it.
+ const [picked, setPicked] = useState<CanvasSavedInsight>()
+ const names = useMemo(
+ () =>
+ new Map([
+ ...(picked ? [[picked.shortId, picked.name] as const] : []),
+ ...savedInsights.map((insight) => [insight.shortId, insight.name] as const),
+ ]),
+ [savedInsights, picked]
+ )
+ const options = useMemo(() => savedInsights.map((insight) => insight.shortId), [savedInsights])
+ const format = useCallback((shortId: string) => names.get(shortId) ?? shortId, [names])
+ return (
+ <SearchPicker
+ value={value}
+ onChange={(next) => {
+ const name = next ? names.get(next) : undefined
+ if (next && name) {
+ setPicked({ shortId: next, name })
+ }
+ onChange(next)
+ }}
+ options={options}
+ loading={savedInsightsLoading}
+ onOpen={() => setInsightSearch('')}
+ placeholder="Pick a saved insight"
+ searchPlaceholder="Search insights…"
+ ariaLabel="Insight"
+ format={format}
+ onSearchChange={setInsightSearch}
+ />
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/InspectorField.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/InspectorField.tsx
new file mode 100644
index 000000000000..1bdf41dc88b7
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/InspectorField.tsx
@@ -0,0 +1,24 @@
+import { ReactNode, useId } from 'react'
+
+import { Field, FieldDescription, FieldTitle } from '@posthog/quill'
+
+/** A labeled inspector control, with an optional hint under it. */
+export function InspectorField({
+ label,
+ hint,
+ children,
+}: {
+ label: string
+ hint?: ReactNode
+ children: ReactNode
+}): JSX.Element {
+ // Controls here name themselves with aria-label, so the title only labels the group.
+ const titleId = useId()
+ return (
+ <Field aria-labelledby={titleId}>
+ <FieldTitle id={titleId}>{label}</FieldTitle>
+ {children}
+ {hint ? <FieldDescription>{hint}</FieldDescription> : null}
+ </Field>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/InspectorSwitch.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/InspectorSwitch.tsx
new file mode 100644
index 000000000000..ab38fcec44d0
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/InspectorSwitch.tsx
@@ -0,0 +1,27 @@
+import { useId } from 'react'
+
+import { Field, FieldContent, FieldDescription, FieldLabel, Switch } from '@posthog/quill'
+
+/** An on or off inspector setting that applies at once, with its label on the left. */
+export function InspectorSwitch({
+ label,
+ hint,
+ checked,
+ onChange,
+}: {
+ label: string
+ hint?: string
+ checked: boolean
+ onChange: (checked: boolean) => void
+}): JSX.Element {
+ const id = useId()
+ return (
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldLabel htmlFor={id}>{label}</FieldLabel>
+ {hint ? <FieldDescription>{hint}</FieldDescription> : null}
+ </FieldContent>
+ <Switch id={id} checked={checked} onCheckedChange={onChange} size="sm" />
+ </Field>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/OptionSelect.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/OptionSelect.tsx
new file mode 100644
index 000000000000..c838298ebf90
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/OptionSelect.tsx
@@ -0,0 +1,42 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@posthog/quill'
+
+export interface InspectorOption<T extends string = string> {
+ value: T
+ label: string
+}
+
+/** A dropdown of fixed options, for settings with more options than a segmented control fits. */
+export function OptionSelect<T extends string>({
+ value,
+ options,
+ onChange,
+ ariaLabel,
+}: {
+ value: T
+ options: InspectorOption<T>[]
+ onChange: (value: T) => void
+ ariaLabel: string
+}): JSX.Element {
+ const labelOf = (selected: T): string => options.find((option) => option.value === selected)?.label ?? selected
+ return (
+ <Select
+ value={value}
+ onValueChange={(next: T | null) => {
+ if (next) {
+ onChange(next)
+ }
+ }}
+ >
+ <SelectTrigger aria-label={ariaLabel} size="sm" className="w-full">
+ <SelectValue>{(selected: T) => 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>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/ParamField.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/ParamField.tsx
new file mode 100644
index 000000000000..6599f3b5d829
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/ParamField.tsx
@@ -0,0 +1,152 @@
+import type { BlockPropValue } from '../../../editing/blockLibrary/blockDefinitions'
+import type { ParamSpec } from '../../../editing/blockLibrary/params'
+import { DraftInput } from './DraftInput'
+import { DraftTextarea } from './DraftTextarea'
+import { EventPicker } from './EventPicker'
+import { EventStepList } from './EventStepList'
+import { InsightPicker } from './InsightPicker'
+import { InspectorField } from './InspectorField'
+import { InspectorSwitch } from './InspectorSwitch'
+import { asBoolean, asNumber, asString, asStrings } from './inspectorValues'
+import { OptionSelect } from './OptionSelect'
+import { ParamSlider } from './ParamSlider'
+import { PropertyPicker } from './PropertyPicker'
+import { Segmented } from './Segmented'
+
+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))
+}
+
+/** One param a component declared with `editable()`, drawn as the control its kind calls for. */
+export function ParamField({
+ name,
+ spec,
+ value,
+ onChange,
+}: {
+ name: string
+ spec: ParamSpec
+ value: unknown
+ onChange: (value: BlockPropValue) => void
+}): JSX.Element {
+ 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 (
+ <EventStepList
+ label={spec.label}
+ itemLabel="event"
+ 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"
+ // The swatch shows the author's own color value, which no token can.
+ style={{ backgroundColor: color }}
+ >
+ <input
+ type="color"
+ aria-label={spec.label}
+ key={color}
+ defaultValue={HEX_COLOR.test(color) ? color : '#000000'}
+ onBlur={(event) => {
+ if (event.target.value !== color) {
+ 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>
+ )
+ }
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/ParamSlider.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/ParamSlider.tsx
new file mode 100644
index 000000000000..ee7244ec3830
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/ParamSlider.tsx
@@ -0,0 +1,69 @@
+import { useEffect, useState } from 'react'
+
+import { Slider, Text } from '@posthog/quill'
+
+import type { ParamSpec } from '../../../editing/blockLibrary/params'
+
+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)
+}
+
+/** A bounded number param. The source changes when the author lets go, not while they drag. */
+export function ParamSlider({
+ value,
+ spec,
+ onCommit,
+}: {
+ value: number
+ spec: ParamSpec
+ onCommit: (value: number) => void
+}): JSX.Element {
+ 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') {
+ const rounded = Number(raw.toFixed(decimals))
+ if (rounded !== value) {
+ onCommit(rounded)
+ }
+ }
+ }}
+ />
+ <Text
+ size="xs"
+ variant="muted"
+ render={<span />}
+ className="w-9 shrink-0 text-right tabular-nums"
+ translate="no"
+ >
+ {draft.toFixed(decimals)}
+ </Text>
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/PropertyPicker.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/PropertyPicker.tsx
new file mode 100644
index 000000000000..add14611f3d5
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/PropertyPicker.tsx
@@ -0,0 +1,37 @@
+import { useActions, useValues } from 'kea'
+
+import { propertyDisplayName } from '../../../editing/blockLibrary/propertyNames'
+import { canvasBlockPickersLogic } from './canvasBlockPickersLogic'
+import { SearchPicker } from './SearchPicker'
+
+/** Picks one event property, from the project's most common ones or typed in. */
+export function PropertyPicker({
+ value,
+ onChange,
+ allowNone,
+ noneLabel,
+}: {
+ value: string | null
+ onChange: (value: string | null) => void
+ allowNone?: boolean
+ noneLabel?: string
+}): JSX.Element {
+ const { topProperties, topPropertiesLoading, topPropertiesError } = useValues(canvasBlockPickersLogic)
+ const { ensureTopProperties } = useActions(canvasBlockPickersLogic)
+ return (
+ <SearchPicker
+ value={value}
+ onChange={onChange}
+ options={topProperties ?? []}
+ loading={topPropertiesLoading}
+ error={topPropertiesError ? 'Options did not load. Close and reopen this list to try again.' : null}
+ onOpen={ensureTopProperties}
+ placeholder="Pick a property"
+ searchPlaceholder="Search properties…"
+ ariaLabel="Property"
+ format={propertyDisplayName}
+ allowNone={allowNone}
+ noneLabel={noneLabel}
+ />
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/QueryModeFields.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/QueryModeFields.tsx
new file mode 100644
index 000000000000..933a5cd57079
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/QueryModeFields.tsx
@@ -0,0 +1,51 @@
+import { ReactNode } from 'react'
+
+import type { BlockPropsRecord } from '../../../editing/blockLibrary/blockDefinitions'
+import { builderSql } from '../../../editing/blockLibrary/blockSql'
+import { InspectorField } from './InspectorField'
+import { BlockPropsChange } from './inspectorValues'
+import { Segmented } from './Segmented'
+import { SqlField } from './SqlField'
+import { TitleField } from './TitleField'
+
+/** Switches a data block between its builder settings and a HogQL query written from them. */
+export function QueryModeFields({
+ type,
+ props,
+ onChange,
+ children,
+}: {
+ type: string
+ props: BlockPropsRecord
+ onChange: BlockPropsChange
+ children: ReactNode
+}): JSX.Element {
+ 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 })} />
+ </>
+ )}
+ </>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/SearchPicker.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/SearchPicker.tsx
new file mode 100644
index 000000000000..5950278f9a85
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/SearchPicker.tsx
@@ -0,0 +1,174 @@
+import { useMemo, useRef, useState } from 'react'
+
+import { IconBolt, IconChevronDown } from '@posthog/icons'
+import {
+ Button,
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ Text,
+} from '@posthog/quill'
+
+const CUSTOM_PREFIX = '__custom__:'
+const NONE_VALUE = '__none__'
+const MAX_OPTIONS = 150
+
+function sameText(value: string): string {
+ return value
+}
+
+export interface SearchPickerProps {
+ value: string | null
+ onChange: (value: string | null) => void
+ options: string[]
+ loading: boolean
+ error?: string | null
+ placeholder: string
+ searchPlaceholder: string
+ ariaLabel: string
+ allowNone?: boolean
+ noneLabel?: string
+ format?: (value: string) => string
+ onSearchChange?: (search: string) => void
+ onOpen?: () => void
+}
+
+/** A searchable list of values. Typing a value that is not in the list offers it as a custom one. */
+export function SearchPicker({
+ value,
+ onChange,
+ options,
+ loading,
+ error,
+ placeholder,
+ searchPlaceholder,
+ ariaLabel,
+ allowNone,
+ noneLabel = 'None',
+ format = sameText,
+ onSearchChange,
+ onOpen,
+}: SearchPickerProps): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const [search, setSearchState] = useState('')
+ const setSearch = (next: string): void => {
+ 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, MAX_OPTIONS), ...custom]
+ }, [search, options, value, allowNone, format])
+
+ const choose = (next: string | null): void => {
+ 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) {
+ onOpen?.()
+ } else {
+ 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>
+ <IconChevronDown />
+ </Button>
+ }
+ />
+ <ComboboxContent anchor={anchorRef} side="bottom" align="start" sideOffset={4} className="w-64">
+ <ComboboxInput placeholder={searchPlaceholder} showTrigger={false} />
+ {error && (
+ <Text size="xs" variant="destructive" role="alert">
+ {error}
+ </Text>
+ )}
+ <ComboboxEmpty>{loading ? 'Loading…' : 'No matches. Type a name to use it anyway.'}</ComboboxEmpty>
+ <ComboboxList className="max-h-72">
+ {(item: string) => {
+ if (item === NONE_VALUE) {
+ return (
+ <ComboboxItem key={item} value={item}>
+ <Text size="xs" variant="muted" render={<span />}>
+ {noneLabel}
+ </Text>
+ </ComboboxItem>
+ )
+ }
+ if (item.startsWith(CUSTOM_PREFIX)) {
+ const raw = item.slice(CUSTOM_PREFIX.length)
+ return (
+ <ComboboxItem key={item} value={item}>
+ <IconBolt 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 ? (
+ <Text
+ size="xs"
+ variant="muted"
+ render={<span />}
+ className="shrink-0 font-mono"
+ translate="no"
+ >
+ {item}
+ </Text>
+ ) : null}
+ </ComboboxItem>
+ )
+ }}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ </div>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/Segmented.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/Segmented.tsx
new file mode 100644
index 000000000000..9a816c90170b
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/Segmented.tsx
@@ -0,0 +1,36 @@
+import { ToggleGroup, ToggleGroupItem } from '@posthog/quill'
+
+import type { InspectorOption } from './OptionSelect'
+
+/** A row of mutually exclusive options, for settings with a few short choices. */
+export function Segmented<T extends string>({
+ value,
+ options,
+ onChange,
+ ariaLabel,
+}: {
+ value: T
+ options: InspectorOption<T>[]
+ onChange: (value: T) => void
+ ariaLabel: string
+}): JSX.Element {
+ return (
+ <ToggleGroup
+ value={[value]}
+ onValueChange={(next: string[]) => {
+ const selected = next[0] as T | undefined
+ if (selected && selected !== value) {
+ onChange(selected)
+ }
+ }}
+ aria-label={ariaLabel}
+ className="flex-wrap"
+ >
+ {options.map((option) => (
+ <ToggleGroupItem key={option.value} value={option.value} size="sm" variant="outline">
+ {option.label}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/SqlField.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/SqlField.tsx
new file mode 100644
index 000000000000..87612d74c0a7
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/SqlField.tsx
@@ -0,0 +1,66 @@
+import { ChangeEvent, KeyboardEvent, useEffect, useState } from 'react'
+
+import { IconPlay } from '@posthog/icons'
+import { Button, Kbd, KbdGroup, Text, Textarea } from '@posthog/quill'
+
+import { SQL_COLUMN_HINTS } from '../../../editing/blockLibrary/blockSql'
+import { InspectorField } from './InspectorField'
+
+/** The HogQL behind a block. It runs on Cmd+Enter or the button, not on every key. */
+export function SqlField({
+ type,
+ sql,
+ onCommit,
+}: {
+ type: string
+ sql: string
+ onCommit: (sql: string) => void
+}): JSX.Element {
+ 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.
+ </>
+ }
+ >
+ <Textarea
+ value={draft}
+ rows={8}
+ aria-label="HogQL"
+ spellCheck={false}
+ className="font-mono"
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => setDraft(event.target.value)}
+ onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && changed) {
+ onCommit(draft)
+ }
+ }}
+ />
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Text size="xs" variant="muted" render={<span />} className="flex items-center gap-1">
+ <KbdGroup>
+ <Kbd>{navigator.platform.toLowerCase().includes('mac') ? '⌘' : 'Ctrl'}</Kbd>
+ <Kbd>↵</Kbd>
+ </KbdGroup>
+ <span>to run</span>
+ </Text>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={!changed}
+ onClick={() => onCommit(draft)}
+ data-attr="canvas-block-sql-run"
+ >
+ <IconPlay />
+ Run query
+ </Button>
+ </div>
+ </InspectorField>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/TitleField.tsx b/products/canvas/frontend/sidePanel/blocks/inspector/TitleField.tsx
new file mode 100644
index 000000000000..790b26e5fb11
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/TitleField.tsx
@@ -0,0 +1,18 @@
+import type { BlockPropsRecord } from '../../../editing/blockLibrary/blockDefinitions'
+import { DraftInput } from './DraftInput'
+import { InspectorField } from './InspectorField'
+import { BlockPropsChange, asString } from './inspectorValues'
+
+/** A block's title. Empty falls back to the block's own default. */
+export function TitleField({ props, onChange }: { props: BlockPropsRecord; onChange: BlockPropsChange }): JSX.Element {
+ 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>
+ )
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/canvasBlockPickersLogic.ts b/products/canvas/frontend/sidePanel/blocks/inspector/canvasBlockPickersLogic.ts
new file mode 100644
index 000000000000..4a85d17004c1
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/canvasBlockPickersLogic.ts
@@ -0,0 +1,189 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { hogql } from '~/queries/utils'
+
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+
+// The same lookups PostHog Desktop's block pickers run: the most common events and property keys, by volume.
+const TOP_EVENTS_HOGQL = hogql`SELECT event, count() AS c FROM events WHERE timestamp > now() - INTERVAL 30 DAY GROUP BY event ORDER BY c DESC LIMIT 300`
+const TOP_EVENT_PROPERTIES_HOGQL = 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`
+const INSIGHT_SEARCH_DEBOUNCE_MS = 250
+const QUERY_TAGS = { productKey: 'canvas', scene: 'Canvas' }
+
+export interface CanvasSavedInsight {
+ shortId: string
+ name: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasBlockPickersLogicValues {
+ currentProjectId: number | null // projectLogic
+ insightSearch: string
+ savedInsights: CanvasSavedInsight[]
+ savedInsightsLoading: boolean
+ topEvents: string[] | null
+ topEventsError: string | null
+ topEventsLoading: boolean
+ topProperties: string[] | null
+ topPropertiesError: string | null
+ topPropertiesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface canvasBlockPickersLogicActions {
+ ensureTopEvents: () => {
+ value: true
+ }
+ ensureTopProperties: () => {
+ value: true
+ }
+ loadSavedInsights: (search: string) => string
+ loadSavedInsightsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSavedInsightsSuccess: (
+ savedInsights: {
+ name: string
+ shortId: string
+ }[],
+ payload?: string
+ ) => {
+ savedInsights: {
+ name: string
+ shortId: string
+ }[]
+ payload?: string
+ }
+ loadTopEvents: () => any
+ loadTopEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTopEventsSuccess: (
+ topEvents: string[],
+ payload?: any
+ ) => {
+ topEvents: string[]
+ payload?: any
+ }
+ loadTopProperties: () => any
+ loadTopPropertiesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTopPropertiesSuccess: (
+ topProperties: string[],
+ payload?: any
+ ) => {
+ topProperties: string[]
+ payload?: any
+ }
+ setInsightSearch: (search: string) => {
+ search: string
+ }
+}
+
+export type canvasBlockPickersLogicType = MakeLogicType<canvasBlockPickersLogicValues, canvasBlockPickersLogicActions>
+
+async function firstColumn(query: ReturnType<typeof hogql>, name: string): Promise<string[]> {
+ const response = await api.queryHogQL<unknown[][]>(query, { ...QUERY_TAGS, name })
+ return (response.results ?? []).map((row) => String(row[0]))
+}
+
+/** The options the block inspector's event, property and insight pickers offer. Shared by every canvas. */
+export const canvasBlockPickersLogic = kea<canvasBlockPickersLogicType>([
+ path(['products', 'canvas', 'frontend', 'sidePanel', 'blocks', 'inspector', 'canvasBlockPickersLogic']),
+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),
+ actions({
+ ensureTopEvents: true,
+ ensureTopProperties: true,
+ setInsightSearch: (search: string) => ({ search }),
+ }),
+ loaders(({ values }) => ({
+ // Null until loaded, so a picker tells "loading" from "no events yet".
+ topEvents: [
+ null as string[] | null,
+ { loadTopEvents: async () => await firstColumn(TOP_EVENTS_HOGQL, 'canvas_block_picker_events') },
+ ],
+ topProperties: [
+ null as string[] | null,
+ {
+ loadTopProperties: async () =>
+ await firstColumn(TOP_EVENT_PROPERTIES_HOGQL, 'canvas_block_picker_properties'),
+ },
+ ],
+ savedInsights: [
+ [] as CanvasSavedInsight[],
+ {
+ loadSavedInsights: async (search: string, breakpoint) => {
+ await breakpoint(INSIGHT_SEARCH_DEBOUNCE_MS)
+ if (!values.currentProjectId) {
+ return []
+ }
+ const response = await insightsList(String(values.currentProjectId), {
+ saved: true,
+ basic: true,
+ limit: 200,
+ ...(search.trim() ? { search: search.trim() } : {}),
+ })
+ breakpoint()
+ return response.results.flatMap((insight) =>
+ insight.short_id
+ ? [
+ {
+ shortId: insight.short_id,
+ name: insight.name?.trim() || insight.derived_name?.trim() || 'Untitled insight',
+ },
+ ]
+ : []
+ )
+ },
+ },
+ ],
+ })),
+ reducers({
+ topEventsError: [
+ null as string | null,
+ { loadTopEvents: () => null, loadTopEventsFailure: (_, { error }) => error },
+ ],
+ topPropertiesError: [
+ null as string | null,
+ { loadTopProperties: () => null, loadTopPropertiesFailure: (_, { error }) => error },
+ ],
+ insightSearch: [
+ '',
+ {
+ setInsightSearch: (_, { search }) => search,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ ensureTopEvents: () => {
+ if (values.topEvents === null && !values.topEventsLoading) {
+ actions.loadTopEvents()
+ }
+ },
+ ensureTopProperties: () => {
+ if (values.topProperties === null && !values.topPropertiesLoading) {
+ actions.loadTopProperties()
+ }
+ },
+ setInsightSearch: ({ search }) => {
+ actions.loadSavedInsights(search)
+ },
+ })),
+])
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/inspectorOptions.ts b/products/canvas/frontend/sidePanel/blocks/inspector/inspectorOptions.ts
new file mode 100644
index 000000000000..1c4a62ecc984
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/inspectorOptions.ts
@@ -0,0 +1,23 @@
+import type { InspectorOption } from './OptionSelect'
+
+export type MathValue = 'total' | 'dau' | 'weekly_active' | 'monthly_active'
+
+export const MATH_OPTIONS: InspectorOption<MathValue>[] = [
+ { value: 'total', label: 'Total count' },
+ { value: 'dau', label: 'Unique users' },
+ { value: 'weekly_active', label: 'Weekly active users' },
+ { value: 'monthly_active', label: 'Monthly active users' },
+]
+
+export const NUMBER_FORMATS: InspectorOption[] = [
+ { value: 'number', label: 'Number' },
+ { value: 'percent', label: 'Percent' },
+ { value: 'currency', label: 'Currency' },
+ { value: 'duration', label: 'Duration' },
+]
+
+export const WIDTHS: InspectorOption[] = [
+ { value: 'normal', label: 'Normal' },
+ { value: 'wide', label: 'Wide' },
+ { value: 'full', label: 'Full' },
+]
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/inspectorValues.ts b/products/canvas/frontend/sidePanel/blocks/inspector/inspectorValues.ts
new file mode 100644
index 000000000000..dcdb3f12f4c2
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/inspectorValues.ts
@@ -0,0 +1,30 @@
+import type { BlockPropValue, BlockPropsRecord } from '../../../editing/blockLibrary/blockDefinitions'
+
+export type BlockPropsChange = (props: BlockPropsRecord) => void
+
+export function asString(value: unknown, fallback = ''): string {
+ return typeof value === 'string' ? value : fallback
+}
+
+export function asStrings(value: unknown, fallback: string[]): string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : fallback
+}
+
+export function asNumber(value: unknown, fallback: number): number {
+ return typeof value === 'number' ? value : fallback
+}
+
+export function asBoolean(value: unknown, fallback: boolean): boolean {
+ return typeof value === 'boolean' ? value : fallback
+}
+
+/** The props an author can change. The block id ties the block to its source, so it never shows. */
+export function editableProps(props: Record<string, unknown>): BlockPropsRecord {
+ const result: BlockPropsRecord = {}
+ for (const [key, value] of Object.entries(props)) {
+ if (key !== 'blockId') {
+ result[key] = value as BlockPropValue
+ }
+ }
+ return result
+}
diff --git a/products/canvas/frontend/sidePanel/blocks/inspector/pickerLabels.ts b/products/canvas/frontend/sidePanel/blocks/inspector/pickerLabels.ts
new file mode 100644
index 000000000000..0102f9ee84ce
--- /dev/null
+++ b/products/canvas/frontend/sidePanel/blocks/inspector/pickerLabels.ts
@@ -0,0 +1,24 @@
+const KNOWN_EVENTS: 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',
+}
+
+/** A readable name for an event: known PostHog events get their label, other `$` events a sentence-case one. */
+export function eventLabel(event: string): string {
+ if (KNOWN_EVENTS[event]) {
+ return KNOWN_EVENTS[event]
+ }
+ if (!event.startsWith('$')) {
+ return event
+ }
+ const words = event.slice(1).replaceAll('_', ' ')
+ return words.charAt(0).toUpperCase() + words.slice(1)
+}
diff --git a/products/canvas/frontend/sidePanel/canvasPanelTabs.ts b/products/canvas/frontend/sidePanel/canvasPanelTabs.ts
index def09961bf2d..6558a082ad68 100644
--- a/products/canvas/frontend/sidePanel/canvasPanelTabs.ts
+++ b/products/canvas/frontend/sidePanel/canvasPanelTabs.ts
@@ -1,11 +1,12 @@
import { SidePanelTab } from '~/types'
// pinned: panel tab keys, sent as the `tab` property of the panel_tab_change action
-export type CanvasPanelTab = 'chat' | 'comments' | 'timeline'
+export type CanvasPanelTab = 'chat' | 'blocks' | 'comments' | 'timeline'
/** The app side panel tab each canvas panel tab shows in. A new tab adds a row here and a case in CanvasSidePanelTabBody. */
export const CANVAS_PANEL_SIDE_PANEL_TABS: Record<CanvasPanelTab, SidePanelTab> = {
chat: SidePanelTab.CanvasChat,
+ blocks: SidePanelTab.CanvasBlocks,
comments: SidePanelTab.CanvasComments,
timeline: SidePanelTab.CanvasTimeline,
}
diff --git a/products/canvas/frontend/sidePanel/canvasSidePanelLogic.ts b/products/canvas/frontend/sidePanel/canvasSidePanelLogic.ts
index 1cc78b6ac80a..2c52a74f4aa5 100644
--- a/products/canvas/frontend/sidePanel/canvasSidePanelLogic.ts
+++ b/products/canvas/frontend/sidePanel/canvasSidePanelLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { sidePanelContextLogic } from '~/layout/navigation-3000/sidepanel/sidePanelContextLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
@@ -13,6 +13,7 @@ export interface canvasSidePanelLogicValues {
sceneSidePanelContext: SidePanelSceneContext // sidePanelContextLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
+ blocksCanvasId: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -31,6 +32,12 @@ export interface canvasSidePanelLogicActions {
canvasId: string
tab: CanvasPanelTab
}
+ setBlocksCanvasId: (canvasId: string | null) => {
+ canvasId: string | null
+ }
+ switchTab: (tab: CanvasPanelTab) => {
+ tab: CanvasPanelTab
+ }
}
export type canvasSidePanelLogicType = MakeLogicType<canvasSidePanelLogicValues, canvasSidePanelLogicActions>
@@ -56,11 +63,34 @@ export const canvasSidePanelLogic = kea<canvasSidePanelLogicType>([
actions({
/** Something asked for a tab, for example a comment anchor clicked in the canvas. */
openTab: (tab: CanvasPanelTab, canvasId: string) => ({ tab, canvasId }),
+ /** Shows a tab without opening a hidden panel, for example the inspector when the author selects a block. */
+ switchTab: (tab: CanvasPanelTab) => ({ tab }),
+ /** The canvas being edited by hand, the only one whose panel has a Blocks tab. */
+ setBlocksCanvasId: (canvasId: string | null) => ({ canvasId }),
+ }),
+ reducers({
+ blocksCanvasId: [
+ null as string | null,
+ {
+ setBlocksCanvasId: (_, { canvasId }) => canvasId,
+ },
+ ],
}),
listeners(({ actions, values }) => ({
openTab: ({ tab }) => {
actions.openSidePanel(CANVAS_PANEL_SIDE_PANEL_TABS[tab])
},
+ switchTab: ({ tab }) => {
+ if (values.sidePanelOpen) {
+ actions.openSidePanel(CANVAS_PANEL_SIDE_PANEL_TABS[tab])
+ }
+ },
+ setBlocksCanvasId: ({ canvasId }) => {
+ // The Blocks tab leaves with edit mode, so a panel showing it moves to the chat.
+ if (!canvasId && values.sidePanelOpen && values.selectedTab === CANVAS_PANEL_SIDE_PANEL_TABS.blocks) {
+ actions.openSidePanel(CANVAS_PANEL_SIDE_PANEL_TABS.chat)
+ }
+ },
[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab }, _, __, previousState) => {
const canvasId = values.sceneSidePanelContext.canvas_id
const next = canvasPanelTab(tab)
diff --git a/products/canvas/package.json b/products/canvas/package.json
index e6e2764c34b0..b5ecac34ae2e 100644
--- a/products/canvas/package.json
+++ b/products/canvas/package.json
@@ -21,6 +21,7 @@
"@posthog/lemon-ui": "*",
"@storybook/react": "catalog:",
"@types/react": "*",
+ "@types/react-dom": "*",
"react": "*",
"react-dom": "*",
"zod": "*"
diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts
index 4df81de1d9a8..c20804d9e834 100644
--- a/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts
@@ -619,7 +619,7 @@ export function installCanvasEditing(
};
const onMove = (event: MouseEvent) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
const pressed = (event.buttons & 1) === 1;
if (forwarding) {
if (!pressed) {
@@ -706,24 +706,32 @@ export function installCanvasEditing(
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 onTextKey = (event: KeyboardEvent) => {
+ if (
+ !event.isTrusted ||
+ !editingText ||
+ event.target !== editingText.element
+ )
+ return;
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ finishText(true);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ finishText(false);
+ }
+ };
+ const onTextBlur = (event: FocusEvent) => {
+ if (event.isTrusted && event.target === editingText?.element)
+ finishText(true);
+ };
+
const onDouble = (event: MouseEvent) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
event.preventDefault();
event.stopPropagation();
const element = candidateOf(event.target as Element);
@@ -731,6 +739,7 @@ export function installCanvasEditing(
};
const onDown = (event: MouseEvent) => {
+ if (!event.isTrusted) return;
forwarding = false;
if (!enabled || event.button !== 0) return;
if (editingText?.element.contains(event.target as Node)) return;
@@ -749,12 +758,13 @@ export function installCanvasEditing(
};
const swallow = (event: Event) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
event.preventDefault();
event.stopPropagation();
};
- const onUp = (_event: MouseEvent) => {
+ const onUp = (event: MouseEvent) => {
+ if (!event.isTrusted) return;
dragOrigin = null;
if (!forwarding) return;
forwarding = false;
@@ -764,7 +774,7 @@ export function installCanvasEditing(
};
const onKey = (event: KeyboardEvent) => {
- if (!enabled) return;
+ if (!enabled || !event.isTrusted) return;
const target = event.target as HTMLElement | null;
if (
target &&
@@ -912,6 +922,8 @@ export function installCanvasEditing(
window.addEventListener("mouseup", onUp, true);
window.addEventListener("click", swallow, true);
window.addEventListener("dblclick", onDouble, true);
+ window.addEventListener("keydown", onTextKey, true);
+ window.addEventListener("blur", onTextBlur, true);
window.addEventListener("keydown", onKey, true);
document.addEventListener("mouseleave", () => {
hovered = null;
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
index 45abf8dbf87d..7768dcf12461 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -228,6 +228,7 @@ export function buildSandboxDocument(
const portOnly = new URLSearchParams(location.hash.slice(1)).get("bridge") === "port";
let bridgePort = null;
let sendToHost = null;
+ let disconnectBridge = null;
const post = (msg) => {
const message = { channel: CHANNEL, ...msg };
if (sendToHost) sendToHost(message);
@@ -745,13 +746,14 @@ export function buildSandboxDocument(
if (e.data?.channel === CHANNEL && e.data.type === "connect" && e.ports[0] && !bridgePort) {
bridgePort = e.ports[0];
sendToHost = bridgePort.postMessage.bind(bridgePort);
+ disconnectBridge = bridgePort.close.bind(bridgePort);
bridgePort.onmessage = (event) => receive(event.data);
post({ type: "ready" });
} else if (!portOnly && !bridgePort) {
receive(e.data);
}
});
- window.addEventListener("pagehide", () => bridgePort?.close());
+ window.addEventListener("pagehide", () => disconnectBridge?.());
post({ type: "ready" });
`;