openpencil/tests/e2e/code/panel.spec.ts
Danila Poyarkov 6a3960a5d4
feat(code): link the Code tab to canvas layers and sync both ways (#805)
* feat(code): link code to canvas layers and underline design issues

Code in the Code tab and layers on the canvas were unrelated: finding the
element behind a layer, or the layer behind an element, meant reading names.

Generated Design JSX and Tailwind JSX report the layer behind each element
in the order elements open, and edited Design JSX keeps the source line of
every element through the sandbox and renderer, so hovering an element
highlights its layer, Cmd/Ctrl-click brings it into view without changing
the selection the code shows, and errors and warnings from the design check
are underlined on the property that causes them.

* feat(code): explain the Code tab when nothing is selected

With no selection the editor showed a starter frame that read like a real
layer. The tab now says it shows the selected layers' code and offers Write
JSX, which opens the editor focused on the starter template.

* refactor(code): group code-to-layer linking into its own domain

Layer link types, issue mapping, and the hover and reveal behavior move
from the Code panel and a component file into src/app/code/layers, with
useCodeLayers as the panel's entry point, so app code no longer imports
types from components.

* fix(code): underline off-scale gaps after the spacing rule renamed its property

* feat(code): mark the layer of the element around the cursor

Hover highlighting and ⌘-click reveal replaced by one model: the element
around the cursor marks its opening and closing tag names and outlines its
layer on the canvas while the editor has focus. ⌘-click also collided
with CodeMirror's add-a-cursor gesture. Read-only Tailwind JSX now takes a
cursor so it links the same way.

Leaving the editor now ends a live Design JSX edit as one undo step.
Before, canvas edits made after typing never reached the code until the
tab was reopened, and their undo entries landed before the edit's.

* feat(code): sync the Code tab and the canvas both ways by patching

Canvas edits now patch the Design JSX a person wrote instead of waiting
for them to leave the editor: each linked element remembers the layer as
Design JSX last wrote it, and a canvas change rewrites only the attributes,
text and child elements that differ from that base, as CodeMirror changes
that keep the cursor, comments, formatting and history. Attributes written
as expressions are never overwritten; the code marks them when the canvas
now differs. Untouched code is regenerated with a minimal text change.

Code edits update layers in place: the new render is reconciled into the
existing layers (reconcileRenderedLayers), which keep their ids, so links,
selection and canvas edits survive typing. Each edit is one coalesced undo
step, replacing the restore-and-rerender preview and the commit on blur.

* feat(code): patch reordered layers and aliased properties in edited code

Reordering layers on the canvas now moves their elements in code a person
wrote: each child element and the blank lines and comments above it form a
block kept as written, and the children are written again in the new
order, staying linked. Children that cannot move safely, such as a loop
between them, keep their order and are marked.

Properties accepted under several names now come from one alias table in
the Design JSX schema, which the renderer resolves through and the patcher
and issue underlines use, so a canvas change to `w` patches `width` where
the person wrote that, instead of adding a second attribute.

* feat(code): keep the cursor in moved code and patch values written in style

A reorder rewrites the children span in one change, which collapsed a
cursor or out-of-sync marker inside a moved element to the span's edge.
The patch now carries where each block moved and places selections and
markers inside it at their new position.

Properties the renderer also reads from style={{ … }} come from a table in
the Design JSX schema instead of a hand-written list, keeping the rule
that an attribute under any of its names wins. The patcher uses it to
update a value written in style where it is, as a number or a px string
as written; values the renderer cannot read, such as '50%', are marked.

The layer patcher is split by concern: syntax helpers, attribute and
style patches, child patches, out-of-sync state and transaction assembly.

* feat(code): show the code's layer on the canvas as a tinted box

The layer of the element around the cursor used the canvas hover slot, so
moving the pointer over the canvas replaced it and the two read the same.
It now has its own shared editor state, codeFocusNodeId, drawn as the hover
outline over a light tint in every pane: hover stays an outline and the
selection keeps its handles, without borrowing the dashed outlines that
already mean component sets, drag parents and ghosts.

* fix(code): write added and removed layers when a reorder cannot move the code

When children could not be moved, such as two written on one line, the
patch marked the order and returned before adding or removing elements,
so a layer created in the same change never reached the code. It now
marks the order and still writes additions and removals.

* refactor(design-jsx): format the rebased layer description and stroke aliases

* feat(code): mount the layer-linked code editor through useCodeMirror

Master moved the code editor onto the shared useCodeMirror composable.
Its layer links, issue underlines, canvas patches, minimal text updates,
autofocus and read-only cursor now sit on that composable instead of a
hand-mounted view.
2026-10-04 10:08:40 +00:00

220 lines
9 KiB
TypeScript

import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
import {
getCodeNodeSummaries,
getFirstSelectedNodeId,
getUndoLabel,
hasNode,
hasNodeNamed,
waitForNode,
waitForNodeNamed
} from '#tests/helpers/code-panel'
const editor = useEditorSetup()
test.beforeEach(async () => {
await editor.page.reload()
await editor.canvas.waitForInit()
})
function codeTab() {
return editor.page.getByTestId('properties-tab-code')
}
function designTab() {
return editor.page.getByTestId('properties-tab-design')
}
function codePanel() {
return editor.page.getByTestId('code-panel-root')
}
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()
}
async function selectSource(label: string) {
await editor.page.getByTestId('code-panel-source').click()
await editor.page.getByRole('option', { name: label }).click()
}
test('inactive Code tab defers JSX generation for large selections', async () => {
const selectionDuration = await editor.page.evaluate(async () => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
const ids: string[] = []
for (let frameIndex = 0; frameIndex < 50; frameIndex++) {
const frame = store.graph.createNode('FRAME', store.state.currentPageId, {
name: `Frame ${frameIndex}`
})
ids.push(frame.id)
for (let childIndex = 0; childIndex < 100; childIndex++) {
store.graph.createNode('RECTANGLE', frame.id, { name: `Child ${childIndex}` })
}
}
const startedAt = performance.now()
store.select(ids)
await new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
})
return performance.now() - startedAt
})
expect(selectionDuration).toBeLessThan(1000)
await expect(designTab()).toHaveAttribute('data-state', 'active')
await openCodePanel()
await expect(codeEditor()).toContainText('Frame')
})
test('shows one editor with line numbers and no import form', async () => {
await openCodePanel()
await expect(codePanel().locator('[data-slot="code-editor"]')).toHaveCount(1)
await expect(codePanel().locator('.cm-lineNumbers')).toBeVisible()
await expect(codePanel().locator('textarea')).toHaveCount(0)
await expect(codePanel().getByRole('button', { name: /^Import$/ })).toHaveCount(0)
})
test('desktop exposes one Code panel and one editor', async () => {
await openCodePanel()
await expect(codePanel()).toHaveCount(1)
await expect(codePanel().locator('.cm-editor')).toHaveCount(1)
})
test('live previews Design JSX and keeps one undo transaction', async () => {
await editor.canvas.drawRect(100, 100, 200, 150)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
await codeEditor().fill('<Frame name="Live JSX" w={320} h={180} fill="#ffffff" />')
await waitForNodeNamed(editor.page, 'Live JSX')
await codeEditor().fill('<Frame name="Live JSX final" w={360} h={180} fill="#ffffff" />')
await waitForNodeNamed(editor.page, 'Live JSX final')
await designTab().click()
await editor.page.waitForTimeout(50)
await editor.page.keyboard.press('Meta+z')
await waitForNode(editor.page, originalId)
expect(await hasNode(editor.page, originalId)).toBe(true)
expect(await hasNodeNamed(editor.page, 'Live JSX final')).toBe(false)
})
test('Ctrl+Z edits the CodeMirror draft before touching the canvas transaction', async () => {
await openCodePanel()
const initial = await codeEditor().textContent()
await codeEditor().pressSequentially('\n// local draft')
await expect(codeEditor()).toContainText('local draft')
await codeEditor().press('Control+z')
await expect(codeEditor()).not.toContainText('local draft')
expect(await codeEditor().textContent()).toBe(initial)
})
test('keeps the last valid preview while showing invalid-code diagnostics', async () => {
await openCodePanel()
await codeEditor().fill('<Frame name="Last valid" />')
await waitForNodeNamed(editor.page, 'Last valid')
await codeEditor().fill('<Frame>')
const errorAlert = editor.page.getByTestId('code-panel-error')
await expect(errorAlert).toBeVisible()
await expect(errorAlert).toHaveCSS('color', 'rgb(248, 113, 113)')
await editor.page.evaluate(async () => {
const themeModulePath = '/src/app/shell/theme.ts'
const themeModule = await import(themeModulePath)
themeModule.useAppTheme().setTheme('light')
})
await editor.page.waitForFunction(() => document.documentElement.dataset.theme === 'light')
await expect(errorAlert).toHaveCSS('color', 'rgb(185, 28, 28)')
expect(await hasNodeNamed(editor.page, 'Last valid')).toBe(true)
})
test('Reset restores generated source and original canvas state', async () => {
await editor.canvas.drawRect(100, 100, 200, 150)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
await codeEditor().fill('<Frame name="Reset preview" />')
await waitForNodeNamed(editor.page, 'Reset preview')
await expect(editor.page.getByTestId('code-panel-reset').locator('svg')).toHaveCount(1)
await editor.page.getByTestId('code-panel-reset').click()
await waitForNode(editor.page, originalId)
expect(await hasNode(editor.page, originalId)).toBe(true)
await expect(codeEditor()).toContainText('Rectangle')
})
test('HTML/CSS live preview commits as one undoable session', async () => {
await editor.canvas.drawRect(80, 80, 120, 90)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
await selectSource('HTML/CSS')
await codeEditor().fill('<div style="width: 180px; height: 90px">First</div>')
await expect.poll(() => hasNode(editor.page, originalId)).toBe(false)
await codeEditor().fill('<div style="width: 220px; height: 110px">Final</div>')
await expect(editor.page.getByTestId('code-panel-status')).toContainText('Updated live')
await expect(editor.page.getByTestId('code-panel-status')).toHaveAttribute('data-tone', 'success')
await designTab().click()
await expect.poll(() => getUndoLabel(editor.page)).toBe('Edit HTML/CSS')
await editor.page.keyboard.press('Meta+z')
await waitForNode(editor.page, originalId)
expect(await hasNode(editor.page, originalId)).toBe(true)
await editor.page.keyboard.press('Meta+Shift+z')
await expect.poll(() => hasNode(editor.page, originalId)).toBe(false)
})
test('switching source formats commits the current live session', async () => {
await editor.canvas.drawRect(90, 90, 140, 100)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
await codeEditor().fill('<Frame name="Committed on switch" />')
await waitForNodeNamed(editor.page, 'Committed on switch')
await selectSource('HTML/CSS')
await expect(codeEditor()).toContainText('<style>')
await expect.poll(() => getUndoLabel(editor.page)).toBe('Edit JSX')
await editor.page.keyboard.press('Meta+z')
await waitForNode(editor.page, originalId)
})
test('Reset before debounce cancels the pending preview', async () => {
await editor.canvas.drawRect(100, 100, 200, 150)
const originalId = await getFirstSelectedNodeId(editor.page)
await openCodePanel()
await codeEditor().fill('<Frame name="Stale reset preview" />')
await editor.page.getByTestId('code-panel-reset').click()
await editor.page.waitForTimeout(450)
expect(await hasNode(editor.page, originalId)).toBe(true)
expect(await hasNodeNamed(editor.page, 'Stale reset preview')).toBe(false)
})
test('HTML/CSS uses the same editor and live reloads the canvas', async () => {
await openCodePanel()
await selectSource('HTML/CSS')
await expect(codePanel().locator('[data-slot="code-editor"]')).toHaveCount(1)
await expect(codeEditor()).toHaveAttribute('aria-label', 'HTML and CSS')
await codeEditor().fill(
'<style>.card { width: 240px; height: 120px; background: red; }</style><div class="card">Hello</div>'
)
await expect(editor.page.getByTestId('code-panel-status')).toContainText('Updated live')
const importedNodes = await getCodeNodeSummaries(editor.page)
expect(importedNodes.some((node) => node.type !== 'DOCUMENT' && node.type !== 'PAGE')).toBe(true)
})
test('Tailwind JSX is generated read-only in the same editor', async () => {
await editor.canvas.drawRect(100, 100, 200, 150)
await openCodePanel()
await selectSource('Tailwind JSX')
await expect(editor.page.getByTestId('code-panel-status')).toContainText('Generated, read only')
// 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 () => {
await openCodePanel()
await editor.page.getByTestId('code-panel-copy').click()
await expect(editor.page.getByTestId('code-panel-copy')).toContainText('Copied')
})