openpencil/tests/engine/lint/variable-binding-validation.test.ts
Danila Poyarkov f6848434ec
feat: check designs live with a Lint panel, canvas markers, and fixes (#804)
* feat: check designs live with a Check panel and canvas issue markers

Design lint only ran from the CLI and AI tools, and its rules were too noisy
to show continuously: on a real imported page 786 of 888 layers had a
warning. The rules now report where a finding is actionable (a hardcoded
color only when a variable matches it, nesting only where the limit is
crossed, instance sublayers through their main component) and carry
structured data, and Recommended keeps warnings for likely problems.

The app checks the current page after edits settle. The Check tab groups
issues by rule with hover highlighting, reveal on click, and one-step
variable binding. Errors and warnings are marked on the canvas with
clustered markers that roll up to visible ancestors when zoomed out; markers
explain themselves on hover, open Check on click, and toggle with
View > Design issues.

* fix: keep the right panel and markers stable

The Check tab made the right-panel tab row overflow at common window widths,
so focusing the zoom menu scrolled the row and shifted the panel. Code and
AI tabs now drop their labels to screen readers when the row is narrow.

Touch target names are matched as whole words: "Rectangle" contained "cta"
and marked every rectangle. Markers also stay drawn during interactive edits
instead of blinking while a value is scrubbed.

* fix(ui): show right panel tab labels whenever they fit

* fix(ui): name the design check tab Lint and keep panel tabs consistent

The tab was an unlabelled icon between labelled Code and AI tabs. It is now
Lint, with the same icon and label anatomy as its neighbours, and its icon
takes the severity color instead of a count badge. All labelled tabs show
their labels when the row fits and drop them together when it does not.

* refactor(ui): build the Lint panel from shared components

Issue groups use AppCollapsible, actions use AppButton, and the severity
filters are a Reka toggle group with keyboard navigation. Issue rows no
longer nest a button inside a button. Panel state, visibility and the
focused-issue scroll live in useDesignCheckPanel, the rules menu is its own
component, and rule preferences change through preference actions.
Severity ordering reuses Core's ranking, detail numbers follow the app
language, and the check debounce uses useTimeoutFn.

* fix(lint): check the WCAG AA touch target size in the Recommended preset

Recommended flagged a 394 × 39 input because it required the 44 × 44 AAA size. It now checks the 24 × 24 AA minimum through a minSize option; Strict and Accessibility keep 44 × 44.

* feat(lint): fix design issues from rules, the Lint panel, the CLI, and agents

Rules attach fixes as data: a safe fix keeps the design as it looks (bind a
color to the variable it matches, round subpixel geometry that layout does
not own), a suggestion changes values (snap radius and spacing to the
scale, raise small text to the minimum). One Core applier re-validates
each fix against the current graph and merges changes per layer.

The Lint panel offers a fix per row and Fix all for safe fixes as one undo
step; openpencil lint --fix writes the fixed document; the lint and
lint_fix tools expose the same to MCP and AI chat.

The design-check spec's Close button is now 24 x 20: at 24 x 24 it passes
the WCAG AA touch target size that Recommended checks.

* feat(lint): pin issues outside the view to the canvas edge

Errors and warnings on layers outside the viewport had no marker, so a
check could report issues nobody could see. They are now pinned to the
canvas edge where a ray from the viewport center toward them leaves it,
with a chevron pointing their way; pins in one direction merge like
markers. Hovering lists them under the direction they lie in, and
clicking reveals and opens the most severe, nearest one.

Pins keep clear of UI floating over the canvas: the toolbar marks itself
with data-canvas-obstacle, and canvases report such rectangles to the
renderer through getOverlayObstacles each frame.

* feat(lint): mark layers with design issues in the Layers panel

Like an IDE marks files with problems and the folders holding them, a
layer with errors or warnings shows the most severe as an icon, and a
collapsed layer with issues inside it shows a dot in that color.
Suggestions stay in the Lint panel, as on the canvas, and the marks
follow the View → Design issues toggle.

* feat(lint): show issues per page and across the document

Loaded pages beyond the current one are now checked in the background,
one page at a time while the editor is idle, and checked again only when
an edit touches them; pages a large .fig file has not loaded are left
alone until opened rather than forced in. The page list shows each page's
errors and warnings like an IDE's problem count, and the Lint panel gains
a Document scope that lists every page's issues, tags the ones on other
pages, and switches to a row's page when it is opened.

* test(lint): use the core-tests alias and no comma operator in lint tests

Master now rejects ../../ imports and the comma operator in tests.

* refactor(app): create the Lint session with the editor store modules

The composition root passed its line budget once master added recent
pages; the Lint session belongs with the other per-editor services that
the modules factory creates and disposes.

* docs(changelog): keep master's latest Unreleased entries
2026-10-04 10:08:39 +00:00

249 lines
7.8 KiB
TypeScript

import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/core'
import noHardcodedColors from '@open-pencil/core/lint/rules/no-hardcoded-colors'
function pageId(graph: SceneGraph): string {
return graph.getPages()[0].id
}
function setupColorVars(graph: SceneGraph, ...ids: string[]): void {
graph.addCollection({
id: 'col1',
name: 'Colors',
modes: [{ modeId: 'm1', name: 'Light' }],
defaultModeId: 'm1',
variableIds: []
})
for (const id of ids) {
graph.addVariable({
id,
name: `Var ${id}`,
type: 'COLOR',
collectionId: 'col1',
valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },
description: '',
hiddenFromPublishing: false
})
}
}
// ─── bindVariable emits node:updated event ──────────────────────────────────
describe('bindVariable emits node:updated event', () => {
test('bindVariable emits node:updated event', () => {
const graph = new SceneGraph()
setupColorVars(graph, 'v1')
const node = graph.createNode('RECTANGLE', pageId(graph), {
name: 'Rect',
fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]
})
const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []
graph.onNodeEvents({
updated: (nodeId, changes) => {
events.push({ nodeId, changes })
}
})
graph.bindVariable(node.id, 'fills/0/color', 'v1')
expect(events.length).toBeGreaterThanOrEqual(1)
expect(events[0].nodeId).toBe(node.id)
expect(events[0].changes).toHaveProperty('boundVariables')
})
})
// ─── no-hardcoded-colors lint checks indexed bindings ──────────────────────
/** Variables whose only color matches the tests' 50% gray paint. */
const GRAY_VARIABLES = {
counts: { COLOR: 1, FLOAT: 0, STRING: 0, BOOLEAN: 0 },
colorsByHex: new Map([['#808080', { id: 'v1', name: 'Gray' }]])
}
describe('no-hardcoded-colors lint checks indexed bindings', () => {
test('node with fills/0/color binding passes lint (no false positive)', () => {
const node = {
id: 'n1',
name: 'Rect',
type: 'RECTANGLE',
width: 100,
height: 100,
x: 0,
y: 0,
rotation: 0,
visible: true,
locked: false,
layoutMode: 'NONE',
layoutPositioning: 'AUTO' as const,
layoutGrow: 0,
layoutAlignSelf: 'AUTO',
primaryAxisSizing: 'FIXED',
counterAxisSizing: 'FIXED',
textAutoResize: 'NONE',
itemSpacing: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
cornerRadius: 0,
childIds: [],
text: '',
fontSize: 14,
styleRunCount: 0,
boundVariables: { 'fills/0/color': 'v1' },
fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],
strokes: [],
effects: []
}
const messages: Array<{ message: string }> = []
const context = {
variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
getChildren: () => []
}
noHardcodedColors.check(node, context)
// Should NOT report a violation — the color is bound to a variable
expect(messages.length).toBe(0)
})
test('node with top-level fills binding still reports violation (no false negative)', () => {
const node = {
id: 'n2',
name: 'Rect',
type: 'RECTANGLE',
width: 100,
height: 100,
x: 0,
y: 0,
rotation: 0,
visible: true,
locked: false,
layoutMode: 'NONE',
layoutPositioning: 'AUTO' as const,
layoutGrow: 0,
layoutAlignSelf: 'AUTO',
primaryAxisSizing: 'FIXED',
counterAxisSizing: 'FIXED',
textAutoResize: 'NONE',
itemSpacing: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
cornerRadius: 0,
childIds: [],
text: '',
fontSize: 14,
styleRunCount: 0,
boundVariables: { fills: 'v1' }, // top-level — renderer-ignored
fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],
strokes: [],
effects: []
}
const messages: Array<{ message: string }> = []
const context = {
variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
getChildren: () => []
}
noHardcodedColors.check(node, context)
// SHOULD report a violation — top-level 'fills' binding is renderer-ignored
expect(messages.length).toBeGreaterThanOrEqual(1)
})
})
// ─── bindVariable validation ──────────────────────────────────────────────
describe('bindVariable validation', () => {
function setupGraph(): SceneGraph {
const graph = new SceneGraph()
graph.addCollection({
id: 'col1',
name: 'Colors',
modes: [{ modeId: 'm1', name: 'Light' }],
defaultModeId: 'm1',
variableIds: []
})
graph.addVariable({
id: 'v-color',
name: 'Primary',
type: 'COLOR',
collectionId: 'col1',
valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },
description: '',
hiddenFromPublishing: false
})
graph.addVariable({
id: 'v-float',
name: 'Spacing',
type: 'FLOAT',
collectionId: 'col1',
valuesByMode: { m1: 16 },
description: '',
hiddenFromPublishing: false
})
return graph
}
test('bindVariable rejects nonexistent variable', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'nonexistent')
}).toThrow()
expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()
})
test('bindVariable rejects FLOAT variable on color field', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'v-float')
}).toThrow()
expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()
})
test('bindVariable rejects COLOR variable on scalar field', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'opacity', 'v-color')
}).toThrow()
expect(graph.getNode(node.id).boundVariables['opacity']).toBeUndefined()
})
test('bindVariable rejects binding to fills that do not yet exist', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
// Rect has 0 fills — binding to fills/0/color must be rejected (index >= length)
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'v-color')
}).toThrow(/out of range/)
})
test('bindVariable auto-removes top-level fills binding when indexed binding is set', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), {
name: 'Rect',
fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]
})
const n = graph.getNode(node.id)
// Set top-level dead data first
n.boundVariables['fills'] = 'v-color'
// Now set a proper indexed binding — should auto-remove top-level
graph.bindVariable(node.id, 'fills/0/color', 'v-color')
expect(n.boundVariables['fills']).toBeUndefined()
expect(n.boundVariables['fills/0/color']).toBe('v-color')
})
})