AI-native design editor. Open-source Figma alternative.
feat(code): link the Code tab to canvas layers and sync both ways (#805)
Danila Poyarkov6a3960a5d444
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a341cb65..0697a7818 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@### Added- Check designs from the new Lint tab in the right panel: issues on the page, in the selection, or across the document are grouped by rule, hovering one highlights its layer on the canvas, clicking selects it and brings it into view, and one-click fixes bind colors to the variable they match and round subpixel geometry for a row or a whole group, and snap radius, spacing, and small text to the scale one row at a time. Rules can be turned off individually or switched between the Recommended, Strict, and Accessibility presets.+- See which layer the code is about in the Code tab's Design JSX and Tailwind JSX: the element around the cursor marks its opening and closing tag and shows its layer on the canvas as a tinted box, apart from canvas hover, and design issues are underlined on the property that causes them, including while you edit Design JSX live.- Fix lint issues outside the app: `openpencil lint --fix -o fixed.fig` binds colors to the variable they match and rounds subpixel geometry, and the `lint` and `lint_fix` tools let MCP clients and AI chat check a page and apply those fixes, plus radius, spacing, and text size suggestions on request. Lint messages carry each fix as data in `fix` and `suggestions`.- Mark layers with errors and warnings on the canvas while you work, and pin those outside the view to the canvas edge in their direction, with matching marks in the Layers panel and error and warning counts in the page list; hover a marker or pin for its issues or click it to open them in Lint, and turn markers on or off with View → Design issues.- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. A frame in their color and a “Following …” bar show whom you follow; Escape, clicking, scrolling, zooming, or switching pages stops it. Your own avatar renames your agents and leaves the room.@@ -41,6 +42,7 @@### Changed+- With nothing selected, the Code tab explains that it shows the selection's code and offers Write JSX for new layers, instead of showing a template frame that looked like a real layer.- Design lint reports far fewer false positives in `openpencil lint` and the app: `no-hardcoded-colors` flags only colors that match a color variable and names it, `no-deeply-nested` flags only the layer that crosses the depth limit, `touch-target-size` checks the WCAG 2.2 AA minimum of 24 × 24 in the Recommended preset (Strict and Accessibility keep 44 × 44), matches control names as whole words (a layer named "Rectangle" is no longer a call to action) and ignores icons and controls inside other controls, `consistent-spacing` accepts multiples of 4, `color-contrast` checks text bound to color variables, and layers inside instances are checked once through their main component. The Recommended preset reports unbound colors, deep nesting, mixed text styles, and off-scale spacing as suggestions instead of warnings. Lint messages carry the measured values in `data`.- Keep the Share button labeled Share while you are in a room, instead of turning it into a Connected status; a green dot on your avatar shows the room is live.- Show Flatten, Outline text, and Outline stroke in the canvas context menu without icons, like every other item there.@@ -77,6 +79,7 @@- Reject malformed effects assigned to `node.effects` in the plugin API with an error naming the invalid field, as Figma does, instead of storing them. `node.effects` now reads back in Figma's shape: layer blurs are `LAYER_BLUR` with `blurType`, and blurs no longer carry shadow fields (#786).- Render fragments (`<>…</>`) nested inside other elements in JSX from the AI and MCP `render` tool, which previously failed with `Unknown element: <>`.- Judge text contrast in the AI and MCP `describe` tool by its WCAG 2 ratio (4.5:1, or 3:1 for large text), the same ratio the `color-contrast` lint rule computes. It no longer reports passing dark text on mid-tone backgrounds as "dark on dark", now reports low-contrast light text, measures translucent and faded text as it is drawn, skips text whose color is bound to a variable, and says the ratio and the threshold it missed (#735).+- Keep the Code tab and the canvas in sync while you edit Design JSX. Canvas edits patch only the values, text, layers, and layer order that changed, under the property names you wrote (such as `width` for `w`), keeping your comments, formatting, and expressions; an expression or loop the canvas has changed is marked instead of overwritten. Code edits update the existing layers instead of recreating them, and each edit is one undo step. Before, canvas changes did not reach edited code until the tab was reopened.- Warn about options the paint and effect helpers ignore when rendering JSX instead of dropping them silently, and point `blur` in effect helpers at `radius`, the name Figma uses (#736).- Size groups and boolean operations made through the AI and MCP `group_nodes` and `boolean_*` tools to what they contain, as the editor's commands already do, instead of a default 100 × 100 box or the first operand's box (#738).- Keep a layer where it is drawn when it moves into or out of a rotated or flipped parent, instead of shifting it and leaving it at its old angle (#737).diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex d3cdc79a1..cf06eed8a 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -9,6 +9,7 @@ import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import {HANDLE_HALF_SIZE,ROTATION_HANDLE_DISTANCE,+ CODE_FOCUS_FILL_ALPHA,SELECTION_DASH_ALPHA,SECTION_HOVER_STROKE_WIDTH} from '#core/constants'@@ -40,6 +41,33 @@ export function drawHoverHighlight(canvas.restore()}+/**+ * The layer of the code element around the cursor: the hover outline over a light tint, so it+ * reads apart from canvas hover (outline only) and selection (outline and handles).+ */+export function drawCodeFocus(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ nodeId?: string | null,+ preview?: RotationPreview | null+): void {+ const node = nodeId ? graph.getNode(nodeId) : undefined+ if (!node) return+ const component = r.isComponentType(node.type)+ r.auxFill.setColor(+ component ? r.compColor(CODE_FOCUS_FILL_ALPHA) : r.selColor(CODE_FOCUS_FILL_ALPHA)+ )+ r.auxStroke.setStrokeWidth(1 / r.zoom)+ r.auxStroke.setColor(component ? r.compColor() : r.selColor())+ r.auxStroke.setPathEffect(null)+ canvas.save()+ canvas.concat(createSceneGeometry(graph, preview).screenMatrix(node, r))+ r.strokeNodeShape(canvas, node, r.auxFill)+ r.strokeNodeShape(canvas, node, r.auxStroke)+ canvas.restore()+}+export function drawEnteredContainer(r: SkiaRenderer,canvas: Canvas,diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.tsindex 5fdb3f585..1821874f2 100644--- a/packages/core/src/canvas/renderer/overlay-pass.ts+++ b/packages/core/src/canvas/renderer/overlay-pass.ts@@ -6,6 +6,7 @@ import { drawGuides } from '#core/canvas/guides/draw'import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'import { layoutIssueMarkers } from '#core/canvas/issues/layout'import { drawMeasurementSegment } from '#core/canvas/overlays/measurement'+import { drawCodeFocus } from '#core/canvas/overlays/selection'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import { RULER_SIZE } from '#core/constants'@@ -89,6 +90,7 @@ export function drawOverlayPass(measuring || overlays.hoveredNodeId === overlays.nodeEditState?.nodeId? null: overlays.hoveredNodeId+ drawCodeFocus(r, canvas, graph, overlays.codeFocusNodeId, overlays.rotationPreview)r.drawHoverHighlight(canvas, graph, hoveredNodeId, overlays.rotationPreview)drawIssueHighlight(r, canvas, graph, overlays.designIssues?.highlight, overlays.rotationPreview)r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId, overlays.rotationPreview)diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex d17272f10..e3abd0a49 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -80,6 +80,7 @@ export function renderFromEditorState(nodeEditState: state.nodeEditState ?? null,presenceCursors: state.presenceCursors,designIssues: state.designIssues,+ codeFocusNodeId: state.codeFocusNodeId,autoLayoutHover: state.autoLayoutHover},state.sceneVersion,diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex f92395c3d..80dcb6de2 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -81,4 +81,5 @@ export interface RenderOverlays {} | nullpresenceCursors?: PresenceCursor[]designIssues?: DesignIssueOverlay | null+ codeFocusNodeId?: string | null}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex d40a06c36..b56ded112 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -84,6 +84,8 @@ export const SIZE_PILL_TEXT_OFFSET_Y = 13export const MARQUEE_FILL_ALPHA = 0.08export const SELECTION_DASH_ALPHA = 0.6+/** Tint inside the layer of the code element around the cursor, under its hover outline. */+export const CODE_FOCUS_FILL_ALPHA = 0.1export const DROP_HIGHLIGHT_ALPHA = 0.8export const DROP_HIGHLIGHT_STROKE = 2diff --git a/packages/core/src/editor/selection/overlays.ts b/packages/core/src/editor/selection/overlays.tsindex 1c3f6fd21..88a1c2de1 100644--- a/packages/core/src/editor/selection/overlays.ts+++ b/packages/core/src/editor/selection/overlays.ts@@ -51,6 +51,13 @@ export function createSelectionOverlayActions(ctx: EditorContext) {ctx.requestRepaint()}+ /** Marks the layer of the code element around the cursor, separately from canvas hover. */+ function setCodeFocusNode(id: string | null) {+ if (ctx.state.codeFocusNodeId === id) return+ ctx.state.codeFocusNodeId = id+ ctx.requestRepaint()+ }+function setMeasurementMode(mode: typeof ctx.state.measurementMode) {if (ctx.state.measurementMode === mode) returnctx.state.measurementMode = mode@@ -92,6 +99,7 @@ export function createSelectionOverlayActions(ctx: EditorContext) {setSelectedGuide,setRotationPreview,setHoveredNode,+ setCodeFocusNode,setMeasurementMode,setDropTarget,setLayoutInsertIndicator,diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.tsindex 443885c98..acf136acc 100644--- a/packages/core/src/editor/state/shared.ts+++ b/packages/core/src/editor/state/shared.ts@@ -8,6 +8,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {presenceCursors: [],documentName: 'Untitled',designIssues: null,+ codeFocusNodeId: null,rulerTheme: undefined,sceneVersion: 0}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 392e33ecc..3bcaf67fb 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -42,6 +42,8 @@ export interface EditorSharedState {documentName: string/** Design check markers and highlight, shared by every canvas pane. */designIssues: DesignIssueOverlay | null+ /** The layer of the code element around the cursor in a code editor, shown in every pane. */+ codeFocusNodeId: string | nullrulerTheme?: RulerThemesceneVersion: number}diff --git a/packages/core/src/editor/viewport.ts b/packages/core/src/editor/viewport.tsindex c99ab8496..2e25dd6f6 100644--- a/packages/core/src/editor/viewport.ts+++ b/packages/core/src/editor/viewport.ts@@ -1,3 +1,4 @@+import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'import { computeBounds, computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'@@ -5,6 +6,9 @@ import { emitNavigationTrace } from '#core/profiler'import type { EditorContext } from './types'+/** Space kept between revealed layers and the viewport edge. */+const REVEAL_MARGIN = 48+export function createViewportActions(ctx: EditorContext) {function currentViewport() {return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }@@ -128,7 +132,34 @@ export function createViewportActions(ctx: EditorContext) {zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)}+ /**+ * Brings layers into view: pans to center them when they fit at the current zoom and are not+ * already visible, and zooms out to fit them only when they do not fit.+ */+ function revealNodes(nodeIds: readonly string[], margin = REVEAL_MARGIN) {+ const nodes = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node !== undefined)+ if (nodes.length === 0) return+ const bounds = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))+ const { width, height } = ctx.getViewportSize()+ const { zoom, panX, panY } = ctx.state+ const fits =+ bounds.width * zoom <= width - margin * 2 && bounds.height * zoom <= height - margin * 2+ if (!fits) {+ zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)+ return+ }+ const left = bounds.x * zoom + panX+ const top = bounds.y * zoom + panY+ const right = left + bounds.width * zoom+ const bottom = top + bounds.height * zoom+ const visible =+ left >= margin && top >= margin && right <= width - margin && bottom <= height - margin+ if (visible) return+ pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)+ }+return {+ revealNodes,screenToCanvas,setZoomAroundPoint,applyZoom,diff --git a/packages/core/tests/design-jsx/renderer.test.ts b/packages/core/tests/design-jsx/renderer.test.tsnew file mode 100644index 000000000..38fc18bb3--- /dev/null+++ b/packages/core/tests/design-jsx/renderer.test.ts@@ -0,0 +1,24 @@+import { describe, expect, test } from 'bun:test'++import { renderTree } from '@open-pencil/core/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('renderTree onNode', () => {+ test('reports every element with the layer rendered from it', async () => {+ const graph = new SceneGraph()+ const text: TreeNode = { type: 'text', props: { name: 'Title' }, children: ['Hi'], source: { line: 2 } }+ const root: TreeNode = { type: 'frame', props: { name: 'Card' }, children: [text], source: { line: 1 } }+ const seen: Array<[number | undefined, string]> = []++ const result = await renderTree(graph, root, {+ onNode: (tree, node) => seen.push([tree.source?.line, node.name])+ })++ expect(seen).toEqual([+ [2, 'Title'],+ [1, 'Card']+ ])+ expect(graph.getNode(result.id)?.name).toBe('Card')+ })+})diff --git a/packages/core/tests/editor/reveal.test.ts b/packages/core/tests/editor/reveal.test.tsnew file mode 100644index 000000000..a1270e0ea--- /dev/null+++ b/packages/core/tests/editor/reveal.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++function setup() {+ const editor = createEditor({ getViewportSize: () => ({ width: 800, height: 600 }) })+ const pageId = editor.state.currentPageId+ return { editor, pageId }+}++describe('revealNodes', () => {+ test('leaves the viewport alone when the layers are already in view', () => {+ const { editor, pageId } = setup()+ const card = editor.graph.createNode('FRAME', pageId, { x: 100, y: 100, width: 200, height: 100 })++ editor.revealNodes([card.id])++ expect([editor.state.panX, editor.state.panY, editor.state.zoom]).toEqual([0, 0, 1])+ })++ test('centers off-screen layers that fit without changing zoom', () => {+ const { editor, pageId } = setup()+ const card = editor.graph.createNode('FRAME', pageId, { x: 2000, y: 1000, width: 200, height: 100 })++ editor.revealNodes([card.id])++ expect(editor.state.zoom).toBe(1)+ expect(2100 + editor.state.panX).toBe(400)+ expect(1050 + editor.state.panY).toBe(300)+ })++ test('zooms out only when the layers do not fit', () => {+ const { editor, pageId } = setup()+ const wide = editor.graph.createNode('FRAME', pageId, { x: 0, y: 0, width: 3000, height: 100 })++ editor.revealNodes([wide.id])++ expect(editor.state.zoom).toBeLessThan(1)+ expect(3000 * editor.state.zoom).toBeLessThanOrEqual(800)+ })+})diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex 14dc867fb..3eff40786 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -18,9 +18,22 @@ function propAttribute([name, value]: JSXProp): SyntaxNode {return jsx.attribute(name, propValue(value))}-function nodeToJSX(node: SceneNode, graph: SceneGraph, depth: number): SyntaxNode | null {+/** Design JSX with the layer behind each element, in the order elements open. */+export interface DesignJSXWithLayers {+ code: string+ /** One id per JSX element, in pre-order, so editors can link elements to layers. */+ layerIds: string[]+}++function nodeToJSX(+ node: SceneNode,+ graph: SceneGraph,+ depth: number,+ layerIds?: string[]+): SyntaxNode | null {const tag = NODE_TYPE_TO_TAG[node.type]if (!tag) return null+ layerIds?.push(node.id)const attributes = collectProps(node, graph).map(propAttribute)if (node.type === 'TEXT') {return jsx.element(tag, attributes, node.text ? [jsx.text(node.text)] : [], depth, true)@@ -28,7 +41,7 @@ function nodeToJSX(node: SceneNode, graph: SceneGraph, depth: number): SyntaxNod// Hidden children export with `visible={false}` rather than disappearing.const children = graph.getChildren(node.id)- .flatMap((child) => nodeToJSX(child, graph, depth + 1) ?? [])+ .flatMap((child) => nodeToJSX(child, graph, depth + 1, layerIds) ?? [])return jsx.element(tag, attributes, children, depth)}@@ -61,6 +74,43 @@ export function sceneNodeAttributes(}))}+/**+ * One layer as Design JSX writes it, so an editor can patch the code a person has edited+ * instead of writing it again.+ */+export interface DesignJSXElement {+ tag: string+ /** Each attribute as `sceneNodeAttributes` prints it, keyed by name: `w={320}`. */+ attributes: Record<string, string>+ /** Text content of a text layer as JSX writes it, else `null`. */+ text: string | null+ /** The layers written as child elements, in order. */+ childIds: string[]+}++export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElement | null {+ const node = graph.getNode(nodeId)+ const tag = node && NODE_TYPE_TO_TAG[node.type]+ const printed = sceneNodeAttributes(nodeId, graph)+ if (!node || !tag || !printed) return null+ // A text layer's content is written as its children, not as the `text` attribute.+ const isText = node.type === 'TEXT'+ const attributes = Object.fromEntries(+ printed+ .filter(({ name }) => !isText || name !== 'text')+ .map(({ name, source }) => [name, source])+ )+ if (isText) {+ const text = node.text ? jsx.printJSX(jsx.text(node.text)) : null+ return { tag, attributes, text, childIds: [] }+ }+ const childIds = graph+ .getChildren(node.id)+ .filter((child) => NODE_TYPE_TO_TAG[child.type])+ .map((child) => child.id)+ return { tag, attributes, text: null, childIds }+}+export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {const node = graph.getNode(nodeId)const syntax = node ? nodeToJSX(node, graph, 0) : null@@ -68,8 +118,21 @@ export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {}export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {- return nodeIds- .map((id) => sceneNodeToJSX(id, graph))+ return selectionToJSXWithLayers(nodeIds, graph).code+}++export function selectionToJSXWithLayers(+ nodeIds: string[],+ graph: SceneGraph+): DesignJSXWithLayers {+ const layerIds: string[] = []+ const code = nodeIds+ .map((id) => {+ const node = graph.getNode(id)+ const syntax = node ? nodeToJSX(node, graph, 0, layerIds) : null+ return syntax ? jsx.printJSX(syntax) : ''+ }).filter(Boolean).join('\n\n')+ return { code, layerIds }}diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex d9c94906f..6f1d80957 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -70,20 +70,35 @@ export {DESIGN_JSX_PROPERTIES,DESIGN_JSX_SUPPORTED_PROPERTIES,DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,+ DESIGN_JSX_PROPERTY_ALIASES,+ DESIGN_JSX_STYLE_KEYS,+ type DesignJSXStyleKey,+ designJSXProp,+ designJSXPropertyNames,type DesignJSXElementDefinition,type DesignJSXHelperDefinition,type DesignJSXPropertyDefinition} from './schema'-export { transformDesignJSXExpression } from './transform'+export {+ transformDesignJSXExpression,+ transformDesignJSXProgram,+ type DesignJSXChunk,+ type DesignJSXProgram+} from './transform'export {+ designJSXElement,sceneNodeAttributes,sceneNodeToJSX,selectionToJSX,+ selectionToJSXWithLayers,+ type DesignJSXElement,+ type DesignJSXWithLayers,type JSXAttributeSource} from './export'export { parseJSXAttributes } from './attributes'export { jsxNodeFields, type JSXNodeFields } from './fields'+export { reconcileRenderedLayers } from './reconcile'export { JSX_REFERENCE, AUTHORING_EXAMPLES, type AuthoringExample } from './reference'export {createStreamingJSXParser,diff --git a/packages/design-jsx/src/overrides/strokes.ts b/packages/design-jsx/src/overrides/strokes.tsindex 0b1b05da0..dd081b789 100644--- a/packages/design-jsx/src/overrides/strokes.ts+++ b/packages/design-jsx/src/overrides/strokes.ts@@ -1,3 +1,5 @@+import { designJSXProp } from '#design-jsx/schema'+import type { SceneNode, Stroke, StrokeCap, StrokeJoin } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'import type { Color } from '@open-pencil/scene-graph/primitives'@@ -116,7 +118,7 @@ export function applyStrokeOverrides(props: Record<string, unknown>, o: Partial<return}- const color = props.stroke ?? props.border ?? props.borderColor+ const color = designJSXProp(props, 'stroke')if (typeof color !== 'string' && !isColor(color)) returno.strokes = [toStroke({diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.tsindex 6c3b4f74f..127bb1c3d 100644--- a/packages/design-jsx/src/props-overrides.ts+++ b/packages/design-jsx/src/props-overrides.ts@@ -5,6 +5,7 @@ import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'import { applyEffectOverrides } from './overrides/effects'import { applyStateOverrides } from './overrides/state'import { applyStrokeOverrides } from './overrides/strokes'+import { DESIGN_JSX_STYLE_KEYS, designJSXProp } from './schema'const WEIGHT_MAP: Record<string, number> = {normal: 400,@@ -79,22 +80,11 @@ function normalizeStyleProps(props: Record<string, unknown>): Record<string, unkconst source = style as JSONObjectconst normalized = { ...props }- const copyIfUnset = (from: string, to: string, convert?: (value: unknown) => unknown): void => {- if (normalized[to] !== undefined || source[from] === undefined) return- normalized[to] = convert ? convert(source[from]) : source[from]+ for (const [name, keys] of Object.entries(DESIGN_JSX_STYLE_KEYS)) {+ if (designJSXProp(normalized, name) !== undefined) continue+ const found = keys.find(({ key }) => source[key] !== undefined)+ if (found) normalized[name] = found.px ? numberFromPx(source[found.key]) : source[found.key]}-- copyIfUnset('background', 'bg')- copyIfUnset('backgroundColor', 'bg')- copyIfUnset('color', 'color')- copyIfUnset('borderColor', 'stroke')- copyIfUnset('borderWidth', 'strokeWidth', numberFromPx)- copyIfUnset('borderRadius', 'rounded', numberFromPx)- copyIfUnset('fontSize', 'fontSize', numberFromPx)- copyIfUnset('fontWeight', 'fontWeight')- copyIfUnset('width', 'width', numberFromPx)- copyIfUnset('height', 'height', numberFromPx)- copyIfUnset('opacity', 'opacity')return normalized}@@ -103,8 +93,8 @@ export function applySizeOverrides(o: Partial<SceneNode>,parentLayout: SceneNode['layoutMode']): { w: unknown; h: unknown } {- const w = props.w ?? props.width- const h = props.h ?? props.height+ const w = designJSXProp(props, 'w')+ const h = designJSXProp(props, 'h')if (typeof w === 'number') o.width = wif (typeof h === 'number') o.height = h@@ -188,12 +178,12 @@ function applyFillOverride(props: Record<string, unknown>, o: Partial<SceneNode>return}- const bg = props.bg ?? props.fill ?? props.background ?? props.backgroundColor+ const bg = designJSXProp(props, 'bg')if (isFillValue(bg)) o.fills = [fillFromValue(bg)]}function applyCornerOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const rounded = props.rounded ?? props.cornerRadius ?? props.borderRadius+ const rounded = designJSXProp(props, 'rounded')if (typeof rounded === 'number') o.cornerRadius = roundedif (@@ -226,12 +216,12 @@ function applyVisualOverrides(props: Record<string, unknown>, o: Partial<SceneNo}function applyTransformOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const rotation = props.rotate ?? props.rotation+ const rotation = designJSXProp(props, 'rotate')if (rotation !== undefined) o.rotation = rotation as number}function applyPaddingOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const p = props.p ?? props.padding+ const p = designJSXProp(props, 'p')if (typeof p === 'number') {o.paddingTop = po.paddingRight = p@@ -324,8 +314,8 @@ function applyGridOverrides(}function applyGridChildOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const col = props.colStart ?? props.col- const row = props.rowStart ?? props.row+ const col = designJSXProp(props, 'colStart')+ const row = designJSXProp(props, 'rowStart')const colSpan = (props.colSpan as number | undefined) ?? 1const rowSpan = (props.rowSpan as number | undefined) ?? 1@@ -365,11 +355,11 @@ function applyLayoutAlignmentOverrides(props: Record<string, unknown>,o: Partial<SceneNode>): void {- const justify = props.justify ?? props.justifyContent+ const justify = designJSXProp(props, 'justify')if (justify) {o.primaryAxisAlign = ALIGN_MAP[justify as string] ?? 'MIN'}- const items = props.items ?? props.align ?? props.alignItems+ const items = designJSXProp(props, 'items')if (items) {o.counterAxisAlign = COUNTER_ALIGN_MAP[items as string] ?? 'MIN'}@@ -422,13 +412,13 @@ function applyLayoutOverrides(}function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const fontSize = props.size ?? props.fontSize+ const fontSize = designJSXProp(props, 'size')if (typeof fontSize === 'number') o.fontSize = fontSize- const fontFamily = props.font ?? props.fontFamily+ const fontFamily = designJSXProp(props, 'font')if (typeof fontFamily === 'string') o.fontFamily = fontFamily- const weight = props.weight ?? props.fontWeight+ const weight = designJSXProp(props, 'weight')if (typeof props.italic === 'boolean') o.italic = props.italicif (typeof weight === 'number') {@@ -459,12 +449,12 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scen}function applyTextAlignmentOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const textAlign = props.textAlign ?? props.textAlignHorizontal ?? props.textHorizontalAlignment+ const textAlign = designJSXProp(props, 'textAlign')if (typeof textAlign === 'string') {o.textAlignHorizontal = TEXT_ALIGN_ALIAS_MAP[textAlign.toLowerCase()] ?? 'LEFT'}- const textAlignVertical = props.textAlignVertical ?? props.textVerticalAlignment+ const textAlignVertical = designJSXProp(props, 'textAlignVertical')if (typeof textAlignVertical === 'string') {o.textAlignVertical = TEXT_VERTICAL_ALIGN_MAP[textAlignVertical.toLowerCase()] ?? 'TOP'}@@ -475,7 +465,7 @@ function applyTextAutoResize(o: Partial<SceneNode>,parentLayout: SceneNode['layoutMode']): void {- const w = props.w ?? props.width+ const w = designJSXProp(props, 'w')const hasExplicitWidth = w !== undefinedconst fillsParent = w === 'fill' || (props.grow as number) > 0const isInsideAutoLayout = parentLayout !== 'NONE'diff --git a/packages/design-jsx/src/reconcile.ts b/packages/design-jsx/src/reconcile.tsnew file mode 100644index 000000000..c32ee25b4--- /dev/null+++ b/packages/design-jsx/src/reconcile.ts@@ -0,0 +1,134 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++/**+ * Fields a layer keeps when its code is rendered again: its place in the tree and the identity+ * that other layers, libraries and files refer to.+ */+const IDENTITY_FIELDS = new Set<keyof SceneNode>([+ 'id',+ 'type',+ 'parentId',+ 'childIds',+ 'source',+ 'componentKey',+ 'sourceLibraryKey',+ 'publishId',+ 'overrideKey'+])++/**+ * Types rebuilt as a whole: instance overrides are keyed by the ids of their sublayers, and icon+ * and SVG artwork is drawn again from its paths.+ */+const REPLACED_TYPES = new Set<SceneNode['type']>(['INSTANCE', 'VECTOR', 'BOOLEAN_OPERATION'])++function updatesInPlace(existing: SceneNode, rendered: SceneNode): boolean {+ return existing.type === rendered.type && !REPLACED_TYPES.has(existing.type)+}++/** Pairs rendered children with existing ones: same type and name first, then same type in order. */+function matchChildren(+ existing: readonly SceneNode[],+ rendered: readonly SceneNode[]+): Map<SceneNode, SceneNode> {+ const pairs = new Map<SceneNode, SceneNode>()+ const free = new Set(existing)+ const take = (node: SceneNode, test: (candidate: SceneNode) => boolean) => {+ for (const candidate of free) {+ if (!test(candidate)) continue+ free.delete(candidate)+ pairs.set(node, candidate)+ return+ }+ }+ for (const node of rendered) {+ take(node, (candidate) => candidate.type === node.type && candidate.name === node.name)+ }+ for (const node of rendered) {+ if (!pairs.has(node)) take(node, (candidate) => candidate.type === node.type)+ }+ return pairs+}++function authoredChanges(existing: SceneNode, rendered: SceneNode): Partial<SceneNode> {+ const changes: Partial<SceneNode> = {}+ for (const key of Object.keys(rendered) as (keyof SceneNode)[]) {+ if (IDENTITY_FIELDS.has(key)) continue+ const next = rendered[key]+ if (JSON.stringify(existing[key]) === JSON.stringify(next)) continue+ Object.assign(changes, { [key]: structuredClone(next) })+ }+ return changes+}++class Reconciler {+ /** Rendered layer id → the id it has once reconciled: the existing layer's, or its own. */+ readonly ids = new Map<string, string>()++ constructor(private readonly graph: SceneGraph) {}++ keepRendered(node: SceneNode) {+ this.ids.set(node.id, node.id)+ for (const child of this.graph.getChildren(node.id)) this.keepRendered(child)+ }++ /** Makes `existing` match `rendered` and returns the id the pair ends up with. */+ pair(existing: SceneNode, rendered: SceneNode): string {+ if (!updatesInPlace(existing, rendered)) {+ const parentId = existing.parentId+ const parent = parentId ? this.graph.getNode(parentId) : undefined+ if (parent && parentId) {+ this.graph.insertChildAt(rendered.id, parentId, parent.childIds.indexOf(existing.id))+ }+ this.graph.deleteNode(existing.id)+ this.keepRendered(rendered)+ return rendered.id+ }+ const changes = authoredChanges(existing, rendered)+ if (Object.keys(changes).length > 0) this.graph.updateNode(existing.id, changes)+ this.ids.set(rendered.id, existing.id)+ this.children(existing.id, rendered.id)+ this.graph.deleteNode(rendered.id)+ return existing.id+ }++ private children(existingId: string, renderedId: string) {+ const renderedChildren = this.graph.getChildren(renderedId)+ const pairs = matchChildren(this.graph.getChildren(existingId), renderedChildren)+ const order = renderedChildren.map((child) => {+ const match = pairs.get(child)+ return match ? this.pair(match, child) : child.id+ })+ for (const child of renderedChildren) if (!pairs.has(child)) this.keepRendered(child)+ const kept = new Set(order)+ for (const child of this.graph.getChildren(existingId)) {+ if (!kept.has(child.id)) this.graph.deleteNode(child.id)+ }+ for (const [index, id] of order.entries()) this.graph.insertChildAt(id, existingId, index)+ }+}++/**+ * Folds freshly rendered layers into the layers they replace, so code edits update layers in+ * place: matched layers keep their ids, and only the properties that differ change. Roots pair+ * by position; extra rendered roots stay, extra existing roots are deleted. Returns the id each+ * rendered layer ends up with.+ */+export function reconcileRenderedLayers(+ graph: SceneGraph,+ existingRootIds: readonly string[],+ renderedRootIds: readonly string[]+): { rootIds: string[]; ids: Map<string, string> } {+ const reconciler = new Reconciler(graph)+ const rootIds = renderedRootIds.flatMap((renderedId, index) => {+ const rendered = graph.getNode(renderedId)+ if (!rendered) return []+ const existingId = existingRootIds.at(index)+ const existing = existingId ? graph.getNode(existingId) : undefined+ if (existing) return [reconciler.pair(existing, rendered)]+ reconciler.keepRendered(rendered)+ return [rendered.id]+ })+ for (const id of existingRootIds.slice(renderedRootIds.length)) graph.deleteNode(id)+ return { rootIds, ids: reconciler.ids }+}diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 72e236394..576e40603 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -87,7 +87,7 @@ export async function renderRoots<Artwork>(const nodes: SceneNode[] = []for (const root of roots) {- const node = await renderNode(services, graph, root, parentId)+ const node = await renderNode(services, graph, root, parentId, options.onNode)if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })nodes.push(node)@@ -546,7 +546,20 @@ async function renderNode<Artwork>(services: DesignJSXServices<Artwork>,graph: SceneGraph,tree: TreeNode,- parentId: string+ parentId: string,+ onNode?: RenderOptions['onNode']+): Promise<SceneNode> {+ const node = await renderNodeContent(services, graph, tree, parentId, onNode)+ onNode?.(tree, node)+ return node+}++async function renderNodeContent<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ onNode?: RenderOptions['onNode']): Promise<SceneNode> {if (tree.type === 'icon' || tree.type === 'svg')return renderArtworkNode(services, graph, tree, parentId)@@ -562,7 +575,7 @@ async function renderNode<Artwork>(for (const child of tree.children) {if (typeof child === 'string') continueif (isTreeNode(child)) {- await renderNode(services, graph, child, node.id)+ await renderNode(services, graph, child, node.id, onNode)}}diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex 2e02ec3d9..8f8e6e569 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -154,6 +154,66 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = [export const DESIGN_JSX_SUPPORTED_PROPERTIES = new Set<string>(DESIGN_JSX_SUPPORTED_PROPERTY_NAMES)+/**+ * Properties accepted under more than one name, keyed by the name Design JSX writes. The+ * renderer reads the first one set, in this order; editors use it to find a value written+ * under any of its names.+ */+export const DESIGN_JSX_PROPERTY_ALIASES: Readonly<Record<string, readonly string[]>> = {+ w: ['width'],+ h: ['height'],+ bg: ['fill', 'background', 'backgroundColor'],+ stroke: ['border', 'borderColor'],+ rounded: ['cornerRadius', 'borderRadius'],+ rotate: ['rotation'],+ p: ['padding'],+ colStart: ['col'],+ rowStart: ['row'],+ justify: ['justifyContent'],+ items: ['align', 'alignItems'],+ size: ['fontSize'],+ font: ['fontFamily'],+ weight: ['fontWeight'],+ textAlign: ['textAlignHorizontal', 'textHorizontalAlignment'],+ textAlignVertical: ['textVerticalAlignment']+}++/** A CSS-style key read from the `style` prop; `px` values like `'320px'` become numbers. */+export interface DesignJSXStyleKey {+ key: string+ px?: boolean+}++/**+ * Properties also read from `style={{ … }}`, keyed by the name Design JSX writes, in the order+ * the renderer reads them. An attribute under any of the property's names wins over `style`.+ */+export const DESIGN_JSX_STYLE_KEYS: Readonly<Record<string, readonly DesignJSXStyleKey[]>> = {+ bg: [{ key: 'background' }, { key: 'backgroundColor' }],+ color: [{ key: 'color' }],+ stroke: [{ key: 'borderColor' }],+ strokeWidth: [{ key: 'borderWidth', px: true }],+ rounded: [{ key: 'borderRadius', px: true }],+ size: [{ key: 'fontSize', px: true }],+ weight: [{ key: 'fontWeight' }],+ w: [{ key: 'width', px: true }],+ h: [{ key: 'height', px: true }],+ opacity: [{ key: 'opacity' }]+}++/** Every name a property is accepted under, the written name first. */+export function designJSXPropertyNames(name: string): readonly string[] {+ return [name, ...(DESIGN_JSX_PROPERTY_ALIASES[name] ?? [])]+}++/** The value of a property under the first of its names that is set. */+export function designJSXProp(props: Readonly<Record<string, unknown>>, name: string): unknown {+ for (const key of designJSXPropertyNames(name)) {+ if (props[key] !== undefined && props[key] !== null) return props[key]+ }+ return undefined+}+export const DESIGN_JSX_PROPERTIES: DesignJSXPropertyDefinition[] =DESIGN_JSX_SUPPORTED_PROPERTY_NAMES.map((name) => ({name,diff --git a/packages/design-jsx/src/transform.ts b/packages/design-jsx/src/transform.tsindex d29700caa..6926b25ec 100644--- a/packages/design-jsx/src/transform.ts+++ b/packages/design-jsx/src/transform.ts@@ -7,8 +7,34 @@ const options = {production: true}-function transformExpression(source: string): string {- return transform(`return (${source.trim()})`, options).code+/** The part of an authored program a JSX element was written in. */+export type DesignJSXChunk = 'statements' | 'expression'++/**+ * Transformed Design JSX whose elements carry `__source: { fileName, lineNumber }` props.+ * `fileName` names the chunk; adding its offset to `lineNumber` gives the 1-based line in the+ * source that was passed in.+ */+export interface DesignJSXProgram {+ code: string+ lineOffsets: Readonly<Record<DesignJSXChunk, number>>+}++function lineCount(text: string): number {+ let lines = 0+ for (const char of text) if (char === '\n') lines+++ return lines+}++function transformChunk(source: string, chunk: DesignJSXChunk | null): string {+ if (!chunk) return transform(source, options).code+ const { code } = transform(source, { ...options, production: false, filePath: chunk })+ // Both chunks share one function body, and Sucrase declares `_jsxFileName` in each.+ return chunk === 'statements' ? code.replaceAll('_jsxFileName', '_jsxStatementsFileName') : code+}++function transformExpression(source: string, chunk: DesignJSXChunk | null): string {+ return transformChunk(`return (${source.trim()})`, chunk)}function statementBoundaries(source: string): number[] {@@ -19,22 +45,30 @@ function statementBoundaries(source: string): number[] {return [...boundaries].sort((left, right) => right - left)}-/**- * Transform Design JSX into a function body. A plain JSX expression is accepted directly.- * For authored programs, top-level declarations must precede a final expression on a new line.- */-export function transformDesignJSXExpression(source: string): string {+function transformProgram(source: string, withLines: boolean): DesignJSXProgram {+ const leadingLines = lineCount(source.slice(0, source.length - source.trimStart().length))const trimmed = source.trim()try {- return transformExpression(trimmed)+ return {+ code: transformExpression(trimmed, withLines ? 'expression' : null),+ lineOffsets: { statements: leadingLines, expression: leadingLines }+ }} catch (expressionError) {for (const boundary of statementBoundaries(trimmed)) {const statements = trimmed.slice(0, boundary).trim()- const expression = trimmed.slice(boundary).trim()+ const rawExpression = trimmed.slice(boundary)+ const expression = rawExpression.trim()if (!statements || !expression) continuetry {- const transformedStatements = transform(statements, options).code- return `${transformedStatements}\n${transformExpression(expression)}`+ const transformedStatements = transformChunk(statements, withLines ? 'statements' : null)+ const expressionStart = boundary + rawExpression.length - rawExpression.trimStart().length+ return {+ code: `${transformedStatements}\n${transformExpression(expression, withLines ? 'expression' : null)}`,+ lineOffsets: {+ statements: leadingLines,+ expression: leadingLines + lineCount(trimmed.slice(0, expressionStart))+ }+ }} catch {continue}@@ -42,3 +76,16 @@ export function transformDesignJSXExpression(source: string): string {throw expressionError}}++/**+ * Transform Design JSX into a function body. A plain JSX expression is accepted directly.+ * For authored programs, top-level declarations must precede a final expression on a new line.+ */+export function transformDesignJSXExpression(source: string): string {+ return transformProgram(source, false).code+}++/** Like {@link transformDesignJSXExpression}, keeping the source line of every element. */+export function transformDesignJSXProgram(source: string): DesignJSXProgram {+ return transformProgram(source, true)+}diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.tsindex f1635d0e4..18da4babb 100644--- a/packages/design-jsx/src/tree.ts+++ b/packages/design-jsx/src/tree.ts@@ -7,6 +7,8 @@ export interface TreeNode {type: stringprops: Record<string, unknown>children: (TreeNode | string)[]+ /** Where the element was written, when the source is known. */+ source?: { line: number }}/** A fragment (`<>…</>`) groups siblings without creating a node of its own. */diff --git a/packages/design-jsx/src/types.ts b/packages/design-jsx/src/types.tsindex bca4f9e4d..e1247007d 100644--- a/packages/design-jsx/src/types.ts+++ b/packages/design-jsx/src/types.ts@@ -1,5 +1,11 @@+import type { SceneNode } from '@open-pencil/scene-graph'++import type { TreeNode } from './tree'+export interface RenderOptions {x?: numbery?: numberparentId?: string+ /** Called for every layer created from an element, so callers can map source to layers. */+ onNode?: (tree: TreeNode, node: SceneNode) => void}diff --git a/packages/design-jsx/tests/layer-order.test.ts b/packages/design-jsx/tests/layer-order.test.tsnew file mode 100644index 000000000..c5d7b92bf--- /dev/null+++ b/packages/design-jsx/tests/layer-order.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test'++import { selectionToJSX, selectionToJSXWithLayers } from '#design-jsx/index'++import { SceneGraph } from '@open-pencil/scene-graph'++/** Names written on each opening tag, in the order the tags open. */+function openingTagNames(code: string): string[] {+ return [...code.matchAll(/<(?!\/)[A-Za-z]\w*[^>]*?\bname="([^"]*)"/g)].map((match) => match[1])+}++describe('Design JSX layer order', () => {+ test('lists one layer per element in the order elements open, hidden layers included', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 100 })+ const title = graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello' })+ const hidden = graph.createNode('RECTANGLE', card.id, { name: 'Hidden', visible: false })+ const row = graph.createNode('FRAME', card.id, { name: 'Row', width: 100, height: 20 })+ const dot = graph.createNode('ELLIPSE', row.id, { name: 'Dot', width: 8, height: 8 })+ const badge = graph.createNode('FRAME', pageId, { name: 'Badge', width: 40, height: 20 })++ const result = selectionToJSXWithLayers([card.id, badge.id], graph)++ // Hidden layers are written with `visible={false}`, so they have elements too.+ expect(result.layerIds).toEqual([card.id, title.id, hidden.id, row.id, dot.id, badge.id])+ expect(openingTagNames(result.code)).toEqual(+ result.layerIds.map((id) => graph.getNode(id)?.name)+ )+ expect(result.code).toBe(selectionToJSX([card.id, badge.id], graph))+ })+})diff --git a/packages/design-jsx/tests/props-overrides.test.ts b/packages/design-jsx/tests/props-overrides.test.tsnew file mode 100644index 000000000..c83e31597--- /dev/null+++ b/packages/design-jsx/tests/props-overrides.test.ts@@ -0,0 +1,22 @@+import { describe, expect, test } from 'bun:test'++import { designJSXProp } from '#design-jsx/index'+import { propsToOverrides } from '#design-jsx/props-overrides'++describe('property names', () => {+ test('reads the first name of a property that is set', () => {+ expect(designJSXProp({ width: 10 }, 'w')).toBe(10)+ expect(designJSXProp({ w: 20, width: 10 }, 'w')).toBe(20)+ expect(designJSXProp({ fill: '#000', backgroundColor: '#FFF' }, 'bg')).toBe('#000')+ })++ test('an attribute under any of its names wins over style', () => {+ const overrides = propsToOverrides(+ { width: 100, style: { width: '200px', height: '50px', borderRadius: 8 } },+ false,+ 'NONE'+ )++ expect(overrides).toMatchObject({ width: 100, height: 50, cornerRadius: 8 })+ })+})diff --git a/packages/design-jsx/tests/reconcile.test.ts b/packages/design-jsx/tests/reconcile.test.tsnew file mode 100644index 000000000..e2af431b7--- /dev/null+++ b/packages/design-jsx/tests/reconcile.test.ts@@ -0,0 +1,117 @@+import { describe, expect, test } from 'bun:test'++import { reconcileRenderedLayers } from '#design-jsx/index'++import { SceneGraph, type NodeType, type SceneNode } from '@open-pencil/scene-graph'++interface Layer {+ type: NodeType+ name: string+ width?: number+ children?: Layer[]+}++/** Builds layers the way a render leaves them: a fresh subtree under the page. */+function build(graph: SceneGraph, layer: Layer, parentId = graph.getPages()[0].id): string {+ const node = graph.createNode(layer.type, parentId, {+ name: layer.name,+ width: layer.width ?? 10+ })+ for (const child of layer.children ?? []) build(graph, child, node.id)+ return node.id+}++function children(graph: SceneGraph, id: string): SceneNode[] {+ return graph.getChildren(id)+}++describe('reconcileRenderedLayers', () => {+ test('updates matched layers in place and keeps their ids', () => {+ const graph = new SceneGraph()+ const before = build(graph, {+ type: 'FRAME',+ name: 'Card',+ width: 200,+ children: [{ type: 'RECTANGLE', name: 'Swatch', width: 40 }]+ })+ const swatchId = children(graph, before)[0].id+ const after = build(graph, {+ type: 'FRAME',+ name: 'Card',+ width: 320,+ children: [{ type: 'RECTANGLE', name: 'Swatch', width: 80 }]+ })++ const { rootIds, ids } = reconcileRenderedLayers(graph, [before], [after])++ expect(rootIds).toEqual([before])+ expect(graph.getNode(after)).toBeUndefined()+ expect(graph.getNode(before)?.width).toBe(320)+ expect(children(graph, before).map((child) => [child.id, child.width])).toEqual([+ [swatchId, 80]+ ])+ expect(ids.get(after)).toBe(before)+ })++ test('adds, removes and reorders children to match the code', () => {+ const graph = new SceneGraph()+ const before = build(graph, {+ type: 'FRAME',+ name: 'List',+ children: [+ { type: 'RECTANGLE', name: 'A' },+ { type: 'RECTANGLE', name: 'B' },+ { type: 'RECTANGLE', name: 'C' }+ ]+ })+ const [a, , c] = children(graph, before).map((child) => child.id)+ const after = build(graph, {+ type: 'FRAME',+ name: 'List',+ children: [+ { type: 'RECTANGLE', name: 'C' },+ { type: 'ELLIPSE', name: 'New' },+ { type: 'RECTANGLE', name: 'A' }+ ]+ })++ reconcileRenderedLayers(graph, [before], [after])++ expect(children(graph, before).map((child) => child.name)).toEqual(['C', 'New', 'A'])+ const [first, , last] = children(graph, before).map((child) => child.id)+ expect([first, last]).toEqual([c, a])+ })++ test('replaces a layer whose type changed', () => {+ const graph = new SceneGraph()+ const before = build(graph, {+ type: 'FRAME',+ name: 'Card',+ children: [{ type: 'RECTANGLE', name: 'Dot' }]+ })+ const after = build(graph, {+ type: 'FRAME',+ name: 'Card',+ children: [{ type: 'ELLIPSE', name: 'Dot' }]+ })++ const { ids } = reconcileRenderedLayers(graph, [before], [after])++ const [dot] = children(graph, before)+ expect(dot.type).toBe('ELLIPSE')+ expect([...ids.values()]).toContain(dot.id)+ })++ test('keeps extra rendered roots and deletes missing ones', () => {+ const graph = new SceneGraph()+ const one = build(graph, { type: 'FRAME', name: 'One' })+ const two = build(graph, { type: 'FRAME', name: 'Two' })+ const next = build(graph, { type: 'FRAME', name: 'One again' })++ const { rootIds } = reconcileRenderedLayers(graph, [one, two], [next])++ expect(rootIds).toEqual([one])+ expect(graph.getNode(one)?.name).toBe('One again')+ expect(graph.getNode(two)).toBeUndefined()+ })+})diff --git a/packages/design-jsx/tests/transform.test.ts b/packages/design-jsx/tests/transform.test.tsnew file mode 100644index 000000000..062df6871--- /dev/null+++ b/packages/design-jsx/tests/transform.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'bun:test'++import { transformDesignJSXProgram } from '#design-jsx/index'++interface Located {+ type: string+ line: number+}++/** Runs transformed code with a JSX factory that records where each element was written. */+function locate(source: string): Located[] {+ const program = transformDesignJSXProgram(source)+ const located: Located[] = []+ const h = (type: unknown, props: Record<string, unknown> | null, ...children: unknown[]) => {+ if (typeof type === 'function')+ return (type as (props: unknown) => unknown)({ ...props, children })+ const origin = props?.__source as { fileName: 'statements' | 'expression'; lineNumber: number }+ located.push({+ type: String(type),+ line: program.lineOffsets[origin.fileName] + origin.lineNumber+ })+ return null+ }+ // eslint-disable-next-line typescript-eslint/no-implied-eval -- evaluates the transformed test fixture+ new Function('__h', '__fragment', 'Frame', 'Text', program.code)(h, '', 'frame', 'text')+ return located+}++describe('transformDesignJSXProgram', () => {+ test('reports the source line of elements in a plain expression', () => {+ const source = `\n\n<Frame name="Card">\n <Text>Hi</Text>\n</Frame>`+ expect(locate(source).map(({ type, line }) => `${type}@${line}`)).toEqual(['text@4', 'frame@3'])+ })++ test('reports lines in both declarations and the final expression of a program', () => {+ const source = [+ '',+ 'const Card = () => (',+ ' <Frame>',+ ' <Text>Hi</Text>',+ ' </Frame>',+ ')',+ '',+ '<Frame name="Root">',+ ' <Card />',+ '</Frame>'+ ].join('\n')+ expect(locate(source).map(({ type, line }) => `${type}@${line}`)).toEqual([+ 'text@4',+ 'frame@3',+ 'frame@8'+ ])+ })+})diff --git a/packages/docs/overview/features.md b/packages/docs/overview/features.mdindex 33b701eae..49bd365b4 100644--- a/packages/docs/overview/features.md+++ b/packages/docs/overview/features.md@@ -28,6 +28,7 @@ Context-sensitive Design | Code | AI | Lint tabs:- **Typography** — font picker with virtual scroll and search, weight, size, alignment, style buttons- **Layout** — auto-layout controls when enabled- **Export** — scale, format (PNG/JPG/WEBP/SVG), live preview+- **Code** — Design JSX and Tailwind JSX for the selection, with live two-way Design JSX editing that patches your code as layers change; the element around the cursor outlines its layer on the canvas, and design issues are underlined on the property that causes them- **Lint** — live design lint for the page or selection: low contrast, small touch targets, unbound colors, off-scale spacing, with issue markers on the canvas and one-click variable binding ([Checking Designs](/user-guide/checking-designs))## Renderingdiff --git a/packages/docs/user-guide/checking-designs.md b/packages/docs/user-guide/checking-designs.mdindex 5a3ed6f4e..584136d9c 100644--- a/packages/docs/user-guide/checking-designs.md+++ b/packages/docs/user-guide/checking-designs.md@@ -44,6 +44,10 @@ Pages with errors or warnings show their count in the page list, checked in theTurn markers and Layers panel marks on or off with **View → Design issues**, or with **Show issues on canvas** in the Lint panel's settings menu.+## In the Code Panel++The Code tab underlines errors and warnings on the Design JSX or Tailwind JSX of their layers, on the property that causes the issue when there is one, such as `size={10}` for small text. Hover the underline to read the issue. The underlines follow your edits while you change the code live.+## RulesThe settings menu in the Lint panel switches between rule presets:diff --git a/packages/dom-css/src/export/index.ts b/packages/dom-css/src/export/index.tsindex 4629a17c9..5a6613dfb 100644--- a/packages/dom-css/src/export/index.ts+++ b/packages/dom-css/src/export/index.ts@@ -1,7 +1,12 @@// SceneGraph → HTML and JSX without the CSS runtimes, so browsers can bundle it.export { sceneGraphToDesignDocument, sceneNodeToDesignDocument } from './projection'export { exportHTMLBundle } from './bundle'-export { designDocumentToTailwindJSX, sceneNodesToTailwindJSX } from './tailwind-jsx'+export {+ designDocumentToTailwindJSX,+ sceneNodesToTailwindJSX,+ sceneNodesToTailwindJSXWithLayers,+ type TailwindJSXWithLayers+} from './tailwind-jsx'export { serializeHTML } from './html'export type {ExportHTMLBundle,diff --git a/packages/dom-css/src/export/tailwind-jsx.ts b/packages/dom-css/src/export/tailwind-jsx.tsindex f8c893e2e..522d75719 100644--- a/packages/dom-css/src/export/tailwind-jsx.ts+++ b/packages/dom-css/src/export/tailwind-jsx.ts@@ -46,8 +46,34 @@ export function designDocumentToTailwindJSX(document: DesignDocument): string {/** Tailwind JSX for scene nodes, separated by blank lines. */export function sceneNodesToTailwindJSX(graph: SceneGraph, nodeIds: string[]): string {- return nodeIds- .map((id) => designDocumentToTailwindJSX(sceneNodeToDesignDocument(graph, id, false)))- .filter(Boolean)- .join('\n\n')+ return sceneNodesToTailwindJSXWithLayers(graph, nodeIds).code+}++/** Tailwind JSX with the layer behind each element, in the order elements open. */+export interface TailwindJSXWithLayers {+ code: string+ /** One entry per JSX element in pre-order; `null` for an element no layer produced. */+ layerIds: Array<string | null>+}++function collectLayerIds(node: DesignNode, layerIds: Array<string | null>): void {+ if (node.type === 'text') return+ layerIds.push(node.sourceSceneNodeId ?? node.sourceSceneNode?.id ?? null)+ for (const child of node.children) collectLayerIds(child, layerIds)+}++export function sceneNodesToTailwindJSXWithLayers(+ graph: SceneGraph,+ nodeIds: string[]+): TailwindJSXWithLayers {+ const layerIds: Array<string | null> = []+ const blocks: string[] = []+ for (const id of nodeIds) {+ const document = sceneNodeToDesignDocument(graph, id, false)+ const code = designDocumentToTailwindJSX(document)+ if (!code) continue+ blocks.push(code)+ for (const node of document.children) collectLayerIds(node, layerIds)+ }+ return { code: blocks.join('\n\n'), layerIds }}diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.tsindex 68cf74ef3..1713235d8 100644--- a/packages/dom-css/src/index.ts+++ b/packages/dom-css/src/index.ts@@ -12,7 +12,12 @@ export {} from './import/html'export { designDocumentToSceneGraph } from './import/scene-graph'export { sceneGraphToDesignDocument, sceneNodeToDesignDocument } from './export/projection'-export { designDocumentToTailwindJSX, sceneNodesToTailwindJSX } from './export/tailwind-jsx'+export {+ designDocumentToTailwindJSX,+ sceneNodesToTailwindJSX,+ sceneNodesToTailwindJSXWithLayers,+ type TailwindJSXWithLayers+} from './export/tailwind-jsx'export { compileTailwindCSS } from './import/tailwind'export {browserHTMLToDesignDocument,diff --git a/packages/dom-css/tests/export/tailwind-jsx/layers.test.ts b/packages/dom-css/tests/export/tailwind-jsx/layers.test.tsnew file mode 100644index 000000000..f6c9001bc--- /dev/null+++ b/packages/dom-css/tests/export/tailwind-jsx/layers.test.ts@@ -0,0 +1,28 @@+import { describe, expect, test } from 'bun:test'++import { sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers } from '#dom-css/index'++import { makeGraph, pageId } from './helpers'++/** `data-name` of each opening tag, in the order the tags open. */+function openingTagNames(code: string): Array<string | null> {+ return [...code.matchAll(/<(?!\/)[a-z][\w-]*((?:"[^"]*"|[^>"])*)>/g)].map(+ ([, attributes]) => /data-name="([^"]*)"/.exec(attributes)?.[1] ?? null+ )+}++describe('Tailwind JSX layer order', () => {+ test('lists the layer behind each element in the order elements open', () => {+ const graph = makeGraph()+ const card = graph.createNode('FRAME', pageId(graph), { name: 'Card', width: 200, height: 100 })+ const title = graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello' })+ const swatch = graph.createNode('RECTANGLE', card.id, { name: 'Swatch', width: 20, height: 20 })+ const badge = graph.createNode('FRAME', pageId(graph), { name: 'Badge', width: 40, height: 20 })++ const result = sceneNodesToTailwindJSXWithLayers(graph, [card.id, badge.id])++ expect(result.layerIds).toEqual([card.id, title.id, swatch.id, badge.id])+ expect(openingTagNames(result.code)).toEqual(['Card', 'Title', 'Swatch', 'Badge'])+ expect(result.code).toBe(sceneNodesToTailwindJSX(graph, [card.id, badge.id]))+ })+})diff --git a/packages/vue/src/i18n/locales/de/code.json b/packages/vue/src/i18n/locales/de/code.jsonindex 7143b47cc..7b1ac09c0 100644--- a/packages/vue/src/i18n/locales/de/code.json+++ b/packages/vue/src/i18n/locales/de/code.json@@ -11,5 +11,11 @@"updatedLive": "Live aktualisiert","previewFailed": "Vorschau fehlgeschlagen","generatedReadOnly": "Generiert, schreibgeschützt",- "reset": "Zurücksetzen"+ "reset": "Zurücksetzen",+ "noSelection": "Wähle eine Ebene aus, um ihren Code zu sehen",+ "noSelectionDesignJSX": "Oder schreibe Design JSX, um der Seite neue Ebenen hinzuzufügen.",+ "noSelectionTailwindJSX": "Tailwind JSX wird für die ausgewählten Ebenen erzeugt.",+ "writeJSX": "JSX schreiben",+ "canvasChangedExpression": "Auf der Arbeitsfläche jetzt {value}; der Ausdruck bleibt, wie er geschrieben ist.",+ "canvasChangedOrder": "Auf der Arbeitsfläche sind diese Ebenen jetzt anders angeordnet; der Code bleibt, wie er geschrieben ist."}diff --git a/packages/vue/src/i18n/locales/es/code.json b/packages/vue/src/i18n/locales/es/code.jsonindex 3812db520..49b2009c3 100644--- a/packages/vue/src/i18n/locales/es/code.json+++ b/packages/vue/src/i18n/locales/es/code.json@@ -11,5 +11,11 @@"updatedLive": "Actualizado en vivo","previewFailed": "Error de vista previa","generatedReadOnly": "Generado, solo lectura",- "reset": "Restablecer"+ "reset": "Restablecer",+ "noSelection": "Selecciona una capa para ver su código",+ "noSelectionDesignJSX": "O escribe Design JSX para añadir capas nuevas a la página.",+ "noSelectionTailwindJSX": "Tailwind JSX se genera para las capas seleccionadas.",+ "writeJSX": "Escribir JSX",+ "canvasChangedExpression": "El lienzo tiene ahora {value}; la expresión se mantiene tal como está escrita.",+ "canvasChangedOrder": "El lienzo ordena ahora estas capas de otra forma; el código se mantiene tal como está escrito."}diff --git a/packages/vue/src/i18n/locales/fr/code.json b/packages/vue/src/i18n/locales/fr/code.jsonindex abb6497be..4993220cd 100644--- a/packages/vue/src/i18n/locales/fr/code.json+++ b/packages/vue/src/i18n/locales/fr/code.json@@ -11,5 +11,11 @@"updatedLive": "Mis à jour en direct","previewFailed": "Échec de l’aperçu","generatedReadOnly": "Généré, lecture seule",- "reset": "Réinitialiser"+ "reset": "Réinitialiser",+ "noSelection": "Sélectionnez un calque pour voir son code",+ "noSelectionDesignJSX": "Ou écrivez du Design JSX pour ajouter de nouveaux calques à la page.",+ "noSelectionTailwindJSX": "Le Tailwind JSX est généré pour les calques sélectionnés.",+ "writeJSX": "Écrire du JSX",+ "canvasChangedExpression": "Le canevas indique maintenant {value} ; l’expression reste telle qu’écrite.",+ "canvasChangedOrder": "Le canevas ordonne maintenant ces calques autrement ; le code reste tel qu’écrit."}diff --git a/packages/vue/src/i18n/locales/it/code.json b/packages/vue/src/i18n/locales/it/code.jsonindex 072aa941c..fd55eb4a6 100644--- a/packages/vue/src/i18n/locales/it/code.json+++ b/packages/vue/src/i18n/locales/it/code.json@@ -11,5 +11,11 @@"updatedLive": "Aggiornato in tempo reale","previewFailed": "Anteprima non riuscita","generatedReadOnly": "Generato, in sola lettura",- "reset": "Reimposta"+ "reset": "Reimposta",+ "noSelection": "Seleziona un livello per vederne il codice",+ "noSelectionDesignJSX": "Oppure scrivi Design JSX per aggiungere nuovi livelli alla pagina.",+ "noSelectionTailwindJSX": "Il Tailwind JSX viene generato per i livelli selezionati.",+ "writeJSX": "Scrivi JSX",+ "canvasChangedExpression": "Sulla tela ora è {value}; l’espressione resta com’è scritta.",+ "canvasChangedOrder": "Sulla tela questi livelli ora sono in un altro ordine; il codice resta com’è scritto."}diff --git a/packages/vue/src/i18n/locales/ja/code.json b/packages/vue/src/i18n/locales/ja/code.jsonindex 79ba3f8c7..b556a3ed2 100644--- a/packages/vue/src/i18n/locales/ja/code.json+++ b/packages/vue/src/i18n/locales/ja/code.json@@ -11,5 +11,11 @@"updatedLive": "リアルタイム更新済み","previewFailed": "プレビューに失敗しました","generatedReadOnly": "生成済み、読み取り専用",- "reset": "リセット"+ "reset": "リセット",+ "noSelection": "レイヤーを選択するとコードが表示されます",+ "noSelectionDesignJSX": "または Design JSX を書いて、ページに新しいレイヤーを追加できます。",+ "noSelectionTailwindJSX": "Tailwind JSX は選択したレイヤーから生成されます。",+ "writeJSX": "JSX を書く",+ "canvasChangedExpression": "キャンバスでは {value} になりました。式は書かれたまま残しています。",+ "canvasChangedOrder": "キャンバスではこれらのレイヤーの順序が変わりました。コードは書かれたまま残しています。"}diff --git a/packages/vue/src/i18n/locales/pl/code.json b/packages/vue/src/i18n/locales/pl/code.jsonindex 736f06775..31778b682 100644--- a/packages/vue/src/i18n/locales/pl/code.json+++ b/packages/vue/src/i18n/locales/pl/code.json@@ -11,5 +11,11 @@"updatedLive": "Zaktualizowano na żywo","previewFailed": "Podgląd nie powiódł się","generatedReadOnly": "Wygenerowany, tylko do odczytu",- "reset": "Resetuj"+ "reset": "Resetuj",+ "noSelection": "Zaznacz warstwę, aby zobaczyć jej kod",+ "noSelectionDesignJSX": "Albo napisz Design JSX, aby dodać nowe warstwy do strony.",+ "noSelectionTailwindJSX": "Tailwind JSX jest generowany dla zaznaczonych warstw.",+ "writeJSX": "Napisz JSX",+ "canvasChangedExpression": "Na płótnie jest teraz {value}; wyrażenie pozostaje bez zmian.",+ "canvasChangedOrder": "Na płótnie te warstwy są teraz w innej kolejności; kod pozostaje bez zmian."}diff --git a/packages/vue/src/i18n/locales/ru/code.json b/packages/vue/src/i18n/locales/ru/code.jsonindex fc2db9d97..6ea5b2716 100644--- a/packages/vue/src/i18n/locales/ru/code.json+++ b/packages/vue/src/i18n/locales/ru/code.json@@ -11,5 +11,11 @@"updatedLive": "Обновлено в реальном времени","previewFailed": "Ошибка предпросмотра","generatedReadOnly": "Сгенерировано, только чтение",- "reset": "Сбросить"+ "reset": "Сбросить",+ "noSelection": "Выделите слой, чтобы увидеть его код",+ "noSelectionDesignJSX": "Или напишите Design JSX, чтобы добавить на страницу новые слои.",+ "noSelectionTailwindJSX": "Tailwind JSX создаётся для выделенных слоёв.",+ "writeJSX": "Написать JSX",+ "canvasChangedExpression": "На холсте теперь {value}; выражение оставлено как написано.",+ "canvasChangedOrder": "На холсте эти слои теперь в другом порядке; код оставлен как написан."}diff --git a/packages/vue/src/i18n/locales/zh-cn/code.json b/packages/vue/src/i18n/locales/zh-cn/code.jsonindex a4228d0b1..02618c532 100644--- a/packages/vue/src/i18n/locales/zh-cn/code.json+++ b/packages/vue/src/i18n/locales/zh-cn/code.json@@ -11,5 +11,11 @@"updatedLive": "已实时更新","previewFailed": "预览失败","generatedReadOnly": "已生成,只读",- "reset": "重置"+ "reset": "重置",+ "noSelection": "选择图层以查看其代码",+ "noSelectionDesignJSX": "也可以编写 Design JSX,向页面添加新图层。",+ "noSelectionTailwindJSX": "Tailwind JSX 会为所选图层生成。",+ "writeJSX": "编写 JSX",+ "canvasChangedExpression": "画布上现在是 {value};表达式保持原样。",+ "canvasChangedOrder": "画布上这些图层的顺序已改变;代码保持原样。"}diff --git a/packages/vue/src/i18n/messages/code.ts b/packages/vue/src/i18n/messages/code.tsindex 486b8c2fc..37e603d9a 100644--- a/packages/vue/src/i18n/messages/code.ts+++ b/packages/vue/src/i18n/messages/code.ts@@ -1,3 +1,5 @@+import { params } from '@nanostores/i18n'+import { i18n } from '#vue/i18n/create'export const codeMessageDefaults = {@@ -13,7 +15,13 @@ export const codeMessageDefaults = {generatedReadOnly: 'Generated, read only',reset: 'Reset',copyJSXReference: 'Copy JSX prop reference to clipboard',- jsxUpToDate: 'Up to date'+ jsxUpToDate: 'Up to date',+ canvasChangedExpression: params('The canvas now has {value}; the expression stays as written.'),+ canvasChangedOrder: 'The canvas now orders these layers differently; the code stays as written.',+ noSelection: 'Select a layer to see its code',+ noSelectionDesignJSX: 'Or write Design JSX to add new layers to the page.',+ noSelectionTailwindJSX: 'Tailwind JSX is generated for the selected layers.',+ writeJSX: 'Write JSX'} as constexport const codeMessages = i18n('code', codeMessageDefaults)diff --git a/src/app/code/generated.ts b/src/app/code/generated.tsindex 34f26463c..a5c2756e6 100644--- a/src/app/code/generated.ts+++ b/src/app/code/generated.ts@@ -1,17 +1,23 @@-import { selectionToJSX } from '@open-pencil/design-jsx'-import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/export'+import { selectionToJSXWithLayers } from '@open-pencil/design-jsx'+import { sceneNodesToTailwindJSXWithLayers } from '@open-pencil/dom-css/export'import type { SceneGraph } from '@open-pencil/scene-graph'import { starterSourceFor, type CodeSource } from '@/app/code/templates'+/** Generated code and the layer behind each of its elements, in pre-order. */+export interface GeneratedCode {+ code: string+ layerIds: ReadonlyArray<string | null>+}+/** Code shown for the selection: editable Design JSX, or read-only Tailwind JSX. */-export function generatedSourceFor(+export function generatedCodeFor(source: Exclude<CodeSource, 'html-css'>,graph: SceneGraph,nodeIds: string[]-): string {- if (nodeIds.length === 0) return starterSourceFor(source)+): GeneratedCode {+ if (nodeIds.length === 0) return { code: starterSourceFor(source), layerIds: [] }return source === 'tailwind-jsx'- ? sceneNodesToTailwindJSX(graph, nodeIds)- : selectionToJSX(nodeIds, graph)+ ? sceneNodesToTailwindJSXWithLayers(graph, nodeIds)+ : selectionToJSXWithLayers(nodeIds, graph)}diff --git a/src/app/code/layers/issues.ts b/src/app/code/layers/issues.tsnew file mode 100644index 000000000..a45772f15--- /dev/null+++ b/src/app/code/layers/issues.ts@@ -0,0 +1,76 @@+import type { CodeSource } from '@/app/code/templates'+import { issueDetail, ruleTitle, type DesignCheckMessages } from '@/app/editor/design-check/format'+import type { DesignIssue } from '@/app/editor/design-check/issues'++/** A design issue on a layer, shown on the code that produces the layer. */+export interface LayerIssue {+ nodeId: string+ severity: 'error' | 'warning' | 'info'+ message: string+ /** Attribute names that carry the offending value, most specific first. */+ props: readonly string[]+}++const PADDING_PROPS: Record<string, readonly string[]> = {+ itemSpacing: ['gap'],+ paddingTop: ['pt', 'py', 'p'],+ paddingRight: ['pr', 'px', 'p'],+ paddingBottom: ['pb', 'py', 'p'],+ paddingLeft: ['pl', 'px', 'p']+}++function stringData(issue: DesignIssue, key: string): string | undefined {+ const value = issue.data?.[key]+ return typeof value === 'string' ? value : undefined+}++/** The Design JSX props the exporter writes for the value a rule reports. */+function designJSXProps(issue: DesignIssue): readonly string[] {+ switch (issue.ruleId) {+ case 'color-contrast':+ return ['color']+ case 'min-text-size':+ return ['size']+ case 'touch-target-size':+ return ['w', 'h']+ case 'consistent-radius':+ return ['rounded']+ case 'consistent-spacing':+ return PADDING_PROPS[stringData(issue, 'property') ?? ''] ?? []+ case 'no-hardcoded-colors':+ return stringData(issue, 'paint') === 'stroke' ? ['stroke'] : ['bg', 'color']+ case 'effect-style-required':+ return ['shadow', 'blur']+ default:+ return []+ }+}++/** Tailwind carries every visual value in `className`; names come from `data-name`. */+function tailwindProps(issue: DesignIssue): readonly string[] {+ return issue.ruleId === 'no-default-names' ? ['data-name'] : ['className']+}++/**+ * Errors and warnings as code issues, matching the canvas markers: suggestions stay in the+ * Check panel so the editor does not underline most of a generated document.+ */+export function codeLayerIssues(+ issues: readonly DesignIssue[],+ source: CodeSource,+ messages: DesignCheckMessages+): LayerIssue[] {+ if (source === 'html-css') return []+ return issues+ .filter((issue) => issue.severity !== 'info')+ .map((issue) => {+ const detail = issueDetail(issue, messages)+ const title = ruleTitle(issue.ruleId, messages)+ return {+ nodeId: issue.nodeId,+ severity: issue.severity,+ message: detail ? `${title} · ${detail}` : title,+ props: source === 'tailwind-jsx' ? tailwindProps(issue) : designJSXProps(issue)+ }+ })+}diff --git a/src/app/code/layers/links.ts b/src/app/code/layers/links.tsnew file mode 100644index 000000000..97cfe86cc--- /dev/null+++ b/src/app/code/layers/links.ts@@ -0,0 +1,12 @@+import type { DesignJSXLayerLine } from '@/app/code/live-preview'++/**+ * How the code in an editor relates to layers.+ *+ * Generated code emits one element per layer in pre-order, so `order` pairs elements with layer+ * ids by position. Authored code can create many layers from one element (components, `map`)+ * or none, so `lines` names the line and runtime type each rendered layer came from.+ */+export type LayerLinkSource =+ | { kind: 'order'; layerIds: ReadonlyArray<string | null> }+ | { kind: 'lines'; layers: readonly DesignJSXLayerLine[] }diff --git a/src/app/code/layers/use.ts b/src/app/code/layers/use.tsnew file mode 100644index 000000000..03045b673--- /dev/null+++ b/src/app/code/layers/use.ts@@ -0,0 +1,68 @@+import { computed, shallowRef, type Ref } from 'vue'++import {+ designJSXElement,+ selectionToJSXWithLayers,+ type DesignJSXElement+} from '@open-pencil/design-jsx'+import { useDesignCheckMessages } from '@open-pencil/vue'++import type { GeneratedCode } from '@/app/code/generated'+import type { DesignJSXLayerLine } from '@/app/code/live-preview'+import type { CodeSource } from '@/app/code/templates'+import { useEditorStore } from '@/app/editor/active-store'++import { codeLayerIssues } from './issues'+import type { LayerLinkSource } from './links'++/**+ * Connects the code in the Code tab to canvas layers: which layer each element produced, the+ * design issues to underline, and the layer marked for the element around the cursor.+ */+export function useCodeLayers(source: Readonly<Ref<CodeSource>>) {+ const store = useEditorStore()+ const messages = useDesignCheckMessages()+ const links = shallowRef<LayerLinkSource | null>(null)++ const issues = computed(() => {+ const snapshot = store.designCheck.snapshot.value+ if (!snapshot || snapshot.pageId !== store.state.currentPageId) return []+ return codeLayerIssues(snapshot.issues, source.value, messages.value)+ })++ /** Generated code lists its layers in element order. */+ function showGenerated(generated: GeneratedCode | null) {+ links.value = generated ? { kind: 'order', layerIds: generated.layerIds } : null+ }++ /** A live preview reports the line each rendered layer came from. */+ function showPreview(layers: readonly DesignJSXLayerLine[]) {+ links.value = { kind: 'lines', layers }+ }++ /** Marks the layer of the element around the cursor on the canvas, apart from hover. */+ function markActive(nodeIds: readonly string[] | null) {+ store.setCodeFocusNode(nodeIds?.find((id) => store.graph.getNode(id)) ?? null)+ }++ /** A linked layer as Design JSX writes it, the unit code is patched in. */+ function describe(nodeId: string): DesignJSXElement | null {+ return designJSXElement(nodeId, store.graph)+ }++ /** Design JSX for a layer added on the canvas, with the layer of each of its elements. */+ function snippet(nodeId: string): { code: string; layerIds: string[] } | null {+ const { code, layerIds } = selectionToJSXWithLayers([nodeId], store.graph)+ return code ? { code, layerIds } : null+ }++ return {+ links,+ issues,+ showGenerated,+ showPreview,+ markActive,+ describe,+ snippet+ }+}diff --git a/src/app/code/live-preview.ts b/src/app/code/live-preview.tsindex f91a2d0b0..d912c52af 100644--- a/src/app/code/live-preview.ts+++ b/src/app/code/live-preview.ts@@ -1,24 +1,34 @@import { renderTree } from '@open-pencil/core/design-jsx'import { computeAllLayouts } from '@open-pencil/core/layout'-import type { TreeNode } from '@open-pencil/design-jsx'+import { reconcileRenderedLayers, type TreeNode } from '@open-pencil/design-jsx'import type { Vector } from '@open-pencil/scene-graph'import { convertDesignJSXRoots } from '@/app/code/sandbox/convert'import { evaluateDesignJSX } from '@/app/code/sandbox/evaluate'import type { EditorStore } from '@/app/editor/active-store'-export type ApplyDesignJSXResult = { ok: true; nodeIds: string[] } | { ok: false; error: string }+/** A layer rendered from an element written on `line`, with the element's runtime type. */+export type DesignJSXLayerLine = { line: number; type: string; nodeId: string }++export type ApplyDesignJSXResult =+ | { ok: true; nodeIds: string[]; layers: DesignJSXLayerLine[] }+ | { ok: false; error: string }export type DesignJSXEditSession = {- originalSnapshot: ReturnType<EditorStore['snapshotPage']>- originalSelectionIds: string[]+ /** The layers the code describes; previews update them in place. */+ rootIds: string[]targetParentId: stringtargetIndex: numberorigins: Vector[]fallbackOrigin: Vector- previewSnapshot: ReturnType<EditorStore['snapshotPage']> | null- previewNodeIds: string[]+ /** The page before the edit, which Reset brings back. */+ originalSnapshot: ReturnType<EditorStore['snapshotPage']>+ originalSelectionIds: string[]+ /** Previews of one edit coalesce into a single undo step. */+ undoKey: string}+let sessionCount = 0+function lockedSelectionError(store: EditorStore, ids: string[]): string | null {const locked = ids.some((id) => {const node = store.graph.getNode(id)@@ -58,14 +68,14 @@ export function createDesignJSXEditSession(return {ok: true,session: {- originalSnapshot: store.snapshotPage(),- originalSelectionIds: selected.map(({ id }) => id),+ rootIds: selected.map(({ id }) => id),targetParentId,targetIndex,origins: selected.map(({ x, y }) => ({ x, y })),fallbackOrigin: first ? { x: first.x, y: first.y } : store.viewportCanvasCenter(),- previewSnapshot: null,- previewNodeIds: []+ originalSnapshot: store.snapshotPage(),+ originalSelectionIds: selected.map(({ id }) => id),+ undoKey: `design-jsx-edit:${++sessionCount}`}}}@@ -80,68 +90,100 @@ export async function previewDesignJSX(let roots: TreeNode[]try {- roots = convertDesignJSXRoots(evaluated.roots)+ roots = convertDesignJSXRoots(evaluated.roots, evaluated.lineOffsets)} catch (error) {return { ok: false, error: error instanceof Error ? error.message : String(error) }}- store.restorePageFromSnapshot(session.originalSnapshot)+ const before = store.snapshotPage()+ const selectionBefore = [...store.state.selectedIds]try {- for (const id of session.originalSelectionIds) store.graph.deleteNode(id)- const results = []+ const renderedIds: string[] = []+ const layers: DesignJSXLayerLine[] = []+ const onNode = (tree: TreeNode, node: { id: string }) => {+ if (tree.source) layers.push({ line: tree.source.line, type: tree.type, nodeId: node.id })+ }for (const [index, root] of roots.entries()) {const origin = session.origins.at(index) ?? {x: session.fallbackOrigin.x + index * 24,y: session.fallbackOrigin.y + index * 24}+ // Code that places a root keeps it there; code that does not lands where the layer was.const result = await renderTree(store.graph, root, {parentId: session.targetParentId,- x: origin.x,- y: origin.y+ x: 'x' in root.props ? undefined : origin.x,+ y: 'y' in root.props ? undefined : origin.y,+ onNode})- results.push(result)- if (session.targetIndex >= 0) {- store.graph.insertChildAt(result.id, session.targetParentId, session.targetIndex + index)+ renderedIds.push(result.id)+ }+ const { rootIds, ids } = reconcileRenderedLayers(store.graph, session.rootIds, renderedIds)+ if (session.targetIndex >= 0) {+ for (const [index, id] of rootIds.entries()) {+ store.graph.insertChildAt(id, session.targetParentId, session.targetIndex + index)}}- const nodeIds = results.map(({ id }) => id)computeAllLayouts(store.graph, store.state.currentPageId)- store.select(nodeIds)+ session.rootIds = rootIds+ if (!sameIds(selectionBefore, rootIds)) store.select(rootIds)store.requestRender()- session.previewSnapshot = store.snapshotPage()- session.previewNodeIds = nodeIds- return { ok: true, nodeIds }+ recordPreview(store, session, before, selectionBefore)+ return {+ ok: true,+ nodeIds: rootIds,+ layers: layers.map((layer) => ({ ...layer, nodeId: ids.get(layer.nodeId) ?? layer.nodeId }))+ }} catch (error) {- store.restorePageFromSnapshot(session.previewSnapshot ?? session.originalSnapshot)- store.select(- session.previewNodeIds.length > 0 ? session.previewNodeIds : session.originalSelectionIds- )+ store.restorePageFromSnapshot(before)+ store.select(selectionBefore)return { ok: false, error: error instanceof Error ? error.message : String(error) }}}-export function resetDesignJSXPreview(store: EditorStore, session: DesignJSXEditSession): void {- store.restorePageFromSnapshot(session.originalSnapshot)- store.select(session.originalSelectionIds)- session.previewSnapshot = null- session.previewNodeIds = []+function sameIds(a: readonly string[], b: readonly string[]): boolean {+ return a.length === b.length && a.every((id, index) => id === b[index])}-export function commitDesignJSXSession(store: EditorStore, session: DesignJSXEditSession): void {- const after = session.previewSnapshot- if (!after) return- const previewIds = [...session.previewNodeIds]- const originalSnapshot = session.originalSnapshot- const originalSelectionIds = [...session.originalSelectionIds]+/** One undo step per edit: consecutive previews of a session coalesce into the first one. */+function recordPreview(+ store: EditorStore,+ session: DesignJSXEditSession,+ before: ReturnType<EditorStore['snapshotPage']>,+ selectionBefore: string[]+): void {+ const after = store.snapshotPage()+ const rootIds = [...session.rootIds]store.pushUndoEntry({label: session.originalSelectionIds.length > 0 ? 'Edit JSX' : 'Insert JSX',+ coalesceKey: session.undoKey,forward: () => {store.restorePageFromSnapshot(after)- store.select(previewIds)+ store.select(rootIds)},inverse: () => {+ store.restorePageFromSnapshot(before)+ store.select(selectionBefore)+ }+ })+}++/** Brings back the page from before the edit, as one undo step. */+export function resetDesignJSXPreview(store: EditorStore, session: DesignJSXEditSession): void {+ const before = store.snapshotPage()+ const selectionBefore = [...store.state.selectedIds]+ const { originalSnapshot, originalSelectionIds } = session+ store.restorePageFromSnapshot(originalSnapshot)+ store.select(originalSelectionIds)+ session.rootIds = [...originalSelectionIds]+ store.pushUndoEntry({+ label: 'Reset JSX',+ forward: () => {store.restorePageFromSnapshot(originalSnapshot)store.select(originalSelectionIds)+ },+ inverse: () => {+ store.restorePageFromSnapshot(before)+ store.select(selectionBefore)}})}diff --git a/src/app/code/sandbox/convert.ts b/src/app/code/sandbox/convert.tsindex aa5e37309..d37877df1 100644--- a/src/app/code/sandbox/convert.ts+++ b/src/app/code/sandbox/convert.ts@@ -12,6 +12,7 @@ import {linearGradient,radialGradient,solid,+ type DesignJSXProgram,type TreeNode} from '@open-pencil/design-jsx'@@ -41,6 +42,18 @@ type SerializedDesignJSXElement = {type: stringprops: PlainRecordchildren: unknown[]+ /** `[chunk, line]` from the transform, when the element's source line is known. */+ source?: unknown+}++type LineOffsets = DesignJSXProgram['lineOffsets']++function sourceLine(value: unknown, lineOffsets: LineOffsets | undefined): number | undefined {+ if (!lineOffsets || !Array.isArray(value) || value.length !== 2) return undefined+ const [chunk, line] = value as unknown[]+ if ((chunk !== 'statements' && chunk !== 'expression') || typeof line !== 'number')+ return undefined+ return lineOffsets[chunk] + line}function isRecord(value: unknown): value is PlainRecord {@@ -79,19 +92,26 @@ function convertValue(value: unknown): unknown {return value}-function convertTree(value: unknown): TreeNode {+function convertTree(value: unknown, lineOffsets?: LineOffsets): TreeNode {if (!isSerializedElement(value)) {throw new Error('Design JSX must return an OpenPencil element.')}const children = value.children.map((child): TreeNode | string => {if (typeof child === 'string') return childif (typeof child === 'number') return String(child)- return convertTree(child)+ return convertTree(child, lineOffsets)})- return { type: value.type, props: convertValue(value.props) as PlainRecord, children }+ const tree: TreeNode = {+ type: value.type,+ props: convertValue(value.props) as PlainRecord,+ children+ }+ const line = sourceLine(value.source, lineOffsets)+ if (line !== undefined) tree.source = { line }+ return tree}-export function convertDesignJSXRoots(values: unknown[]): TreeNode[] {+export function convertDesignJSXRoots(values: unknown[], lineOffsets?: LineOffsets): TreeNode[] {// Call validateDesignJSXOutput first; it enforces the depth bound used by this recursion.- return values.map(convertTree)+ return values.map((value) => convertTree(value, lineOffsets))}diff --git a/src/app/code/sandbox/document.ts b/src/app/code/sandbox/document.tsindex e4050ac34..aa1a51db0 100644--- a/src/app/code/sandbox/document.ts+++ b/src/app/code/sandbox/document.ts@@ -13,11 +13,13 @@ self.onmessage = ({ data }) => {const normalizeChildren = (children) => children.flat(Infinity).filter((child) => child != null && child !== false)const __fragment = ''const __h = (type, props, ...children) => {- const normalizedProps = props == null ? {} : props+ const { __source, __self, ...normalizedProps } = props == null ? {} : propsconst normalizedChildren = normalizeChildren(children)if (typeof type === 'function') return type({ ...normalizedProps, children: normalizedChildren })if (type === __fragment) return normalizedChildren- return { type, props: normalizedProps, children: normalizedChildren }+ const element = { type, props: normalizedProps, children: normalizedChildren }+ if (__source && typeof __source.lineNumber === 'number') element.source = [String(__source.fileName), __source.lineNumber]+ return element}const helper = (name) => (...args) => ({ __openPencilHelper: name, args })const helperRuntime = (name) => {diff --git a/src/app/code/sandbox/evaluate.ts b/src/app/code/sandbox/evaluate.tsindex 494070e4a..4a6a62292 100644--- a/src/app/code/sandbox/evaluate.ts+++ b/src/app/code/sandbox/evaluate.ts@@ -2,7 +2,8 @@ import { IS_BROWSER } from '@open-pencil/core/constants'import {DESIGN_JSX_ELEMENTS,DESIGN_JSX_HELPERS,- transformDesignJSXExpression+ transformDesignJSXProgram,+ type DesignJSXProgram} from '@open-pencil/design-jsx'import { sandboxDocument } from '@/app/code/sandbox/document'@@ -32,9 +33,9 @@ export async function evaluateDesignJSX(return { ok: false, error: 'Design JSX source is too large.' }}- let code: string+ let program: DesignJSXProgramtry {- code = transformDesignJSXExpression(source)+ program = transformDesignJSXProgram(source)} catch (error) {return { ok: false, error: error instanceof Error ? error.message : String(error) }}@@ -84,7 +85,10 @@ export async function evaluateDesignJSX(() => finish({ ok: false, error: 'Design JSX execution timed out.' }),timeoutMs)- iframe.contentWindow?.postMessage({ type: 'open-pencil-design-jsx-run', id, code }, '*')+ iframe.contentWindow?.postMessage(+ { type: 'open-pencil-design-jsx-run', id, code: program.code },+ '*'+ )return}if (message.type !== 'open-pencil-design-jsx-result' || message.id !== id) return@@ -94,7 +98,7 @@ export async function evaluateDesignJSX(}try {const roots = validateDesignJSXOutput(message.value, validationLimits)- finish({ ok: true, roots })+ finish({ ok: true, roots, lineOffsets: program.lineOffsets })} catch (error) {finish({ ok: false, error: error instanceof Error ? error.message : String(error) })}diff --git a/src/app/code/sandbox/types.ts b/src/app/code/sandbox/types.tsindex 7b04415d6..c361e407a 100644--- a/src/app/code/sandbox/types.ts+++ b/src/app/code/sandbox/types.ts@@ -1,3 +1,5 @@+import type { DesignJSXProgram } from '@open-pencil/design-jsx'+export const DESIGN_JSX_MAX_SOURCE_BYTES = 256_000export const DESIGN_JSX_MAX_OUTPUT_BYTES = 2_000_000export const DESIGN_JSX_MAX_ELEMENTS = 5_000@@ -47,4 +49,6 @@ export type DesignJSXHelperDescriptor = {args: unknown[]}-export type DesignJSXSandboxResult = { ok: true; roots: unknown[] } | { ok: false; error: string }+export type DesignJSXSandboxResult =+ | { ok: true; roots: unknown[]; lineOffsets: DesignJSXProgram['lineOffsets'] }+ | { ok: false; error: string }diff --git a/src/app/editor/design-check/session.ts b/src/app/editor/design-check/session.tsindex 2672319a2..a2142e6fb 100644--- a/src/app/editor/design-check/session.ts+++ b/src/app/editor/design-check/session.ts@@ -4,7 +4,6 @@ import { computed, effectScope, ref, shallowRef, watch } from 'vue'import type { Editor } from '@open-pencil/core/editor'import { isFigPagePending } from '@open-pencil/core/io/formats/fig'import { createLinter, type LintConfig, type LintFixRequest } from '@open-pencil/core/lint'-import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'import type { AppEditorState } from '@/app/editor/session/types'import { appPreferences, type DesignCheckPreset } from '@/app/settings/preferences/store'@@ -20,8 +19,6 @@ import { createPageChecks, pageOf } from './pages'/** Quiet period after an edit before the page is checked again. */const CHECK_DELAY_MS = 180-/** Margin kept between a revealed layer and the viewport edge. */-const REVEAL_MARGIN = 48export interface DesignCheckSnapshot {pageId: string@@ -41,11 +38,7 @@ function linterConfig(preset: DesignCheckPreset, disabledRules: readonly string[* Checks run once edits settle and wait out interactive property edits, so a burst of changes* costs one check. Nothing runs while both surfaces are off.*/-export function createDesignCheck(- editor: Editor,- state: AppEditorState,- getViewportSize: () => { width: number; height: number }-) {+export function createDesignCheck(editor: Editor, state: AppEditorState) {const scope = effectScope(true)const snapshot = shallowRef<DesignCheckSnapshot | null>(null)const panelVisible = ref(false)@@ -198,33 +191,6 @@ export function createDesignCheck(focusedIssueId.value = mostSevereIssue(issuesOn(present))?.id ?? null}- /** Brings a layer into view without changing zoom when it already fits. */- function revealNode(nodeId: string) {- const node = editor.graph.getNode(nodeId)- if (!node) return- const bounds = getAxisAlignedWorldBounds(node, editor.graph)- const { width, height } = getViewportSize()- const zoom = state.zoom- const fits =- bounds.width * zoom <= width - REVEAL_MARGIN * 2 &&- bounds.height * zoom <= height - REVEAL_MARGIN * 2- if (!fits) {- editor.zoomToBounds(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height)- return- }- const left = bounds.x * zoom + state.panX- const top = bounds.y * zoom + state.panY- const right = left + bounds.width * zoom- const bottom = top + bounds.height * zoom- const visible =- left >= REVEAL_MARGIN &&- top >= REVEAL_MARGIN &&- right <= width - REVEAL_MARGIN &&- bottom <= height - REVEAL_MARGIN- if (visible) return- editor.pan(width / 2 - (left + right) / 2, height / 2 - (top + bottom) / 2)- }-/** Selects the issue's layer, on its page, keeps it in view and marks the row as focused. */async function openIssue(issue: DesignIssue) {// A page switch clears the focused issue, so focus follows the switch.@@ -234,7 +200,7 @@ export function createDesignCheck(focusedIssueId.value = issue.idif (!editor.graph.getNode(issue.nodeId)) returneditor.select([issue.nodeId])- revealNode(issue.nodeId)+ editor.revealNodes([issue.nodeId])}/** Applies fixes as one undo step and re-checks right away, so fixed rows leave at once. */@@ -262,7 +228,6 @@ export function createDesignCheck(highlightMarker,openIssue,openMarker,- revealNode,applyFixes,dispose}diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex f81862289..80b78e998 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -66,7 +66,7 @@ export function createEditorStoreModules(const documentExport = createDocumentExportActions(editor, state, io, documentIO.downloadBlob)const mobileClipboard = createMobileClipboardActions(editor)const profiler = createProfilerActions(editor)- const designCheck = createDesignCheck(editor, state, () => viewportSize)+ const designCheck = createDesignCheck(editor, state)return {...flash,diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vueindex 2ca9f1f41..184c57818 100644--- a/src/components/CodePanel.vue+++ b/src/components/CodePanel.vue@@ -1,10 +1,18 @@<script setup lang="ts">import { useClipboard, useDebounceFn } from '@vueuse/core'import { tv } from 'tailwind-variants'-import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef, watch } from 'vue'+import {+ computed,+ defineAsyncComponent,+ onBeforeUnmount,+ ref,+ shallowRef,+ useTemplateRef,+ watch+} from 'vue'import { JSX_REFERENCE } from '@open-pencil/design-jsx'-import { useI18n, useSceneComputed } from '@open-pencil/vue'+import { useI18n } from '@open-pencil/vue'import {commitDOMCodeSession,@@ -13,17 +21,19 @@ import {resetDOMCodePreview,type DOMCodeSession} from '@/app/code/dom-preview'-import { generatedSourceFor } from '@/app/code/generated'+import { generatedCodeFor, type GeneratedCode } from '@/app/code/generated'+import { useCodeLayers } from '@/app/code/layers/use'import {- commitDesignJSXSession,createDesignJSXEditSession,previewDesignJSX,resetDesignJSXPreview,- type DesignJSXEditSession+ type DesignJSXEditSession,+ type DesignJSXLayerLine} from '@/app/code/live-preview'import { starterSourceFor, type CodeSource } from '@/app/code/templates'import { useEditorStore } from '@/app/editor/active-store'import AppButton from '@/components/ui/button/AppButton.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import Tip from '@/components/ui/overlay/Tip.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'import statusTheme from '@/theme/feedback/status'@@ -38,22 +48,51 @@ const { copy, copied } = useClipboard({ copiedDuring: 2000 })const { copy: copyReference, copied: copiedReference } = useClipboard({ copiedDuring: 2000 })const source = ref<CodeSource>('design-jsx')const draft = ref('')-const baseline = ref('')+/** The person has written in the code since it was generated for the current selection. */+const edited = ref(false)const status = ref<'idle' | 'updating' | 'updated' | 'error'>('idle')const error = ref('')const designSession = shallowRef<DesignJSXEditSession | null>(null)+const codeEditor = useTemplateRef<InstanceType<typeof CodeEditor>>('codeEditor')let domSession: DOMCodeSession | null = nulllet previewQueue = Promise.resolve()let pendingPreview: Promise<void> | undefinedlet commitPromise: Promise<void> | undefinedlet updateVersion = 0-let disposing = false+/** Previews in flight; their canvas changes come from the code, not onto it. */+let previewing = 0+/** Scene version a preview left the canvas at, which the code already describes. */+let previewedVersion: number | null = null+/** The selection the code was generated for. */+let followedSelection: string | null = null-const generatedJSX = useSceneComputed(() => {- if (!editorActive.value || source.value === 'html-css' || designSession.value) return ''- void store.state.sceneVersion- return generatedSourceFor(source.value, store.graph, [...store.state.selectedIds])-})+/** Set by "Write JSX": the editor stays open for new layers until something is selected. */+const composing = ref(false)++/**+ * Generated code needs a selection; without one the panel says so instead of showing a+ * template that looks like a real layer. Writing new Design JSX is an explicit action.+ */+const showEmptyState = computed(+ () =>+ source.value !== 'html-css' &&+ store.state.selectedIds.size === 0 &&+ !composing.value &&+ !designSession.value &&+ !edited.value+)++watch(+ () => store.state.selectedIds.size,+ (size) => {+ if (size > 0) composing.value = false+ }+)++function writeJSX() {+ composing.value = true+}+const codeLayers = useCodeLayers(source)const sourceOptions = computed(() => [{ value: 'design-jsx' as const, label: code.value.sourceDesignJSX },@@ -61,7 +100,6 @@ const sourceOptions = computed(() => [{ value: 'html-css' as const, label: code.value.sourceHTMLCSS }])const readOnly = computed(() => source.value === 'tailwind-jsx')-const dirty = computed(() => draft.value !== baseline.value)const editorLabel = computed(() =>source.value === 'html-css' ? code.value.editorHTMLCSSLabel : code.value.editorDesignLabel)@@ -75,7 +113,7 @@ const statusStyles = computed(() => tv(statusTheme)({ tone: statusTone.value }))const statusText = computed(() => {if (status.value === 'updating') return code.value.updatingif (status.value === 'error') return code.value.previewFailed- if (dirty.value) return code.value.updatedLive+ if (edited.value) return code.value.updatedLivereturn code.value.jsxUpToDate})@@ -96,17 +134,16 @@ function beginDOMSession(): DOMCodeSession {return domSession}+/** Design JSX previews are recorded as they apply; an HTML/CSS preview is committed here. */async function commitCurrentSession(): Promise<void> {if (commitPromise) return commitPromiseconst operation = (async () => {await pendingPreviewawait previewQueueupdateVersion += 1- const design = designSession.valueconst dom = domSessiondesignSession.value = nulldomSession = null- if (design) commitDesignJSXSession(store, design)if (dom) commitDOMCodeSession(store, dom)pendingPreview = undefined})()@@ -122,16 +159,27 @@ async function runPreview(version: number): Promise<void> {if (version !== updateVersion || readOnly.value || !draft.value.trim()) returnstatus.value = 'updating'error.value = ''+ previewing += 1let result: { ok: true } | { ok: false; error: string }- if (source.value === 'html-css') {- result = await previewDOMCode(store, beginDOMSession(), draft.value)- } else {- const session = beginDesignSession()- result = session- ? await previewDesignJSX(store, session, draft.value)- : { ok: false, error: error.value }+ let previewLayers: DesignJSXLayerLine[] | null = null+ try {+ if (source.value === 'html-css') {+ result = await previewDOMCode(store, beginDOMSession(), draft.value)+ } else {+ const session = beginDesignSession()+ const preview = session+ ? await previewDesignJSX(store, session, draft.value)+ : ({ ok: false, error: error.value } as const)+ if (preview.ok) previewLayers = preview.layers+ result = preview+ }+ } finally {+ previewing -= 1+ previewedVersion = store.state.sceneVersion+ followedSelection = selectionKey.value}if (version !== updateVersion) return+ if (previewLayers) codeLayers.showPreview(previewLayers)if (!result.ok) {status.value = 'error'error.value = result.error@@ -149,8 +197,11 @@ const schedulePreview = useDebounceFn({ maxWait: 1_000 })-function updateDraft(value: string): void {+function updateDraft(value: string, origin: 'user' | 'layers'): void {draft.value = value+ // Patches from the canvas already match it; only the person's typing renders.+ if (origin === 'layers') return+ edited.value = trueerror.value = ''updateVersion += 1pendingPreview = schedulePreview(updateVersion)@@ -167,45 +218,70 @@ async function resetDraft(): Promise<void> {if (design) resetDesignJSXPreview(store, design)if (dom) resetDOMCodePreview(store, dom)pendingPreview = undefined- draft.value = baseline.valueerror.value = ''status.value = 'idle'+ edited.value = false+ if (source.value === 'html-css') draft.value = starterSourceFor('html-css')+ else showCanvas(source.value)}async function changeSource(next: CodeSource): Promise<void> {if (next === source.value) returnawait commitCurrentSession()source.value = next- const initial = next === 'html-css' ? starterSourceFor(next) : generatedFor(next)- baseline.value = initial- draft.value = initial+ edited.value = falseerror.value = ''status.value = 'idle'+ if (next === 'html-css') {+ codeLayers.showGenerated(null)+ draft.value = starterSourceFor(next)+ } else {+ showCanvas(next)+ }}-function generatedFor(next: Exclude<CodeSource, 'html-css'>): string {- return generatedSourceFor(next, store.graph, [...store.state.selectedIds])+const selectionKey = computed(() => [...store.state.selectedIds].join(','))++/** Shows the code generated for the selection, replacing whatever the editor held. */+function showCanvas(next: Exclude<CodeSource, 'html-css'>) {+ const generated: GeneratedCode = generatedCodeFor(next, store.graph, [...store.state.selectedIds])+ followedSelection = selectionKey.value+ codeLayers.showGenerated(generated)+ draft.value = generated.code}-watch(- generatedJSX,- (value) => {- if (source.value === 'html-css' || designSession.value || dirty.value) return- baseline.value = value- draft.value = value- },- { immediate: true }-)+/**+ * Keeps the code in step with the canvas, like the Design panel. Code nobody has written in is+ * generated again; code the person wrote is patched where layers changed, keeping the rest as+ * written. Another selection starts over with its generated code.+ */+function followCanvas() {+ const current = source.value+ if (!editorActive.value || current === 'html-css' || previewing > 0) return+ if (selectionKey.value !== followedSelection) {+ if (designSession.value) designSession.value = null+ edited.value = false+ }+ if (!edited.value) {+ showCanvas(current)+ return+ }+ if (store.state.sceneVersion === previewedVersion) return+ codeEditor.value?.patchFromLayers()+}++watch([() => store.state.sceneVersion, selectionKey, source, editorActive], followCanvas, {+ immediate: true+})onBeforeUnmount(() => {- disposing = truevoid commitCurrentSession()})watch(() => editorActive.value,(value) => {- if (!value && !disposing) void commitCurrentSession()+ if (!value) void commitCurrentSession()})</script>@@ -236,13 +312,41 @@ watch(</Tip></header>- <div class="flex min-h-0 flex-1 flex-col overflow-hidden">+ <AppPlaceholder+ v-if="showEmptyState"+ :label="code.noSelection"+ :description="+ source === 'design-jsx' ? code.noSelectionDesignJSX : code.noSelectionTailwindJSX+ "+ :fill="false"+ :ui="{ root: 'pt-10' }"+ data-test-id="code-panel-empty"+ >+ <template #icon>+ <icon-lucide-code class="size-4" />+ </template>+ <template v-if="source === 'design-jsx'" #action>+ <AppButton color="neutral" variant="soft" size="xs" @click="writeJSX">+ <icon-lucide-pencil class="size-3" />+ {{ code.writeJSX }}+ </AppButton>+ </template>+ </AppPlaceholder>++ <div v-else class="flex min-h-0 flex-1 flex-col overflow-hidden"><CodeEditor+ ref="codeEditor"+ :autofocus="composing":model-value="draft":language="source":read-only="readOnly":label="editorLabel"+ :layer-links="codeLayers.links.value"+ :layer-issues="codeLayers.issues.value"@update:model-value="updateDraft"+ :describe-layer="source === 'design-jsx' ? codeLayers.describe : undefined"+ :layer-snippet="source === 'design-jsx' ? codeLayers.snippet : undefined"+ @active-layers="codeLayers.markActive"/></div>@@ -256,6 +360,7 @@ watch(</div><footer+ v-if="!showEmptyState"class="flex shrink-0 items-center justify-between gap-2 border-t border-border px-3 py-2"><span@@ -268,7 +373,7 @@ watch(</span><div class="flex items-center gap-1"><AppButton- v-if="dirty && !readOnly"+ v-if="edited && !readOnly"color="neutral"variant="ghost"size="xs"diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex edc43371f..77645bf95 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -143,7 +143,7 @@ const { detailMarker: hoveredIssueMarker, cursor: issueMarkerCursor } = useCanva// An edge pin leads to its nearest issue; a marker opens every layer it covers.const nodeIds = marker.direction ? marker.nodeIds.slice(0, 1) : marker.nodeIdsstore.designCheck.openMarker(nodeIds)- if (marker.direction && nodeIds[0]) store.designCheck.revealNode(nodeIds[0])+ if (marker.direction) store.revealNodes(nodeIds)}})diff --git a/src/components/code-editor/CodeEditor.vue b/src/components/code-editor/CodeEditor.vueindex 21bb637ca..741f4b822 100644--- a/src/components/code-editor/CodeEditor.vue+++ b/src/components/code-editor/CodeEditor.vue@@ -18,7 +18,20 @@ import {} from '@codemirror/view'import { useTemplateRef, watch } from 'vue'+import { DESIGN_JSX_ELEMENTS, type DesignJSXElement } from '@open-pencil/design-jsx'+import { useI18n } from '@open-pencil/vue'++import type { LayerIssue } from '@/app/code/layers/issues'+import type { LayerLinkSource } from '@/app/code/layers/links'import { designJSXExtensions } from '@/components/code-editor/extensions'+import type { LayerSnippet } from '@/components/code-editor/layers/context'+import { layerIssueDiagnostics, setLayerIssues } from '@/components/code-editor/layers/issues'+import {+ layerLinks as layerLinksExtension,+ setLayerLinks+} from '@/components/code-editor/layers/links'+import { fromLayers, layerPatch } from '@/components/code-editor/layers/patch'+import { staleAttributes } from '@/components/code-editor/layers/stale'import type { CodeEditorLanguage } from '@/components/code-editor/types'import { useCodeMirror } from '@/components/code-editor/useCodeMirror'import { codeEditorTheme } from '@/theme/code/editor'@@ -27,18 +40,42 @@ const {modelValue,language = 'design-jsx',readOnly = false,- label = 'Code'+ label = 'Code',+ layerLinks = null,+ layerIssues = [],+ autofocus = false,+ describeLayer,+ layerSnippet} = defineProps<{modelValue: stringlanguage?: CodeEditorLanguagereadOnly?: booleanlabel?: string+ /** How elements in the code map to canvas layers; `null` when they do not. */+ layerLinks?: LayerLinkSource | null+ /** Design issues to underline on the code of their layers. */+ layerIssues?: readonly LayerIssue[]+ /** Places the caret at the end of the code once the editor mounts. */+ autofocus?: boolean+ /** Describes a linked layer as Design JSX, which enables patching the code from the canvas. */+ describeLayer?: (nodeId: string) => DesignJSXElement | null+ /** Design JSX for a layer added on the canvas, with the layer of each element. */+ layerSnippet?: LayerSnippet}>()const emit = defineEmits<{- 'update:modelValue': [value: string]+ /** Text changed: typed by the person, or patched from the canvas (`layers`). */+ 'update:modelValue': [value: string, origin: 'user' | 'layers']+ /** The layers of the element around the cursor, or `null` when there is none or focus left. */+ activeLayers: [nodeIds: readonly string[] | null]}>()+const { code } = useI18n()++const RUNTIME_TYPES = new Map(+ DESIGN_JSX_ELEMENTS.map(({ name, runtimeType }) => [name, runtimeType])+)+let externalUpdate = falsefunction languageExtensions(language: CodeEditorLanguage): Extension {@@ -49,8 +86,12 @@ function languageExtensions(language: CodeEditorLanguage): Extension {]}+/** Read-only code still takes a cursor, which picks the layer to mark on the canvas. */function editableExtensions(readOnly: boolean): Extension {- return [EditorState.readOnly.of(readOnly), EditorView.editable.of(!readOnly)]+ return [+ EditorState.readOnly.of(readOnly),+ EditorView.contentAttributes.of({ 'aria-readonly': String(readOnly) })+ ]}const view = useCodeMirror(useTemplateRef('host'), {@@ -80,15 +121,70 @@ const view = useCodeMirror(useTemplateRef('host'), {...completionKeymap,...lintKeymap]),+ layerLinksExtension({+ typeOf: (tagName) => RUNTIME_TYPES.get(tagName),+ onActive: (nodeIds) => emit('activeLayers', nodeIds),+ describe: (nodeId) => describeLayer?.(nodeId) ?? null,+ staleMessage: (stale) =>+ stale.kind === 'value'+ ? code.value.canvasChangedExpression({ value: stale.value })+ : code.value.canvasChangedOrder+ }),+ staleAttributes,+ layerIssueDiagnostics(),EditorView.lineWrapping,EditorView.updateListener.of((update) => {if (!update.docChanged || externalUpdate) return- emit('update:modelValue', update.state.doc.toString())+ const patched = update.transactions.some((tr) => tr.annotation(fromLayers))+ emit('update:modelValue', update.state.doc.toString(), patched ? 'layers' : 'user')})],reactive: [() => languageExtensions(language), () => editableExtensions(readOnly)]})+/** Links and issues describe the current text, so they follow a text replacement. */+function syncLayers() {+ view.value?.dispatch({+ effects: [setLayerLinks.of(layerLinks), setLayerIssues.of(layerIssues)]+ })+}++function focusEnd() {+ const editor = view.value+ if (!editor) return+ editor.focus()+ editor.dispatch({ selection: { anchor: editor.state.doc.length } })+}++// The view exists once mounted; it then takes the links, issues and focus it was given.+watch(+ view,+ (editor) => {+ if (!editor) return+ syncLayers()+ if (autofocus) focusEnd()+ },+ { once: true }+)++/**+ * Replaces only the span that differs, so the cursor and scroll position outside it stay put+ * when regenerated code changes one value.+ */+function minimalChange(current: string, next: string) {+ let start = 0+ while (start < current.length && current[start] === next[start]) start+++ let end = 0+ while (+ end < current.length - start &&+ end < next.length - start &&+ current[current.length - 1 - end] === next[next.length - 1 - end]+ ) {+ end+++ }+ return { from: start, to: current.length - end, insert: next.slice(start, next.length - end) }+}+watch(() => modelValue,(value) => {@@ -96,12 +192,43 @@ watch(if (!editor || editor.state.doc.toString() === value) returnexternalUpdate = trueeditor.dispatch({- changes: { from: 0, to: editor.state.doc.length, insert: value },+ changes: minimalChange(editor.state.doc.toString(), value),annotations: Transaction.addToHistory.of(false)})externalUpdate = false+ syncLayers()})++// A link source describes the text it arrived with; re-applying it after patches would link+// elements by stale lines, so only a new source re-links.+watch(+ () => layerLinks,+ (links) => view.value?.dispatch({ effects: setLayerLinks.of(links) })+)+watch(+ () => layerIssues,+ (issues) => view.value?.dispatch({ effects: setLayerIssues.of(issues) })+)++/**+ * Brings canvas changes to linked layers into the code as small edits, keeping everything else+ * as written. Returns whether the code changed.+ */+function patchFromLayers(): boolean {+ const editor = view.value+ if (!editor || !layerSnippet) return false+ const spec = layerPatch(editor.state, layerSnippet)+ if (!spec) return false+ const before = editor.state.doc+ editor.dispatch({+ ...spec,+ annotations: [fromLayers.of(true), Transaction.addToHistory.of(false)]+ })+ return editor.state.doc !== before+}++defineExpose({ patchFromLayers })</script><template>diff --git a/src/components/code-editor/layers/attributes.ts b/src/components/code-editor/layers/attributes.tsnew file mode 100644index 000000000..e7bcb2268--- /dev/null+++ b/src/components/code-editor/layers/attributes.ts@@ -0,0 +1,177 @@+import type { EditorState } from '@codemirror/state'++import {+ DESIGN_JSX_PROPERTY_ALIASES,+ DESIGN_JSX_STYLE_KEYS,+ designJSXPropertyNames,+ type DesignJSXElement+} from '@open-pencil/design-jsx'++import type { PatchContext } from './context'+import { attributeName, isLiteralAttribute, type SyntaxNode } from './syntax'++/** Alias → the name Design JSX writes, e.g. `width` → `w`. */+const CANONICAL_NAMES = new Map(+ Object.entries(DESIGN_JSX_PROPERTY_ALIASES).flatMap(([name, aliases]) =>+ aliases.map((alias) => [alias, name] as const)+ )+)++/**+ * The attributes of a tag by the name Design JSX writes, so `width={320}` answers for `w`. When+ * several names of one property are written, the one the renderer reads wins.+ */+function writtenAttributes(+ state: EditorState,+ tag: SyntaxNode+): Map<string, { attribute: SyntaxNode; name: string }> {+ const written = new Map<string, { attribute: SyntaxNode; name: string; rank: number }>()+ for (const attribute of tag.getChildren('JSXAttribute')) {+ const name = attributeName(state, attribute)+ const canonical = CANONICAL_NAMES.get(name) ?? name+ const rank = designJSXPropertyNames(canonical).indexOf(name)+ const current = written.get(canonical)+ if (!current || rank < current.rank) written.set(canonical, { attribute, name, rank })+ }+ return written+}++/** The value an exported attribute holds: `w={400}` → 400, `bg="#FFF"` → `#FFF`. */+function attributeValue(attribute: string): number | string | null {+ const raw = attribute.slice(attribute.indexOf('=') + 1)+ if (raw.startsWith('"')) return raw.slice(1, -1)+ if (!raw.startsWith('{')) return null+ try {+ const value: unknown = JSON.parse(raw.slice(1, -1))+ return typeof value === 'number' || typeof value === 'string' ? value : null+ } catch {+ return null+ }+}++/** The `style={{ … }}` entry the renderer reads for a property, if written as a literal object. */+function styleEntry(+ state: EditorState,+ tag: SyntaxNode,+ name: string+): { property: SyntaxNode; px: boolean } | null {+ const keys = Object.hasOwn(DESIGN_JSX_STYLE_KEYS, name) ? DESIGN_JSX_STYLE_KEYS[name] : null+ const style = tag+ .getChildren('JSXAttribute')+ .find((attribute) => attributeName(state, attribute) === 'style')+ const object = style?.getChild('JSXEscape')?.getChild('ObjectExpression')+ if (!keys || !object) return null+ const properties = object.getChildren('Property').map((property) => {+ const key = property.firstChild+ const text = key ? state.doc.sliceString(key.from, key.to) : ''+ return { property, key: text.replace(/^["']|["']$/g, '') }+ })+ for (const { key, px } of keys) {+ const found = properties.find((candidate) => candidate.key === key)+ if (found) return { property: found.property, px: px ?? false }+ }+ return null+}++/** A value for a style entry in the format already written there: `400`, or `'400px'`. */+function styleValue(written: string, kind: string, value: number | string, px: boolean) {+ if (kind === 'Number') return typeof value === 'number' ? String(value) : null+ const quote = written[0]+ const text =+ typeof value === 'number' && px && written.slice(1, -1).endsWith('px')+ ? `${value}px`+ : String(value)+ return `${quote}${text.replaceAll(quote, `\\${quote}`)}${quote}`+}++/**+ * Patches a property the person wrote inside `style={{ … }}` instead of as an attribute. Values+ * the renderer cannot read as written, such as `'50%'`, are marked rather than rewritten.+ * Returns whether the property was found there.+ */+function patchStyle(+ ctx: PatchContext,+ tag: SyntaxNode,+ name: string,+ attribute: string | undefined+): boolean {+ const entry = styleEntry(ctx.state, tag, name)+ if (!entry) return false+ const { property, px } = entry+ const valueNode = property.lastChild+ const value = attribute ? attributeValue(attribute) : null+ const written = valueNode ? ctx.state.doc.sliceString(valueNode.from, valueNode.to) : ''+ const pxReadable = !px || valueNode?.name !== 'String' || written.slice(1, -1).endsWith('px')+ const next =+ valueNode &&+ value !== null &&+ pxReadable &&+ (valueNode.name === 'Number' || valueNode.name === 'String')+ ? styleValue(written, valueNode.name, value, px)+ : null+ if (valueNode && next !== null) {+ ctx.changes.push({ from: valueNode.from, to: valueNode.to, insert: next })+ } else if (attribute) {+ ctx.stale.push({ kind: 'value', from: property.from, to: property.to, value: attribute })+ }+ return true+}++export function patchAttributes(+ ctx: PatchContext,+ tag: SyntaxNode,+ base: DesignJSXElement,+ next: DesignJSXElement+) {+ const { state } = ctx+ const written = writtenAttributes(state, tag)+ const names = new Set([...Object.keys(base.attributes), ...Object.keys(next.attributes)])+ const additions: string[] = []+ for (const name of names) {+ const value = next.attributes[name]+ if (base.attributes[name] === value) continue+ const { attribute, name: writtenName } = written.get(name) ?? {}+ if (!attribute || !writtenName) {+ if (patchStyle(ctx, tag, name, value)) continue+ if (value) additions.push(value)+ continue+ }+ if (!isLiteralAttribute(attribute)) {+ if (value) ctx.stale.push({ kind: 'value', from: attribute.from, to: attribute.to, value })+ continue+ }+ if (value) {+ // The value changes; the name stays the one the person wrote, such as `width`.+ const insert = writtenName + value.slice(name.length)+ ctx.changes.push({ from: attribute.from, to: attribute.to, insert })+ continue+ }+ const before = state.doc.sliceString(0, attribute.from)+ ctx.changes.push({+ from: attribute.from - (before.length - before.trimEnd().length),+ to: attribute.to+ })+ }+ if (additions.length === 0) return+ const attributes = tag.getChildren('JSXAttribute')+ const anchor = attributes.at(-1) ?? tag.getChild('JSXIdentifier')+ if (anchor) ctx.changes.push({ from: anchor.to, insert: ` ${additions.join(' ')}` })+}++export function patchText(ctx: PatchContext, node: SyntaxNode, text: string | null) {+ const open = node.getChild('JSXOpenTag')+ const close = node.getChild('JSXCloseTag')+ if (!open || !close) return+ // Text with expressions or elements in it is the author's; only plain text is replaced.+ for (let child = open.nextSibling; child && child.from < close.from; child = child.nextSibling) {+ if (child.name !== 'JSXText') return+ }+ const content = ctx.state.doc.sliceString(open.to, close.from)+ const leading = content.length - content.trimStart().length+ const trailing = content.length - content.trimEnd().length+ ctx.changes.push({+ from: open.to + leading,+ to: Math.max(open.to + leading, close.from - trailing),+ insert: text ?? ''+ })+}diff --git a/src/components/code-editor/layers/children.ts b/src/components/code-editor/layers/children.tsnew file mode 100644index 000000000..e1c697ef1--- /dev/null+++ b/src/components/code-editor/layers/children.ts@@ -0,0 +1,257 @@+import { ensureSyntaxTree, syntaxTree } from '@codemirror/language'+import type { EditorState } from '@codemirror/state'++import type { DesignJSXElement } from '@open-pencil/design-jsx'++import type { PatchContext, Rewrite } from './context'+import type { LinkedElement } from './links'+import { indentAt, reindent, removal, type SyntaxNode } from './syntax'++function linkedChildren(+ elements: readonly LinkedElement[],+ element: LinkedElement+): Map<string, LinkedElement> {+ const children = new Map<string, LinkedElement>()+ for (const candidate of elements) {+ if (candidate === element || candidate.from < element.from || candidate.to > element.to)+ continue+ const nodeId = candidate.nodeIds[0]+ if (!children.has(nodeId)) children.set(nodeId, candidate)+ }+ return children+}++function insertChild(+ ctx: PatchContext,+ node: SyntaxNode,+ element: LinkedElement,+ written: Map<string, LinkedElement>,+ order: readonly string[],+ nodeId: string+) {+ const snippet = ctx.snippet(nodeId)+ if (!snippet) return+ const { state } = ctx+ const index = order.indexOf(nodeId)+ const previous = order+ .slice(0, index)+ .toReversed()+ .map((id) => written.get(id))+ .find(Boolean)+ const following = order+ .slice(index + 1)+ .map((id) => written.get(id))+ .find(Boolean)+ const parentIndent = indentAt(state, element.from)+ const sibling = previous ?? following+ const indent = sibling ? indentAt(state, sibling.from) : `${parentIndent} `+ const code = reindent(snippet.code, indent)+ if (previous) {+ const text = `\n${indent}${code}`+ ctx.insertions.push({+ at: previous.to,+ text,+ offset: 1 + indent.length,+ layerIds: snippet.layerIds+ })+ return+ }+ if (following) {+ const at = state.doc.lineAt(following.from).from+ ctx.insertions.push({+ at,+ text: `${indent}${code}\n`,+ offset: indent.length,+ layerIds: snippet.layerIds+ })+ return+ }+ const open = node.getChild('JSXOpenTag')+ if (open) {+ ctx.insertions.push({+ at: open.to,+ text: `\n${indent}${code}`,+ offset: 1 + indent.length,+ layerIds: snippet.layerIds+ })+ return+ }+ // A self-closing parent opens up to hold its first child.+ const selfClosing = node.getChild('JSXSelfClosingTag')+ const end = selfClosing?.lastChild+ if (!selfClosing || !end) return+ const before = state.doc.sliceString(selfClosing.from, end.from)+ const from = selfClosing.from + before.trimEnd().length+ const tag = state.doc.sliceString(element.nameFrom, element.nameTo)+ const text = `>\n${indent}${code}\n${parentIndent}</${tag}>`+ ctx.changes.push({ from, to: end.to })+ ctx.insertions.push({ at: end.to, text, offset: 2 + indent.length, layerIds: snippet.layerIds })+}++/** A blank line or a JSX comment, which travels with the element below it. */+const TRIVIA_LINE = /^\s*(\{\s*\/\*.*\*\/\s*\})?\s*$/++/** Layer ids of the elements in a range, in pre-order, `null` for unlinked ones. */+function layerIdsWithin(+ state: EditorState,+ elements: readonly LinkedElement[],+ from: number,+ to: number+): Array<string | null> {+ const ids: Array<string | null> = []+ const tree = ensureSyntaxTree(state, state.doc.length, 250) ?? syntaxTree(state)+ tree.iterate({+ from,+ to,+ enter(node) {+ if (node.name !== 'JSXElement' || node.from < from || node.to > to) return+ const linked = elements.find((e) => e.from === node.from && e.to === node.to)+ ids.push(linked?.nodeIds[0] ?? null)+ }+ })+ return ids+}++/** A child element with the blank lines and comments above it, kept exactly as written. */+interface Block {+ /** Where the block, comments included, starts in the document. */+ start: number+ text: string+ /** Where the element starts in the block's text, and its length. */+ offset: number+ length: number+ /** Where the element starts in the document. */+ from: number+}++/** Whether only blank lines and JSX comments sit between two child elements. */+function isTrivia(text: string): boolean {+ return (+ !text ||+ text+ .slice(0, -1)+ .split('\n')+ .every((line) => TRIVIA_LINE.test(line))+ )+}++/**+ * Splits the children span into blocks, or returns `null` when a child shares its lines with+ * other code or something other than comments sits between children.+ */+function childBlocks(+ state: EditorState,+ start: number,+ children: ReadonlyArray<{ id: string; child: LinkedElement }>+): Map<string, Block> | null {+ const { doc } = state+ const blocks = new Map<string, Block>()+ let leadFrom = start+ for (const { id, child } of children) {+ const first = doc.lineAt(child.from)+ const last = doc.lineAt(child.to)+ const aloneOnLines =+ !doc.sliceString(first.from, child.from).trim() && !doc.sliceString(child.to, last.to).trim()+ if (!aloneOnLines || leadFrom > first.from) return null+ if (!isTrivia(doc.sliceString(leadFrom, first.from))) return null+ blocks.set(id, {+ start: leadFrom,+ text: doc.sliceString(leadFrom, last.to),+ offset: child.from - leadFrom,+ length: child.to - child.from,+ from: child.from+ })+ leadFrom = last.to + 1+ }+ return blocks+}++/**+ * Moves child elements into the canvas order: each child, with the blank lines and comments+ * above it, is a block kept exactly as written, and the span of all blocks is written again in+ * the new order, with added layers generated and removed ones left out. Returns `false` when+ * the children cannot be moved safely, such as code between them that is not a layer.+ */+function reorderChildren(+ ctx: PatchContext,+ node: SyntaxNode,+ elements: readonly LinkedElement[],+ written: Map<string, LinkedElement>,+ base: DesignJSXElement,+ next: DesignJSXElement+): boolean {+ const { doc } = ctx.state+ const open = node.getChild('JSXOpenTag')+ const children = base.childIds.flatMap((id) => {+ const child = written.get(id)+ return child ? [{ id, child }] : []+ })+ const last = children.at(-1)+ if (!open || !last || doc.sliceString(open.to, doc.lineAt(open.to).to).trim()) return false+ const from = doc.lineAt(open.to).to + 1+ const blocks = childBlocks(ctx.state, from, children)+ if (!blocks) return false+ const indent = indentAt(ctx.state, children[0].child.from)+ const rewrite: Rewrite = {+ from,+ to: doc.lineAt(last.child.to).to,+ text: '',+ links: [],+ moves: []+ }+ const parts: string[] = []+ let offset = 0+ for (const id of next.childIds) {+ const block = blocks.get(id)+ const snippet = block ? null : ctx.snippet(id)+ const text = block?.text ?? (snippet && `${indent}${reindent(snippet.code, indent)}`)+ if (!text) continue+ if (block) rewrite.moves.push({ from: block.start, to: block.start + text.length, offset })+ rewrite.links.push({+ offset: offset + (block?.offset ?? indent.length),+ length: block?.length ?? text.length - indent.length,+ layerIds: block+ ? layerIdsWithin(ctx.state, elements, block.from, block.from + block.length)+ : (snippet?.layerIds ?? [])+ })+ parts.push(text)+ offset += text.length + 1+ }+ rewrite.text = parts.join('\n')+ ctx.rewrites.push(rewrite)+ ctx.removed.push({ from: rewrite.from, to: rewrite.to })+ return true+}++export function patchChildren(+ ctx: PatchContext,+ node: SyntaxNode,+ element: LinkedElement,+ elements: readonly LinkedElement[],+ base: DesignJSXElement,+ next: DesignJSXElement+) {+ const written = linkedChildren(elements, element)+ const survivors = new Set(next.childIds.filter((id) => base.childIds.includes(id)))+ const before = base.childIds.filter((id) => survivors.has(id) && written.has(id))+ const after = next.childIds.filter((id) => survivors.has(id) && written.has(id))+ if (before.some((id, index) => id !== after[index])) {+ // A reorder rewrites the children with their additions and removals included.+ if (reorderChildren(ctx, node, elements, written, base, next)) return+ // Children that cannot move keep their order, which is marked; layers added or deleted+ // in the same change still reach the code.+ ctx.stale.push({ kind: 'order', from: element.nameFrom, to: element.nameTo })+ }+ const kept = new Set(next.childIds)+ for (const id of base.childIds) {+ const child = written.get(id)+ if (kept.has(id) || !child) continue+ const change = removal(ctx.state, child.from, child.to)+ ctx.changes.push(change)+ ctx.removed.push({ from: child.from, to: child.to })+ }+ const previous = new Set(base.childIds)+ for (const id of next.childIds) {+ if (!previous.has(id)) insertChild(ctx, node, element, written, next.childIds, id)+ }+}diff --git a/src/components/code-editor/layers/context.ts b/src/components/code-editor/layers/context.tsnew file mode 100644index 000000000..828ceb524--- /dev/null+++ b/src/components/code-editor/layers/context.ts@@ -0,0 +1,26 @@+import type { ChangeSpec, EditorState } from '@codemirror/state'++import type { StaleAttribute } from './stale'++/** Snippets of new layers: exported Design JSX and the layer of each element, in order. */+export type LayerSnippet = (nodeId: string) => { code: string; layerIds: string[] } | null++/** Text replacing a range, with the elements in it to link, by offset into the text. */+export interface Rewrite {+ from: number+ to: number+ text: string+ links: Array<{ offset: number; length: number; layerIds: Array<string | null> }>+ /** Blocks kept from the old text: their range there and their offset into the new text. */+ moves: Array<{ from: number; to: number; offset: number }>+}++export interface PatchContext {+ state: EditorState+ changes: ChangeSpec[]+ stale: StaleAttribute[]+ rewrites: Rewrite[]+ insertions: Array<{ at: number; text: string; offset: number; layerIds: string[] }>+ removed: Array<{ from: number; to: number }>+ snippet: LayerSnippet+}diff --git a/src/components/code-editor/layers/issues.ts b/src/components/code-editor/layers/issues.tsnew file mode 100644index 000000000..698cc44b0--- /dev/null+++ b/src/components/code-editor/layers/issues.ts@@ -0,0 +1,101 @@+import { syntaxTree } from '@codemirror/language'+import { linter, type Diagnostic } from '@codemirror/lint'+import { StateEffect, StateField, type EditorState, type Extension } from '@codemirror/state'++import { designJSXPropertyNames } from '@open-pencil/design-jsx'++import type { LayerIssue } from '@/app/code/layers/issues'++import { layerLinkConfig, linkedElements, setLayerLinks, type LinkedElement } from './links'+import { staleAttributes } from './stale'++export const setLayerIssues = StateEffect.define<readonly LayerIssue[]>()++const layerIssues = StateField.define<readonly LayerIssue[]>({+ create: () => [],+ update(value, transaction) {+ for (const effect of transaction.effects) if (effect.is(setLayerIssues)) return effect.value+ return value+ }+})++interface TextRange {+ from: number+ to: number+}++/** The first of `props` set on the element's opening tag, as written in the code. */+function attributeRange(+ state: EditorState,+ element: LinkedElement,+ props: readonly string[]+): TextRange | null {+ if (props.length === 0) return null+ // A property written under an alias, such as `width` for `w`, is the same property.+ const names = props.flatMap((name) => designJSXPropertyNames(name))+ const matches: Array<TextRange & { rank: number }> = []+ syntaxTree(state).iterate({+ from: element.from,+ to: element.openTo,+ enter(node) {+ // Ancestors contain the element; only nested elements' attributes belong to others.+ if (node.name === 'JSXElement' && node.from > element.from) return false+ if (node.name !== 'JSXAttribute') return undefined+ const name = node.node.firstChild+ const rank = name ? names.indexOf(state.doc.sliceString(name.from, name.to)) : -1+ if (rank !== -1) matches.push({ from: node.from, to: node.to, rank })+ return false+ }+ })+ const best = matches.toSorted((a, b) => a.rank - b.rank).at(0)+ return best ? { from: best.from, to: best.to } : null+}++function diagnosticsFor(state: EditorState): Diagnostic[] {+ const issues = state.field(layerIssues)+ const byNode = new Map<string, LayerIssue[]>()+ for (const issue of issues) byNode.set(issue.nodeId, [...(byNode.get(issue.nodeId) ?? []), issue])+ const diagnostics: Diagnostic[] = []+ const seen = new Set<string>()+ for (const element of state.field(linkedElements)) {+ for (const nodeId of element.nodeIds) {+ for (const issue of byNode.get(nodeId) ?? []) {+ const range = attributeRange(state, element, issue.props) ?? {+ from: element.nameFrom,+ to: element.nameTo+ }+ // Layers repeated from one element, such as a component used twice, report once.+ const key = `${range.from}:${range.to}:${issue.message}`+ if (seen.has(key)) continue+ seen.add(key)+ diagnostics.push({ ...range, severity: issue.severity, message: issue.message })+ }+ }+ }+ for (const range of state.field(staleAttributes, false) ?? []) {+ const message = state.facet(layerLinkConfig)?.staleMessage?.(range)+ if (message) diagnostics.push({ from: range.from, to: range.to, severity: 'info', message })+ }+ return diagnostics+}++/**+ * Underlines code whose layers have design issues, on the attribute that causes them, and+ * expression attributes whose layers changed on the canvas since.+ */+export function layerIssueDiagnostics(): Extension {+ return [+ layerIssues,+ linter((view) => diagnosticsFor(view.state), {+ delay: 0,+ needsRefresh: (update) =>+ update.transactions.some((transaction) =>+ transaction.effects.some(+ (effect) => effect.is(setLayerIssues) || effect.is(setLayerLinks)+ )+ ) ||+ update.startState.field(staleAttributes, false) !==+ update.state.field(staleAttributes, false)+ })+ ]+}diff --git a/src/components/code-editor/layers/links.ts b/src/components/code-editor/layers/links.tsnew file mode 100644index 000000000..7b9de387d--- /dev/null+++ b/src/components/code-editor/layers/links.ts@@ -0,0 +1,294 @@+import { ensureSyntaxTree, syntaxTree } from '@codemirror/language'+import {+ Facet,+ StateEffect,+ StateField,+ type ChangeDesc,+ type EditorState,+ type Extension+} from '@codemirror/state'+import {+ Decoration,+ EditorView,+ ViewPlugin,+ type DecorationSet,+ type ViewUpdate+} from '@codemirror/view'++import type { DesignJSXElement } from '@open-pencil/design-jsx'++import type { LayerLinkSource } from '@/app/code/layers/links'++import type { StaleAttribute } from './stale'++/** A JSX element in the document and the layers it produced. */+export interface LinkedElement {+ from: number+ to: number+ /** End of the opening tag, where issues on the element's attributes are underlined. */+ openTo: number+ nameFrom: number+ nameTo: number+ /** The closing tag's name; an empty range for a self-closing element. */+ closeNameFrom: number+ closeNameTo: number+ nodeIds: string[]+ /**+ * The layer as Design JSX wrote it when the code was last in sync with it; a canvas change+ * patches the code where the layer's description differs from this base.+ */+ base: DesignJSXElement | null+}++export interface LayerLinkConfig {+ /** Runtime type of a tag name, to tell elements on the same line apart. */+ typeOf?: (tagName: string) => string | undefined+ /** The layers of the element around the cursor while the editor has focus, else `null`. */+ onActive: (nodeIds: readonly string[] | null) => void+ /** The layer as Design JSX writes it now, or `null` when it cannot be patched. */+ describe?: (nodeId: string) => DesignJSXElement | null+ /** Explains code the canvas has changed since but could not patch. */+ staleMessage?: (stale: StaleAttribute) => string+}++type SyntaxNode = ReturnType<typeof syntaxTree>['topNode']++export const setLayerLinks = StateEffect.define<LayerLinkSource | null>()++/** The code now matches these layers as described: the new base of each. */+export const setLayerBases = StateEffect.define<ReadonlyMap<string, DesignJSXElement | null>>()++/** Links elements written into `from`..`to` of the new document to layers, in element order. */+export const linkInsertedElements = StateEffect.define<{+ from: number+ to: number+ layerIds: ReadonlyArray<string | null>+}>()++export const layerLinkConfig = Facet.define<LayerLinkConfig, LayerLinkConfig | null>({+ combine: (values) => values.at(-1) ?? null+})++const TAG_NAMES = new Set([+ 'JSXIdentifier',+ 'JSXBuiltin',+ 'JSXMemberExpression',+ 'JSXNamespacedName'+])++interface ParsedElement {+ from: number+ to: number+ openTo: number+ nameFrom: number+ nameTo: number+ closeNameFrom: number+ closeNameTo: number+ name: string+ line: number+}++function openingTag(element: SyntaxNode): SyntaxNode | null {+ return element.getChild('JSXOpenTag') ?? element.getChild('JSXSelfClosingTag')+}++function tagName(tag: SyntaxNode): SyntaxNode | null {+ for (let child = tag.firstChild; child; child = child.nextSibling) {+ if (TAG_NAMES.has(child.name)) return child+ }+ return null+}++/** JSX elements in pre-order, the order in which exporters write layers. */+function parseElements(state: EditorState, from = 0, to = state.doc.length): ParsedElement[] {+ const tree = ensureSyntaxTree(state, state.doc.length, 250) ?? syntaxTree(state)+ const elements: ParsedElement[] = []+ tree.iterate({+ from,+ to,+ enter(node) {+ if (node.from < from || node.to > to) return+ if (node.name !== 'JSXElement') return+ const tag = openingTag(node.node)+ const name = tag && tagName(tag)+ if (!tag || !name) return+ const closeTag = node.node.getChild('JSXCloseTag')+ const closeName = closeTag && tagName(closeTag)+ elements.push({+ from: node.from,+ to: node.to,+ openTo: tag.to,+ nameFrom: name.from,+ nameTo: name.to,+ closeNameFrom: closeName?.from ?? name.to,+ closeNameTo: closeName?.to ?? name.to,+ name: state.doc.sliceString(name.from, name.to),+ line: state.doc.lineAt(node.from).number+ })+ }+ })+ return elements+}++function linkByOrder(+ elements: ParsedElement[],+ layerIds: ReadonlyArray<string | null>+): LinkedElement[] {+ const linked: LinkedElement[] = []+ for (const [index, element] of elements.entries()) {+ const nodeId = layerIds[index]+ if (nodeId) linked.push({ ...element, nodeIds: [nodeId], base: null })+ }+ return linked+}++function linkByLines(+ elements: ParsedElement[],+ layers: ReadonlyArray<{ line: number; type: string; nodeId: string }>,+ typeOf: LayerLinkConfig['typeOf']+) {+ const byElement = new Map<ParsedElement, string[]>()+ for (const layer of layers) {+ const onLine = elements.filter((element) => element.line === layer.line)+ const element =+ onLine.find((candidate) => typeOf?.(candidate.name) === layer.type) ?? onLine.at(0)+ if (!element) continue+ const ids = byElement.get(element) ?? []+ ids.push(layer.nodeId)+ byElement.set(element, ids)+ }+ return [...byElement].map(([element, nodeIds]): LinkedElement => ({+ ...element,+ nodeIds,+ base: null+ }))+}++/** Records what each layer looks like now, which is what the code was linked against. */+function withBases(state: EditorState, elements: LinkedElement[]): LinkedElement[] {+ const describe = state.facet(layerLinkConfig)?.describe+ if (!describe) return elements+ return elements.map((element) => ({ ...element, base: describe(element.nodeIds[0]) }))+}++function resolveLinks(state: EditorState, source: LayerLinkSource | null): LinkedElement[] {+ if (!source) return []+ const elements = parseElements(state)+ const linked =+ source.kind === 'order'+ ? linkByOrder(elements, source.layerIds)+ : linkByLines(elements, source.layers, state.facet(layerLinkConfig)?.typeOf)+ return withBases(state, linked)+}++function mapElement(element: LinkedElement, changes: ChangeDesc): LinkedElement | null {+ const from = changes.mapPos(element.from, 1)+ const to = changes.mapPos(element.to, -1)+ if (to <= from) return null+ return {+ ...element,+ from,+ to,+ openTo: changes.mapPos(element.openTo, -1),+ nameFrom: changes.mapPos(element.nameFrom, 1),+ nameTo: changes.mapPos(element.nameTo, -1),+ closeNameFrom: changes.mapPos(element.closeNameFrom, 1),+ closeNameTo: changes.mapPos(element.closeNameTo, -1)+ }+}++/** Linked elements, kept in place through edits until the next source replaces them. */+export const linkedElements = StateField.define<LinkedElement[]>({+ create: () => [],+ update(value, transaction) {+ for (const effect of transaction.effects) {+ if (effect.is(setLayerLinks)) return resolveLinks(transaction.state, effect.value)+ }+ let next = value+ if (transaction.docChanged) {+ next = next.flatMap((element) => mapElement(element, transaction.changes) ?? [])+ }+ for (const effect of transaction.effects) {+ if (effect.is(setLayerBases)) {+ const bases = effect.value+ next = next.map((element) => {+ const id = element.nodeIds[0]+ return bases.has(id) ? { ...element, base: bases.get(id) ?? null } : element+ })+ }+ if (effect.is(linkInsertedElements)) {+ const { from, to, layerIds } = effect.value+ const inserted = linkByOrder(parseElements(transaction.state, from, to), layerIds)+ next = [...next, ...withBases(transaction.state, inserted)].sort((a, b) => a.from - b.from)+ }+ }+ return next+ }+})++/** The innermost linked element around a document position. */+export function linkedElementAt(state: EditorState, pos: number): LinkedElement | null {+ let best: LinkedElement | null = null+ for (const element of state.field(linkedElements)) {+ if (pos < element.from || pos >= element.to) continue+ if (!best || element.to - element.from < best.to - best.from) best = element+ }+ return best+}++const activeTheme = EditorView.baseTheme({+ '.cm-layer-tag': { backgroundColor: 'rgb(59 130 246 / 0.22)', borderRadius: '2px' }+})++/** Marks the tag names of the element, opening and closing, like an editor's matching tag. */+function tagDecorations(element: LinkedElement | null): DecorationSet {+ if (!element) return Decoration.none+ const mark = Decoration.mark({ class: 'cm-layer-tag' })+ const ranges = [mark.range(element.nameFrom, element.nameTo)]+ if (element.closeNameTo > element.closeNameFrom) {+ ranges.push(mark.range(element.closeNameFrom, element.closeNameTo))+ }+ return Decoration.set(ranges)+}++function sameElement(a: LinkedElement | null, b: LinkedElement | null): boolean {+ return a?.from === b?.from && a?.nodeIds.join(',') === b?.nodeIds.join(',')+}++/** Follows the cursor: the element it is in while the editor has focus is the active one. */+const activeElement = ViewPlugin.fromClass(+ class {+ active: LinkedElement | null = null+ decorations: DecorationSet = Decoration.none++ constructor(readonly view: EditorView) {+ this.refresh()+ }++ update(update: ViewUpdate) {+ const replaced = update.transactions.some((tr) => tr.effects.some((e) => e.is(setLayerLinks)))+ if (update.docChanged || update.selectionSet || update.focusChanged || replaced) {+ this.refresh()+ }+ }++ destroy() {+ if (this.active) this.view.state.facet(layerLinkConfig)?.onActive(null)+ }++ refresh() {+ const { state } = this.view+ const element = this.view.hasFocus ? linkedElementAt(state, state.selection.main.head) : null+ const changed = !sameElement(element, this.active)+ this.active = element+ this.decorations = tagDecorations(element)+ if (changed) state.facet(layerLinkConfig)?.onActive(element?.nodeIds ?? null)+ }+ },+ { decorations: (plugin) => plugin.decorations }+)++/** Links JSX elements to canvas layers: the element around the cursor marks its layer. */+export function layerLinks(config: LayerLinkConfig): Extension {+ return [layerLinkConfig.of(config), linkedElements, activeElement, activeTheme]+}diff --git a/src/components/code-editor/layers/patch.ts b/src/components/code-editor/layers/patch.tsnew file mode 100644index 000000000..72830705c--- /dev/null+++ b/src/components/code-editor/layers/patch.ts@@ -0,0 +1,117 @@+import {+ Annotation,+ EditorSelection,+ type ChangeSpec,+ type EditorState,+ type StateEffect,+ type TransactionSpec+} from '@codemirror/state'++import type { DesignJSXElement } from '@open-pencil/design-jsx'++import { patchAttributes, patchText } from './attributes'+import { patchChildren } from './children'+import type { LayerSnippet, PatchContext } from './context'+import { layerLinkConfig, linkedElements, linkInsertedElements, setLayerBases } from './links'+import { markStaleAttributes, movedBlocks, movedPosition, type MovedBlock } from './stale'+import { elementNode, openingTagOf } from './syntax'++/** Marks changes written from the canvas, so they are not rendered back onto it. */+export const fromLayers = Annotation.define<boolean>()++function sameElement(a: DesignJSXElement, b: DesignJSXElement): boolean {+ return JSON.stringify(a) === JSON.stringify(b)+}++/**+ * Patches the code where linked layers changed since it was last in sync with them: attribute+ * values, text, and added or removed child layers. Values written as expressions stay as+ * written. Returns `null` when nothing changed.+ */+export function layerPatch(state: EditorState, snippet: LayerSnippet): TransactionSpec | null {+ const describe = state.facet(layerLinkConfig)?.describe+ if (!describe) return null+ const elements = state.field(linkedElements)+ const ctx: PatchContext = {+ state,+ changes: [],+ stale: [],+ rewrites: [],+ insertions: [],+ removed: [],+ snippet+ }+ const bases = new Map<string, DesignJSXElement | null>()+ for (const element of elements) {+ const nodeId = element.nodeIds[0]+ const next = describe(nodeId)+ const base = element.base+ if (!next || !base || sameElement(base, next)) {+ if (next && !base) bases.set(nodeId, next)+ continue+ }+ bases.set(nodeId, next)+ if (ctx.removed.some((range) => element.from >= range.from && element.to <= range.to)) continue+ const node = elementNode(state, element)+ const tag = node && openingTagOf(node)+ if (!node || !tag || next.tag !== base.tag) continue+ patchAttributes(ctx, tag, base, next)+ if (base.text !== next.text) patchText(ctx, node, next.text)+ patchChildren(ctx, node, element, elements, base, next)+ }+ if (bases.size === 0) return null+ return patchTransaction(ctx, bases)+}++/** The changes a patch makes, with the links, bases and markers that describe the result. */+function patchTransaction(+ ctx: PatchContext,+ bases: Map<string, DesignJSXElement | null>+): TransactionSpec {+ const { state } = ctx+ const specs: ChangeSpec[] = [+ ...ctx.changes,+ ...ctx.rewrites.map(({ from, to, text }) => ({ from, to, insert: text })),+ ...ctx.insertions.map(({ at, text }) => ({ from: at, insert: text }))+ ]+ const changes = state.changes(specs)+ const effects: StateEffect<unknown>[] = [setLayerBases.of(bases)]+ if (ctx.stale.length > 0) {+ effects.push(+ markStaleAttributes.of(+ ctx.stale.map((range) => ({+ ...range,+ from: changes.mapPos(range.from, 1),+ to: changes.mapPos(range.to, -1)+ }))+ )+ )+ }+ const moved: MovedBlock[] = []+ for (const rewrite of ctx.rewrites) {+ const start = changes.mapPos(rewrite.from, -1)+ for (const { offset, length, layerIds } of rewrite.links) {+ effects.push(+ linkInsertedElements.of({ from: start + offset, to: start + offset + length, layerIds })+ )+ }+ for (const { from, to, offset } of rewrite.moves)+ moved.push({ from, to, newFrom: start + offset })+ }+ for (const { at, text, offset, layerIds } of ctx.insertions) {+ const from = changes.mapPos(at, -1) + offset+ effects.push(linkInsertedElements.of({ from, to: from + text.length - offset, layerIds }))+ }+ if (moved.length === 0) return { changes, effects }+ effects.push(movedBlocks.of(moved))+ const selection = EditorSelection.create(+ state.selection.ranges.map((range) =>+ EditorSelection.range(+ movedPosition(moved, changes, range.anchor, 1),+ movedPosition(moved, changes, range.head, 1)+ )+ ),+ state.selection.mainIndex+ )+ return { changes, effects, selection }+}diff --git a/src/components/code-editor/layers/stale.ts b/src/components/code-editor/layers/stale.tsnew file mode 100644index 000000000..fce7fb486--- /dev/null+++ b/src/components/code-editor/layers/stale.ts@@ -0,0 +1,70 @@+import { StateEffect, StateField, type ChangeDesc } from '@codemirror/state'++import { setLayerLinks } from './links'++/**+ * Code the canvas could not patch since its layer changed: an attribute written as an+ * expression (`value`), or children that could not be moved into the new layer order.+ */+export type StaleAttribute =+ | { kind: 'value'; from: number; to: number; /** e.g. `w={100}` */ value: string }+ | { kind: 'order'; from: number; to: number }++export const markStaleAttributes = StateEffect.define<readonly StaleAttribute[]>()++/** A block of text moved by a reorder: its range before, and where it starts after. */+export interface MovedBlock {+ from: number+ to: number+ newFrom: number+}++/** Blocks a reorder moved, so positions inside them move with their text. */+export const movedBlocks = StateEffect.define<readonly MovedBlock[]>()++/**+ * Where a position ends up: with its block when a reorder moved it, otherwise mapped like any+ * edit. A replaced span would otherwise collapse positions inside it to its edges.+ */+export function movedPosition(+ moved: readonly MovedBlock[],+ changes: ChangeDesc,+ pos: number,+ assoc: -1 | 1+): number {+ const block = moved.find((candidate) => pos >= candidate.from && pos <= candidate.to)+ return block ? block.newFrom + pos - block.from : changes.mapPos(pos, assoc)+}++/**+ * Expression attributes the canvas could not patch, until the person edits them or the code is+ * linked again. They stay as written; this only says the canvas now differs.+ */+export const staleAttributes = StateField.define<readonly StaleAttribute[]>({+ create: () => [],+ update(value, transaction) {+ if (transaction.effects.some((effect) => effect.is(setLayerLinks))) return []+ let next = value+ if (transaction.docChanged) {+ const { changes } = transaction+ const moved = transaction.effects.flatMap((effect) =>+ effect.is(movedBlocks) ? effect.value : []+ )+ next = next.flatMap((range) => {+ const block = moved.find((m) => range.from >= m.from && range.to <= m.to)+ if (block) {+ const shift = block.newFrom - block.from+ return [{ ...range, from: range.from + shift, to: range.to + shift }]+ }+ if (changes.touchesRange(range.from, range.to)) return []+ return [{ ...range, from: changes.mapPos(range.from, 1), to: changes.mapPos(range.to, -1) }]+ })+ }+ for (const effect of transaction.effects) {+ if (!effect.is(markStaleAttributes)) continue+ const marked = new Set(effect.value.map((range) => range.from))+ next = [...next.filter((range) => !marked.has(range.from)), ...effect.value]+ }+ return next+ }+})diff --git a/src/components/code-editor/layers/syntax.ts b/src/components/code-editor/layers/syntax.tsnew file mode 100644index 000000000..1ebaef0e5--- /dev/null+++ b/src/components/code-editor/layers/syntax.ts@@ -0,0 +1,82 @@+import { ensureSyntaxTree, syntaxTree } from '@codemirror/language'+import type { ChangeSpec, EditorState } from '@codemirror/state'++import type { LinkedElement } from './links'++export type SyntaxNode = ReturnType<typeof syntaxTree>['topNode']++/**+ * Expression nodes that make a value a literal: numbers, strings, booleans, negative numbers,+ * and objects or arrays of those. Anything else is the author's expression and is never+ * overwritten.+ */+const LITERAL_NODES = new Set([+ 'Number',+ 'String',+ 'BooleanLiteral',+ 'null',+ 'UnaryExpression',+ 'ArithOp',+ 'ObjectExpression',+ 'ArrayExpression',+ 'Property',+ 'PropertyDefinition',+ 'PropertyName',+ '{',+ '}',+ '[',+ ']',+ ',',+ ':'+])++export function isLiteralAttribute(attribute: SyntaxNode): boolean {+ const value = attribute.getChild('JSXEscape')+ if (!value) return true+ let literal = true+ value.cursor().iterate((node) => {+ if (node.from === value.from && node.name === 'JSXEscape') return true+ if (!LITERAL_NODES.has(node.name)) literal = false+ return literal+ })+ return literal+}++export function openingTagOf(element: SyntaxNode): SyntaxNode | null {+ return element.getChild('JSXOpenTag') ?? element.getChild('JSXSelfClosingTag')+}++export function attributeName(state: EditorState, attribute: SyntaxNode): string {+ const name = attribute.firstChild+ return name ? state.doc.sliceString(name.from, name.to) : ''+}++/** The syntax node of a linked element, if the code there is still that element. */+export function elementNode(state: EditorState, element: LinkedElement): SyntaxNode | null {+ const tree = ensureSyntaxTree(state, state.doc.length, 250) ?? syntaxTree(state)+ let node: SyntaxNode | null = tree.resolveInner(element.nameFrom, 1)+ while (node && node.name !== 'JSXElement') node = node.parent+ return node && node.from === element.from && node.to === element.to ? node : null+}++export function indentAt(state: EditorState, pos: number): string {+ return /^\s*/.exec(state.doc.lineAt(pos).text)?.[0] ?? ''+}++export function reindent(code: string, indent: string): string {+ return code+ .split('\n')+ .map((line, index) => (index === 0 || !line ? line : indent + line))+ .join('\n')+}++/** Removes a range and, when it is alone on its line, the line with it. */+export function removal(state: EditorState, from: number, to: number): ChangeSpec {+ const first = state.doc.lineAt(from)+ const last = state.doc.lineAt(to)+ const aloneOnLine =+ !first.text.slice(0, from - first.from).trim() && !last.text.slice(to - last.from).trim()+ if (!aloneOnLine) return { from, to }+ if (first.number > 1) return { from: first.from - 1, to: last.to }+ return { from: first.from, to: Math.min(last.to + 1, state.doc.length) }+}diff --git a/tests/e2e/code/layer-links.spec.ts b/tests/e2e/code/layer-links.spec.tsnew file mode 100644index 000000000..746ab28a9--- /dev/null+++ b/tests/e2e/code/layer-links.spec.ts@@ -0,0 +1,354 @@+import type { Page } from '@playwright/test'++import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'++const editor = useEditorSetup('/?test&no-rulers')++function buildScene(page: Page): Promise<void> {+ return page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageId = store.state.currentPageId+ const card = store.graph.createNode('FRAME', pageId, {+ name: 'Card',+ x: 80,+ y: 80,+ width: 320,+ height: 160,+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]+ })+ store.graph.createNode('TEXT', card.id, {+ name: 'Fine print',+ x: 16,+ y: 16,+ width: 200,+ height: 14,+ text: 'Terms apply',+ fontSize: 10,+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })+ store.graph.createNode('RECTANGLE', card.id, {+ name: 'Swatch',+ x: 16,+ y: 60,+ width: 80,+ height: 60,+ fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.4, b: 0.9, a: 1 }, visible: true, opacity: 1 }]+ })+ store.select([card.id])+ store.requestRender()+ })+}++function codeLine(page: Page, text: string) {+ return page.locator('[data-slot="code-editor"] .cm-line', { hasText: text })+}++/** The layer under the pointer on the canvas, which is separate from the code's layer. */+function hoveredLayer(page: Page) {+ return page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const id = store?.state.hoveredNodeId+ return id ? (store.graph.getNode(id)?.name ?? null) : null+ })+}++function focusedLayer(page: Page) {+ return page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const id = store?.state.codeFocusNodeId+ return id ? (store.graph.getNode(id)?.name ?? null) : null+ })+}++test.beforeEach(async () => {+ await editor.page.reload()+ await editor.canvas.waitForInit()+})++async function openCode(page: Page) {+ await page.getByTestId('properties-tab-code').click()+ await expect(codeLine(page, 'name="Swatch"')).toBeVisible()+}++function activeTags(page: Page) {+ return page.locator('[data-slot="code-editor"] .cm-layer-tag')+}++/** Moves focus out of the code, as clicking anywhere else in the app does. */+async function leaveCode(page: Page) {+ await page.getByTestId('code-panel-copy').focus()+}++function cardSize(page: Page) {+ return page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const card = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === 'Card')+ return card ? `${card.width}x${card.height}` : null+ })+}++test('the element around the cursor marks its tags and its layer', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)++ await codeLine(editor.page, 'name="Swatch"').click({ position: { x: 24, y: 8 } })+ await expect(activeTags(editor.page)).toHaveText(['Rectangle'])+ await expect.poll(() => focusedLayer(editor.page)).toBe('Swatch')++ await codeLine(editor.page, 'name="Fine print"').click({ position: { x: 24, y: 8 } })+ // Both the opening and the closing tag name are marked.+ await expect(activeTags(editor.page)).toHaveText(['Text', 'Text'])+ await expect.poll(() => focusedLayer(editor.page)).toBe('Fine print')++ // Canvas hover is a separate mark: hovering another layer keeps the code's layer marked.+ await editor.canvas.hover(130, 170)+ await expect.poll(() => hoveredLayer(editor.page)).toBe('Swatch')+ expect(await focusedLayer(editor.page)).toBe('Fine print')+ await editor.canvas.waitForRender()+ const canvas = await editor.canvas.canvas.boundingBox()+ if (!canvas) throw new Error('Canvas has no bounding box')+ expect(+ await editor.page.screenshot({+ clip: { x: canvas.x + 60, y: canvas.y + 60, width: 360, height: 200 }+ })+ ).toMatchSnapshot('code-focus-and-hover.png')++ await leaveCode(editor.page)+ await expect(activeTags(editor.page)).toHaveCount(0)+ await expect.poll(() => focusedLayer(editor.page)).toBeNull()+})++test('design issues are underlined on the property that causes them', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)++ const warning = editor.page.locator('[data-slot="code-editor"] .cm-lintRange-warning')+ await expect(warning).toHaveText('size={10}')+})++test('links follow the code after a live edit', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)++ await codeLine(editor.page, 'name="Card"').click()+ await editor.page.keyboard.press('End')+ await editor.page.keyboard.type(' ')+ await expect(editor.page.getByTestId('code-panel-status')).toHaveText('Updated live')++ // The preview replaced the layers; the cursor must resolve to a layer that still exists.+ await codeLine(editor.page, 'name="Swatch"').click({ position: { x: 24, y: 8 } })+ await expect.poll(() => focusedLayer(editor.page)).toBe('Swatch')+ await expect(editor.page.locator('[data-slot="code-editor"] .cm-lintRange-warning')).toHaveText(+ 'size={10}'+ )+})++/** Runs a canvas edit through the store, as a Design panel or canvas gesture commits it. */+function editLayer(page: Page, name: string, changes: Record<string, unknown>) {+ return page.evaluate(+ ({ name, changes }) => {+ const store = window.openPencil?.getStore?.()+ const node = [...(store?.graph.getAllNodes() ?? [])].find((n) => n.name === name)+ if (!store || !node) throw new Error(`${name} not found`)+ store.updateNodeWithUndo(node.id, changes, 'Edit')+ },+ { name, changes }+ )+}++function layerId(page: Page, name: string) {+ return page.evaluate((name) => {+ const store = window.openPencil?.getStore?.()+ return [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === name)?.id ?? null+ }, name)+}++function codeText(page: Page) {+ return page.locator('[data-slot="code-editor"] .cm-content').innerText()+}++/** Writes like a person: a comment above the card and an expression for the swatch width. */+async function personalizeCode(page: Page) {+ await codeLine(page, 'name="Card"').click()+ await page.keyboard.press('ControlOrMeta+Home')+ await page.keyboard.type('// Pricing card')+ await page.keyboard.press('Enter')+ await codeLine(page, 'name="Swatch"').locator('span', { hasText: /^80$/ }).dblclick()+ await page.keyboard.type('40 * 2')+ await expect(page.getByTestId('code-panel-status')).toHaveText('Updated live')+}++test('code edits update the layers in place', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ const swatchId = await layerId(editor.page, 'Swatch')++ await codeLine(editor.page, 'name="Swatch"').locator('span', { hasText: /^80$/ }).dblclick()+ await editor.page.keyboard.type('120')++ await expect+ .poll(() =>+ editor.page.evaluate(+ (id) => (id ? window.openPencil?.getStore?.().graph.getNode(id)?.width : null),+ swatchId+ )+ )+ .toBe(120)+})++test('canvas edits patch code a person wrote and keep the rest as written', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ await personalizeCode(editor.page)++ await editLayer(editor.page, 'Card', { width: 400 })+ await editLayer(editor.page, 'Swatch', { width: 100 })++ await expect(codeLine(editor.page, 'name="Card"')).toContainText('w={400}')+ const text = await codeText(editor.page)+ expect(text).toContain('// Pricing card')+ // The width the person wrote as an expression is theirs; the canvas does not overwrite it,+ // and the code says the canvas now differs.+ expect(text).toContain('w={40 * 2}')+ await expect(editor.page.locator('[data-slot="code-editor"] .cm-lintRange-info')).toHaveText(+ 'w={40 * 2}'+ )+})++test('layers added or deleted on the canvas are written into the code', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ await personalizeCode(editor.page)++ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const card = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === 'Card')+ const note = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === 'Fine print')+ if (!store || !card || !note) throw new Error('scene not found')+ store.graph.createNode('ELLIPSE', card.id, {+ name: 'Dot',+ x: 200,+ y: 60,+ width: 24,+ height: 24+ })+ store.graph.deleteNode(note.id)+ store.requestRender()+ })++ await expect(codeLine(editor.page, 'name="Dot"')).toBeVisible()+ await expect(codeLine(editor.page, 'name="Fine print"')).toHaveCount(0)+ expect(await codeText(editor.page)).toContain('// Pricing card')++ await codeLine(editor.page, 'name="Dot"').click({ position: { x: 24, y: 8 } })+ await expect.poll(() => focusedLayer(editor.page)).toBe('Dot')+})++test('undo reverts a code edit on the canvas and in the code', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ await codeLine(editor.page, 'name="Card"').locator('span', { hasText: /^320$/ }).dblclick()+ await editor.page.keyboard.type('360')+ await expect.poll(() => cardSize(editor.page)).toBe('360x160')++ await editLayer(editor.page, 'Card', { height: 200 })+ await expect(codeLine(editor.page, 'name="Card"')).toContainText('h={200}')++ await editor.page.evaluate(() => window.openPencil?.getStore?.().undoAction())+ await expect(codeLine(editor.page, 'name="Card"')).toContainText('h={160}')+ await editor.page.evaluate(() => window.openPencil?.getStore?.().undoAction())+ await expect.poll(() => cardSize(editor.page)).toBe('320x160')+ await expect(codeLine(editor.page, 'name="Card"')).toContainText('w={320}')+})++test('a value written under another name is patched under that name', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ // The person renames `w` to `width`, which Design JSX also accepts.+ await codeLine(editor.page, 'name="Card"').locator('span', { hasText: /^w$/ }).dblclick()+ await editor.page.keyboard.type('width')+ await expect(editor.page.getByTestId('code-panel-status')).toHaveText('Updated live')++ await editLayer(editor.page, 'Card', { width: 400 })++ await expect(codeLine(editor.page, 'name="Card"')).toContainText('width={400}')+ await expect(codeLine(editor.page, 'name="Card"')).not.toContainText(' w={')+})++test('reordering layers on the canvas moves their elements and keeps them linked', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ await personalizeCode(editor.page)+ // The cursor sits in the swatch element, which the reorder is about to move.+ await codeLine(editor.page, 'name="Swatch"').click({ position: { x: 24, y: 8 } })++ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const swatch = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === 'Swatch')+ if (!store || !swatch?.parentId) throw new Error('Swatch not found')+ store.graph.reorderChild(swatch.id, swatch.parentId, 0)+ store.requestRender()+ })++ await expect+ .poll(async () => {+ const text = await codeText(editor.page)+ return text.indexOf('name="Swatch"') < text.indexOf('name="Fine print"')+ })+ .toBe(true)+ const text = await codeText(editor.page)+ expect(text).toContain('// Pricing card')+ expect(text).toContain('w={40 * 2}')++ // The cursor moved with its element and still marks the swatch.+ await expect(editor.page.locator('[data-slot="code-editor"] .cm-activeLine')).toContainText(+ 'name="Swatch"'+ )+ await expect.poll(() => focusedLayer(editor.page)).toBe('Swatch')+})++test('a value written inside style is patched there in its own format', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ const code = (await codeText(editor.page))+ .replace(/(name="Card"[^>]*?) w=\{320\}/, "$1 style={{ width: '320px' }}")+ .replace(/(name="Card"[^>]*?) h=\{160\}/, '$1 h={170}')+ await codeLine(editor.page, 'name="Card"').click()+ await editor.page.keyboard.press('ControlOrMeta+a')+ await editor.page.keyboard.insertText(code)+ // Replacing all the code links it again once its preview applies, shown by the new height.+ await expect.poll(() => cardSize(editor.page)).toBe('320x170')++ await editLayer(editor.page, 'Card', { width: 400 })++ await expect(codeLine(editor.page, 'name="Card"')).toContainText("style={{ width: '400px' }}")+ await expect(codeLine(editor.page, 'name="Card"')).not.toContainText(' w={')+})++test('a reorder that cannot move the code still writes layers added with it', async () => {+ await buildScene(editor.page)+ await openCode(editor.page)+ // Two children on one line cannot be moved as blocks of their own.+ const code = (await codeText(editor.page))+ .replace(/<\/Text>\n\s*<Rectangle/, '</Text> <Rectangle')+ .replace(/(name="Card"[^>]*?) h=\{160\}/, '$1 h={170}')+ await codeLine(editor.page, 'name="Card"').click()+ await editor.page.keyboard.press('ControlOrMeta+a')+ await editor.page.keyboard.insertText(code)+ await expect.poll(() => cardSize(editor.page)).toBe('320x170')++ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const swatch = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.name === 'Swatch')+ if (!store || !swatch?.parentId) throw new Error('Swatch not found')+ store.graph.reorderChild(swatch.id, swatch.parentId, 0)+ store.graph.createNode('ELLIPSE', swatch.parentId, { name: 'Dot', width: 24, height: 24 })+ store.requestRender()+ })++ await expect(codeLine(editor.page, 'name="Dot"')).toBeVisible()+ await expect(editor.page.locator('[data-slot="code-editor"] .cm-lintRange-info')).toHaveText(+ 'Frame'+ )+})diff --git a/tests/e2e/code/layer-links.spec.ts-snapshots/code-focus-and-hover-openpencil-darwin.png b/tests/e2e/code/layer-links.spec.ts-snapshots/code-focus-and-hover-openpencil-darwin.pngnew file mode 100644index 000000000..65cd60c20Binary files /dev/null and b/tests/e2e/code/layer-links.spec.ts-snapshots/code-focus-and-hover-openpencil-darwin.png differdiff --git a/tests/e2e/code/panel.spec.ts b/tests/e2e/code/panel.spec.tsindex 3e9716610..8791501fa 100644--- a/tests/e2e/code/panel.spec.ts+++ b/tests/e2e/code/panel.spec.ts@@ -32,8 +32,12 @@ function codeEditor() {return editor.page.locator('[data-slot="code-editor"] .cm-content')}+/** Opens the editor; with nothing selected that means choosing to write new Design JSX. */async function openCodePanel() {await codeTab().click()+ const writeJSX = codePanel().getByRole('button', { name: 'Write JSX' })+ await expect(codeEditor().or(writeJSX)).toBeVisible()+ if (await writeJSX.isVisible()) await writeJSX.click()await expect(codeEditor()).toBeVisible()}@@ -204,7 +208,8 @@ test('Tailwind JSX is generated read-only in the same editor', async () => {await openCodePanel()await selectSource('Tailwind JSX')await expect(editor.page.getByTestId('code-panel-status')).toContainText('Generated, read only')- await expect(codeEditor()).toHaveAttribute('contenteditable', 'false')+ // It still takes a cursor, which marks the layer of the element around it.+ await expect(codeEditor()).toHaveAttribute('aria-readonly', 'true')})test('copy button works and shows confirmation', async () => {diff --git a/tests/e2e/code/sandbox.spec.ts b/tests/e2e/code/sandbox.spec.tsindex f391d4fcd..d49aea512 100644--- a/tests/e2e/code/sandbox.spec.ts+++ b/tests/e2e/code/sandbox.spec.ts@@ -38,9 +38,11 @@ test('evaluates JSX into plain inert data', async ({ page }) => {w: 320,fill: { __openPencilHelper: 'solid', args: ['#fff'] }},- children: [{ type: 'text', props: {}, children: ['Hello'] }]+ children: [{ type: 'text', props: {}, children: ['Hello'], source: ['expression', 1] }],+ source: ['expression', 1]}- ]+ ],+ lineOffsets: { statements: 0, expression: 0 }})})@@ -59,6 +61,7 @@ const Card = ({ title, visible }) => (<Card title="Hello" visible />`)+ // Elements carry the chunk and line they were written on; the offsets map them to the source.expect(result).toEqual({ok: true,roots: [@@ -66,12 +69,14 @@ const Card = ({ title, visible }) => (type: 'frame',props: { fill: '#fff' },children: [- { type: 'text', props: {}, children: ['Hello'] },- { type: 'text', props: {}, children: [1] },- { type: 'text', props: {}, children: [2] }- ]+ { type: 'text', props: {}, children: ['Hello'], source: ['statements', 4] },+ { type: 'text', props: {}, children: [1], source: ['statements', 5] },+ { type: 'text', props: {}, children: [2], source: ['statements', 5] }+ ],+ source: ['statements', 3]}- ]+ ],+ lineOffsets: { statements: 0, expression: 7 }})})@@ -96,9 +101,10 @@ test('supports multiple roots through fragments', async ({ page }) => {expect(result).toEqual({ok: true,roots: [- { type: 'rectangle', props: { name: 'One' }, children: [] },- { type: 'ellipse', props: { name: 'Two' }, children: [] }- ]+ { type: 'rectangle', props: { name: 'One' }, children: [], source: ['expression', 1] },+ { type: 'ellipse', props: { name: 'Two' }, children: [], source: ['expression', 1] }+ ],+ lineOffsets: { statements: 0, expression: 0 }})})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex c38e2f2f2..ed194a1b0 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -66,6 +66,9 @@ ja:automation.webmcpSetupja:automation.webmcpUnsupportedja:code.copyJSXReferenceja:code.editorHTMLCSSLabel+ja:code.noSelectionDesignJSX+ja:code.noSelectionTailwindJSX+ja:code.writeJSXja:collaboration.pasteRoomLinkOrIdja:commands.paletteDescriptionja:credentials.apiKey@@ -205,6 +208,9 @@ zh-cn:automation.webmcpSetupzh-cn:automation.webmcpUnsupportedzh-cn:code.copyJSXReferencezh-cn:code.editorHTMLCSSLabel+zh-cn:code.noSelectionDesignJSX+zh-cn:code.noSelectionTailwindJSX+zh-cn:code.writeJSXzh-cn:collaboration.pasteRoomLinkOrIdzh-cn:commands.paletteDescriptionzh-cn:credentials.apiKey