:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(canvas): let authors open blocks in canvas edit mode (#115543)
Shy Alter7b54bb7fc7b0
diff --git a/products/canvas/backend/sandbox/sandbox_document.html b/products/canvas/backend/sandbox/sandbox_document.htmlindex 8e5a888c136a..25347221b42d 100644--- a/products/canvas/backend/sandbox/sandbox_document.html+++ b/products/canvas/backend/sandbox/sandbox_document.html@@ -807,6 +807,8 @@const selectBox = document.createElement("div");const label = document.createElement("div");const line = document.createElement("div");+ const openBox = document.createElement("div");+ openBox.style.cssText = `position:fixed;left:0;top:0;border:1px dashed rgba(245,78,0,.55);border-radius:12px;opacity:0;transition:opacity 120ms ease;`;hoverBox.style.cssText = `position:fixed;left:0;top:0;border:1px solid rgba(245,78,0,.45);border-radius:8px;opacity:0;transition:opacity 100ms ease;`;selectBox.style.cssText = `position:fixed;left:0;top:0;border:1.5px solid ${PRIMARY};border-radius:10px;opacity:0;box-shadow:0 0 0 3px rgba(245,78,0,.08);transition:opacity 120ms ease;`;label.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};color:#fff;font:600 10.5px/18px system-ui,sans-serif;padding:0 7px;border-radius:5px 5px 0 0;opacity:0;white-space:nowrap;transition:opacity 120ms ease;`;@@ -814,7 +816,7 @@const emptyHint = document.createElement("div");emptyHint.textContent = "Drop blocks here, or click one in the panel";emptyHint.style.cssText = "position:fixed;display:flex;align-items:center;justify-content:center;border:1.5px dashed rgba(128,128,128,.35);border-radius:12px;color:rgba(128,128,128,.95);font:500 13px/1.4 system-ui,sans-serif;opacity:0;transition:opacity 160ms;";- layer.append(emptyHint, hoverBox, selectBox, label, line);+ layer.append(emptyHint, openBox, hoverBox, selectBox, label, line);const parseSource = (element) => {const raw = element.getAttribute("data-ph-src");if (!raw) return null;@@ -827,12 +829,52 @@repeated: flag === "r"};};- let openBlock = null;+ const sourceAt = (key) => document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);+ const sourceKey = (element) => {+ const source = parseSource(element);+ return source ? `${source.file}|${source.start}` : null;+ };+ const openBlocks = new Set();+ const isOpen = (block) => {+ if (block === document.getElementById("root")?.firstElementChild) return true;+ const key = sourceKey(block);+ return !!key && openBlocks.has(key);+ };+ const openAncestor = (element) => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ let current = element?.closest("[data-ph-block]") ?? null;+ while (current && current !== rootElement) {+ if (current instanceof HTMLElement && isOpen(current)) return current;+ current = current.parentElement?.closest("[data-ph-block]") ?? null;+ };+ return null;+ };+ const closeBlock = (block) => {+ for (const key of Array.from(openBlocks)) {+ const element = sourceAt(key);+ if (!element || block.contains(element)) openBlocks.delete(key);+ }+ };+ const openAround = (element) => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ let block = element.parentElement?.closest("[data-ph-block]") ?? null;+ while (block && block !== rootElement) {+ const key = sourceKey(block);+ if (key) openBlocks.add(key);+ block = block.parentElement?.closest("[data-ph-block]") ?? null;+ }+ };+ const closeOutside = (element) => {+ for (const key of Array.from(openBlocks)) {+ const block = sourceAt(key);+ if (!block || !element || !block.contains(element)) openBlocks.delete(key);+ }+ };const candidateOf = (start) => {let element = start;while (element && element !== document.body) {const blockRoot = element.closest("[data-ph-block]");- if (blockRoot instanceof HTMLElement && blockRoot !== openBlock && blockRoot.hasAttribute("data-ph-src")) return blockRoot;+ if (blockRoot instanceof HTMLElement && !isOpen(blockRoot) && blockRoot.hasAttribute("data-ph-src")) return blockRoot;const source = parseSource(element);const rect = element.getBoundingClientRect();if (source && !source.repeated && rect.width >= 24 && rect.height >= 12) {@@ -942,9 +984,11 @@const paint = () => {place(hoverBox, hovered && hovered !== selected ? hovered : null, 3);place(selectBox, selected, 4);+ const parent = openAncestor(selected ?? hovered);+ place(openBox, parent, 8);if (selected?.isConnected) {const rect = selected.getBoundingClientRect();- label.textContent = labelFor(selected);+ label.textContent = parent && parent !== selected ? `${labelFor(parent)} › ${labelFor(selected)}` : labelFor(selected);label.style.transform = `translate3d(${rect.left - 4}px, ${rect.top - 22}px, 0)`;label.style.opacity = "1";} else {@@ -1000,6 +1044,16 @@};return best;};+ const enter = (block, x, y) => {+ const key = sourceKey(block);+ if (!key) return null;+ openBlocks.add(key);+ let inner = candidateOf(document.elementFromPoint(x, y));+ if (!inner || inner === block || !block.contains(inner)) inner = nearestChild(block, x, y);+ if (inner && inner !== block && block.contains(inner)) return inner;+ openBlocks.delete(key);+ return null;+ };const isBox = (element) => {const style = getComputedStyle(element);const bordered = Number.parseFloat(style.borderTopWidth) > 0 && Number.parseFloat(style.borderBottomWidth) > 0;@@ -1033,7 +1087,7 @@const layout = getComputedStyle(target).display;const arrangesChildren = layout.includes("grid") || layout.includes("flex") || rect.height > 160;const atomic = coarse && target !== root && isBox(target);- const isContainer = target === root || !atomic && target.children.length > 1 && !target.hasAttribute("data-ph-block") && arrangesChildren;+ const isContainer = target === root || !atomic && target.children.length > 1 && (!target.hasAttribute("data-ph-block") || isOpen(target)) && arrangesChildren;if (isContainer) {const child = nearestChild(target, x, y);if (child) target = child;@@ -1083,15 +1137,6 @@indicator};};- const dropTarget = (x, y, exclude, coarse) => {- const rootElement = document.getElementById("root")?.firstElementChild;- openBlock = rootElement?.hasAttribute("data-ph-block") ? rootElement : null;- try {- return findDropTarget(x, y, exclude, coarse);- } finally {- openBlock = null;- }- };const showLine = (indicator) => {if (!indicator) {line.style.opacity = "0";@@ -1227,7 +1272,13 @@event.preventDefault();event.stopPropagation();const element = candidateOf(event.target);- if (element && element !== editingText?.element) startText(element);+ if (!element || element === editingText?.element) return;+ if (element.hasAttribute("data-ph-block") && !isOpen(element)) {+ const inner = enter(element, event.clientX, event.clientY);+ if (inner) select(inner);+ return;+ };+ startText(element);};const onDown = (event) => {if (!event.isTrusted) return;@@ -1237,6 +1288,7 @@const element = candidateOf(event.target);event.preventDefault();event.stopPropagation();+ closeOutside(element);if (!element) {select(null);return;@@ -1261,14 +1313,37 @@forwarding = false;post({ type: "canvas-edit-pointer-up" });};+ const climb = () => {+ const parent = openAncestor(selected);+ if (!parent) return false;+ closeBlock(parent);+ select(parent);+ return true;+ };+ const descend = () => {+ if (!selected?.hasAttribute("data-ph-block") || isOpen(selected)) return false;+ const box = selected.getBoundingClientRect();+ const inner = enter(selected, box.left + 1, box.top + 1);+ if (!inner) return false;+ select(inner);+ return true;+ };const onKey = (event) => {- if (!enabled || !event.isTrusted) return;+ if (!enabled || !event.isTrusted || event.defaultPrevented) return;const target = event.target;if (target && (target.isContentEditable || ["INPUT","TEXTAREA","SELECT"].includes(target.tagName))) return;+ if (event.key === "Enter") {+ if (event.shiftKey ? climb() : descend()) event.preventDefault();+ return;+ };+ if (event.key === "Escape" && climb()) {+ event.preventDefault();+ return;+ };if (["Backspace","Delete",@@ -1346,13 +1421,16 @@end: rootSource.end} : null});+ for (const key of Array.from(openBlocks)) {+ if (!sourceAt(key)?.hasAttribute("data-ph-block")) openBlocks.delete(key);+ };const id = focusBlockId ?? selectedBlockId;- const sourceAt = (key) => document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);const previous = selectedSource ? sourceAt(selectedSource.key) : null;const sameBlock = previous?.getAttribute("data-ph-block") === selectedSource?.block;const bySource = focusSource ? sourceAt(focusSource) : sameBlock ? previous : null;const element = id ? document.querySelector(`[data-ph-block-id="${CSS.escape(id)}"]`) : bySource;if (element instanceof HTMLElement) {+ openAround(element);remember(element);post({type: "canvas-edit-select",@@ -1380,6 +1458,7 @@cancelAnimationFrame(frame);selected = null;hovered = null;+ openBlocks.clear();}};window.addEventListener("mousemove", onMove, true);@@ -1399,7 +1478,7 @@afterMount,handle(message) {if (message.type === "canvas-edit-drag-move") {- const hit = enabled ? dropTarget(Number(message.x), Number(message.y), message.exclude ?? null, message.coarse === true) : null;+ const hit = enabled ? findDropTarget(Number(message.x), Number(message.y), message.exclude ?? null, message.coarse === true) : null;showLine(hit?.indicator ?? null);post({type: "canvas-edit-drop-target",@@ -1423,6 +1502,22 @@remember(null);return true;};+ if (message.type === "canvas-edit-escape") {+ if (enabled && climb()) return true;+ remember(null);+ post({+ type: "canvas-edit-select",+ element: null+ });+ return true;+ };+ if (message.type === "canvas-edit-enter") {+ if (enabled) {+ if (message.shiftKey === true) climb();+ else descend();+ };+ return true;+ };return false;}};diff --git a/products/canvas/frontend/editing/CanvasSourceEditor.tsx b/products/canvas/frontend/editing/CanvasSourceEditor.tsxindex b2fd2af6c2d1..da93a2ed6067 100644--- a/products/canvas/frontend/editing/CanvasSourceEditor.tsx+++ b/products/canvas/frontend/editing/CanvasSourceEditor.tsx@@ -87,11 +87,15 @@ export function CanvasSourceEditor({if (drag) {drag.end(false)} else {- select(null)- postToCanvasEditor({ type: 'canvas-edit-deselect' })+ postToCanvasEditor({ type: 'canvas-edit-escape' })}return}+ if (key.key === 'Enter') {+ prevent?.()+ postToCanvasEditor({ type: 'canvas-edit-enter', shiftKey: key.shiftKey })+ return+ }if ((mod && ['z', 'd'].includes(key.key.toLowerCase())) || key.key === 'Backspace' || key.key === 'Delete') {prevent?.()editKey(key)diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 5a54e61a880d..187549bacbc2 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -79,6 +79,21 @@ Expose the values a person may want to change as params. They can then change thParams are optional, but add them to each panel, card, or tool that has values worth changing: titles, copy, events, properties, thresholds, limits, colors.Params need React components. A plain HTML canvas has no params.+### How the editor uses `editable()`++In the desktop editor, a person can select any element of the canvas: a heading, a paragraph, a section. They can move, duplicate, or delete it, and double-click text to change it. This works with no `editable()` call.++`editable()` makes a component one block. The editor then treats the block as one unit:++- A click selects the full block, not the element inside it.+- Move, duplicate, and delete act on the full block.+- The side panel shows the block's params as fields. A change writes the new value into the block's props in the source.+- To reach the elements inside a block, the person double-clicks the block to open it.++So use `editable()` on the parts a person thinks of as one thing and configures as one thing: a card, a chart, a table, a form. Keep the page layout around them as plain JSX. The person can then select a card as a block, and still select a page heading or section directly. If the component that holds the full page uses `editable()`, the full page becomes one block, and each click selects all of it.++### Adding params+1. Put each panel in its own component. The component takes these values as props, with defaults.2. Spread `editable(name, props, params)` from `@posthog/canvas-sdk` on the root element of the component. `name` is the component name. `params` maps each prop name to its field.3. Use the component with literal props, for example `<SignupFunnel blockId="b-k3m9x2" title="Signup" windowDays={14} />`. The editor writes changes into these props, so do not compute them inline.diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsx b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsxindex db7c3e9cf449..3cbacec77ab8 100644--- a/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsx+++ b/products/desktop/packages/ui/src/features/canvas/blocks/CanvasSourceEditor.tsx@@ -262,10 +262,15 @@ function handleKey(if (key === "Escape") {const drag = activeSourceDrag();if (drag) drag.end(false);- else {- actions.select(null);- postToCanvasEditor({ type: "canvas-edit-deselect" });- }+ else postToCanvasEditor({ type: "canvas-edit-escape" });+ return;+ }+ if (key === "Enter") {+ prevent?.();+ postToCanvasEditor({+ type: "canvas-edit-enter",+ shiftKey: data.shiftKey === true,+ });return;}if (mod && key.toLowerCase() === "z") {diff --git a/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.tsindex c20804d9e834..9780249e536b 100644--- a/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/blocks/canvasEditRuntime.ts@@ -213,6 +213,8 @@ export function installCanvasEditing(const selectBox = document.createElement("div");const label = document.createElement("div");const line = document.createElement("div");+ const openBox = document.createElement("div");+ openBox.style.cssText = `position:fixed;left:0;top:0;border:1px dashed rgba(245,78,0,.55);border-radius:12px;opacity:0;transition:opacity 120ms ease;`;hoverBox.style.cssText = `position:fixed;left:0;top:0;border:1px solid rgba(245,78,0,.45);border-radius:8px;opacity:0;transition:opacity 100ms ease;`;selectBox.style.cssText = `position:fixed;left:0;top:0;border:1.5px solid ${PRIMARY};border-radius:10px;opacity:0;box-shadow:0 0 0 3px rgba(245,78,0,.08);transition:opacity 120ms ease;`;label.style.cssText = `position:fixed;left:0;top:0;background:${PRIMARY};color:#fff;font:600 10.5px/18px system-ui,sans-serif;padding:0 7px;border-radius:5px 5px 0 0;opacity:0;white-space:nowrap;transition:opacity 120ms ease;`;@@ -221,7 +223,7 @@ export function installCanvasEditing(emptyHint.textContent = "Drop blocks here, or click one in the panel";emptyHint.style.cssText ="position:fixed;display:flex;align-items:center;justify-content:center;border:1.5px dashed rgba(128,128,128,.35);border-radius:12px;color:rgba(128,128,128,.95);font:500 13px/1.4 system-ui,sans-serif;opacity:0;transition:opacity 160ms;";- layer.append(emptyHint, hoverBox, selectBox, label, line);+ layer.append(emptyHint, openBox, hoverBox, selectBox, label, line);const parseSource = (element: Element) => {const raw = element.getAttribute("data-ph-src");@@ -236,7 +238,57 @@ export function installCanvasEditing(};};- let openBlock: Element | null = null;+ const sourceAt = (key: string) =>+ document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);++ const sourceKey = (element: Element) => {+ const source = parseSource(element);+ return source ? `${source.file}|${source.start}` : null;+ };++ const openBlocks = new Set<string>();++ const isOpen = (block: Element) => {+ if (block === document.getElementById("root")?.firstElementChild)+ return true;+ const key = sourceKey(block);+ return !!key && openBlocks.has(key);+ };++ const openAncestor = (element: Element | null): HTMLElement | null => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ let current = element?.closest("[data-ph-block]") ?? null;+ while (current && current !== rootElement) {+ if (current instanceof HTMLElement && isOpen(current)) return current;+ current = current.parentElement?.closest("[data-ph-block]") ?? null;+ }+ return null;+ };++ const closeBlock = (block: Element) => {+ for (const key of Array.from(openBlocks)) {+ const element = sourceAt(key);+ if (!element || block.contains(element)) openBlocks.delete(key);+ }+ };++ const openAround = (element: Element) => {+ const rootElement = document.getElementById("root")?.firstElementChild;+ let block = element.parentElement?.closest("[data-ph-block]") ?? null;+ while (block && block !== rootElement) {+ const key = sourceKey(block);+ if (key) openBlocks.add(key);+ block = block.parentElement?.closest("[data-ph-block]") ?? null;+ }+ };++ const closeOutside = (element: Element | null) => {+ for (const key of Array.from(openBlocks)) {+ const block = sourceAt(key);+ if (!block || !element || !block.contains(element))+ openBlocks.delete(key);+ }+ };const candidateOf = (start: Element | null): HTMLElement | null => {let element: Element | null = start;@@ -244,7 +296,7 @@ export function installCanvasEditing(const blockRoot = element.closest("[data-ph-block]");if (blockRoot instanceof HTMLElement &&- blockRoot !== openBlock &&+ !isOpen(blockRoot) &&blockRoot.hasAttribute("data-ph-src"))return blockRoot;@@ -373,9 +425,14 @@ export function installCanvasEditing(const paint = () => {place(hoverBox, hovered && hovered !== selected ? hovered : null, 3);place(selectBox, selected, 4);+ const parent = openAncestor(selected ?? hovered);+ place(openBox, parent, 8);if (selected?.isConnected) {const rect = selected.getBoundingClientRect();- label.textContent = labelFor(selected);+ label.textContent =+ parent && parent !== selected+ ? `${labelFor(parent)} › ${labelFor(selected)}`+ : labelFor(selected);label.style.transform = `translate3d(${rect.left - 4}px, ${rect.top - 22}px, 0)`;label.style.opacity = "1";} else {@@ -452,6 +509,18 @@ export function installCanvasEditing(return best;};+ const enter = (block: HTMLElement, x: number, y: number) => {+ const key = sourceKey(block);+ if (!key) return null;+ openBlocks.add(key);+ let inner = candidateOf(document.elementFromPoint(x, y));+ if (!inner || inner === block || !block.contains(inner))+ inner = nearestChild(block, x, y);+ if (inner && inner !== block && block.contains(inner)) return inner;+ openBlocks.delete(key);+ return null;+ };+const isBox = (element: HTMLElement) => {const style = getComputedStyle(element);const bordered =@@ -506,7 +575,7 @@ export function installCanvasEditing(target === root ||(!atomic &&target.children.length > 1 &&- !target.hasAttribute("data-ph-block") &&+ (!target.hasAttribute("data-ph-block") || isOpen(target)) &&arrangesChildren);if (isContainer) {const child = nearestChild(target, x, y);@@ -570,21 +639,6 @@ export function installCanvasEditing(};};- const dropTarget = (- x: number,- y: number,- exclude: string | null,- coarse: boolean,- ) => {- const rootElement = document.getElementById("root")?.firstElementChild;- openBlock = rootElement?.hasAttribute("data-ph-block") ? rootElement : null;- try {- return findDropTarget(x, y, exclude, coarse);- } finally {- openBlock = null;- }- };-const showLine = (indicator: {left: number;@@ -735,7 +789,13 @@ export function installCanvasEditing(event.preventDefault();event.stopPropagation();const element = candidateOf(event.target as Element);- if (element && element !== editingText?.element) startText(element);+ if (!element || element === editingText?.element) return;+ if (element.hasAttribute("data-ph-block") && !isOpen(element)) {+ const inner = enter(element, event.clientX, event.clientY);+ if (inner) select(inner);+ return;+ }+ startText(element);};const onDown = (event: MouseEvent) => {@@ -746,6 +806,7 @@ export function installCanvasEditing(const element = candidateOf(event.target as Element);event.preventDefault();event.stopPropagation();+ closeOutside(element);if (!element) {select(null);return;@@ -773,8 +834,26 @@ export function installCanvasEditing(});};+ const climb = () => {+ const parent = openAncestor(selected);+ if (!parent) return false;+ closeBlock(parent);+ select(parent);+ return true;+ };++ const descend = () => {+ if (!selected?.hasAttribute("data-ph-block") || isOpen(selected))+ return false;+ const box = selected.getBoundingClientRect();+ const inner = enter(selected, box.left + 1, box.top + 1);+ if (!inner) return false;+ select(inner);+ return true;+ };+const onKey = (event: KeyboardEvent) => {- if (!enabled || !event.isTrusted) return;+ if (!enabled || !event.isTrusted || event.defaultPrevented) return;const target = event.target as HTMLElement | null;if (target &&@@ -782,6 +861,14 @@ export function installCanvasEditing(["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)))return;+ if (event.key === "Enter") {+ if (event.shiftKey ? climb() : descend()) event.preventDefault();+ return;+ }+ if (event.key === "Escape" && climb()) {+ event.preventDefault();+ return;+ }if (["Backspace", "Delete", "Escape"].includes(event.key) ||((event.metaKey || event.ctrlKey) &&@@ -876,9 +963,10 @@ export function installCanvasEditing(}: null,});+ for (const key of Array.from(openBlocks)) {+ if (!sourceAt(key)?.hasAttribute("data-ph-block")) openBlocks.delete(key);+ }const id = focusBlockId ?? selectedBlockId;- const sourceAt = (key: string) =>- document.querySelector(`[data-ph-src^="${CSS.escape(`${key}|`)}"]`);const previous = selectedSource ? sourceAt(selectedSource.key) : null;const sameBlock =previous?.getAttribute("data-ph-block") === selectedSource?.block;@@ -891,6 +979,7 @@ export function installCanvasEditing(? document.querySelector(`[data-ph-block-id="${CSS.escape(id)}"]`): bySource;if (element instanceof HTMLElement) {+ openAround(element);remember(element);post({ type: "canvas-edit-select", element: describe(element) });const arrived =@@ -914,6 +1003,7 @@ export function installCanvasEditing(cancelAnimationFrame(frame);selected = null;hovered = null;+ openBlocks.clear();}};@@ -936,7 +1026,7 @@ export function installCanvasEditing(handle(message: Record<string, unknown>) {if (message.type === "canvas-edit-drag-move") {const hit = enabled- ? dropTarget(+ ? findDropTarget(Number(message.x),Number(message.y),(message.exclude as string | null) ?? null,@@ -963,6 +1053,19 @@ export function installCanvasEditing(remember(null);return true;}+ if (message.type === "canvas-edit-escape") {+ if (enabled && climb()) return true;+ remember(null);+ post({ type: "canvas-edit-select", element: null });+ return true;+ }+ if (message.type === "canvas-edit-enter") {+ if (enabled) {+ if (message.shiftKey === true) climb();+ else descend();+ }+ return true;+ }return false;},};