Skip to content

AI-native design editor. Open-source Figma alternative.

feat: check designs live with a Lint panel, canvas markers, and fixes (#804)

Danila Poyarkovf6848434eca7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25be7d7a3..6a341cb65 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,9 @@
### 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.
+- 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.
- See where the built-in AI chat is working: while it replies, a cursor whose outlined label shows a sparkle and a callsign such as *Fern* marks the layers it edits. In a shared room, collaborators see each other's agents in the color of the person running them.
- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors, the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing.
@@ -38,6 +41,7 @@
### Changed
+- 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.
- Keep an AI chat working on the page where it started when you switch to another page, instead of sending its next edits to whichever page is on screen. When the AI switches pages itself, your view follows.
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index 63d380b42..6399d672d 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -189,6 +189,11 @@
"label": "Multiplayer Cursors",
"checkbox": true
},
+ {
+ "id": "view-design-issues",
+ "label": "Design Issues",
+ "checkbox": true
+ },
{
"type": "separator"
},
diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.ts
index 48f43be58..58c7b1985 100644
--- a/packages/cli/src/commands/lint.ts
+++ b/packages/cli/src/commands/lint.ts
@@ -1,9 +1,22 @@
+import { writeFile } from 'node:fs/promises'
+import { resolve } from 'node:path'
+
import { defineCommand } from 'citty'
-import { allRules, createLinter, presets, type LintMessage } from '@open-pencil/core/lint'
+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+import {
+ allRules,
+ applyLintFixes,
+ createLinter,
+ graphFixTarget,
+ presets,
+ safeFixes,
+ type LintMessage
+} from '@open-pencil/core/lint'
-import { bold, dim, fail, fmtList, ok } from '#cli/format'
-import { loadDocument } from '#cli/headless'
+import { bold, dim, fail, fmtList, ok, printError } from '#cli/format'
+import { loadDocument, populateWholeDocument } from '#cli/headless'
function formatSeverity(severity: LintMessage['severity']) {
if (severity === 'error') return fail('error')
@@ -39,6 +52,16 @@ export default defineCommand({
description: 'Preset: recommended, strict, accessibility'
},
rule: { type: 'string', description: 'Run specific rule(s) only (repeatable)' },
+ fix: {
+ type: 'boolean',
+ default: false,
+ description: 'Apply safe fixes (bind matching color variables, round to whole pixels)'
+ },
+ output: {
+ type: 'string',
+ alias: 'o',
+ description: 'Where --fix writes the fixed document (.fig)'
+ },
json: { type: 'boolean', default: false, description: 'Output as JSON' },
'list-rules': { type: 'boolean', default: false, description: 'List rules and exit' }
},
@@ -61,9 +84,27 @@ export default defineCommand({
return
}
+ if (args.fix && !args.output) {
+ printError('--fix needs --output: the fixed document is written as a new .fig file.')
+ process.exit(1)
+ }
+
const graph = await loadDocument(args.file)
+ // Lazily imported pages hold layers too; lint the whole document, not only what was read.
+ populateWholeDocument(graph)
const rules = args.rule ? (Array.isArray(args.rule) ? args.rule : [args.rule]) : undefined
- const result = createLinter({ preset: args.preset, rules }).lintGraph(graph)
+ const linter = createLinter({ preset: args.preset, rules })
+ let result = linter.lintGraph(graph)
+
+ if (args.fix && args.output) {
+ const applied = applyLintFixes(graphFixTarget(graph), safeFixes(result.messages))
+ computeAllLayouts(graph)
+ const output = resolve(args.output)
+ const written = await new IORegistry(BUILTIN_IO_FORMATS).writeDocument('fig', graph)
+ await writeFile(output, written.data as Uint8Array)
+ if (!args.json) console.log(ok(`Applied ${applied} fixes → ${output}`))
+ result = linter.lintGraph(graph)
+ }
if (args.json) {
console.log(JSON.stringify(result, null, 2))
diff --git a/packages/core/src/canvas/index.ts b/packages/core/src/canvas/index.ts
index d3161b059..11335f2e5 100644
--- a/packages/core/src/canvas/index.ts
+++ b/packages/core/src/canvas/index.ts
@@ -15,3 +15,18 @@ export { hitTestGuides, type GuideHit } from './guides/hit-test'
export type { GuideOverlayState, GuidePreview, GuideSelection } from './guides/types'
export { canvasLabelForeground } from './labels/color'
export { SkiaRenderer, type PresenceCursor, type RenderOverlays, type RulerTheme } from './renderer'
+export {
+ hitTestIssueMarkers,
+ issueMarkerLabel,
+ issueSeverityRank,
+ layoutIssueMarkers,
+ type IssueMarkerLayoutOptions,
+ type IssueMarkerView
+} from './issues/layout'
+export type {
+ DesignIssueHighlight,
+ DesignIssueMarker,
+ DesignIssueOverlay,
+ DesignIssueSeverity,
+ PlacedIssueMarker
+} from './issues/types'
diff --git a/packages/core/src/canvas/issues/draw.ts b/packages/core/src/canvas/issues/draw.ts
new file mode 100644
index 000000000..e0825738d
--- /dev/null
+++ b/packages/core/src/canvas/issues/draw.ts
@@ -0,0 +1,231 @@
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import {
+ ISSUE_EDGE_ARROW,
+ ISSUE_ERROR_COLOR,
+ ISSUE_HIGHLIGHT_FILL_ALPHA,
+ ISSUE_HIGHLIGHT_STROKE_WIDTH,
+ ISSUE_INFO_COLOR,
+ ISSUE_MARKER_RING_WIDTH,
+ ISSUE_WARNING_COLOR
+} from '#core/constants'
+import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+
+import { issueMarkerLabel } from './layout'
+import type { DesignIssueHighlight, DesignIssueSeverity, PlacedIssueMarker } from './types'
+
+const MARKER_SHADOW_SIGMA = 1.5
+/** Half the base of an edge pin's chevron. */
+const EDGE_ARROW_HALF_WIDTH = 4
+const MARKER_SHADOW_OFFSET_Y = 1
+const MARKER_SHADOW_ALPHA = 0.3
+const MARKER_HOVER_HALO = 3
+const MARKER_HOVER_HALO_ALPHA = 0.28
+/** Baseline below the vertical center for 10px Inter digits and the exclamation mark. */
+const MARKER_TEXT_BASELINE = 3.5
+const TARGET_DASH = 3
+
+export function issueSeverityColor(severity: DesignIssueSeverity): Color {
+ if (severity === 'error') return ISSUE_ERROR_COLOR
+ if (severity === 'warning') return ISSUE_WARNING_COLOR
+ return ISSUE_INFO_COLOR
+}
+
+/** Amber needs dark text; red and gray read best with white. */
+function issueSeverityForeground(severity: DesignIssueSeverity): Color {
+ return severity === 'warning' ? { r: 0, g: 0, b: 0, a: 0.85 } : { r: 1, g: 1, b: 1, a: 1 }
+}
+
+function color4f(r: SkiaRenderer, color: Color, alpha = color.a) {
+ return r.ck.Color4f(color.r, color.g, color.b, alpha)
+}
+
+export function drawIssueHighlight(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ highlight: DesignIssueHighlight | null | undefined,
+ preview?: RotationPreview | null
+): void {
+ const node = highlight ? graph.getNode(highlight.nodeId) : undefined
+ if (!highlight || !node) return
+ const color = issueSeverityColor(highlight.severity)
+
+ canvas.save()
+ try {
+ canvas.concat(createSceneGeometry(graph, preview).screenMatrix(node, r))
+ r.auxFill.setColor(color4f(r, color, ISSUE_HIGHLIGHT_FILL_ALPHA))
+ canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxFill)
+
+ r.auxStroke.setPathEffect(null)
+ r.auxStroke.setColor(color4f(r, color))
+ r.auxStroke.setStrokeWidth(ISSUE_HIGHLIGHT_STROKE_WIDTH / r.zoom)
+ r.strokeNodeShape(canvas, node, r.auxStroke)
+
+ const minSize = highlight.minSize
+ if (minSize && (node.width < minSize.width || node.height < minSize.height)) {
+ const width = Math.max(node.width, minSize.width)
+ const height = Math.max(node.height, minSize.height)
+ const left = (node.width - width) / 2
+ const top = (node.height - height) / 2
+ const dash = r.ck.PathEffect.MakeDash([TARGET_DASH / r.zoom, TARGET_DASH / r.zoom], 0)
+ r.auxStroke.setStrokeWidth(1 / r.zoom)
+ r.auxStroke.setPathEffect(dash)
+ canvas.drawRect(r.ck.LTRBRect(left, top, left + width, top + height), r.auxStroke)
+ r.auxStroke.setPathEffect(null)
+ dash.delete()
+ }
+ } finally {
+ canvas.restore()
+ }
+}
+
+/**
+ * The chevron an edge pin points with: a triangle from the pill's border toward the issues,
+ * outlined in white like the pill so it reads on any canvas.
+ */
+function drawEdgeArrow(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ marker: PlacedIssueMarker,
+ color: Color,
+ ring: number
+): void {
+ const { rect, direction } = marker
+ if (!direction) return
+ const center = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
+ const tx = direction.x === 0 ? Infinity : rect.width / 2 / Math.abs(direction.x)
+ const ty = direction.y === 0 ? Infinity : rect.height / 2 / Math.abs(direction.y)
+ const border = Math.min(tx, ty)
+ const normal = { x: -direction.y, y: direction.x }
+ const triangle = (reach: number, half: number) => {
+ const path = new r.ck.PathBuilder()
+ const base = border - 1
+ path.moveTo(
+ center.x + direction.x * (border + reach),
+ center.y + direction.y * (border + reach)
+ )
+ path.lineTo(
+ center.x + direction.x * base + normal.x * half,
+ center.y + direction.y * base + normal.y * half
+ )
+ path.lineTo(
+ center.x + direction.x * base - normal.x * half,
+ center.y + direction.y * base - normal.y * half
+ )
+ path.close()
+ return path.detachAndDelete()
+ }
+ const outline = triangle(ISSUE_EDGE_ARROW + ring * 2, EDGE_ARROW_HALF_WIDTH + ring)
+ const fill = triangle(ISSUE_EDGE_ARROW, EDGE_ARROW_HALF_WIDTH)
+ r.auxFill.setColor(r.ck.WHITE)
+ canvas.drawPath(outline, r.auxFill)
+ r.auxFill.setColor(color4f(r, color))
+ canvas.drawPath(fill, r.auxFill)
+ outline.delete()
+ fill.delete()
+}
+
+function drawMarker(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ marker: PlacedIssueMarker,
+ hovered: boolean
+): void {
+ const { rect } = marker
+ const radius = rect.height / 2
+ const color = issueSeverityColor(marker.severity)
+ const ring = ISSUE_MARKER_RING_WIDTH
+
+ const shadow = r.ck.RRectXY(
+ r.ck.LTRBRect(
+ rect.x - ring,
+ rect.y - ring + MARKER_SHADOW_OFFSET_Y,
+ rect.x + rect.width + ring,
+ rect.y + rect.height + ring + MARKER_SHADOW_OFFSET_Y
+ ),
+ radius + ring,
+ radius + ring
+ )
+ r.auxFill.setColor(r.ck.Color4f(0, 0, 0, MARKER_SHADOW_ALPHA))
+ r.auxFill.setMaskFilter(r.getCachedMaskBlur(MARKER_SHADOW_SIGMA))
+ canvas.drawRRect(shadow, r.auxFill)
+ r.auxFill.setMaskFilter(null)
+
+ if (hovered) {
+ const halo = ring + MARKER_HOVER_HALO
+ r.auxFill.setColor(color4f(r, color, MARKER_HOVER_HALO_ALPHA))
+ canvas.drawRRect(
+ r.ck.RRectXY(
+ r.ck.LTRBRect(
+ rect.x - halo,
+ rect.y - halo,
+ rect.x + rect.width + halo,
+ rect.y + rect.height + halo
+ ),
+ radius + halo,
+ radius + halo
+ ),
+ r.auxFill
+ )
+ }
+
+ if (marker.direction) drawEdgeArrow(r, canvas, marker, color, ring)
+
+ r.auxFill.setColor(r.ck.WHITE)
+ canvas.drawRRect(
+ r.ck.RRectXY(
+ r.ck.LTRBRect(
+ rect.x - ring,
+ rect.y - ring,
+ rect.x + rect.width + ring,
+ rect.y + rect.height + ring
+ ),
+ radius + ring,
+ radius + ring
+ ),
+ r.auxFill
+ )
+ r.auxFill.setColor(color4f(r, color))
+ canvas.drawRRect(
+ r.ck.RRectXY(
+ r.ck.LTRBRect(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height),
+ radius,
+ radius
+ ),
+ r.auxFill
+ )
+
+ const font = r.sizeFont
+ if (!font) return
+ const label = issueMarkerLabel(marker.count)
+ let textWidth = 0
+ for (const width of font.getGlyphWidths(font.getGlyphIDs(label))) textWidth += width
+ font.setEmbolden(true)
+ r.auxFill.setColor(color4f(r, issueSeverityForeground(marker.severity)))
+ canvas.drawText(
+ label,
+ rect.x + (rect.width - textWidth) / 2,
+ rect.y + rect.height / 2 + MARKER_TEXT_BASELINE,
+ r.auxFill,
+ font
+ )
+ font.setEmbolden(false)
+}
+
+/** Draws placed markers so the first placed, most severe marker ends up on top. */
+export function drawIssueMarkers(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ placed: readonly PlacedIssueMarker[],
+ hoveredKey: string | null | undefined
+): void {
+ for (let index = placed.length - 1; index >= 0; index--) {
+ const marker = placed[index]
+ drawMarker(r, canvas, marker, marker.key === hoveredKey)
+ }
+}
diff --git a/packages/core/src/canvas/issues/layout.ts b/packages/core/src/canvas/issues/layout.ts
new file mode 100644
index 000000000..d152d23bc
--- /dev/null
+++ b/packages/core/src/canvas/issues/layout.ts
@@ -0,0 +1,376 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+
+import {
+ ISSUE_EDGE_ARROW,
+ ISSUE_EDGE_MERGE_GAP,
+ ISSUE_MARKER_GAP,
+ ISSUE_MARKER_HEIGHT,
+ ISSUE_MARKER_MAX_COUNT,
+ ISSUE_MARKER_MIN_TARGET,
+ ISSUE_MARKER_OFFSET,
+ ISSUE_MARKER_PADDING_X,
+ ISSUE_MARKER_RING_WIDTH,
+ ISSUE_MARKER_VIEWPORT_INSET
+} from '#core/constants'
+import { createSceneGeometry, type RotationPreview, type ViewportTransform } from '#core/geometry'
+
+import type { DesignIssueMarker, DesignIssueSeverity, PlacedIssueMarker } from './types'
+
+export interface IssueMarkerView extends ViewportTransform {
+ width: number
+ height: number
+ /** Space taken by chrome along the top and left edges, such as rulers. */
+ insetTop: number
+ insetLeft: number
+}
+
+export interface IssueMarkerLayoutOptions {
+ pageId: string
+ view: IssueMarkerView
+ /** Layers whose markers would cover an active edit, such as the text being typed. */
+ suppressedIds?: ReadonlySet<string>
+ preview?: RotationPreview | null
+ measureText: (text: string) => number
+ /** Screen rectangles of UI floating over the canvas, such as a toolbar, to keep pins clear of. */
+ obstacles?: readonly Rect[]
+}
+
+const SEVERITY_RANK: Record<DesignIssueSeverity, number> = { error: 3, warning: 2, info: 1 }
+
+export function issueSeverityRank(severity: DesignIssueSeverity): number {
+ return SEVERITY_RANK[severity]
+}
+
+export function issueMarkerLabel(count: number): string {
+ if (count <= 1) return '!'
+ return count > ISSUE_MARKER_MAX_COUNT ? `${ISSUE_MARKER_MAX_COUNT}+` : String(count)
+}
+
+export function issueMarkerWidth(count: number, measureText: (text: string) => number): number {
+ const textWidth = measureText(issueMarkerLabel(count))
+ return Math.max(ISSUE_MARKER_HEIGHT, Math.ceil(textWidth + ISSUE_MARKER_PADDING_X * 2))
+}
+
+function intersect(a: Rect, b: Rect): Rect | null {
+ const x = Math.max(a.x, b.x)
+ const y = Math.max(a.y, b.y)
+ const right = Math.min(a.x + a.width, b.x + b.width)
+ const bottom = Math.min(a.y + a.height, b.y + b.height)
+ if (right < x || bottom < y) return null
+ return { x, y, width: right - x, height: bottom - y }
+}
+
+function overlaps(a: Rect, b: Rect, gap: number): boolean {
+ return (
+ a.x < b.x + b.width + gap &&
+ b.x < a.x + a.width + gap &&
+ a.y < b.y + b.height + gap &&
+ b.y < a.y + a.height + gap
+ )
+}
+
+function screenBounds(
+ node: SceneNode,
+ geometry: ReturnType<typeof createSceneGeometry>,
+ view: ViewportTransform
+): Rect {
+ const points = Matrix.mapPoints(geometry.screenMatrix(node, view), [
+ 0,
+ 0,
+ node.width,
+ 0,
+ node.width,
+ node.height,
+ 0,
+ node.height
+ ])
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (let index = 0; index < points.length; index += 2) {
+ minX = Math.min(minX, points[index])
+ maxX = Math.max(maxX, points[index])
+ minY = Math.min(minY, points[index + 1])
+ maxY = Math.max(maxY, points[index + 1])
+ }
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
+}
+
+/**
+ * The screen rectangle a layer's marker attaches to, or null when the layer should not be marked.
+ *
+ * Hidden and clipped-out layers stay listed in the panel but get no marker, so a marker never
+ * points at empty canvas. A layer too small to point at on screen hands its marker to the nearest
+ * ancestor that is large enough, so zoomed-out designs gather markers at frame corners instead of
+ * scattering them over detail that cannot be seen.
+ */
+function markerTarget(
+ graph: SceneGraph,
+ node: SceneNode,
+ pageId: string,
+ geometry: ReturnType<typeof createSceneGeometry>,
+ view: ViewportTransform
+): Rect | null {
+ const chain: SceneNode[] = []
+ let current: SceneNode | undefined = node
+ while (current) {
+ if (!current.visible) return null
+ chain.push(current)
+ if (current.parentId === pageId) break
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
+ }
+ if (!current) return null
+
+ // Clip each layer's bounds by the clipping ancestors above it, walking top-down. A clipping
+ // layer that is entirely clipped away hides everything inside it.
+ const visible = Array.from<Rect | null>({ length: chain.length })
+ let clip: Rect | null = null
+ for (let index = chain.length - 1; index >= 0; index--) {
+ const layer = chain[index]
+ const bounds = screenBounds(layer, geometry, view)
+ const clipped: Rect | null = clip ? intersect(bounds, clip) : bounds
+ visible[index] = clipped
+ if (!layer.clipsContent) continue
+ if (!clipped) return null
+ clip = clipped
+ }
+
+ if (!visible[0]) return null
+ for (let index = 0; index < chain.length; index++) {
+ const bounds = visible[index]
+ if (!bounds) continue
+ const last = index === chain.length - 1
+ if (last || Math.max(bounds.width, bounds.height) >= ISSUE_MARKER_MIN_TARGET) return bounds
+ }
+ return visible[0]
+}
+
+interface Candidate {
+ marker: DesignIssueMarker
+ anchor: Vector
+}
+
+interface EdgeCandidate {
+ marker: DesignIssueMarker
+ /** Where the ray toward the layer leaves the viewport. */
+ point: Vector
+ direction: Vector
+ distance: number
+}
+
+/**
+ * Where the ray from the viewport center toward a layer leaves `area`, so an off-screen issue
+ * is pinned in its own direction, on a side or in a corner.
+ */
+function edgePoint(
+ area: Rect,
+ target: Vector
+): { point: Vector; direction: Vector; distance: number } {
+ const center = { x: area.x + area.width / 2, y: area.y + area.height / 2 }
+ const dx = target.x - center.x
+ const dy = target.y - center.y
+ const distance = Math.hypot(dx, dy) || 1
+ const direction = { x: dx / distance, y: dy / distance }
+ const tx = direction.x === 0 ? Infinity : area.width / 2 / Math.abs(direction.x)
+ const ty = direction.y === 0 ? Infinity : area.height / 2 / Math.abs(direction.y)
+ const t = Math.min(tx, ty)
+ return {
+ point: { x: center.x + direction.x * t, y: center.y + direction.y * t },
+ direction,
+ distance
+ }
+}
+
+/** Slides a pin along the edge it sits on until it no longer covers floating UI. */
+function avoidObstacles(rect: Rect, area: Rect, obstacles: readonly Rect[]): Rect {
+ let placed = rect
+ for (const obstacle of obstacles) {
+ if (!overlaps(placed, obstacle, ISSUE_MARKER_GAP)) continue
+ const onHorizontalEdge =
+ placed.y <= area.y + 1 || placed.y + placed.height >= area.y + area.height - 1
+ if (onHorizontalEdge) {
+ const left = obstacle.x - ISSUE_MARKER_GAP - placed.width
+ const right = obstacle.x + obstacle.width + ISSUE_MARKER_GAP
+ const x =
+ Math.abs(left - placed.x) <= Math.abs(right - placed.x) && left >= area.x
+ ? left
+ : Math.min(right, area.x + area.width - placed.width)
+ placed = { ...placed, x }
+ } else {
+ const above = obstacle.y - ISSUE_MARKER_GAP - placed.height
+ const below = obstacle.y + obstacle.height + ISSUE_MARKER_GAP
+ const y =
+ Math.abs(above - placed.y) <= Math.abs(below - placed.y) && above >= area.y
+ ? above
+ : Math.min(below, area.y + area.height - placed.height)
+ placed = { ...placed, y }
+ }
+ }
+ return placed
+}
+
+/**
+ * Pins issues outside the viewport to its edge, in their direction. Pins near each other along
+ * the edge merge, keeping the most severe; each lists its layers most severe first, then
+ * nearest, so following a pin reaches the closest issue of the severity it shows.
+ */
+function layoutEdgePins(
+ candidates: EdgeCandidate[],
+ area: Rect,
+ obstacles: readonly Rect[],
+ measureText: (text: string) => number
+): PlacedIssueMarker[] {
+ candidates.sort(
+ (a, b) =>
+ SEVERITY_RANK[b.marker.severity] - SEVERITY_RANK[a.marker.severity] || a.distance - b.distance
+ )
+ const rectAt = (point: Vector, count: number): Rect => {
+ const width = issueMarkerWidth(count, measureText)
+ const x = Math.min(Math.max(point.x - width / 2, area.x), area.x + area.width - width)
+ const y = Math.min(
+ Math.max(point.y - ISSUE_MARKER_HEIGHT / 2, area.y),
+ area.y + area.height - ISSUE_MARKER_HEIGHT
+ )
+ const rect = { x: Math.round(x), y: Math.round(y), width, height: ISSUE_MARKER_HEIGHT }
+ return avoidObstacles(rect, area, obstacles)
+ }
+ type Pin = PlacedIssueMarker & { point: Vector; order: Map<string, [number, number]> }
+ const pins: Pin[] = []
+ for (const { marker, point, direction, distance } of candidates) {
+ const rect = rectAt(point, marker.count)
+ const pin = pins.find((existing) => overlaps(existing.rect, rect, ISSUE_EDGE_MERGE_GAP))
+ if (pin) {
+ pin.nodeIds.push(marker.nodeId)
+ pin.order.set(marker.nodeId, [SEVERITY_RANK[marker.severity], distance])
+ pin.count += marker.count
+ pin.rect = rectAt(pin.point, pin.count)
+ continue
+ }
+ pins.push({
+ key: `edge:${marker.nodeId}`,
+ nodeIds: [marker.nodeId],
+ severity: marker.severity,
+ count: marker.count,
+ rect,
+ anchor: point,
+ direction,
+ point,
+ order: new Map([[marker.nodeId, [SEVERITY_RANK[marker.severity], distance]]])
+ })
+ }
+ const rank = (order: Pin['order'], id: string) => order.get(id) ?? [0, 0]
+ return pins.map(({ point: _point, order, ...pin }) => ({
+ ...pin,
+ nodeIds: pin.nodeIds.toSorted((a, b) => {
+ const [severityA, distanceA] = rank(order, a)
+ const [severityB, distanceB] = rank(order, b)
+ return severityB - severityA || distanceA - distanceB
+ })
+ }))
+}
+
+/**
+ * Places one marker at the outer top-right corner of each marked layer, then merges markers that
+ * would overlap. Merging keeps the position of the most severe marker, so the canvas never shows
+ * a warning on top of an error it hides.
+ */
+export function layoutIssueMarkers(
+ graph: SceneGraph,
+ markers: readonly DesignIssueMarker[],
+ options: IssueMarkerLayoutOptions
+): PlacedIssueMarker[] {
+ const { view, pageId, suppressedIds, measureText } = options
+ const geometry = createSceneGeometry(graph, options.preview)
+ const viewport: Rect = {
+ x: view.insetLeft,
+ y: view.insetTop,
+ width: Math.max(0, view.width - view.insetLeft),
+ height: Math.max(0, view.height - view.insetTop)
+ }
+
+ const candidates: Candidate[] = []
+ const edgeCandidates: EdgeCandidate[] = []
+ // Edge pins keep room between themselves and the edge for the chevron they point with.
+ const edgeInset = ISSUE_MARKER_VIEWPORT_INSET + ISSUE_EDGE_ARROW + ISSUE_MARKER_RING_WIDTH * 2
+ const edgeArea: Rect = {
+ x: viewport.x + edgeInset,
+ y: viewport.y + edgeInset,
+ width: Math.max(0, viewport.width - edgeInset * 2),
+ height: Math.max(0, viewport.height - edgeInset * 2)
+ }
+ for (const marker of markers) {
+ if (marker.count <= 0 || suppressedIds?.has(marker.nodeId)) continue
+ const node = graph.getNode(marker.nodeId)
+ if (!node) continue
+ const bounds = markerTarget(graph, node, pageId, geometry, view)
+ if (!bounds) continue
+ if (intersect(bounds, viewport)) {
+ candidates.push({ marker, anchor: { x: bounds.x + bounds.width, y: bounds.y } })
+ continue
+ }
+ const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 }
+ edgeCandidates.push({ marker, ...edgePoint(edgeArea, center) })
+ }
+
+ candidates.sort(
+ (a, b) =>
+ SEVERITY_RANK[b.marker.severity] - SEVERITY_RANK[a.marker.severity] ||
+ a.anchor.y - b.anchor.y ||
+ b.anchor.x - a.anchor.x
+ )
+
+ const minX = viewport.x + ISSUE_MARKER_VIEWPORT_INSET
+ const minY = viewport.y + ISSUE_MARKER_VIEWPORT_INSET
+ const maxRight = view.width - ISSUE_MARKER_VIEWPORT_INSET
+ const maxBottom = view.height - ISSUE_MARKER_VIEWPORT_INSET
+
+ function rectAt(anchor: Vector, count: number): Rect {
+ const width = issueMarkerWidth(count, measureText)
+ const x = Math.min(Math.max(anchor.x + ISSUE_MARKER_OFFSET, minX), maxRight - width)
+ const y = Math.min(
+ Math.max(anchor.y - ISSUE_MARKER_OFFSET - ISSUE_MARKER_HEIGHT, minY),
+ maxBottom - ISSUE_MARKER_HEIGHT
+ )
+ return { x: Math.round(x), y: Math.round(y), width, height: ISSUE_MARKER_HEIGHT }
+ }
+
+ const placed: PlacedIssueMarker[] = []
+ for (const { marker, anchor } of candidates) {
+ const rect = rectAt(anchor, marker.count)
+ const target = placed.find((existing) => overlaps(existing.rect, rect, ISSUE_MARKER_GAP))
+ if (target) {
+ target.nodeIds.push(marker.nodeId)
+ target.count += marker.count
+ target.rect = rectAt(target.anchor, target.count)
+ continue
+ }
+ placed.push({
+ key: marker.nodeId,
+ nodeIds: [marker.nodeId],
+ severity: marker.severity,
+ count: marker.count,
+ rect,
+ anchor
+ })
+ }
+ const edgePins = layoutEdgePins(edgeCandidates, edgeArea, options.obstacles ?? [], measureText)
+ return [...placed, ...edgePins]
+}
+
+/** Topmost marker under a screen point; markers placed first are drawn on top. */
+export function hitTestIssueMarkers(
+ placed: readonly PlacedIssueMarker[],
+ x: number,
+ y: number
+): PlacedIssueMarker | null {
+ for (const marker of placed) {
+ const { rect } = marker
+ if (x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height) {
+ return marker
+ }
+ }
+ return null
+}
diff --git a/packages/core/src/canvas/issues/types.ts b/packages/core/src/canvas/issues/types.ts
new file mode 100644
index 000000000..4754b53ef
--- /dev/null
+++ b/packages/core/src/canvas/issues/types.ts
@@ -0,0 +1,44 @@
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+
+export type DesignIssueSeverity = 'error' | 'warning' | 'info'
+
+/** Issues reported on one layer, collapsed to what the canvas marker shows. */
+export interface DesignIssueMarker {
+ nodeId: string
+ severity: DesignIssueSeverity
+ count: number
+}
+
+/** A layer the user is inspecting through a marker or an issue row. */
+export interface DesignIssueHighlight {
+ nodeId: string
+ severity: DesignIssueSeverity
+ /** Minimum size the layer should reach, drawn as a ghost target around it. */
+ minSize?: { width: number; height: number }
+}
+
+export interface DesignIssueOverlay {
+ /** Layers to mark on the canvas; empty while markers are turned off. */
+ markers: readonly DesignIssueMarker[]
+ highlight: DesignIssueHighlight | null
+ /** `key` of the placed marker under the pointer. */
+ hoveredMarkerKey: string | null
+}
+
+/** A marker placed in screen space; nearby layers share one marker. */
+export interface PlacedIssueMarker {
+ /** Stable while the leading layer stays the same, for hover state. */
+ key: string
+ nodeIds: string[]
+ severity: DesignIssueSeverity
+ count: number
+ /** Screen-space rectangle in CSS pixels. */
+ rect: Rect
+ /** Screen-space corner of the layer the marker is attached to. */
+ anchor: Vector
+ /**
+ * Set for an edge pin: issues outside the viewport, pinned to its edge. A unit vector from the
+ * viewport center toward them; `nodeIds` are ordered most severe first, then nearest.
+ */
+ direction?: Vector
+}
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 24989607b..cd63f7c64 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -67,6 +67,7 @@ export interface PendingFontNode {
keys: Set<string>
}
+import type { PlacedIssueMarker } from './issues/types'
import { EffectRasterCache } from './renderer/effect-raster-cache'
import { TiledSceneController } from './renderer/tiles'
import type { TransientCanvasPreview } from './renderer/transient-previews'
@@ -174,6 +175,10 @@ export class SkiaRenderer {
pageColor = CANVAS_BG_COLOR
rulerTheme: RulerTheme | null = null
pageId: string | null = null
+ /** Issue markers placed in the last overlay pass; hit testing reads the same layout. */
+ issueMarkers: PlacedIssueMarker[] = []
+ /** Screen rectangles of UI floating over this canvas, which overlays such as edge pins avoid. */
+ overlayObstacles: readonly Rect[] = []
boundEffectLayersToViewport = false
worldViewport = { x: 0, y: 0, w: 0, h: 0 }
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index 32d368d2f..5fdb3f585 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -3,8 +3,11 @@ import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
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 type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
+import { RULER_SIZE } from '#core/constants'
function measurementVisible(overlays: RenderOverlays): boolean {
return (
@@ -31,6 +34,49 @@ export function drawLabelPass(
profiler.endPhase('render:componentLabels')
}
+function suppressedIssueIds(overlays: RenderOverlays): Set<string> {
+ const ids = new Set<string>()
+ if (overlays.editingTextId) ids.add(overlays.editingTextId)
+ if (overlays.nodeEditState) ids.add(overlays.nodeEditState.nodeId)
+ return ids
+}
+
+/**
+ * Lays out markers for this frame and keeps them for hit testing, so the pointer always targets
+ * what is drawn. Markers stay attached to their layers through edits and hide while drawing a path.
+ */
+function updateIssueMarkers(r: SkiaRenderer, graph: SceneGraph, overlays: RenderOverlays): void {
+ const markers = overlays.designIssues?.markers
+ if (!markers || markers.length === 0 || overlays.penState) {
+ r.issueMarkers = []
+ return
+ }
+ const measureText = (text: string) => {
+ const font = r.sizeFont
+ if (!font) return 0
+ let width = 0
+ for (const glyph of font.getGlyphWidths(font.getGlyphIDs(text))) width += glyph
+ return width
+ }
+ const inset = r.showRulers ? RULER_SIZE : 0
+ r.issueMarkers = layoutIssueMarkers(graph, markers, {
+ pageId: r.pageId ?? '',
+ view: {
+ panX: r.panX,
+ panY: r.panY,
+ zoom: r.zoom,
+ width: r.viewportWidth,
+ height: r.viewportHeight,
+ insetTop: inset,
+ insetLeft: inset
+ },
+ suppressedIds: suppressedIssueIds(overlays),
+ preview: overlays.rotationPreview,
+ measureText,
+ obstacles: r.overlayObstacles
+ })
+}
+
export function drawOverlayPass(
r: SkiaRenderer,
canvas: Canvas,
@@ -44,6 +90,7 @@ export function drawOverlayPass(
? null
: overlays.hoveredNodeId
r.drawHoverHighlight(canvas, graph, hoveredNodeId, overlays.rotationPreview)
+ drawIssueHighlight(r, canvas, graph, overlays.designIssues?.highlight, overlays.rotationPreview)
r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId, overlays.rotationPreview)
r.profiler.beginPhase('render:selection')
r.drawSelection(canvas, graph, selectedIds, overlays)
@@ -59,6 +106,8 @@ export function drawOverlayPass(
if (!measuring) r.drawAutoLayoutHover(canvas, graph, overlays.autoLayoutHover)
r.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)
r.drawPenOverlay(canvas, overlays.penState)
+ updateIssueMarkers(r, graph, overlays)
+ drawIssueMarkers(r, canvas, r.issueMarkers, overlays.designIssues?.hoveredMarkerKey)
r.drawPresenceCursors(canvas, graph, overlays.presenceCursors)
}
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 1937a52c4..d17272f10 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -79,6 +79,7 @@ export function renderFromEditorState(
: null,
nodeEditState: state.nodeEditState ?? null,
presenceCursors: state.presenceCursors,
+ designIssues: state.designIssues,
autoLayoutHover: state.autoLayoutHover
},
state.sceneVersion,
diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.ts
index f8183d5b3..f92395c3d 100644
--- a/packages/core/src/canvas/renderer/types.ts
+++ b/packages/core/src/canvas/renderer/types.ts
@@ -3,6 +3,7 @@ import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'
import type { SnapGuide } from '@open-pencil/scene-graph/snap'
import type { GuideOverlayState } from '#core/canvas/guides/types'
+import type { DesignIssueOverlay } from '#core/canvas/issues/types'
import type { RotationPreview } from '#core/geometry'
import type { TextEditor } from '#core/text/editor'
@@ -79,4 +80,5 @@ export interface RenderOverlays {
hoveredHandleInfo?: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null
} | null
presenceCursors?: PresenceCursor[]
+ designIssues?: DesignIssueOverlay | null
}
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 96d689660..d40a06c36 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -135,6 +135,27 @@ export const FLASH_PADDING = 5
export const FLASH_OVERSHOOT = 30
export const FLASH_RADIUS = 4
+export const ISSUE_ERROR_COLOR = { r: 0.949, g: 0.282, b: 0.133, a: 1 } satisfies Color // #F24822
+export const ISSUE_WARNING_COLOR = { r: 1, g: 0.702, b: 0.078, a: 1 } satisfies Color // #FFB314
+export const ISSUE_INFO_COLOR = { r: 0.55, g: 0.55, b: 0.55, a: 1 } satisfies Color
+export const ISSUE_MARKER_HEIGHT = 16
+export const ISSUE_MARKER_PADDING_X = 5
+/** Gap between a layer's corner and its marker; clears the 8px selection handle. */
+export const ISSUE_MARKER_OFFSET = 4
+/** Markers closer than this merge into one. */
+export const ISSUE_MARKER_GAP = 2
+export const ISSUE_MARKER_VIEWPORT_INSET = 4
+/** Layers smaller than this on screen pass their marker to an ancestor. */
+export const ISSUE_MARKER_MIN_TARGET = 24
+export const ISSUE_MARKER_MAX_COUNT = 99
+/** Edge pins closer than this along the viewport edge merge into one. */
+export const ISSUE_EDGE_MERGE_GAP = 24
+/** Length of the chevron an edge pin points with, beyond its ring. */
+export const ISSUE_EDGE_ARROW = 5
+export const ISSUE_MARKER_RING_WIDTH = 1.5
+export const ISSUE_HIGHLIGHT_STROKE_WIDTH = 1.5
+export const ISSUE_HIGHLIGHT_FILL_ALPHA = 0.08
+
export const AI_ACTIVE_COLOR = { r: 0.26, g: 0.52, b: 0.96 }
export const AI_DONE_COLOR = { r: 0.16, g: 0.73, b: 0.36 }
export const AI_PULSE_PERIOD_MS = 1500
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 2b7c10b1a..264fe3ced 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -29,6 +29,7 @@ import { createComponentActions } from './components'
import { createGraphEventSubscription } from './graph-events'
import { createGraphReadActions } from './graph-reads'
import { createGuideActions } from './guides'
+import { createDesignIssueActions } from './issues'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
import { createSelectionActions } from './selection'
@@ -218,6 +219,7 @@ export function createEditor(options?: EditorOptions) {
const selection = createSelectionActions(ctx)
const pages = createPageActions(ctx)
const guides = createGuideActions(ctx)
+ const designIssues = createDesignIssueActions(ctx)
const shapes = createShapeActions(ctx)
const structure = createStructureActions(ctx)
const components = createComponentActions(ctx)
@@ -331,6 +333,7 @@ export function createEditor(options?: EditorOptions) {
// Canvas and frame guides
...guides,
+ ...designIssues,
// Shapes & tools
...shapes,
diff --git a/packages/core/src/editor/issues.ts b/packages/core/src/editor/issues.ts
new file mode 100644
index 000000000..61b0a8f7c
--- /dev/null
+++ b/packages/core/src/editor/issues.ts
@@ -0,0 +1,57 @@
+import type { DesignIssueHighlight, DesignIssueMarker } from '#core/canvas/issues/types'
+
+import type { EditorContext } from './types'
+
+/**
+ * Canvas presentation of design check results. The check itself runs outside the editor; these
+ * actions only publish what the canvas marks and highlights.
+ */
+function sameHighlight(a: DesignIssueHighlight | null, b: DesignIssueHighlight | null): boolean {
+ if (!a || !b) return a === b
+ return (
+ a.nodeId === b.nodeId &&
+ a.severity === b.severity &&
+ a.minSize?.width === b.minSize?.width &&
+ a.minSize?.height === b.minSize?.height
+ )
+}
+
+export function createDesignIssueActions(ctx: EditorContext) {
+ function current() {
+ return ctx.state.designIssues ?? { markers: [], highlight: null, hoveredMarkerKey: null }
+ }
+
+ function setDesignIssueMarkers(markers: readonly DesignIssueMarker[]) {
+ const overlay = current()
+ if (overlay.markers.length === 0 && markers.length === 0) return
+ ctx.state.designIssues = { ...overlay, markers }
+ ctx.requestRepaint()
+ }
+
+ function setDesignIssueHighlight(highlight: DesignIssueHighlight | null) {
+ const overlay = current()
+ if (sameHighlight(overlay.highlight, highlight)) return
+ ctx.state.designIssues = { ...overlay, highlight }
+ ctx.requestRepaint()
+ }
+
+ function setHoveredIssueMarker(key: string | null) {
+ const overlay = current()
+ if (overlay.hoveredMarkerKey === key) return
+ ctx.state.designIssues = { ...overlay, hoveredMarkerKey: key }
+ ctx.requestRepaint()
+ }
+
+ function clearDesignIssues() {
+ if (!ctx.state.designIssues) return
+ ctx.state.designIssues = null
+ ctx.requestRepaint()
+ }
+
+ return {
+ setDesignIssueMarkers,
+ setDesignIssueHighlight,
+ setHoveredIssueMarker,
+ clearDesignIssues
+ }
+}
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index 56e060923..a1a9552aa 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -9,6 +9,7 @@ import {
} from '@open-pencil/scene-graph'
import { reconcileVariableLayouts } from '#core/layout/variables'
+import { applyLintFixes as applyFixes, type LintFixRequest } from '#core/lint/fixes'
import { createLayoutModeActions } from './layout-mode'
import { createNodePreviewActions } from './node-preview'
@@ -110,8 +111,23 @@ export function createNodeActions(ctx: EditorContext) {
)
}
+ /** Applies lint fixes that still hold as one undo step; returns how many applied. */
+ function applyLintFixes(requests: readonly LintFixRequest[]): number {
+ return ctx.undo.runBatch('Fix design issues', () =>
+ applyFixes(
+ {
+ graph: ctx.graph,
+ updateNode: (id, changes) => updateNodeWithUndo(id, changes, 'Fix design issue'),
+ bindVariable: variableBindingActions.bindVariable
+ },
+ requests
+ )
+ )
+ }
+
return {
updateNode,
+ applyLintFixes,
...createNodePreviewActions(ctx, updateNode),
updateNodeWithUndo,
setOpacity,
diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.ts
index 1a2e399e8..443885c98 100644
--- a/packages/core/src/editor/state/shared.ts
+++ b/packages/core/src/editor/state/shared.ts
@@ -7,6 +7,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {
snappingPreferences: { ...DEFAULT_SNAPPING_PREFERENCES },
presenceCursors: [],
documentName: 'Untitled',
+ designIssues: null,
rulerTheme: undefined,
sceneVersion: 0
}
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 49e239739..392e33ecc 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -14,6 +14,7 @@ import type { SnapGuide } from '@open-pencil/scene-graph/snap'
import type { UndoManager } from '@open-pencil/scene-graph/undo'
import type { GuideOverlayState } from '#core/canvas/guides/types'
+import type { DesignIssueOverlay } from '#core/canvas/issues/types'
import type { RulerTheme, SkiaRenderer } from '#core/canvas/renderer'
import type { MeasurementMode, PresenceCursor, RenderOverlays } from '#core/canvas/renderer/types'
import type { SnappingPreferences } from '#core/editor/preferences'
@@ -39,6 +40,8 @@ export interface EditorSharedState {
snappingPreferences: SnappingPreferences
presenceCursors: PresenceCursor[]
documentName: string
+ /** Design check markers and highlight, shared by every canvas pane. */
+ designIssues: DesignIssueOverlay | null
rulerTheme?: RulerTheme
sceneVersion: number
}
diff --git a/packages/core/src/io/formats/fig/index.ts b/packages/core/src/io/formats/fig/index.ts
index f7a44f674..cbc319181 100644
--- a/packages/core/src/io/formats/fig/index.ts
+++ b/packages/core/src/io/formats/fig/index.ts
@@ -2,6 +2,7 @@ export { readFigFile, parseFigFile, type ParseFigFileOptions } from './read'
export { exportFigFile, compressFigData, compressFigDataSync } from './write'
export { findFigThumbnailPageId } from './thumbnail-page'
export {
+ isReaderPagePending as isFigPagePending,
populateFigPage,
populateAllFigPages,
readerDiagnostics
diff --git a/packages/core/src/lint/fixes.ts b/packages/core/src/lint/fixes.ts
new file mode 100644
index 000000000..5be55b39a
--- /dev/null
+++ b/packages/core/src/lint/fixes.ts
@@ -0,0 +1,78 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
+
+import type { LintFix, LintMessage } from './types'
+
+/** A fix for the layer it was reported on. A `LintMessage` with a `fix` is one. */
+export interface LintFixRequest {
+ nodeId: string
+ fix: LintFix
+}
+
+/**
+ * Where fixes are written. The editor supplies undoable actions; headless callers write the
+ * graph directly with {@link graphFixTarget}.
+ */
+export interface LintFixTarget {
+ readonly graph: SceneGraph
+ updateNode(nodeId: string, changes: Partial<SceneNode>): void
+ bindVariable(nodeId: string, path: string, variableId: string): void
+}
+
+export function graphFixTarget(graph: SceneGraph): LintFixTarget {
+ return {
+ graph,
+ updateNode: (nodeId, changes) => graph.updateNode(nodeId, changes),
+ bindVariable: (nodeId, path, variableId) => graph.bindVariable(nodeId, path, variableId)
+ }
+}
+
+/** The safe fixes of a lint run, which apply together without review. */
+export function safeFixes(messages: readonly LintMessage[]): LintFixRequest[] {
+ return messages.flatMap(({ nodeId, fix }) => (fix ? [{ nodeId, fix }] : []))
+}
+
+const PAINT_PATH = /^(fills|strokes)\/(\d+)\/color$/
+
+/**
+ * Binding is safe only while the paint still shows the variable's color: a paint edited since
+ * the lint run would change appearance, so its fix is skipped.
+ */
+function canBind(graph: SceneGraph, node: SceneNode, path: string, variableId: string): boolean {
+ if (node.boundVariables[path] === variableId) return false
+ const match = PAINT_PATH.exec(path)
+ if (!match) return false
+ const index = Number(match[2])
+ const paint = match[1] === 'fills' ? node.fills.at(index) : node.strokes.at(index)
+ const color = graph.resolveColorVariableForNode(node.id, variableId)
+ if (!paint || !color || ('type' in paint && paint.type !== 'SOLID')) return false
+ return colorToHex({ ...paint.color, a: 1 }) === colorToHex({ ...color, a: 1 })
+}
+
+/**
+ * Applies fixes that still hold against the current graph. Changes to one layer merge into a
+ * single update. Returns the number of fixes applied.
+ */
+export function applyLintFixes(target: LintFixTarget, requests: readonly LintFixRequest[]): number {
+ const { graph } = target
+ const updates = new Map<string, Partial<SceneNode>>()
+ let applied = 0
+ for (const { nodeId, fix } of requests) {
+ const node = graph.getNode(nodeId)
+ if (!node) continue
+ if (fix.kind === 'bind-variable') {
+ if (!canBind(graph, node, fix.path, fix.variableId)) continue
+ target.bindVariable(nodeId, fix.path, fix.variableId)
+ applied++
+ continue
+ }
+ const changes = Object.fromEntries(
+ Object.entries(fix.changes).filter(([key, value]) => Reflect.get(node, key) !== value)
+ )
+ if (Object.keys(changes).length === 0) continue
+ updates.set(nodeId, { ...updates.get(nodeId), ...changes })
+ applied++
+ }
+ for (const [nodeId, changes] of updates) target.updateNode(nodeId, changes)
+ return applied
+}
diff --git a/packages/core/src/lint/index.ts b/packages/core/src/lint/index.ts
index 8da9db27a..2944fb993 100644
--- a/packages/core/src/lint/index.ts
+++ b/packages/core/src/lint/index.ts
@@ -1,5 +1,7 @@
export { Linter, createLinter } from './linter'
export { defineRule } from './rule'
+export { applyLintFixes, graphFixTarget, safeFixes } from './fixes'
+export type { LintFixRequest, LintFixTarget } from './fixes'
export { allRules } from './rules'
export { presets, recommended, strict, accessibility } from './presets'
export type {
@@ -8,6 +10,9 @@ export type {
RuleContext,
LintNode,
LintMessage,
+ LintMessageData,
+ LintFix,
+ LintFixProperty,
LintResult,
LintConfig,
Severity,
diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.ts
index 3aaef2439..36c85331b 100644
--- a/packages/core/src/lint/linter.ts
+++ b/packages/core/src/lint/linter.ts
@@ -1,9 +1,11 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { colorToHex } from '@open-pencil/scene-graph/color'
import { presets } from './presets'
import { allRules } from './rules'
import type {
LintConfig,
+ LintVariables,
LintMessage,
LintNode,
LintResult,
@@ -18,6 +20,10 @@ export class Linter {
private ruleConfigs = new Map<string, { severity: Severity; options?: Record<string, unknown> }>()
private messages: LintMessage[] = []
private nodes = new Map<string, LintNode>()
+ private variables: LintVariables = {
+ counts: { COLOR: 0, FLOAT: 0, STRING: 0, BOOLEAN: 0 },
+ colorsByHex: new Map()
+ }
constructor(options: { config?: LintConfig; preset?: string; rules?: string[] } = {}) {
let baseConfig: Record<
@@ -46,6 +52,7 @@ export class Linter {
lintGraph(graph: SceneGraph, rootIds?: string[]): LintResult {
this.messages = []
this.nodes.clear()
+ this.variables = describeVariables(graph)
const roots = rootIds && rootIds.length > 0 ? rootIds : graph.getPages().map((p) => p.id)
for (const id of roots) this.capture(graph, id, undefined)
for (const id of roots) this.lintNode(id)
@@ -60,13 +67,22 @@ export class Linter {
private capture(graph: SceneGraph, id: string, parent?: LintNode) {
const raw = graph.getNode(id)
if (!raw) return
- const node = this.toLintNode(raw)
+ const node = this.toLintNode(graph, raw)
node.parent = parent
this.nodes.set(id, node)
for (const childId of raw.childIds) this.capture(graph, childId, node)
}
- private toLintNode(raw: SceneNode): LintNode {
+ private toLintNode(graph: SceneGraph, raw: SceneNode): LintNode {
+ // Rules see the color a paint renders with, including a bound variable in this node's mode.
+ const paintColor = (
+ field: 'fills' | 'strokes',
+ index: number,
+ color: SceneNode['fills'][number]['color']
+ ) => {
+ const variableId = raw.boundVariables[`${field}/${index}/color`]
+ return (variableId && graph.resolveColorVariableForNode(raw.id, variableId)) || color
+ }
return {
id: raw.id,
name: raw.name,
@@ -79,6 +95,12 @@ export class Linter {
visible: raw.visible,
locked: raw.locked,
layoutMode: raw.layoutMode,
+ layoutPositioning: raw.layoutPositioning,
+ layoutGrow: raw.layoutGrow,
+ layoutAlignSelf: raw.layoutAlignSelf,
+ primaryAxisSizing: raw.primaryAxisSizing,
+ counterAxisSizing: raw.counterAxisSizing,
+ textAutoResize: raw.textAutoResize,
itemSpacing: raw.itemSpacing,
paddingTop: raw.paddingTop,
paddingRight: raw.paddingRight,
@@ -91,16 +113,16 @@ export class Linter {
fontSize: raw.fontSize,
styleRunCount: raw.styleRuns.length,
boundVariables: raw.boundVariables,
- fills: raw.fills.map((f) => ({
+ fills: raw.fills.map((f, index) => ({
type: f.type,
visible: f.visible,
opacity: f.opacity,
- color: f.type === 'SOLID' ? f.color : undefined
+ color: f.type === 'SOLID' ? paintColor('fills', index, f.color) : undefined
})),
- strokes: raw.strokes.map((stroke) => ({
+ strokes: raw.strokes.map((stroke, index) => ({
visible: stroke.visible,
opacity: stroke.opacity,
- color: stroke.color
+ color: paintColor('strokes', index, stroke.color)
})),
effects: raw.effects.map((effect) => ({
type: effect.type,
@@ -118,7 +140,8 @@ export class Linter {
const config = this.ruleConfigs.get(ruleId)
if (!config || config.severity === 'off') continue
const context: RuleContext = {
- report: ({ node, message, suggest }) => {
+ variables: this.variables,
+ report: ({ node, message, suggest, data, fix, suggestions }) => {
this.messages.push({
ruleId,
severity: config.severity as Exclude<Severity, 'off'>,
@@ -126,7 +149,10 @@ export class Linter {
nodeId: node.id,
nodeName: node.name,
nodePath: getNodePath(this.nodes.get(node.id) ?? node),
- suggest
+ suggest,
+ data,
+ fix,
+ suggestions
})
},
getConfig: () => config.options,
@@ -138,10 +164,27 @@ export class Linter {
}
rule.check(node, context)
}
+ // Instance sublayers mirror their main component: issues there are fixed once in the
+ // component, so reporting every placed copy only multiplies the same finding.
+ if (node.type === 'INSTANCE') return
for (const childId of node.childIds) this.lintNode(childId)
}
}
+function describeVariables(graph: SceneGraph): LintVariables {
+ const counts = { COLOR: 0, FLOAT: 0, STRING: 0, BOOLEAN: 0 }
+ const colorsByHex = new Map<string, { id: string; name: string }>()
+ for (const variable of graph.variables.values()) {
+ counts[variable.type]++
+ if (variable.type !== 'COLOR') continue
+ const color = graph.resolveColorVariable(variable.id)
+ if (!color || color.a < 1) continue
+ const hex = colorToHex(color)
+ if (!colorsByHex.has(hex)) colorsByHex.set(hex, { id: variable.id, name: variable.name })
+ }
+ return { counts, colorsByHex }
+}
+
export function createLinter(options?: { config?: LintConfig; preset?: string; rules?: string[] }) {
return new Linter(options)
}
diff --git a/packages/core/src/lint/presets.ts b/packages/core/src/lint/presets.ts
index 4a1e0cb96..28818f4e4 100644
--- a/packages/core/src/lint/presets.ts
+++ b/packages/core/src/lint/presets.ts
@@ -5,24 +5,30 @@ export interface Preset {
rules: Record<string, RuleConfig>
}
+/**
+ * Errors and warnings mean a layer is likely wrong for people using the design: low contrast,
+ * small targets or text, spacing off the scale. Token adoption and structure hygiene are
+ * suggestions, which interfaces can list without marking every layer that has one.
+ */
export const recommended: Preset = {
rules: {
- 'no-hardcoded-colors': 'warning',
+ 'no-hardcoded-colors': 'info',
'no-default-names': 'info',
'prefer-auto-layout': 'info',
- 'consistent-spacing': 'warning',
+ 'consistent-spacing': 'info',
'consistent-radius': 'info',
'color-contrast': 'error',
- 'touch-target-size': 'warning',
+ // WCAG 2.2 AA minimum; Strict and Accessibility keep the rule's 44×44 (AAA).
+ 'touch-target-size': { severity: 'warning', options: { minSize: 24 } },
'text-style-required': 'info',
'min-text-size': 'warning',
'no-hidden-layers': 'info',
- 'no-deeply-nested': 'warning',
+ 'no-deeply-nested': 'info',
'no-empty-frames': 'info',
'pixel-perfect': 'info',
'no-groups': 'info',
'effect-style-required': 'info',
- 'no-mixed-styles': 'warning',
+ 'no-mixed-styles': 'info',
'no-detached-instances': 'off'
}
}
diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.ts
index 3701c98b9..c321a7db5 100644
--- a/packages/core/src/lint/rules/color-contrast.ts
+++ b/packages/core/src/lint/rules/color-contrast.ts
@@ -1,7 +1,9 @@
-import { contrastRatio } from '@open-pencil/scene-graph/color'
+import { colorToHex, contrastRatio } from '@open-pencil/scene-graph/color'
import { defineRule } from '#core/lint/rule'
+const MIN_CONTRAST = 4.5
+
export default defineRule({
meta: {
id: 'color-contrast',
@@ -11,22 +13,24 @@ export default defineRule({
},
match: ['TEXT'],
check(node, context) {
- const textFillIndex = node.fills.findIndex((f) => f.type === 'SOLID' && f.visible && f.color)
- const textColor = node.fills[textFillIndex]?.color
+ const textColor = node.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.color
if (textColor == null) return
- // When the fill color is overridden by a variable binding, the effective
- // color depends on the active mode — static contrast checks are unreliable.
- if (node.boundVariables[`fills/${textFillIndex}/color`]) return
let parent = context.getParent(node)
while (parent) {
const bg = parent.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.color
if (bg) {
const ratio = contrastRatio(textColor, bg)
- if (ratio < 4.5)
+ if (ratio < MIN_CONTRAST)
context.report({
node,
message: `Contrast ratio ${ratio.toFixed(2)}:1 is below WCAG AA`,
- suggest: 'Increase contrast between text and background'
+ suggest: 'Increase contrast between text and background',
+ data: {
+ ratio: Math.floor(ratio * 100) / 100,
+ minRatio: MIN_CONTRAST,
+ foreground: colorToHex({ ...textColor, a: 1 }),
+ background: colorToHex({ ...bg, a: 1 })
+ }
})
return
}
diff --git a/packages/core/src/lint/rules/consistent-radius.ts b/packages/core/src/lint/rules/consistent-radius.ts
index eaddfa7e2..402eebae5 100644
--- a/packages/core/src/lint/rules/consistent-radius.ts
+++ b/packages/core/src/lint/rules/consistent-radius.ts
@@ -1,5 +1,10 @@
import { defineRule } from '#core/lint/rule'
-const SCALE = new Set([0, 2, 4, 6, 8, 12, 16, 20, 24, 32, 9999])
+import { nearestValue } from '#core/lint/utils'
+
+/** Radii from the scale; the pill radius is offered only for a layer that already reads as one. */
+const SCALE = [0, 2, 4, 6, 8, 12, 16, 20, 24, 32]
+const PILL_RADIUS = 9999
+
export default defineRule({
meta: {
id: 'consistent-radius',
@@ -8,11 +13,17 @@ export default defineRule({
},
match: ['RECTANGLE', 'FRAME', 'COMPONENT', 'INSTANCE'],
check(node, context) {
- if (node.cornerRadius > 0 && !SCALE.has(node.cornerRadius))
- context.report({
- node,
- message: `Corner radius ${node.cornerRadius}px is not in scale`,
- suggest: 'Use a radius token or a scale value'
- })
+ const radius = node.cornerRadius
+ if (radius <= 0 || radius === PILL_RADIUS || SCALE.includes(radius)) return
+ const pill = radius >= Math.min(node.width, node.height) / 2
+ const suggested = pill ? PILL_RADIUS : nearestValue(radius, SCALE.slice(1))
+ context.report({
+ node,
+ message: `Corner radius ${radius}px is not in scale`,
+ suggest: 'Use a radius token or a scale value',
+ data: { radius },
+ suggestions:
+ suggested === null ? undefined : [{ kind: 'set', changes: { cornerRadius: suggested } }]
+ })
}
})
diff --git a/packages/core/src/lint/rules/consistent-spacing.ts b/packages/core/src/lint/rules/consistent-spacing.ts
index a97b01117..d31dd1b54 100644
--- a/packages/core/src/lint/rules/consistent-spacing.ts
+++ b/packages/core/src/lint/rules/consistent-spacing.ts
@@ -1,5 +1,5 @@
import { defineRule } from '#core/lint/rule'
-import { isMultipleOf, SPACING_SCALE } from '#core/lint/utils'
+import { isMultipleOf, nearestValue, SPACING_SCALE } from '#core/lint/utils'
export default defineRule({
meta: {
@@ -11,10 +11,10 @@ export default defineRule({
check(node, context) {
if (node.layoutMode === 'NONE') return
const config = context.getConfig() as { base?: number } | undefined
- const base = config?.base ?? 8
+ const base = config?.base ?? 4
const valid = (value: number) => SPACING_SCALE.includes(value) || isMultipleOf(value, base)
const values = [
- ['gap', node.itemSpacing],
+ ['itemSpacing', node.itemSpacing],
['paddingTop', node.paddingTop],
['paddingRight', node.paddingRight],
['paddingBottom', node.paddingBottom],
@@ -22,10 +22,19 @@ export default defineRule({
] as const
for (const [name, value] of values) {
if (value > 0 && !valid(value)) {
+ const step = base > 0 ? base : 1
+ const multiples = [Math.floor(value / step) * step, Math.ceil(value / step) * step]
+ const suggested = nearestValue(
+ value,
+ [...SPACING_SCALE, ...multiples].filter((candidate) => candidate > 0)
+ )
context.report({
node,
- message: `${name} ${value}px is not in spacing scale`,
- suggest: 'Use a spacing token or 8pt-grid multiple'
+ message: `${name === 'itemSpacing' ? 'gap' : name} ${value}px is not in spacing scale`,
+ suggest: `Use a spacing token or a multiple of ${base}px`,
+ data: { property: name, value, base },
+ suggestions:
+ suggested === null ? undefined : [{ kind: 'set', changes: { [name]: suggested } }]
})
}
}
diff --git a/packages/core/src/lint/rules/effect-style-required.ts b/packages/core/src/lint/rules/effect-style-required.ts
index 9d95e1d5f..36d8e48ce 100644
--- a/packages/core/src/lint/rules/effect-style-required.ts
+++ b/packages/core/src/lint/rules/effect-style-required.ts
@@ -12,7 +12,8 @@ export default defineRule({
context.report({
node,
message: `Effect without shared style: ${visibleEffects.map((effect) => `${effect.type} ${effect.radius}px`).join(', ')}`,
- suggest: 'Extract reusable shadows and blurs into shared presets or variables'
+ suggest: 'Extract reusable shadows and blurs into shared presets or variables',
+ data: { effect: visibleEffects[0].type, count: visibleEffects.length }
})
}
})
diff --git a/packages/core/src/lint/rules/min-text-size.ts b/packages/core/src/lint/rules/min-text-size.ts
index 4a93dceec..d12ec7656 100644
--- a/packages/core/src/lint/rules/min-text-size.ts
+++ b/packages/core/src/lint/rules/min-text-size.ts
@@ -14,7 +14,9 @@ export default defineRule({
context.report({
node,
message: `Text size ${node.fontSize}px is below minimum ${minSize}px`,
- suggest: `Increase to at least ${minSize}px for readability`
+ suggest: `Increase to at least ${minSize}px for readability`,
+ data: { fontSize: node.fontSize, minSize },
+ suggestions: [{ kind: 'set', changes: { fontSize: minSize } }]
})
}
})
diff --git a/packages/core/src/lint/rules/no-deeply-nested.ts b/packages/core/src/lint/rules/no-deeply-nested.ts
index c07542ad2..0a0c72eda 100644
--- a/packages/core/src/lint/rules/no-deeply-nested.ts
+++ b/packages/core/src/lint/rules/no-deeply-nested.ts
@@ -15,11 +15,13 @@ export default defineRule({
depth++
current = context.getParent(current)
}
- if (depth > maxDepth) {
+ // Report the layer that crosses the limit, not every descendant below it.
+ if (depth === maxDepth + 1) {
context.report({
node,
message: `Layer nested ${depth} levels deep (max ${maxDepth})`,
- suggest: 'Flatten structure or extract a component'
+ suggest: 'Flatten structure or extract a component',
+ data: { depth, maxDepth }
})
}
}
diff --git a/packages/core/src/lint/rules/no-default-names.ts b/packages/core/src/lint/rules/no-default-names.ts
index 7c0dcc615..d40443fe2 100644
--- a/packages/core/src/lint/rules/no-default-names.ts
+++ b/packages/core/src/lint/rules/no-default-names.ts
@@ -15,7 +15,8 @@ export default defineRule({
context.report({
node,
message: `Default layer name "${node.name}" is not descriptive`,
- suggest: 'Rename to describe the layer purpose'
+ suggest: 'Rename to describe the layer purpose',
+ data: { name: node.name }
})
}
})
diff --git a/packages/core/src/lint/rules/no-hardcoded-colors.ts b/packages/core/src/lint/rules/no-hardcoded-colors.ts
index 7cb0b49e1..7e9f069d1 100644
--- a/packages/core/src/lint/rules/no-hardcoded-colors.ts
+++ b/packages/core/src/lint/rules/no-hardcoded-colors.ts
@@ -1,10 +1,12 @@
+import { colorToHex } from '@open-pencil/scene-graph/color'
+
import { defineRule } from '#core/lint/rule'
export default defineRule({
meta: {
id: 'no-hardcoded-colors',
category: 'design-tokens',
- description: 'Colors should use variables instead of hardcoded values'
+ description: 'Colors that match a color variable should be bound to it'
},
match: [
'RECTANGLE',
@@ -19,6 +21,8 @@ export default defineRule({
'INSTANCE'
],
check(node, context) {
+ const { colorsByHex } = context.variables
+ if (colorsByHex.size === 0) return
const checkPaints = (
paints: ReadonlyArray<{
visible: boolean
@@ -32,10 +36,27 @@ export default defineRule({
if (paint.type !== 'SOLID' || !paint.visible || !paint.color) continue
// Check indexed binding (e.g. "fills/0/color") — the format the renderer actually reads
if (node.boundVariables[`${field}/${i}/color`]) continue
+ // Only a color with an exact variable match has an obvious fix: bind that variable.
+ const color = colorToHex({ ...paint.color, a: 1 })
+ const variable = colorsByHex.get(color)
+ if (!variable) continue
context.report({
node,
- message: `Hardcoded ${field === 'fills' ? 'fill' : 'stroke'} color detected`,
- suggest: 'Bind this color to a design variable for consistency'
+ message: `Hardcoded ${field === 'fills' ? 'fill' : 'stroke'} color ${color} matches variable "${variable.name}"`,
+ suggest: `Bind ${field === 'fills' ? 'fill' : 'stroke'} to "${variable.name}"`,
+ data: {
+ paint: field === 'fills' ? 'fill' : 'stroke',
+ index: i,
+ color,
+ variableId: variable.id,
+ variableName: variable.name
+ },
+ fix: {
+ kind: 'bind-variable',
+ path: `${field}/${i}/color`,
+ variableId: variable.id,
+ variableName: variable.name
+ }
})
}
}
diff --git a/packages/core/src/lint/rules/no-mixed-styles.ts b/packages/core/src/lint/rules/no-mixed-styles.ts
index 9f3044a96..a1b3158ff 100644
--- a/packages/core/src/lint/rules/no-mixed-styles.ts
+++ b/packages/core/src/lint/rules/no-mixed-styles.ts
@@ -12,7 +12,8 @@ export default defineRule({
context.report({
node,
message: 'Text layer has mixed font styles',
- suggest: 'Split into separate text layers or unify the text style'
+ suggest: 'Split into separate text layers or unify the text style',
+ data: { styleRuns: node.styleRunCount }
})
}
}
diff --git a/packages/core/src/lint/rules/pixel-perfect.ts b/packages/core/src/lint/rules/pixel-perfect.ts
index 4a16f1f31..1915bf3fb 100644
--- a/packages/core/src/lint/rules/pixel-perfect.ts
+++ b/packages/core/src/lint/rules/pixel-perfect.ts
@@ -1,4 +1,45 @@
import { defineRule } from '#core/lint/rule'
+import type { LintFixProperty, LintNode } from '#core/lint/types'
+
+type Geometry = Extract<LintFixProperty, 'x' | 'y' | 'width' | 'height'>
+
+/** Vector artwork and the parts of groups and boolean shapes are drawn relative to each other. */
+const ARTWORK_TYPES = new Set(['VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON', 'LINE'])
+const ARTWORK_PARENTS = new Set(['GROUP', 'BOOLEAN_OPERATION'])
+
+/**
+ * Rounding one part of a drawing on its own shifts it against the others, so artwork gets no
+ * fix; its findings stay for review.
+ */
+function isArtwork(node: LintNode, parent: LintNode | null): boolean {
+ return ARTWORK_TYPES.has(node.type) || (parent !== null && ARTWORK_PARENTS.has(parent.type))
+}
+
+/** Width and height along a horizontal or vertical auto layout's primary and counter axes. */
+function axes(layoutMode: string): [Geometry, Geometry] | null {
+ if (layoutMode === 'HORIZONTAL') return ['width', 'height']
+ if (layoutMode === 'VERTICAL') return ['height', 'width']
+ return null
+}
+
+/** Geometry that auto layout or text auto-resize recomputes, where rounding would not stick. */
+function layoutOwnedGeometry(node: LintNode, parent: LintNode | null): Set<Geometry> {
+ const owned = new Set<Geometry>()
+ if (parent && parent.layoutMode !== 'NONE' && node.layoutPositioning === 'AUTO') {
+ owned.add('x').add('y')
+ const parentAxes = axes(parent.layoutMode)
+ if (parentAxes && node.layoutGrow > 0) owned.add(parentAxes[0])
+ if (parentAxes && node.layoutAlignSelf === 'STRETCH') owned.add(parentAxes[1])
+ }
+ if (node.type === 'TEXT') {
+ if (node.textAutoResize === 'WIDTH_AND_HEIGHT') owned.add('width').add('height')
+ if (node.textAutoResize === 'HEIGHT') owned.add('height')
+ }
+ const ownAxes = axes(node.layoutMode)
+ if (ownAxes && node.primaryAxisSizing !== 'FIXED') owned.add(ownAxes[0])
+ if (ownAxes && node.counterAxisSizing !== 'FIXED') owned.add(ownAxes[1])
+ return owned
+}
export default defineRule({
meta: {
@@ -7,7 +48,7 @@ export default defineRule({
description: 'Elements should align to whole pixels'
},
check(node, context) {
- const values: Array<[string, number]> = [
+ const values: Array<[Geometry, number]> = [
['x', node.x],
['y', node.y],
['width', node.width],
@@ -15,10 +56,17 @@ export default defineRule({
]
const subpixel = values.filter(([, value]) => Math.abs(value - Math.round(value)) >= 0.01)
if (subpixel.length === 0) return
+ const parent = context.getParent(node)
+ const owned = layoutOwnedGeometry(node, parent)
+ const rounded = subpixel
+ .filter(([key]) => !isArtwork(node, parent) && !owned.has(key))
+ .map(([key, value]) => [key, Math.round(value)] as const)
context.report({
node,
message: `Subpixel values: ${subpixel.map(([k, v]) => `${k}: ${v}`).join(', ')}`,
- suggest: 'Round to whole pixels for crisp rendering'
+ suggest: 'Round to whole pixels for crisp rendering',
+ data: Object.fromEntries(subpixel),
+ fix: rounded.length > 0 ? { kind: 'set', changes: Object.fromEntries(rounded) } : undefined
})
}
})
diff --git a/packages/core/src/lint/rules/prefer-auto-layout.ts b/packages/core/src/lint/rules/prefer-auto-layout.ts
index 66dd0faba..24f13132b 100644
--- a/packages/core/src/lint/rules/prefer-auto-layout.ts
+++ b/packages/core/src/lint/rules/prefer-auto-layout.ts
@@ -10,11 +10,13 @@ export default defineRule({
check(node, context) {
const config = context.getConfig() as { minChildren?: number } | undefined
const minChildren = config?.minChildren ?? 2
- if (node.layoutMode !== 'NONE' || context.getChildren(node).length < minChildren) return
+ const children = context.getChildren(node).length
+ if (node.layoutMode !== 'NONE' || children < minChildren) return
context.report({
node,
- message: `Frame with ${context.getChildren(node).length} children doesn't use auto layout`,
- suggest: 'Add horizontal or vertical auto layout'
+ message: `Frame with ${children} children doesn't use auto layout`,
+ suggest: 'Add horizontal or vertical auto layout',
+ data: { children }
})
}
})
diff --git a/packages/core/src/lint/rules/text-style-required.ts b/packages/core/src/lint/rules/text-style-required.ts
index fde11bc30..3a9d46bbd 100644
--- a/packages/core/src/lint/rules/text-style-required.ts
+++ b/packages/core/src/lint/rules/text-style-required.ts
@@ -10,6 +10,9 @@ export default defineRule({
check(node, context) {
if (node.text.length <= 2) return
if (node.boundVariables.fontSize || node.boundVariables.fontFamily) return
+ // Suggesting a binding is only actionable when the document has typography values to bind.
+ const { FLOAT, STRING } = context.variables.counts
+ if (FLOAT === 0 && STRING === 0) return
context.report({
node,
message: 'Text layer without typography variable bindings',
diff --git a/packages/core/src/lint/rules/touch-target-size.ts b/packages/core/src/lint/rules/touch-target-size.ts
index 92b1802aa..599164f39 100644
--- a/packages/core/src/lint/rules/touch-target-size.ts
+++ b/packages/core/src/lint/rules/touch-target-size.ts
@@ -1,39 +1,59 @@
import { defineRule } from '#core/lint/rule'
-const PATTERNS = [
- /button/i,
- /btn/i,
- /link/i,
- /cta/i,
- /icon/i,
- /checkbox/i,
- /radio/i,
- /switch/i,
- /toggle/i,
- /input/i,
- /select/i,
- /dropdown/i,
- /menu/i,
- /tab/i,
- /chip/i,
- /tag/i,
- /close/i,
- /dismiss/i,
- /action/i
-]
+import { nameWords } from '#core/lint/utils'
+
+/** WCAG 2.2 target size, enhanced (AAA). `minSize: 24` checks the AA minimum instead. */
+const DEFAULT_MIN_SIZE = 44
+/** Words that name a control; a trailing plural `s` also matches ("Tabs", "Actions"). */
+const CONTROL_WORDS = new Set([
+ 'button',
+ 'btn',
+ 'link',
+ 'cta',
+ 'checkbox',
+ 'radio',
+ 'switch',
+ 'toggle',
+ 'input',
+ 'select',
+ 'dropdown',
+ 'menu',
+ 'tab',
+ 'chip',
+ 'tag',
+ 'close',
+ 'dismiss',
+ 'action'
+])
+
+function isInteractive(name: string): boolean {
+ return nameWords(name).some(
+ (word) =>
+ CONTROL_WORDS.has(word) || (word.endsWith('s') && CONTROL_WORDS.has(word.slice(0, -1)))
+ )
+}
+
export default defineRule({
meta: {
id: 'touch-target-size',
category: 'accessibility',
- description: 'Interactive elements should be at least 44x44px'
+ description:
+ 'Interactive elements should be large enough to tap (44×44px, or 24×24px for WCAG AA)'
},
match: ['FRAME', 'COMPONENT', 'INSTANCE', 'RECTANGLE', 'ELLIPSE'],
check(node, context) {
- if (!PATTERNS.some((p) => p.test(node.name))) return
- if (node.width >= 44 && node.height >= 44) return
+ if (!isInteractive(node.name)) return
+ const config = context.getConfig() as { minSize?: number } | undefined
+ const minSize = config?.minSize ?? DEFAULT_MIN_SIZE
+ if (node.width >= minSize && node.height >= minSize) return
+ // A control nested in another control (the icon of a button) is not its own target.
+ for (let parent = context.getParent(node); parent; parent = context.getParent(parent)) {
+ if (isInteractive(parent.name)) return
+ }
context.report({
node,
message: `Touch target too small: ${node.width}×${node.height}px`,
- suggest: 'Resize to at least 44×44px or add padding'
+ suggest: `Resize to at least ${minSize}×${minSize}px or add padding`,
+ data: { width: node.width, height: node.height, minSize }
})
}
})
diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.ts
index 2d3a2f5d6..543f9990d 100644
--- a/packages/core/src/lint/types.ts
+++ b/packages/core/src/lint/types.ts
@@ -16,6 +16,31 @@ export interface RuleMeta {
description: string
}
+/** Structured values behind a message, so interfaces can present it without parsing text. */
+export type LintMessageData = Readonly<Record<string, string | number>>
+
+/** Numeric layer properties a lint fix may set. */
+export type LintFixProperty =
+ | 'x'
+ | 'y'
+ | 'width'
+ | 'height'
+ | 'cornerRadius'
+ | 'itemSpacing'
+ | 'paddingTop'
+ | 'paddingRight'
+ | 'paddingBottom'
+ | 'paddingLeft'
+ | 'fontSize'
+
+/**
+ * A change that resolves a finding on the reported layer, kept as data so any interface can
+ * preview, apply or serialize it.
+ */
+export type LintFix =
+ | { kind: 'bind-variable'; path: string; variableId: string; variableName: string }
+ | { kind: 'set'; changes: Readonly<Partial<Record<LintFixProperty, number>>> }
+
export interface LintMessage {
ruleId: string
severity: Exclude<Severity, 'off'>
@@ -24,6 +49,11 @@ export interface LintMessage {
nodeName: string
nodePath: string[]
suggest?: string
+ data?: LintMessageData
+ /** Keeps the design's intent, so it can be applied in bulk without review. */
+ fix?: LintFix
+ /** Changes the design's values; offered one finding at a time. */
+ suggestions?: LintFix[]
}
export interface LintResult {
@@ -50,6 +80,12 @@ export interface LintNode {
visible: boolean
locked: boolean
layoutMode: string
+ layoutPositioning: 'AUTO' | 'ABSOLUTE'
+ layoutGrow: number
+ layoutAlignSelf: string
+ primaryAxisSizing: string
+ counterAxisSizing: string
+ textAutoResize: string
itemSpacing: number
paddingTop: number
paddingRight: number
@@ -81,8 +117,24 @@ export interface LintNode {
parent?: LintNode
}
+/** The document's variables, which decide whether a rule suggesting a binding is actionable. */
+export interface LintVariables {
+ /** Number of local variables by type; a rule suggesting a binding needs a candidate to bind. */
+ counts: Readonly<Record<'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN', number>>
+ /** Color variables by their resolved `#RRGGBB` value, for suggesting an exact match. */
+ colorsByHex: ReadonlyMap<string, { id: string; name: string }>
+}
+
export interface RuleContext {
- report(issue: { node: LintNode; message: string; suggest?: string }): void
+ variables: LintVariables
+ report(issue: {
+ node: LintNode
+ message: string
+ suggest?: string
+ data?: LintMessageData
+ fix?: LintFix
+ suggestions?: LintFix[]
+ }): void
getConfig(): unknown
getParent(node: LintNode): LintNode | null
getChildren(node: LintNode): LintNode[]
diff --git a/packages/core/src/lint/utils.ts b/packages/core/src/lint/utils.ts
index baf8bfc1c..eb0f5a149 100644
--- a/packages/core/src/lint/utils.ts
+++ b/packages/core/src/lint/utils.ts
@@ -4,12 +4,38 @@ export function isDefaultName(name: string): boolean {
)
}
+/**
+ * Lowercase words of a layer name, split at separators and camelCase humps, so name heuristics
+ * match whole words: "IconButton" and "icon-button" yield `icon`, `button`, "Button2" yields
+ * `button`, `2`, and "Rectangle" does not contain `cta`.
+ */
+export function nameWords(name: string): string[] {
+ return name
+ .replaceAll(/([a-z\d])([A-Z])/g, '$1 $2')
+ .replaceAll(/([a-z])(\d)/gi, '$1 $2')
+ .toLowerCase()
+ .split(/[^a-z\d]+/)
+ .filter(Boolean)
+}
+
export function isMultipleOf(value: number, base: number, tolerance = 0.01): boolean {
if (base === 0) return false
const remainder = value % base
return remainder < tolerance || base - remainder < tolerance
}
+/** The candidate closest to `value`; a tie goes to the larger candidate. */
+export function nearestValue(value: number, candidates: Iterable<number>): number | null {
+ let best: number | null = null
+ for (const candidate of candidates) {
+ if (best === null) best = candidate
+ const distance = Math.abs(candidate - value)
+ const bestDistance = Math.abs(best - value)
+ if (distance < bestDistance || (distance === bestDistance && candidate > best)) best = candidate
+ }
+ return best
+}
+
interface LintPathNode {
name: string
parent?: LintPathNode
diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.ts
index fdfe3ccf9..df136b341 100644
--- a/packages/core/src/tools/analyze.ts
+++ b/packages/core/src/tools/analyze.ts
@@ -11,6 +11,7 @@ export {
} from './analyze/diff'
export type { DocumentDiff, DocumentDiffOptions, LayerJSXChange } from './analyze/diff'
export { evalCode } from './analyze/eval'
+export { lint, lintFix } from './analyze/lint'
export { wrapEvalCode } from './analyze/eval/wrap'
export { analyzeOverlaps, computeOverlaps } from './analyze/overlaps'
export type {
diff --git a/packages/core/src/tools/analyze/lint.ts b/packages/core/src/tools/analyze/lint.ts
new file mode 100644
index 000000000..19ec816ce
--- /dev/null
+++ b/packages/core/src/tools/analyze/lint.ts
@@ -0,0 +1,111 @@
+import * as v from 'valibot'
+
+import type { FigmaAPI } from '#core/figma-api'
+import {
+ allRules,
+ applyLintFixes,
+ createLinter,
+ graphFixTarget,
+ presets,
+ safeFixes,
+ type LintFixRequest,
+ type LintMessage,
+ type LintResult
+} from '#core/lint'
+import { defineTool } from '#core/tools/schema'
+
+import { analysisLimitInput } from './input'
+
+const lintScopeInput = {
+ ids: v.optional(
+ v.pipe(
+ v.array(v.string()),
+ v.description('Layers to check, with their descendants (default: the current page)')
+ )
+ ),
+ preset: v.optional(
+ v.pipe(
+ v.picklist(Object.keys(presets)),
+ v.description(
+ 'Rule preset: recommended (default), strict, or accessibility (contrast, touch targets, text size)'
+ )
+ ),
+ 'recommended'
+ ),
+ rules: v.optional(
+ v.pipe(
+ v.array(v.picklist(Object.keys(allRules))),
+ v.description('Check only these rules of the preset')
+ )
+ )
+}
+
+type LintScope = v.InferOutput<v.ObjectSchema<typeof lintScopeInput, undefined>>
+
+function runLint(figma: FigmaAPI, scope: LintScope): LintResult {
+ const roots = scope.ids?.length ? scope.ids : [figma.currentPage.id]
+ return createLinter({ preset: scope.preset, rules: scope.rules }).lintGraph(figma.graph, roots)
+}
+
+function summarize(result: LintResult) {
+ return { errors: result.errorCount, warnings: result.warningCount, info: result.infoCount }
+}
+
+function describeMessage(message: LintMessage) {
+ return {
+ rule: message.ruleId,
+ severity: message.severity,
+ message: message.message,
+ node_id: message.nodeId,
+ node_name: message.nodeName,
+ path: message.nodePath.join(' / '),
+ suggest: message.suggest,
+ fix: message.fix,
+ suggestions: message.suggestions
+ }
+}
+
+export const lint = defineTool({
+ name: 'lint',
+ description:
+ 'Check the design for accessibility and consistency issues: low text contrast, small touch targets and text, ' +
+ 'off-scale spacing and radius, colors that match a variable but are not bound, and structure hygiene. ' +
+ 'Findings are sorted by severity. A `fix` is safe to apply with lint_fix; `suggestions` change values and need judgment.',
+ execution: { kind: 'sync', mutation: 'none' },
+ input: v.object({ ...lintScopeInput, limit: analysisLimitInput }),
+ execute: (figma, args) => {
+ const result = runLint(figma, args)
+ const rank = { error: 0, warning: 1, info: 2 }
+ const messages = result.messages.toSorted((a, b) => rank[a.severity] - rank[b.severity])
+ return {
+ ...summarize(result),
+ fixable: safeFixes(result.messages).length,
+ issues: messages.slice(0, args.limit).map(describeMessage),
+ ...(messages.length > args.limit ? { truncated: messages.length - args.limit } : {})
+ }
+ }
+})
+
+export const lintFix = defineTool({
+ name: 'lint_fix',
+ description:
+ 'Apply lint fixes: bind colors to the variable they match and round geometry to whole pixels. ' +
+ 'With suggestions: true, also apply each finding’s first suggestion (snap radius and spacing to the scale, ' +
+ 'raise text to the minimum size). Returns what was applied and what remains.',
+ execution: { kind: 'sync', mutation: 'properties' },
+ input: v.object({
+ ...lintScopeInput,
+ suggestions: v.optional(
+ v.pipe(v.boolean(), v.description('Also apply the first suggestion of each finding')),
+ false
+ )
+ }),
+ execute: (figma, args) => {
+ const requests: LintFixRequest[] = runLint(figma, args).messages.flatMap((message) => {
+ const fix = message.fix ?? (args.suggestions ? message.suggestions?.[0] : undefined)
+ return fix ? [{ nodeId: message.nodeId, fix }] : []
+ })
+ const applied = applyLintFixes(graphFixTarget(figma.graph), requests)
+ return { applied, remaining: summarize(runLint(figma, args)) }
+ }
+})
diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.ts
index 94c7f8dc2..bd8b689a8 100644
--- a/packages/core/src/tools/registry-extended.ts
+++ b/packages/core/src/tools/registry-extended.ts
@@ -5,7 +5,9 @@ import {
analyzeSpacing,
analyzeTypography,
diffApply,
- diffShow
+ diffShow,
+ lint,
+ lintFix
} from './analyze'
import { designToComponentMap, designToTokens } from './codegen'
import {
@@ -192,6 +194,8 @@ export const EXTENDED_TOOLS: ToolDef[] = [
// Analyze & diff
analyzeColors,
analyzeTypography,
+ lint,
+ lintFix,
analyzeSpacing,
analyzeClusters,
analyzeOverlaps,
diff --git a/packages/core/tests/canvas/issues/layout.test.ts b/packages/core/tests/canvas/issues/layout.test.ts
new file mode 100644
index 000000000..11b800def
--- /dev/null
+++ b/packages/core/tests/canvas/issues/layout.test.ts
@@ -0,0 +1,198 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ hitTestIssueMarkers,
+ layoutIssueMarkers,
+ type DesignIssueMarker,
+ type IssueMarkerLayoutOptions
+} from '@open-pencil/core/canvas'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** Every label is one 6px glyph wide, so marker widths stay independent of fonts. */
+const measureText = (text: string) => text.length * 6
+
+function setup() {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const options: IssueMarkerLayoutOptions = {
+ pageId,
+ view: { panX: 0, panY: 0, zoom: 1, width: 800, height: 600, insetTop: 0, insetLeft: 0 },
+ measureText
+ }
+ return { graph, pageId, options }
+}
+
+function warning(nodeId: string, count = 1): DesignIssueMarker {
+ return { nodeId, severity: 'warning', count }
+}
+
+describe('issue marker layout', () => {
+ test('attaches a marker just outside the top-right corner of its layer', () => {
+ const { graph, pageId, options } = setup()
+ const card = graph.createNode('FRAME', pageId, { x: 100, y: 200, width: 120, height: 80 })
+
+ const [marker] = layoutIssueMarkers(graph, [warning(card.id)], options)
+
+ expect(marker?.anchor).toEqual({ x: 220, y: 200 })
+ expect(marker?.rect).toEqual({ x: 224, y: 180, width: 16, height: 16 })
+ })
+
+ test('skips hidden layers, layers inside hidden parents, and other pages', () => {
+ const { graph, pageId, options } = setup()
+ const hidden = graph.createNode('FRAME', pageId, { width: 100, height: 100, visible: false })
+ const child = graph.createNode('RECTANGLE', hidden.id, { width: 40, height: 40 })
+ const otherPage = graph.addPage('Other')
+ const elsewhere = graph.createNode('FRAME', otherPage.id, { width: 100, height: 100 })
+
+ const markers = [warning(hidden.id), warning(child.id), warning(elsewhere.id)]
+
+ expect(layoutIssueMarkers(graph, markers, options)).toEqual([])
+ })
+
+ test('skips layers clipped away by a frame and anchors partly clipped ones to what shows', () => {
+ const { graph, pageId, options } = setup()
+ const frame = graph.createNode('FRAME', pageId, {
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 200,
+ clipsContent: true
+ })
+ const outside = graph.createNode('RECTANGLE', frame.id, { x: 300, y: 0, width: 50, height: 50 })
+ const overflowing = graph.createNode('RECTANGLE', frame.id, {
+ x: 150,
+ y: 100,
+ width: 100,
+ height: 50
+ })
+
+ const placed = layoutIssueMarkers(graph, [warning(outside.id), warning(overflowing.id)], options)
+
+ expect(placed.map((marker) => marker.nodeIds)).toEqual([[overflowing.id]])
+ expect(placed[0]?.anchor).toEqual({ x: 300, y: 200 })
+ })
+
+ test('hands the marker of a layer too small to see to its nearest large enough ancestor', () => {
+ const { graph, pageId, options } = setup()
+ const card = graph.createNode('FRAME', pageId, { x: 0, y: 100, width: 400, height: 300 })
+ const dot = graph.createNode('ELLIPSE', card.id, { x: 20, y: 20, width: 40, height: 40 })
+
+ const zoomedOut = { ...options, view: { ...options.view, zoom: 0.25 } }
+ const [marker] = layoutIssueMarkers(graph, [warning(dot.id)], zoomedOut)
+
+ expect(marker?.nodeIds).toEqual([dot.id])
+ expect(marker?.anchor).toEqual({ x: 100, y: 25 })
+ })
+
+ test('merges overlapping markers behind the most severe one', () => {
+ const { graph, pageId, options } = setup()
+ const parent = graph.createNode('FRAME', pageId, { x: 100, y: 100, width: 200, height: 200 })
+ const child = graph.createNode('FRAME', parent.id, { x: 100, y: 0, width: 100, height: 50 })
+ const far = graph.createNode('FRAME', pageId, { x: 500, y: 400, width: 50, height: 50 })
+
+ const placed = layoutIssueMarkers(
+ graph,
+ [warning(parent.id, 2), { nodeId: child.id, severity: 'error', count: 1 }, warning(far.id)],
+ options
+ )
+
+ expect(placed).toHaveLength(2)
+ expect(placed[0]).toMatchObject({
+ key: child.id,
+ nodeIds: [child.id, parent.id],
+ severity: 'error',
+ count: 3
+ })
+ expect(placed[1]?.nodeIds).toEqual([far.id])
+ })
+
+ test('keeps markers inside the viewport and below the rulers', () => {
+ const { graph, pageId, options } = setup()
+ const wide = graph.createNode('FRAME', pageId, { x: 10, y: 10, width: 1000, height: 100 })
+
+ const withRulers = { ...options, view: { ...options.view, insetTop: 20, insetLeft: 20 } }
+ const [marker] = layoutIssueMarkers(graph, [warning(wide.id)], withRulers)
+
+ expect(marker?.rect).toEqual({ x: 780, y: 24, width: 16, height: 16 })
+ })
+
+ test('leaves out layers under an active edit and widens markers for large counts', () => {
+ const { graph, pageId, options } = setup()
+ const editing = graph.createNode('TEXT', pageId, { x: 0, y: 100, width: 100, height: 20 })
+ const busy = graph.createNode('FRAME', pageId, { x: 300, y: 300, width: 100, height: 100 })
+
+ const placed = layoutIssueMarkers(graph, [warning(editing.id), warning(busy.id, 120)], {
+ ...options,
+ suppressedIds: new Set([editing.id])
+ })
+
+ expect(placed.map((marker) => marker.key)).toEqual([busy.id])
+ expect(placed[0]?.rect.width).toBe(28)
+ })
+})
+
+describe('issue edge pins', () => {
+ test('pins an issue outside the viewport to the edge in its direction', () => {
+ const { graph, pageId, options } = setup()
+ const left = graph.createNode('FRAME', pageId, { x: -500, y: 250, width: 100, height: 100 })
+
+ const [pin] = layoutIssueMarkers(graph, [warning(left.id)], options)
+
+ expect(pin).toMatchObject({
+ key: `edge:${left.id}`,
+ direction: { x: -1, y: 0 },
+ rect: { x: 12, y: 292, width: 16, height: 16 }
+ })
+ })
+
+ test('places an issue off a corner in that corner', () => {
+ const { graph, pageId, options } = setup()
+ const far = graph.createNode('FRAME', pageId, { x: 4380, y: -2720, width: 40, height: 40 })
+
+ const [pin] = layoutIssueMarkers(graph, [warning(far.id)], options)
+
+ expect(pin?.rect).toEqual({ x: 772, y: 12, width: 16, height: 16 })
+ expect(pin?.direction?.x).toBeGreaterThan(0)
+ expect(pin?.direction?.y).toBeLessThan(0)
+ })
+
+ test('merges pins in one direction and leads with the most severe, then nearest, layer', () => {
+ const { graph, pageId, options } = setup()
+ const near = graph.createNode('FRAME', pageId, { x: 900, y: 280, width: 40, height: 40 })
+ const far = graph.createNode('FRAME', pageId, { x: 2000, y: 300, width: 40, height: 40 })
+
+ const [pin, ...rest] = layoutIssueMarkers(
+ graph,
+ [warning(near.id), { nodeId: far.id, severity: 'error', count: 1 }],
+ options
+ )
+
+ expect(rest).toEqual([])
+ // The error is farther than the warning, but the pin shows an error, so it leads there.
+ expect(pin).toMatchObject({ severity: 'error', count: 2, nodeIds: [far.id, near.id] })
+ })
+
+ test('slides a pin along its edge out from under floating UI', () => {
+ const { graph, pageId, options } = setup()
+ const below = graph.createNode('FRAME', pageId, { x: 380, y: 1200, width: 40, height: 40 })
+ const toolbar = { x: 350, y: 560, width: 100, height: 40 }
+
+ const [pin] = layoutIssueMarkers(graph, [warning(below.id)], {
+ ...options,
+ obstacles: [toolbar]
+ })
+
+ expect(pin?.rect).toEqual({ x: 332, y: 572, width: 16, height: 16 })
+ })
+})
+
+describe('issue marker hit testing', () => {
+ test('returns the topmost marker under the point', () => {
+ const { graph, pageId, options } = setup()
+ const card = graph.createNode('FRAME', pageId, { x: 100, y: 200, width: 120, height: 80 })
+ const placed = layoutIssueMarkers(graph, [warning(card.id)], options)
+
+ expect(hitTestIssueMarkers(placed, 232, 188)?.key).toBe(card.id)
+ expect(hitTestIssueMarkers(placed, 200, 188)).toBeNull()
+ })
+})
diff --git a/packages/core/tests/lint/fixes.test.ts b/packages/core/tests/lint/fixes.test.ts
new file mode 100644
index 000000000..402883a13
--- /dev/null
+++ b/packages/core/tests/lint/fixes.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import {
+ applyLintFixes,
+ createLinter,
+ graphFixTarget,
+ safeFixes,
+ type LintMessage
+} from '@open-pencil/core/lint'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+import { getNodeOrThrow } from '../helpers/assert'
+
+const BLUE = { r: 0.23, g: 0.51, b: 0.96, a: 1 }
+const RED = { r: 0.9, g: 0.1, b: 0.1, a: 1 }
+
+function solid(color: typeof BLUE): SceneNode['fills'] {
+ return [{ type: 'SOLID', visible: true, opacity: 1, color }]
+}
+
+function lint(graph: SceneGraph, rule: string): LintMessage[] {
+ return createLinter({ rules: [rule], config: { rules: { [rule]: 'warning' } } }).lintGraph(graph)
+ .messages
+}
+
+function addBlueVariable(graph: SceneGraph) {
+ graph.addCollection({
+ id: 'colors',
+ name: 'Colors',
+ modes: [{ modeId: 'light', name: 'Light' }],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ graph.addVariable({
+ id: 'blue',
+ name: 'Colors/Blue/500',
+ type: 'COLOR',
+ collectionId: 'colors',
+ valuesByMode: { light: BLUE },
+ description: '',
+ hiddenFromPublishing: false
+ })
+}
+
+describe('safe fixes', () => {
+ test('bind a matching color variable and resolve the finding', () => {
+ const graph = new SceneGraph()
+ addBlueVariable(graph)
+ const card = graph.createNode('RECTANGLE', graph.getPages()[0].id, { fills: solid(BLUE) })
+
+ const messages = lint(graph, 'no-hardcoded-colors')
+ expect(messages[0]?.fix).toEqual({
+ kind: 'bind-variable',
+ path: 'fills/0/color',
+ variableId: 'blue',
+ variableName: 'Colors/Blue/500'
+ })
+
+ expect(applyLintFixes(graphFixTarget(graph), safeFixes(messages))).toBe(1)
+ expect(getNodeOrThrow(graph, card.id).boundVariables['fills/0/color']).toBe('blue')
+ expect(lint(graph, 'no-hardcoded-colors')).toEqual([])
+ })
+
+ test('skip a binding whose paint changed since the lint run', () => {
+ const graph = new SceneGraph()
+ addBlueVariable(graph)
+ const card = graph.createNode('RECTANGLE', graph.getPages()[0].id, { fills: solid(BLUE) })
+ const messages = lint(graph, 'no-hardcoded-colors')
+
+ graph.updateNode(card.id, { fills: solid(RED) })
+
+ expect(applyLintFixes(graphFixTarget(graph), safeFixes(messages))).toBe(0)
+ expect(getNodeOrThrow(graph, card.id).boundVariables['fills/0/color']).toBeUndefined()
+ })
+
+ test('round only geometry that layout does not recompute', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const free = graph.createNode('RECTANGLE', pageId, { x: 10.4, y: 3, width: 20.6, height: 8 })
+ const row = graph.createNode('FRAME', pageId, { layoutMode: 'HORIZONTAL' })
+ const item = graph.createNode('RECTANGLE', row.id, { x: 4.5, y: 0, width: 12.3, height: 8 })
+ const filler = graph.createNode('RECTANGLE', row.id, {
+ width: 40.4,
+ height: 8.5,
+ layoutGrow: 1
+ })
+ const label = graph.createNode('TEXT', pageId, {
+ x: 2.2,
+ width: 40.5,
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+
+ const fixes = new Map(lint(graph, 'pixel-perfect').map((m) => [m.nodeId, m.fix]))
+
+ expect(fixes.get(free.id)).toEqual({ kind: 'set', changes: { x: 10, width: 21 } })
+ expect(fixes.get(item.id)).toEqual({ kind: 'set', changes: { width: 12 } })
+ expect(fixes.get(filler.id)).toEqual({ kind: 'set', changes: { height: 9 } })
+ expect(fixes.get(label.id)).toEqual({ kind: 'set', changes: { x: 2 } })
+ })
+
+ test('leave vector artwork and the parts of a group for review', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const logo = graph.createNode('GROUP', pageId, { x: 40, y: 40, width: 30, height: 30 })
+ const part = graph.createNode('ELLIPSE', logo.id, { x: 5.12, width: 20, height: 20 })
+ const icon = graph.createNode('VECTOR', pageId, { x: 0.5, width: 16, height: 16 })
+
+ const messages = lint(graph, 'pixel-perfect')
+
+ expect(messages.map((m) => m.nodeId).toSorted()).toEqual([part.id, icon.id].toSorted())
+ expect(messages.every((m) => m.fix === undefined)).toBe(true)
+ })
+})
+
+describe('suggestions', () => {
+ test('snap radius to the nearest scale value, or full radius for a pill', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const card = graph.createNode('RECTANGLE', pageId, { width: 200, height: 100, cornerRadius: 10 })
+ const pill = graph.createNode('RECTANGLE', pageId, { width: 80, height: 28, cornerRadius: 14 })
+
+ const suggestions = new Map(
+ lint(graph, 'consistent-radius').map((m) => [m.nodeId, m.suggestions])
+ )
+
+ expect(suggestions.get(card.id)).toEqual([{ kind: 'set', changes: { cornerRadius: 12 } }])
+ expect(suggestions.get(pill.id)).toEqual([{ kind: 'set', changes: { cornerRadius: 9999 } }])
+ })
+
+ test('are not safe fixes and merge per layer when applied', () => {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ layoutMode: 'VERTICAL',
+ itemSpacing: 7,
+ paddingTop: 13
+ })
+ const messages = lint(graph, 'consistent-spacing')
+ expect(safeFixes(messages)).toEqual([])
+
+ const updates: Array<Partial<SceneNode>> = []
+ const target = graphFixTarget(graph)
+ const applied = applyLintFixes(
+ {
+ ...target,
+ updateNode: (id, changes) => {
+ updates.push(changes)
+ target.updateNode(id, changes)
+ }
+ },
+ messages.flatMap((m) => (m.suggestions ?? []).map((fix) => ({ nodeId: m.nodeId, fix })))
+ )
+
+ expect(applied).toBe(2)
+ expect(updates).toEqual([{ itemSpacing: 8, paddingTop: 12 }])
+ expect(getNodeOrThrow(graph, frame.id)).toMatchObject({ itemSpacing: 8, paddingTop: 12 })
+ })
+})
+
+describe('editor.applyLintFixes', () => {
+ test('applies fixes as one undo step', () => {
+ const editor = createEditor()
+ addBlueVariable(editor.graph)
+ const pageId = editor.graph.getPages()[0].id
+ const card = editor.graph.createNode('RECTANGLE', pageId, {
+ x: 0.5,
+ width: 10,
+ height: 10,
+ fills: solid(BLUE)
+ })
+ const messages = createLinter({
+ rules: ['no-hardcoded-colors', 'pixel-perfect'],
+ config: { rules: { 'no-hardcoded-colors': 'warning', 'pixel-perfect': 'warning' } }
+ }).lintGraph(editor.graph).messages
+
+ expect(editor.applyLintFixes(safeFixes(messages))).toBe(2)
+ expect(getNodeOrThrow(editor.graph, card.id).x).toBe(1)
+
+ editor.undoAction()
+
+ const restored = getNodeOrThrow(editor.graph, card.id)
+ expect(restored.x).toBe(0.5)
+ expect(restored.boundVariables['fills/0/color']).toBeUndefined()
+ })
+})
diff --git a/packages/core/tests/lint/rules.test.ts b/packages/core/tests/lint/rules.test.ts
new file mode 100644
index 000000000..b28657813
--- /dev/null
+++ b/packages/core/tests/lint/rules.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createLinter, type LintMessage } from '@open-pencil/core/lint'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+const WHITE = { r: 1, g: 1, b: 1, a: 1 }
+const BLUE = { r: 0.23, g: 0.51, b: 0.96, a: 1 }
+const LIGHT_GRAY = { r: 0.8, g: 0.8, b: 0.8, a: 1 }
+
+function solid(color: SceneNode['fills'][number]['color']): SceneNode['fills'] {
+ return [{ type: 'SOLID', visible: true, opacity: 1, color }]
+}
+
+function lint(graph: SceneGraph, rule: string): LintMessage[] {
+ const pageId = graph.getPages()[0].id
+ return createLinter({ rules: [rule], config: { rules: { [rule]: 'warning' } } }).lintGraph(
+ graph,
+ [pageId]
+ ).messages
+}
+
+function addColorVariable(graph: SceneGraph, id: string, name: string, color: typeof BLUE) {
+ graph.addCollection({
+ id: 'colors',
+ name: 'Colors',
+ modes: [{ modeId: 'light', name: 'Light' }],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ graph.addVariable({
+ id,
+ name,
+ type: 'COLOR',
+ collectionId: 'colors',
+ valuesByMode: { light: color },
+ description: '',
+ hiddenFromPublishing: false
+ })
+}
+
+describe('no-hardcoded-colors', () => {
+ test('reports an unbound color only when a variable has the same value', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ addColorVariable(graph, 'blue', 'Colors/Blue/500', BLUE)
+ const matching = graph.createNode('RECTANGLE', pageId, { name: 'Card', fills: solid(BLUE) })
+ graph.createNode('RECTANGLE', pageId, { name: 'Tint', fills: solid(LIGHT_GRAY) })
+
+ const messages = lint(graph, 'no-hardcoded-colors')
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0]?.nodeId).toBe(matching.id)
+ expect(messages[0]?.data).toEqual({
+ paint: 'fill',
+ index: 0,
+ color: '#3B82F5',
+ variableId: 'blue',
+ variableName: 'Colors/Blue/500'
+ })
+ })
+
+ test('stays quiet in a document without color variables', () => {
+ const graph = new SceneGraph()
+ graph.createNode('RECTANGLE', graph.getPages()[0].id, { name: 'Card', fills: solid(BLUE) })
+ expect(lint(graph, 'no-hardcoded-colors')).toEqual([])
+ })
+})
+
+describe('color-contrast', () => {
+ test('uses the resolved color of a bound text fill', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ addColorVariable(graph, 'muted', 'Text/Muted', LIGHT_GRAY)
+ const card = graph.createNode('FRAME', pageId, { name: 'Card', fills: solid(WHITE) })
+ const label = graph.createNode('TEXT', card.id, {
+ name: 'Label',
+ text: 'Hello',
+ fills: solid({ r: 0, g: 0, b: 0, a: 1 })
+ })
+ graph.bindVariable(label.id, 'fills/0/color', 'muted')
+
+ const messages = lint(graph, 'color-contrast')
+
+ expect(messages.map((message) => message.nodeId)).toEqual([label.id])
+ expect(messages[0]?.data).toMatchObject({
+ minRatio: 4.5,
+ foreground: '#CCCCCC',
+ background: '#FFFFFF'
+ })
+ })
+})
+
+describe('no-deeply-nested', () => {
+ test('reports only the layer that crosses the depth limit', () => {
+ const graph = new SceneGraph()
+ let parentId = graph.getPages()[0].id
+ const chain: string[] = []
+ for (let depth = 1; depth <= 9; depth++) {
+ parentId = graph.createNode('FRAME', parentId, { name: `Level ${depth}` }).id
+ chain.push(parentId)
+ }
+
+ const messages = lint(graph, 'no-deeply-nested')
+
+ expect(messages.map((message) => message.nodeId)).toEqual([chain[6]])
+ expect(messages[0]?.data).toEqual({ depth: 7, maxDepth: 6 })
+ })
+})
+
+describe('touch-target-size', () => {
+ test('treats a small control inside a larger control as part of that control', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const button = graph.createNode('FRAME', pageId, { name: 'Button', width: 120, height: 48 })
+ graph.createNode('FRAME', button.id, { name: 'Close button', width: 16, height: 16 })
+ const chip = graph.createNode('FRAME', pageId, { name: 'Chip', width: 60, height: 24 })
+
+ const messages = lint(graph, 'touch-target-size')
+
+ expect(messages.map((message) => message.nodeId)).toEqual([chip.id])
+ expect(messages[0]?.data).toEqual({ width: 60, height: 24, minSize: 44 })
+ })
+
+ test('matches control names as whole words', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ graph.createNode('RECTANGLE', pageId, { name: 'Rectangle', width: 1, height: 80 })
+ graph.createNode('FRAME', pageId, { name: 'Tablet preview', width: 20, height: 20 })
+ const iconButton = graph.createNode('FRAME', pageId, { name: 'IconButton2', width: 32, height: 32 })
+
+ expect(lint(graph, 'touch-target-size').map((message) => message.nodeId)).toEqual([
+ iconButton.id
+ ])
+ })
+
+ test('checks the WCAG AA minimum in Recommended and the AAA size in Strict', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const input = graph.createNode('FRAME', pageId, { name: 'Input', width: 320, height: 40 })
+ const chip = graph.createNode('FRAME', pageId, { name: 'Chip', width: 60, height: 20 })
+ const flagged = (preset: string) =>
+ createLinter({ preset, rules: ['touch-target-size'] })
+ .lintGraph(graph, [pageId])
+ .messages.map((message) => message.nodeId)
+
+ expect(flagged('recommended')).toEqual([chip.id])
+ expect(flagged('strict')).toEqual([input.id, chip.id])
+ })
+
+ test('does not treat icons as touch targets on their own', () => {
+ const graph = new SceneGraph()
+ graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Icon', width: 16, height: 16 })
+ expect(lint(graph, 'touch-target-size')).toEqual([])
+ })
+})
+
+describe('instances', () => {
+ test('are checked themselves but not through their sublayers', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const component = graph.createNode('COMPONENT', pageId, { name: 'Badge' })
+ graph.createNode('TEXT', component.id, { name: 'Label', text: 'New', fontSize: 9 })
+ const instance = graph.createInstance(component.id, pageId)
+ if (!instance) throw new Error('Instance was not created')
+
+ const messages = lint(graph, 'min-text-size')
+
+ expect(messages).toHaveLength(1)
+ expect(graph.getNode(messages[0]?.nodeId ?? '')?.parentId).toBe(component.id)
+ })
+})
diff --git a/packages/core/tests/tools/analyze/lint.test.ts b/packages/core/tests/tools/analyze/lint.test.ts
new file mode 100644
index 000000000..8a3acd747
--- /dev/null
+++ b/packages/core/tests/tools/analyze/lint.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core'
+import { ALL_TOOLS } from '@open-pencil/core/tools'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+function tool(name: string) {
+ const def = ALL_TOOLS.find((candidate) => candidate.name === name)
+ if (!def) throw new Error(`Missing tool ${name}`)
+ return def
+}
+
+function setup() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const pageId = graph.getPages()[0].id
+ const card = graph.createNode('FRAME', pageId, {
+ name: 'Card',
+ x: 0.5,
+ width: 200,
+ height: 100,
+ cornerRadius: 10
+ })
+ return { graph, figma, card }
+}
+
+describe('lint tool', () => {
+ test('lists findings of the current page with their fixes, without changing it', () => {
+ const { graph, figma, card } = setup()
+
+ const result = tool('lint').execute(figma, { rules: ['pixel-perfect', 'consistent-radius'] })
+
+ expect(result).toMatchObject({ info: 2, fixable: 1 })
+ expect(result).toHaveProperty('issues', [
+ expect.objectContaining({
+ rule: 'pixel-perfect',
+ node_id: card.id,
+ fix: { kind: 'set', changes: { x: 1 } }
+ }),
+ expect.objectContaining({
+ rule: 'consistent-radius',
+ suggestions: [{ kind: 'set', changes: { cornerRadius: 12 } }]
+ })
+ ])
+ expect(getNodeOrThrow(graph, card.id).x).toBe(0.5)
+ })
+
+ test('rejects unknown rules', () => {
+ const { figma } = setup()
+ expect(() => tool('lint').execute(figma, { rules: ['no-such-rule'] })).toThrow()
+ })
+})
+
+describe('lint_fix tool', () => {
+ test('applies safe fixes, and suggestions only when asked', () => {
+ const { graph, figma, card } = setup()
+ const rules = ['pixel-perfect', 'consistent-radius']
+
+ expect(tool('lint_fix').execute(figma, { rules })).toEqual({
+ applied: 1,
+ remaining: { errors: 0, warnings: 0, info: 1 }
+ })
+ expect(getNodeOrThrow(graph, card.id)).toMatchObject({ x: 1, cornerRadius: 10 })
+
+ expect(tool('lint_fix').execute(figma, { rules, suggestions: true })).toEqual({
+ applied: 1,
+ remaining: { errors: 0, warnings: 0, info: 0 }
+ })
+ expect(getNodeOrThrow(graph, card.id).cornerRadius).toBe(12)
+ })
+})
diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.ts
index 06799af08..93ed24399 100644
--- a/packages/docs/.vitepress/labels.ts
+++ b/packages/docs/.vitepress/labels.ts
@@ -15,6 +15,7 @@ export interface SidebarLabels {
autoLayout: string
components: string
variables: string
+ checkingDesigns: string
overview: string
gettingStarted: string
features: string
@@ -157,6 +158,7 @@ export const EN: SidebarLabels = {
autoLayout: 'Auto Layout',
components: 'Components',
variables: 'Variables',
+ checkingDesigns: 'Checking Designs',
overview: 'Overview',
gettingStarted: 'Getting Started',
features: 'Features',
@@ -182,6 +184,7 @@ export const DE: SidebarLabels = {
autoLayout: 'Auto-Layout',
components: 'Komponenten',
variables: 'Variablen',
+ checkingDesigns: 'Designs prüfen',
overview: 'Überblick',
gettingStarted: 'Erste Schritte',
features: 'Funktionen',
@@ -207,6 +210,7 @@ export const IT: SidebarLabels = {
autoLayout: 'Auto-layout',
components: 'Componenti',
variables: 'Variabili',
+ checkingDesigns: 'Verificare i design',
overview: 'Panoramica',
gettingStarted: 'Per iniziare',
features: 'Funzionalità',
@@ -232,6 +236,7 @@ export const FR: SidebarLabels = {
autoLayout: 'Mise en page auto',
components: 'Composants',
variables: 'Variables',
+ checkingDesigns: 'Vérifier les designs',
overview: 'Vue d’ensemble',
gettingStarted: 'Premiers pas',
features: 'Fonctionnalités',
@@ -257,6 +262,7 @@ export const ES: SidebarLabels = {
autoLayout: 'Auto-layout',
components: 'Componentes',
variables: 'Variables',
+ checkingDesigns: 'Revisar diseños',
overview: 'Resumen',
gettingStarted: 'Primeros pasos',
features: 'Características',
@@ -282,6 +288,7 @@ export const PL: SidebarLabels = {
autoLayout: 'Auto-layout',
components: 'Komponenty',
variables: 'Zmienne',
+ checkingDesigns: 'Sprawdzanie projektów',
overview: 'Przegląd',
gettingStarted: 'Rozpoczęcie pracy',
features: 'Funkcje',
@@ -307,6 +314,7 @@ export const RU: SidebarLabels = {
autoLayout: 'Авто-раскладка',
components: 'Компоненты',
variables: 'Переменные',
+ checkingDesigns: 'Проверка дизайна',
overview: 'Обзор',
gettingStarted: 'Начало работы',
features: 'Возможности',
diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.ts
index cbb0441bb..b929c7d27 100644
--- a/packages/docs/.vitepress/sidebars.ts
+++ b/packages/docs/.vitepress/sidebars.ts
@@ -46,6 +46,8 @@ export const userGuideSidebar = (
{ text: labels.autoLayout, link: `${prefix}/user-guide/auto-layout` },
{ text: labels.components, link: `${prefix}/user-guide/components` },
{ text: labels.variables, link: `${prefix}/user-guide/variables` },
+ // English only until translated; locales link to the canonical page.
+ { text: labels.checkingDesigns, link: '/user-guide/checking-designs' },
],
},
]
diff --git a/packages/docs/overview/features.md b/packages/docs/overview/features.md
index 425eaf241..33b701eae 100644
--- a/packages/docs/overview/features.md
+++ b/packages/docs/overview/features.md
@@ -19,7 +19,7 @@ Open and save native Figma files directly. The import/export pipeline uses the s
## Properties Panel
-Context-sensitive Design | Code | AI tabs:
+Context-sensitive Design | Code | AI | Lint tabs:
- **Appearance** — opacity, corner radius (uniform or per-corner), visibility
- **Fill** — solid, gradient (linear/radial/angular/diamond), image
@@ -28,6 +28,7 @@ Context-sensitive Design | Code | AI 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
+- **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))
## Rendering
diff --git a/packages/docs/programmable/cli/inspecting.md b/packages/docs/programmable/cli/inspecting.md
index 1c5e09312..0abc9a9ab 100644
--- a/packages/docs/programmable/cli/inspecting.md
+++ b/packages/docs/programmable/cli/inspecting.md
@@ -177,9 +177,10 @@ openpencil lint design.fig
openpencil lint design.pen --preset strict
openpencil lint design.fig --rule color-contrast
openpencil lint design.fig --list-rules
+openpencil lint design.fig --fix -o fixed.fig
```
-Use `--json` for machine-readable output.
+Use `--json` for machine-readable output; each message carries its `fix` and `suggestions` as data. `--fix` applies the safe fixes — binding colors to the color variable they match and rounding geometry to whole pixels — and writes the result to the `.fig` file given with `-o`.
## JSON Output
diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.md
index 60090cbec..3d214a234 100644
--- a/packages/docs/programmable/mcp-server.md
+++ b/packages/docs/programmable/mcp-server.md
@@ -306,6 +306,8 @@ OpenPencil currently registers 100+ shared design tools, plus MCP-only document
| `analyze_typography` | Analyze font/size/weight distribution |
| `analyze_spacing` | Analyze gap and padding values |
| `analyze_clusters` | Detect repeated patterns (potential components) |
+| `lint` | Check accessibility and consistency issues, with fixes and suggestions |
+| `lint_fix` | Apply safe lint fixes, and optionally the first suggestion of each finding |
### Diff
diff --git a/packages/docs/user-guide/checking-designs.md b/packages/docs/user-guide/checking-designs.md
new file mode 100644
index 000000000..5a3ed6f4e
--- /dev/null
+++ b/packages/docs/user-guide/checking-designs.md
@@ -0,0 +1,57 @@
+---
+title: Checking Designs
+description: Find accessibility, consistency, and structure issues with the Lint panel and canvas issue markers.
+---
+
+# Checking Designs
+
+OpenPencil checks the current page as you work and points out layers that break common design rules: text that is hard to read, controls that are too small to tap, colors that should use a variable, and spacing off the scale.
+
+## Lint Panel
+
+Open the **Lint** tab in the right panel. Its badge shows how many errors and warnings the page has.
+
+- **Page** lists every issue on the current page; **Selection** narrows the list to the selected layers and everything inside them; **Document** lists every page's issues, tagging the ones on other pages. Clicking one of those switches to its page. Pages of a large `.fig` file that have not been opened yet are checked once you open them.
+- Issues are grouped by rule, most severe first. Errors and warnings start expanded; suggestions start collapsed.
+- The severity buttons under the scope switch filter errors, warnings, and suggestions on and off.
+- Hover a group title to read what the rule checks and why.
+
+Hover an issue to highlight its layer on the canvas. Click it to select the layer; if it is off screen, the canvas pans to it, and zooms out only when the layer does not fit.
+
+## Fixing Issues
+
+Rows that can be fixed in one step show a button on hover:
+
+- A hardcoded color that matches one of the document's color variables binds to it (link button). The row names the variable.
+- Subpixel positions and sizes round to whole pixels. Values that auto layout or text resizing sets, and vector artwork and the parts of groups, are left alone.
+- Off-scale corner radius and spacing change to the nearest scale value, and text below the minimum size grows to it (wand button). These change the design, so they apply one row at a time.
+
+Binding colors and rounding pixels keep the design as it looks, so their groups also offer **Bind all** or **Fix all**. Every fix is a single undo step.
+
+Other issues show the value that needs attention, such as a contrast ratio or a touch target size, so you can fix them in the Design panel.
+
+## Canvas Markers
+
+Layers with errors and warnings carry a marker at their top-right corner: red for errors, amber for warnings. Suggestions appear only in the Lint panel.
+
+- Hover a marker to see its issues. Click it to select the layer and open its issues in the Lint panel.
+- Markers that would overlap merge into one showing their combined count.
+- When a layer is too small to see at the current zoom, its marker moves to the nearest enclosing layer large enough to point at.
+- Errors and warnings outside the visible canvas are pinned to its edge, pointing toward them. Hover a pin to see them; click it to bring the nearest of the most severe into view and open it in Lint.
+- Hidden layers and layers clipped out of view by a frame keep their issues in the panel but get no marker.
+
+Pages with errors or warnings show their count in the page list, checked in the background while you work. The Layers panel marks the same layers: a layer with errors or warnings shows the most severe as an icon, and a collapsed layer with issues inside it shows a dot.
+
+Turn 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.
+
+## Rules
+
+The settings menu in the Lint panel switches between rule presets:
+
+- **Recommended** — balanced defaults for everyday work.
+- **Strict** — every rule as a warning or error.
+- **Accessibility** — contrast, touch target size, and text size only.
+
+Turn off a single rule from its group's menu. **Turn on turned-off rules** in the settings menu brings them back. Presets and turned-off rules are saved between sessions.
+
+The same rules run from the command line with `openpencil lint`; see [Inspecting Files](/programmable/cli/inspecting).
diff --git a/packages/docs/user-guide/index.md b/packages/docs/user-guide/index.md
index 7bfae94d5..5f49a8775 100644
--- a/packages/docs/user-guide/index.md
+++ b/packages/docs/user-guide/index.md
@@ -34,3 +34,4 @@ Throughout this guide, keyboard shortcuts use Mac notation: <kbd>⌘</kbd> = <kb
- [Auto Layout](./auto-layout) — flexbox-based automatic positioning
- [Components](./components) — reusable components, instances, and overrides
- [Variables](./variables) — design variables, collections, modes, and fill bindings
+- [Checking Designs](./checking-designs) — the Check panel, canvas issue markers, and lint rules
diff --git a/packages/vue/src/canvas/issues/use.ts b/packages/vue/src/canvas/issues/use.ts
new file mode 100644
index 000000000..7295fa02a
--- /dev/null
+++ b/packages/vue/src/canvas/issues/use.ts
@@ -0,0 +1,89 @@
+import { useEventListener } from '@vueuse/core'
+import { computed, onScopeDispose, shallowRef, type Ref } from 'vue'
+
+import type { PlacedIssueMarker } from '@open-pencil/core/canvas'
+import type { Editor } from '@open-pencil/core/editor'
+
+export interface CanvasIssueMarkerOptions {
+ /** Marker under a point in canvas-element CSS pixels; `useCanvas()` returns one. */
+ hitTest: (screenX: number, screenY: number) => PlacedIssueMarker | null
+ /** Called when the pointer enters, moves between, or leaves markers. */
+ onHover?: (marker: PlacedIssueMarker | null) => void
+ /** Called on a primary click on a marker; the click never reaches selection or tools. */
+ onActivate?: (marker: PlacedIssueMarker, event: MouseEvent) => void
+}
+
+/**
+ * Makes design issue markers on an overlay canvas hoverable and clickable.
+ *
+ * Listeners run in the capture phase so a marker click is consumed before canvas input starts a
+ * selection, marquee or drag. The hovered marker is cleared when the viewport moves, because the
+ * marker layout it refers to is replaced on the next frame.
+ */
+export function useCanvasIssueMarkers(
+ canvasRef: Ref<HTMLCanvasElement | null>,
+ editor: Editor,
+ options: CanvasIssueMarkerOptions
+) {
+ const hoveredMarker = shallowRef<PlacedIssueMarker | null>(null)
+ /** Set by a click; the marker's details stay closed until the pointer moves to another one. */
+ const dismissed = shallowRef(false)
+
+ function localPoint(event: MouseEvent) {
+ const canvas = canvasRef.value
+ if (!canvas) return null
+ const rect = canvas.getBoundingClientRect()
+ return { x: event.clientX - rect.left, y: event.clientY - rect.top }
+ }
+
+ function setHovered(marker: PlacedIssueMarker | null) {
+ const previous = hoveredMarker.value
+ if (previous?.key === marker?.key && previous?.count === marker?.count) return
+ hoveredMarker.value = marker
+ editor.setHoveredIssueMarker(marker?.key ?? null)
+ options.onHover?.(marker)
+ }
+
+ function onMouseMove(event: MouseEvent) {
+ if (event.buttons !== 0) {
+ setHovered(null)
+ return
+ }
+ const point = localPoint(event)
+ const marker = point ? options.hitTest(point.x, point.y) : null
+ if (marker?.key !== hoveredMarker.value?.key) dismissed.value = false
+ setHovered(marker)
+ if (!marker) return
+ editor.setHoveredNode(null)
+ event.stopImmediatePropagation()
+ }
+
+ function onMouseDown(event: MouseEvent) {
+ if (event.button !== 0) return
+ const point = localPoint(event)
+ const marker = point ? options.hitTest(point.x, point.y) : null
+ if (!marker) return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ dismissed.value = true
+ options.onActivate?.(marker, event)
+ }
+
+ useEventListener(canvasRef, 'mousemove', onMouseMove, { capture: true })
+ useEventListener(canvasRef, 'mousedown', onMouseDown, { capture: true })
+ useEventListener(canvasRef, 'mouseleave', () => setHovered(null))
+ const stopViewport = editor.onEditorEvent('viewport:changed', () => setHovered(null))
+ const stopPage = editor.onEditorEvent('page:changed', () => setHovered(null))
+ onScopeDispose(() => {
+ stopViewport()
+ stopPage()
+ if (hoveredMarker.value) editor.setHoveredIssueMarker(null)
+ })
+
+ return {
+ hoveredMarker,
+ /** The hovered marker unless a click dismissed its details. */
+ detailMarker: computed(() => (dismissed.value ? null : hoveredMarker.value)),
+ cursor: computed(() => (hoveredMarker.value ? 'pointer' : null))
+ }
+}
diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.ts
index 9835ec44f..1120ec754 100644
--- a/packages/vue/src/canvas/surface/lifecycle.ts
+++ b/packages/vue/src/canvas/surface/lifecycle.ts
@@ -103,8 +103,14 @@ export function createCanvasSurfaceManager({
})
}
+ /** UI floating over the canvas this frame, which edge-pinned overlays avoid. */
+ function overlayObstacles() {
+ return options?.getOverlayObstacles?.() ?? []
+ }
+
function renderNow() {
if (!state.renderer || isDestroyed()) return
+ state.renderer.overlayObstacles = overlayObstacles()
state.renderer.renderFromEditorState(
options?.getRenderState?.() ?? editor.state,
editor.graph,
diff --git a/packages/vue/src/canvas/surface/overlays.ts b/packages/vue/src/canvas/surface/overlays.ts
index 97648dd61..9b23cdfab 100644
--- a/packages/vue/src/canvas/surface/overlays.ts
+++ b/packages/vue/src/canvas/surface/overlays.ts
@@ -1,4 +1,4 @@
-import type { SkiaRenderer } from '@open-pencil/core/canvas'
+import { hitTestIssueMarkers, type SkiaRenderer } from '@open-pencil/core/canvas'
import type { Editor } from '@open-pencil/core/editor'
import { useViewportKind } from '#vue/editor/viewport-kind/use'
@@ -51,5 +51,11 @@ export function createCanvasHitTests(editor: Editor, getRenderer: () => SkiaRend
)
}
- return { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle }
+ /** Issue marker under a point in canvas-element CSS pixels, from the last drawn frame. */
+ function hitTestIssueMarker(screenX: number, screenY: number) {
+ const renderer = getRenderer()
+ return renderer ? hitTestIssueMarkers(renderer.issueMarkers, screenX, screenY) : null
+ }
+
+ return { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, hitTestIssueMarker }
}
diff --git a/packages/vue/src/canvas/surface/types.ts b/packages/vue/src/canvas/surface/types.ts
index 2c7b4e74b..be31d3730 100644
--- a/packages/vue/src/canvas/surface/types.ts
+++ b/packages/vue/src/canvas/surface/types.ts
@@ -1,4 +1,5 @@
import type { EditorState } from '@open-pencil/core/editor'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
import type { PresentationColorSpace } from '#vue/canvas/surface/color-space'
@@ -24,6 +25,11 @@ export interface UseCanvasOptions {
* When omitted, the composable falls back to viewport and URL-param logic.
*/
showRulers?: boolean
+ /**
+ * Screen rectangles of UI floating over this canvas, in canvas CSS pixels, read every frame.
+ * Overlays that pin to the viewport edge, such as issue edge pins, keep clear of them.
+ */
+ getOverlayObstacles?: () => readonly Rect[]
/**
* Keeps the drawing buffer after presenting frames.
*
diff --git a/packages/vue/src/canvas/surface/use.ts b/packages/vue/src/canvas/surface/use.ts
index 9580d407c..8168158f5 100644
--- a/packages/vue/src/canvas/surface/use.ts
+++ b/packages/vue/src/canvas/surface/use.ts
@@ -49,16 +49,15 @@ export function useCanvas(
onReady: options?.onReady
})
- const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = createCanvasHitTests(
- editor,
- surface.getRenderer
- )
+ const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, hitTestIssueMarker } =
+ createCanvasHitTests(editor, surface.getRenderer)
return {
render: surface.markDirty,
renderNow: surface.renderNow,
hitTestSectionTitle,
hitTestComponentLabel,
- hitTestFrameTitle
+ hitTestFrameTitle,
+ hitTestIssueMarker
}
}
diff --git a/packages/vue/src/i18n/index.ts b/packages/vue/src/i18n/index.ts
index 4cc77481b..688c48cd3 100644
--- a/packages/vue/src/i18n/index.ts
+++ b/packages/vue/src/i18n/index.ts
@@ -8,6 +8,7 @@ export {
useCommandMessages,
useCommonMessages,
useCredentialMessages,
+ useDesignCheckMessages,
useDiagnosticsMessages,
useEditorMessages,
useFileMessages,
diff --git a/packages/vue/src/i18n/locales/de/design-check.json b/packages/vue/src/i18n/locales/de/design-check.json
new file mode 100644
index 000000000..79486094b
--- /dev/null
+++ b/packages/vue/src/i18n/locales/de/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Prüfen",
+ "tabCount": "{count} Fehler und Warnungen",
+ "scope": "Bereich",
+ "scopePage": "Seite",
+ "scopeSelection": "Auswahl",
+ "scopeDocument": "Dokument",
+ "errors": "Fehler",
+ "warnings": "Warnungen",
+ "suggestions": "Vorschläge",
+ "filterBySeverity": "{severity} anzeigen",
+ "filterSeverities": "Nach Schweregrad filtern",
+ "showOnCanvas": "Probleme auf der Arbeitsfläche anzeigen",
+ "rules": "Regeln",
+ "presetRecommended": "Empfohlen",
+ "presetStrict": "Streng",
+ "presetAccessibility": "Barrierefreiheit",
+ "ruleActions": "Regelaktionen",
+ "turnOffRule": "Regel ausschalten",
+ "turnOnRules": "{count} ausgeschaltete Regeln einschalten",
+ "checking": "Wird geprüft…",
+ "emptyPage": "Keine Probleme auf dieser Seite",
+ "emptySelection": "Keine Probleme in der Auswahl",
+ "emptyDocument": "Keine Probleme in diesem Dokument",
+ "documentUnchecked": "Noch nicht geprüfte Seiten: {count}",
+ "onPage": "Auf {page}",
+ "emptyDescription": "Mit den Regeln „{preset}“ geprüft.",
+ "noSelection": "Wähle Ebenen aus, um sie zu prüfen",
+ "noSelectionDescription": "Probleme in den ausgewählten Ebenen erscheinen hier.",
+ "noFilteredIssues": "Keine Probleme entsprechen den Filtern",
+ "clearFilters": "Alle Probleme anzeigen",
+ "showMore": "{count} weitere anzeigen",
+ "hiddenLayer": "Ausgeblendet",
+ "missingLayer": "Gelöschte Ebene",
+ "markerMore": "+{count} weitere",
+ "markerLayers": "{count} Ebenen",
+ "markerHint": "Zum Prüfen klicken",
+ "edgeLeft": "Außerhalb links",
+ "edgeRight": "Außerhalb rechts",
+ "edgeAbove": "Außerhalb oben",
+ "edgeBelow": "Außerhalb unten",
+ "edgeHint": "Klicken, um zum nächsten zu springen",
+ "layerIssues": "Fehler und Warnungen: {count}",
+ "layerContainsIssues": "Enthält Fehler oder Warnungen",
+ "ruleColorContrast": "Geringer Textkontrast",
+ "ruleColorContrastHelp": "Text braucht ein Kontrastverhältnis von mindestens 4,5:1 zum Hintergrund, um WCAG AA zu erfüllen.",
+ "ruleTouchTargetSize": "Kleine Touch-Fläche",
+ "ruleTouchTargetSizeHelp": "Schaltflächen, Links und andere Bedienelemente brauchen Platz zum Antippen: mindestens 24 × 24 für WCAG AA, 44 × 44 für AAA.",
+ "ruleMinTextSize": "Kleiner Text",
+ "ruleMinTextSizeHelp": "Text unter 12 px ist auf den meisten Bildschirmen schwer lesbar.",
+ "ruleConsistentSpacing": "Abstand außerhalb der Skala",
+ "ruleConsistentSpacingHelp": "Abstände und Innenabstände im Auto-Layout sollten aus der Abstandsskala stammen oder Vielfache von 4 sein.",
+ "detailSpacingGap": "Abstand {value}",
+ "detailSpacingTop": "Innenabstand oben {value}",
+ "detailSpacingRight": "Innenabstand rechts {value}",
+ "detailSpacingBottom": "Innenabstand unten {value}",
+ "detailSpacingLeft": "Innenabstand links {value}",
+ "ruleConsistentRadius": "Eckenradius außerhalb der Skala",
+ "ruleConsistentRadiusHelp": "Eckenradien sollten aus der Radiusskala oder einer Variablen stammen.",
+ "ruleNoHardcodedColors": "Ungebundene Farbe",
+ "ruleNoHardcodedColorsHelp": "Diese Farbe entspricht einer Farbvariablen. Binde sie, damit Änderungen an Theme und Palette diese Ebene erreichen.",
+ "detailStrokeColor": "Kontur: {variable}",
+ "bindVariable": "An {variable} binden",
+ "bindAll": "Alle {count} binden",
+ "fixRoundPixels": "Auf ganze Pixel runden",
+ "fixUseValue": "Auf {value} ändern",
+ "fixFullRadius": "Vollen Radius verwenden",
+ "fixAll": "Alle {count} beheben",
+ "ruleNoDefaultNames": "Standardname der Ebene",
+ "ruleNoDefaultNamesHelp": "Aussagekräftige Namen machen Ebenen leichter auffindbar, übergebbar und wiederverwendbar.",
+ "rulePreferAutoLayout": "Kein Auto-Layout",
+ "rulePreferAutoLayoutHelp": "Rahmen mit mehreren gestapelten Ebenen passen sich mit Auto-Layout besser an.",
+ "detailChildren": "{children} Ebenen",
+ "ruleTextStyleRequired": "Ungebundener Textstil",
+ "ruleTextStyleRequiredHelp": "Binde Schriftgröße oder Schriftfamilie an eine Variable, damit die Typografie einheitlich bleibt.",
+ "ruleNoHiddenLayers": "Ausgeblendete Ebene",
+ "ruleNoHiddenLayersHelp": "Ausgeblendete Ebenen sind oft Überbleibsel. Lösche sie, wenn kein Zustand sie braucht.",
+ "ruleNoDeeplyNested": "Tiefe Verschachtelung",
+ "ruleNoDeeplyNestedHelp": "Tief verschachtelte Ebenen sind schwer zu bearbeiten. Vereinfache sie oder erstelle eine Komponente.",
+ "detailDepth": "{depth} Ebenen tief",
+ "ruleNoEmptyFrames": "Leerer Rahmen",
+ "ruleNoEmptyFramesHelp": "Rahmen ohne Inhalt oder Füllung sind meist Überbleibsel.",
+ "rulePixelPerfect": "Subpixel-Geometrie",
+ "rulePixelPerfectHelp": "Positionen und Größen in ganzen Pixeln werden scharf dargestellt.",
+ "ruleNoGroups": "Gruppe",
+ "ruleNoGroupsHelp": "Rahmen unterstützen Auto-Layout und Beschränkungen, Gruppen nicht.",
+ "ruleEffectStyleRequired": "Nicht geteilter Effekt",
+ "ruleEffectStyleRequiredHelp": "Verwende Schatten und Unschärfen über geteilte Vorlagen oder Variablen wieder.",
+ "ruleNoMixedStyles": "Gemischte Textstile",
+ "ruleNoMixedStylesHelp": "Mehrere Stile in einer Textebene gehen beim Bearbeiten leicht kaputt.",
+ "ruleNoDetachedInstances": "Sieht wie eine Komponente aus",
+ "ruleNoDetachedInstancesHelp": "Dieser Rahmen sieht wie ein wiederverwendbares Element aus. Verwende eine Komponenteninstanz."
+}
diff --git a/packages/vue/src/i18n/locales/de/index.ts b/packages/vue/src/i18n/locales/de/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/de/index.ts
+++ b/packages/vue/src/i18n/locales/de/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.json
index 32e0690ce..abbd9cb6d 100644
--- a/packages/vue/src/i18n/locales/de/menu.json
+++ b/packages/vue/src/i18n/locales/de/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Mittig ausrichten",
"arrangeAlignBottom": "Unten ausrichten",
"multiplayerCursors": "Multiplayer-Cursor",
+ "designIssues": "Designprobleme",
"preferences": "Einstellungen",
"snapToGeometry": "An Geometrie ausrichten",
"snapToObjects": "An Objekten ausrichten",
diff --git a/packages/vue/src/i18n/locales/es/design-check.json b/packages/vue/src/i18n/locales/es/design-check.json
new file mode 100644
index 000000000..25110129e
--- /dev/null
+++ b/packages/vue/src/i18n/locales/es/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Revisar",
+ "tabCount": "{count} errores y advertencias",
+ "scope": "Alcance",
+ "scopePage": "Página",
+ "scopeSelection": "Selección",
+ "scopeDocument": "Documento",
+ "errors": "Errores",
+ "warnings": "Advertencias",
+ "suggestions": "Sugerencias",
+ "filterBySeverity": "Mostrar {severity}",
+ "filterSeverities": "Filtrar por gravedad",
+ "showOnCanvas": "Mostrar problemas en el lienzo",
+ "rules": "Reglas",
+ "presetRecommended": "Recomendadas",
+ "presetStrict": "Estrictas",
+ "presetAccessibility": "Accesibilidad",
+ "ruleActions": "Acciones de la regla",
+ "turnOffRule": "Desactivar regla",
+ "turnOnRules": "Activar {count} reglas desactivadas",
+ "checking": "Revisando…",
+ "emptyPage": "No hay problemas en esta página",
+ "emptySelection": "No hay problemas en la selección",
+ "emptyDocument": "No hay problemas en este documento",
+ "documentUnchecked": "Páginas sin revisar: {count}",
+ "onPage": "En {page}",
+ "emptyDescription": "Revisado con las reglas {preset}.",
+ "noSelection": "Selecciona capas para revisarlas",
+ "noSelectionDescription": "Los problemas dentro de las capas seleccionadas aparecen aquí.",
+ "noFilteredIssues": "Ningún problema coincide con los filtros",
+ "clearFilters": "Mostrar todos los problemas",
+ "showMore": "Mostrar {count} más",
+ "hiddenLayer": "Oculta",
+ "missingLayer": "Capa eliminada",
+ "markerMore": "+{count} más",
+ "markerLayers": "{count} capas",
+ "markerHint": "Haz clic para revisar",
+ "edgeLeft": "Fuera de la vista, a la izquierda",
+ "edgeRight": "Fuera de la vista, a la derecha",
+ "edgeAbove": "Fuera de la vista, arriba",
+ "edgeBelow": "Fuera de la vista, abajo",
+ "edgeHint": "Haz clic para ir al más cercano",
+ "layerIssues": "Errores y advertencias: {count}",
+ "layerContainsIssues": "Contiene errores o advertencias",
+ "ruleColorContrast": "Contraste de texto bajo",
+ "ruleColorContrastHelp": "El texto necesita una relación de contraste de al menos 4,5:1 con su fondo para cumplir WCAG AA.",
+ "ruleTouchTargetSize": "Área táctil pequeña",
+ "ruleTouchTargetSizeHelp": "Los botones, enlaces y otros controles necesitan espacio para tocarlos: al menos 24 × 24 para WCAG AA y 44 × 44 para AAA.",
+ "ruleMinTextSize": "Texto pequeño",
+ "ruleMinTextSizeHelp": "El texto de menos de 12 px es difícil de leer en la mayoría de las pantallas.",
+ "ruleConsistentSpacing": "Espaciado fuera de escala",
+ "ruleConsistentSpacingHelp": "Los espaciados y rellenos del auto-layout deben salir de la escala de espaciado o ser múltiplos de 4.",
+ "detailSpacingGap": "Espaciado {value}",
+ "detailSpacingTop": "Relleno superior {value}",
+ "detailSpacingRight": "Relleno derecho {value}",
+ "detailSpacingBottom": "Relleno inferior {value}",
+ "detailSpacingLeft": "Relleno izquierdo {value}",
+ "ruleConsistentRadius": "Radio de esquina fuera de escala",
+ "ruleConsistentRadiusHelp": "El radio de esquina debe salir de la escala de radios o de una variable.",
+ "ruleNoHardcodedColors": "Color sin vincular",
+ "ruleNoHardcodedColorsHelp": "Este color coincide con una variable de color. Vincúlalo para que los cambios de tema y paleta lleguen a esta capa.",
+ "detailStrokeColor": "Trazo: {variable}",
+ "bindVariable": "Vincular a {variable}",
+ "bindAll": "Vincular las {count}",
+ "fixRoundPixels": "Redondear a píxeles enteros",
+ "fixUseValue": "Cambiar a {value}",
+ "fixFullRadius": "Usar radio completo",
+ "fixAll": "Corregir las {count}",
+ "ruleNoDefaultNames": "Nombre de capa predeterminado",
+ "ruleNoDefaultNamesHelp": "Los nombres descriptivos facilitan encontrar, entregar y reutilizar capas.",
+ "rulePreferAutoLayout": "Sin auto-layout",
+ "rulePreferAutoLayoutHelp": "Los marcos que apilan varias capas se adaptan mejor con auto-layout.",
+ "detailChildren": "{children} capas",
+ "ruleTextStyleRequired": "Estilo de texto sin vincular",
+ "ruleTextStyleRequiredHelp": "Vincula el tamaño o la familia de fuente a una variable para mantener la tipografía coherente.",
+ "ruleNoHiddenLayers": "Capa oculta",
+ "ruleNoHiddenLayersHelp": "Las capas ocultas suelen ser restos. Elimínalas si ningún estado las necesita.",
+ "ruleNoDeeplyNested": "Anidación profunda",
+ "ruleNoDeeplyNestedHelp": "Las capas muy anidadas son difíciles de editar. Simplifícalas o extrae un componente.",
+ "detailDepth": "{depth} niveles",
+ "ruleNoEmptyFrames": "Marco vacío",
+ "ruleNoEmptyFramesHelp": "Los marcos sin contenido ni relleno suelen ser restos.",
+ "rulePixelPerfect": "Geometría con subpíxeles",
+ "rulePixelPerfectHelp": "Las posiciones y tamaños en píxeles enteros se ven nítidos.",
+ "ruleNoGroups": "Grupo",
+ "ruleNoGroupsHelp": "Los marcos admiten auto-layout y restricciones; los grupos no.",
+ "ruleEffectStyleRequired": "Efecto sin compartir",
+ "ruleEffectStyleRequiredHelp": "Reutiliza sombras y desenfoques mediante ajustes compartidos o variables.",
+ "ruleNoMixedStyles": "Estilos de texto mezclados",
+ "ruleNoMixedStylesHelp": "Varios estilos en una capa de texto se rompen fácilmente al editar.",
+ "ruleNoDetachedInstances": "Parece un componente",
+ "ruleNoDetachedInstancesHelp": "Este marco parece un elemento reutilizable. Usa una instancia de componente."
+}
diff --git a/packages/vue/src/i18n/locales/es/index.ts b/packages/vue/src/i18n/locales/es/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/es/index.ts
+++ b/packages/vue/src/i18n/locales/es/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.json
index d93958c71..1dd01ec16 100644
--- a/packages/vue/src/i18n/locales/es/menu.json
+++ b/packages/vue/src/i18n/locales/es/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Alinear centro verticalmente",
"arrangeAlignBottom": "Alinear abajo",
"multiplayerCursors": "Cursores multijugador",
+ "designIssues": "Problemas de diseño",
"preferences": "Preferencias",
"snapToGeometry": "Ajustar a la geometría",
"snapToObjects": "Ajustar a objetos",
diff --git a/packages/vue/src/i18n/locales/fr/design-check.json b/packages/vue/src/i18n/locales/fr/design-check.json
new file mode 100644
index 000000000..f415872db
--- /dev/null
+++ b/packages/vue/src/i18n/locales/fr/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Vérifier",
+ "tabCount": "{count} erreurs et avertissements",
+ "scope": "Portée",
+ "scopePage": "Page",
+ "scopeSelection": "Sélection",
+ "scopeDocument": "Document",
+ "errors": "Erreurs",
+ "warnings": "Avertissements",
+ "suggestions": "Suggestions",
+ "filterBySeverity": "Afficher : {severity}",
+ "filterSeverities": "Filtrer par gravité",
+ "showOnCanvas": "Afficher les problèmes sur le canevas",
+ "rules": "Règles",
+ "presetRecommended": "Recommandées",
+ "presetStrict": "Strictes",
+ "presetAccessibility": "Accessibilité",
+ "ruleActions": "Actions de la règle",
+ "turnOffRule": "Désactiver la règle",
+ "turnOnRules": "Réactiver {count} règles désactivées",
+ "checking": "Vérification…",
+ "emptyPage": "Aucun problème sur cette page",
+ "emptySelection": "Aucun problème dans la sélection",
+ "emptyDocument": "Aucun problème dans ce document",
+ "documentUnchecked": "Pages pas encore vérifiées : {count}",
+ "onPage": "Sur {page}",
+ "emptyDescription": "Vérifié avec les règles {preset}.",
+ "noSelection": "Sélectionnez des calques pour les vérifier",
+ "noSelectionDescription": "Les problèmes des calques sélectionnés apparaissent ici.",
+ "noFilteredIssues": "Aucun problème ne correspond aux filtres",
+ "clearFilters": "Afficher tous les problèmes",
+ "showMore": "Afficher {count} de plus",
+ "hiddenLayer": "Masqué",
+ "missingLayer": "Calque supprimé",
+ "markerMore": "+{count} autres",
+ "markerLayers": "{count} calques",
+ "markerHint": "Cliquez pour examiner",
+ "edgeLeft": "Hors écran, à gauche",
+ "edgeRight": "Hors écran, à droite",
+ "edgeAbove": "Hors écran, en haut",
+ "edgeBelow": "Hors écran, en bas",
+ "edgeHint": "Cliquer pour aller au plus proche",
+ "layerIssues": "Erreurs et avertissements : {count}",
+ "layerContainsIssues": "Contient des erreurs ou des avertissements",
+ "ruleColorContrast": "Contraste du texte faible",
+ "ruleColorContrastHelp": "Le texte doit avoir un rapport de contraste d’au moins 4,5:1 avec son arrière-plan pour respecter WCAG AA.",
+ "ruleTouchTargetSize": "Zone tactile trop petite",
+ "ruleTouchTargetSizeHelp": "Les boutons, liens et autres contrôles doivent être faciles à toucher : au moins 24 × 24 pour WCAG AA, 44 × 44 pour AAA.",
+ "ruleMinTextSize": "Texte trop petit",
+ "ruleMinTextSizeHelp": "Un texte de moins de 12 px est difficile à lire sur la plupart des écrans.",
+ "ruleConsistentSpacing": "Espacement hors échelle",
+ "ruleConsistentSpacingHelp": "Les espacements et marges intérieures de l’auto-layout doivent venir de l’échelle d’espacement ou être des multiples de 4.",
+ "detailSpacingGap": "Espacement {value}",
+ "detailSpacingTop": "Marge intérieure haute {value}",
+ "detailSpacingRight": "Marge intérieure droite {value}",
+ "detailSpacingBottom": "Marge intérieure basse {value}",
+ "detailSpacingLeft": "Marge intérieure gauche {value}",
+ "ruleConsistentRadius": "Rayon d’angle hors échelle",
+ "ruleConsistentRadiusHelp": "Le rayon d’angle doit venir de l’échelle des rayons ou d’une variable.",
+ "ruleNoHardcodedColors": "Couleur non liée",
+ "ruleNoHardcodedColorsHelp": "Cette couleur correspond à une variable de couleur. Liez-la pour que les changements de thème et de palette atteignent ce calque.",
+ "detailStrokeColor": "Contour : {variable}",
+ "bindVariable": "Lier à {variable}",
+ "bindAll": "Tout lier ({count})",
+ "fixRoundPixels": "Arrondir au pixel entier",
+ "fixUseValue": "Remplacer par {value}",
+ "fixFullRadius": "Utiliser un rayon complet",
+ "fixAll": "Tout corriger ({count})",
+ "ruleNoDefaultNames": "Nom de calque par défaut",
+ "ruleNoDefaultNamesHelp": "Des noms descriptifs facilitent la recherche, la transmission et la réutilisation des calques.",
+ "rulePreferAutoLayout": "Sans auto-layout",
+ "rulePreferAutoLayoutHelp": "Les cadres qui empilent plusieurs calques s’adaptent mieux avec l’auto-layout.",
+ "detailChildren": "{children} calques",
+ "ruleTextStyleRequired": "Style de texte non lié",
+ "ruleTextStyleRequiredHelp": "Liez la taille ou la famille de police à une variable pour garder une typographie cohérente.",
+ "ruleNoHiddenLayers": "Calque masqué",
+ "ruleNoHiddenLayersHelp": "Les calques masqués sont souvent des restes. Supprimez-les si aucun état n’en a besoin.",
+ "ruleNoDeeplyNested": "Imbrication profonde",
+ "ruleNoDeeplyNestedHelp": "Les calques très imbriqués sont difficiles à modifier. Aplatissez-les ou extrayez un composant.",
+ "detailDepth": "{depth} niveaux",
+ "ruleNoEmptyFrames": "Cadre vide",
+ "ruleNoEmptyFramesHelp": "Les cadres sans contenu ni remplissage sont généralement des restes.",
+ "rulePixelPerfect": "Géométrie au sous-pixel",
+ "rulePixelPerfectHelp": "Les positions et tailles en pixels entiers s’affichent nettement.",
+ "ruleNoGroups": "Groupe",
+ "ruleNoGroupsHelp": "Les cadres prennent en charge l’auto-layout et les contraintes, pas les groupes.",
+ "ruleEffectStyleRequired": "Effet non partagé",
+ "ruleEffectStyleRequiredHelp": "Réutilisez ombres et flous grâce à des préréglages partagés ou des variables.",
+ "ruleNoMixedStyles": "Styles de texte mélangés",
+ "ruleNoMixedStylesHelp": "Plusieurs styles dans un même calque de texte se cassent facilement à l’édition.",
+ "ruleNoDetachedInstances": "Ressemble à un composant",
+ "ruleNoDetachedInstancesHelp": "Ce cadre ressemble à un élément réutilisable. Utilisez une instance de composant."
+}
diff --git a/packages/vue/src/i18n/locales/fr/index.ts b/packages/vue/src/i18n/locales/fr/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/fr/index.ts
+++ b/packages/vue/src/i18n/locales/fr/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.json
index 6682b71e0..2303cbde2 100644
--- a/packages/vue/src/i18n/locales/fr/menu.json
+++ b/packages/vue/src/i18n/locales/fr/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Centrer verticalement",
"arrangeAlignBottom": "Aligner en bas",
"multiplayerCursors": "Curseurs multijoueurs",
+ "designIssues": "Problèmes de design",
"preferences": "Préférences",
"snapToGeometry": "Aligner sur la géométrie",
"snapToObjects": "Aligner sur les objets",
diff --git a/packages/vue/src/i18n/locales/it/design-check.json b/packages/vue/src/i18n/locales/it/design-check.json
new file mode 100644
index 000000000..5b3f02929
--- /dev/null
+++ b/packages/vue/src/i18n/locales/it/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Verifica",
+ "tabCount": "{count} errori e avvisi",
+ "scope": "Ambito",
+ "scopePage": "Pagina",
+ "scopeSelection": "Selezione",
+ "scopeDocument": "Documento",
+ "errors": "Errori",
+ "warnings": "Avvisi",
+ "suggestions": "Suggerimenti",
+ "filterBySeverity": "Mostra {severity}",
+ "filterSeverities": "Filtra per gravità",
+ "showOnCanvas": "Mostra i problemi nell’area di lavoro",
+ "rules": "Regole",
+ "presetRecommended": "Consigliate",
+ "presetStrict": "Rigorose",
+ "presetAccessibility": "Accessibilità",
+ "ruleActions": "Azioni della regola",
+ "turnOffRule": "Disattiva regola",
+ "turnOnRules": "Riattiva {count} regole disattivate",
+ "checking": "Verifica in corso…",
+ "emptyPage": "Nessun problema in questa pagina",
+ "emptySelection": "Nessun problema nella selezione",
+ "emptyDocument": "Nessun problema in questo documento",
+ "documentUnchecked": "Pagine non ancora controllate: {count}",
+ "onPage": "In {page}",
+ "emptyDescription": "Verificato con le regole {preset}.",
+ "noSelection": "Seleziona dei livelli per verificarli",
+ "noSelectionDescription": "Qui compaiono i problemi dei livelli selezionati.",
+ "noFilteredIssues": "Nessun problema corrisponde ai filtri",
+ "clearFilters": "Mostra tutti i problemi",
+ "showMore": "Mostra altri {count}",
+ "hiddenLayer": "Nascosto",
+ "missingLayer": "Livello eliminato",
+ "markerMore": "+{count} altri",
+ "markerLayers": "{count} livelli",
+ "markerHint": "Fai clic per esaminare",
+ "edgeLeft": "Fuori schermo a sinistra",
+ "edgeRight": "Fuori schermo a destra",
+ "edgeAbove": "Fuori schermo in alto",
+ "edgeBelow": "Fuori schermo in basso",
+ "edgeHint": "Fai clic per andare al più vicino",
+ "layerIssues": "Errori e avvisi: {count}",
+ "layerContainsIssues": "Contiene errori o avvisi",
+ "ruleColorContrast": "Contrasto del testo basso",
+ "ruleColorContrastHelp": "Il testo richiede un rapporto di contrasto di almeno 4,5:1 con lo sfondo per rispettare WCAG AA.",
+ "ruleTouchTargetSize": "Area di tocco piccola",
+ "ruleTouchTargetSizeHelp": "Pulsanti, link e altri controlli devono essere facili da toccare: almeno 24 × 24 per WCAG AA, 44 × 44 per AAA.",
+ "ruleMinTextSize": "Testo piccolo",
+ "ruleMinTextSizeHelp": "Il testo sotto i 12 px è difficile da leggere sulla maggior parte degli schermi.",
+ "ruleConsistentSpacing": "Spaziatura fuori scala",
+ "ruleConsistentSpacingHelp": "Spazi e padding dell’auto-layout dovrebbero provenire dalla scala di spaziatura o essere multipli di 4.",
+ "detailSpacingGap": "Spazio {value}",
+ "detailSpacingTop": "Padding superiore {value}",
+ "detailSpacingRight": "Padding destro {value}",
+ "detailSpacingBottom": "Padding inferiore {value}",
+ "detailSpacingLeft": "Padding sinistro {value}",
+ "ruleConsistentRadius": "Raggio d’angolo fuori scala",
+ "ruleConsistentRadiusHelp": "Il raggio d’angolo dovrebbe provenire dalla scala dei raggi o da una variabile.",
+ "ruleNoHardcodedColors": "Colore non collegato",
+ "ruleNoHardcodedColorsHelp": "Questo colore corrisponde a una variabile di colore. Collegalo perché le modifiche a tema e palette raggiungano questo livello.",
+ "detailStrokeColor": "Contorno: {variable}",
+ "bindVariable": "Collega a {variable}",
+ "bindAll": "Collega tutti ({count})",
+ "fixRoundPixels": "Arrotonda a pixel interi",
+ "fixUseValue": "Cambia in {value}",
+ "fixFullRadius": "Usa raggio completo",
+ "fixAll": "Correggi tutti ({count})",
+ "ruleNoDefaultNames": "Nome del livello predefinito",
+ "ruleNoDefaultNamesHelp": "Nomi descrittivi rendono i livelli più facili da trovare, consegnare e riutilizzare.",
+ "rulePreferAutoLayout": "Senza auto-layout",
+ "rulePreferAutoLayoutHelp": "Le cornici che impilano più livelli si adattano meglio con l’auto-layout.",
+ "detailChildren": "{children} livelli",
+ "ruleTextStyleRequired": "Stile di testo non collegato",
+ "ruleTextStyleRequiredHelp": "Collega dimensione o famiglia del carattere a una variabile per mantenere coerente la tipografia.",
+ "ruleNoHiddenLayers": "Livello nascosto",
+ "ruleNoHiddenLayersHelp": "I livelli nascosti sono spesso residui. Eliminali se nessuno stato ne ha bisogno.",
+ "ruleNoDeeplyNested": "Annidamento profondo",
+ "ruleNoDeeplyNestedHelp": "I livelli molto annidati sono difficili da modificare. Semplificali o estrai un componente.",
+ "detailDepth": "{depth} livelli di profondità",
+ "ruleNoEmptyFrames": "Cornice vuota",
+ "ruleNoEmptyFramesHelp": "Le cornici senza contenuto né riempimento sono di solito residui.",
+ "rulePixelPerfect": "Geometria subpixel",
+ "rulePixelPerfectHelp": "Posizioni e dimensioni in pixel interi appaiono nitide.",
+ "ruleNoGroups": "Gruppo",
+ "ruleNoGroupsHelp": "Le cornici supportano auto-layout e vincoli, i gruppi no.",
+ "ruleEffectStyleRequired": "Effetto non condiviso",
+ "ruleEffectStyleRequiredHelp": "Riutilizza ombre e sfocature tramite preset condivisi o variabili.",
+ "ruleNoMixedStyles": "Stili di testo misti",
+ "ruleNoMixedStylesHelp": "Più stili in un solo livello di testo si rompono facilmente durante la modifica.",
+ "ruleNoDetachedInstances": "Sembra un componente",
+ "ruleNoDetachedInstancesHelp": "Questa cornice sembra un elemento riutilizzabile. Usa un’istanza di componente."
+}
diff --git a/packages/vue/src/i18n/locales/it/index.ts b/packages/vue/src/i18n/locales/it/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/it/index.ts
+++ b/packages/vue/src/i18n/locales/it/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.json
index 7b0ae4b22..af43a2c56 100644
--- a/packages/vue/src/i18n/locales/it/menu.json
+++ b/packages/vue/src/i18n/locales/it/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Centra verticalmente",
"arrangeAlignBottom": "Allinea in basso",
"multiplayerCursors": "Cursori multigiocatore",
+ "designIssues": "Problemi di design",
"preferences": "Preferenze",
"snapToGeometry": "Aggancia alla geometria",
"snapToObjects": "Aggancia agli oggetti",
diff --git a/packages/vue/src/i18n/locales/ja/design-check.json b/packages/vue/src/i18n/locales/ja/design-check.json
new file mode 100644
index 000000000..2d93790f7
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ja/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "チェック",
+ "tabCount": "エラーと警告 {count} 件",
+ "scope": "範囲",
+ "scopePage": "ページ",
+ "scopeSelection": "選択範囲",
+ "scopeDocument": "ドキュメント",
+ "errors": "エラー",
+ "warnings": "警告",
+ "suggestions": "提案",
+ "filterBySeverity": "{severity}を表示",
+ "filterSeverities": "重大度で絞り込む",
+ "showOnCanvas": "キャンバスに問題を表示",
+ "rules": "ルール",
+ "presetRecommended": "推奨",
+ "presetStrict": "厳格",
+ "presetAccessibility": "アクセシビリティ",
+ "ruleActions": "ルールの操作",
+ "turnOffRule": "ルールをオフにする",
+ "turnOnRules": "オフにした {count} 件のルールをオンにする",
+ "checking": "チェック中…",
+ "emptyPage": "このページに問題はありません",
+ "emptySelection": "選択範囲に問題はありません",
+ "emptyDocument": "このドキュメントに問題はありません",
+ "documentUnchecked": "未チェックのページ: {count}",
+ "onPage": "{page} 上",
+ "emptyDescription": "{preset}ルールでチェックしました。",
+ "noSelection": "チェックするレイヤーを選択してください",
+ "noSelectionDescription": "選択したレイヤー内の問題がここに表示されます。",
+ "noFilteredIssues": "フィルターに一致する問題はありません",
+ "clearFilters": "すべての問題を表示",
+ "showMore": "さらに {count} 件を表示",
+ "hiddenLayer": "非表示",
+ "missingLayer": "削除されたレイヤー",
+ "markerMore": "ほか {count} 件",
+ "markerLayers": "{count} 個のレイヤー",
+ "markerHint": "クリックして確認",
+ "edgeLeft": "画面外(左)",
+ "edgeRight": "画面外(右)",
+ "edgeAbove": "画面外(上)",
+ "edgeBelow": "画面外(下)",
+ "edgeHint": "クリックして最も近いものへ移動",
+ "layerIssues": "エラーと警告: {count}",
+ "layerContainsIssues": "エラーまたは警告を含みます",
+ "ruleColorContrast": "テキストのコントラスト不足",
+ "ruleColorContrastHelp": "WCAG AA を満たすには、テキストと背景のコントラスト比が 4.5:1 以上必要です。",
+ "ruleTouchTargetSize": "タッチ領域が小さい",
+ "ruleTouchTargetSizeHelp": "ボタンやリンクなどの操作要素は、タップしやすい大きさが必要です。WCAG AA では 24 × 24 以上、AAA では 44 × 44 以上です。",
+ "ruleMinTextSize": "文字が小さい",
+ "ruleMinTextSizeHelp": "12 px 未満の文字は多くの画面で読みにくくなります。",
+ "ruleConsistentSpacing": "スケール外の間隔",
+ "ruleConsistentSpacingHelp": "オートレイアウトの間隔とパディングは、スペーシングスケールまたは 4 の倍数にしてください。",
+ "detailSpacingGap": "間隔 {value}",
+ "detailSpacingTop": "上パディング {value}",
+ "detailSpacingRight": "右パディング {value}",
+ "detailSpacingBottom": "下パディング {value}",
+ "detailSpacingLeft": "左パディング {value}",
+ "ruleConsistentRadius": "スケール外の角の半径",
+ "ruleConsistentRadiusHelp": "角の半径は半径スケールまたは変数から選んでください。",
+ "ruleNoHardcodedColors": "変数に紐づいていない色",
+ "ruleNoHardcodedColorsHelp": "この色はカラー変数と一致します。変数に紐づけると、テーマやパレットの変更がこのレイヤーに反映されます。",
+ "detailStrokeColor": "線: {variable}",
+ "bindVariable": "{variable} に紐づける",
+ "bindAll": "{count} 件すべて紐づける",
+ "fixRoundPixels": "整数ピクセルに丸める",
+ "fixUseValue": "{value} に変更",
+ "fixFullRadius": "最大の角丸を使う",
+ "fixAll": "{count} 件すべて修正",
+ "ruleNoDefaultNames": "デフォルトのレイヤー名",
+ "ruleNoDefaultNamesHelp": "わかりやすい名前を付けると、レイヤーを探しやすく、受け渡しや再利用もしやすくなります。",
+ "rulePreferAutoLayout": "オートレイアウトなし",
+ "rulePreferAutoLayoutHelp": "複数のレイヤーを並べるフレームは、オートレイアウトを使うとサイズ変更に強くなります。",
+ "detailChildren": "{children} 個のレイヤー",
+ "ruleTextStyleRequired": "変数に紐づいていないテキストスタイル",
+ "ruleTextStyleRequiredHelp": "フォントサイズまたはファミリーを変数に紐づけて、タイポグラフィを統一してください。",
+ "ruleNoHiddenLayers": "非表示のレイヤー",
+ "ruleNoHiddenLayersHelp": "非表示のレイヤーは消し忘れのことがよくあります。どの状態にも不要なら削除してください。",
+ "ruleNoDeeplyNested": "深いネスト",
+ "ruleNoDeeplyNestedHelp": "深くネストしたレイヤーは編集しにくくなります。階層を浅くするかコンポーネントにしてください。",
+ "detailDepth": "{depth} 階層",
+ "ruleNoEmptyFrames": "空のフレーム",
+ "ruleNoEmptyFramesHelp": "中身も塗りもないフレームは、たいてい消し忘れです。",
+ "rulePixelPerfect": "サブピクセルのジオメトリ",
+ "rulePixelPerfectHelp": "位置とサイズを整数ピクセルにすると、くっきり表示されます。",
+ "ruleNoGroups": "グループ",
+ "ruleNoGroupsHelp": "フレームはオートレイアウトと制約に対応していますが、グループは対応していません。",
+ "ruleEffectStyleRequired": "共有されていないエフェクト",
+ "ruleEffectStyleRequiredHelp": "シャドウやぼかしは、共有プリセットや変数で再利用してください。",
+ "ruleNoMixedStyles": "混在したテキストスタイル",
+ "ruleNoMixedStylesHelp": "1 つのテキストレイヤーに複数のスタイルがあると、編集時に崩れやすくなります。",
+ "ruleNoDetachedInstances": "コンポーネントのようなフレーム",
+ "ruleNoDetachedInstancesHelp": "このフレームは再利用する要素に見えます。コンポーネントのインスタンスを使ってください。"
+}
diff --git a/packages/vue/src/i18n/locales/ja/index.ts b/packages/vue/src/i18n/locales/ja/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/ja/index.ts
+++ b/packages/vue/src/i18n/locales/ja/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.json
index 89e716d65..dbe661c6d 100644
--- a/packages/vue/src/i18n/locales/ja/menu.json
+++ b/packages/vue/src/i18n/locales/ja/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "上下中央揃え",
"arrangeAlignBottom": "下揃え",
"multiplayerCursors": "マルチプレイヤーカーソル",
+ "designIssues": "デザインの問題",
"preferences": "環境設定",
"snapToGeometry": "ジオメトリにスナップ",
"snapToObjects": "オブジェクトにスナップ",
diff --git a/packages/vue/src/i18n/locales/pl/design-check.json b/packages/vue/src/i18n/locales/pl/design-check.json
new file mode 100644
index 000000000..216703b86
--- /dev/null
+++ b/packages/vue/src/i18n/locales/pl/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Sprawdź",
+ "tabCount": "Błędy i ostrzeżenia: {count}",
+ "scope": "Zakres",
+ "scopePage": "Strona",
+ "scopeSelection": "Zaznaczenie",
+ "scopeDocument": "Dokument",
+ "errors": "Błędy",
+ "warnings": "Ostrzeżenia",
+ "suggestions": "Sugestie",
+ "filterBySeverity": "Pokaż: {severity}",
+ "filterSeverities": "Filtruj według ważności",
+ "showOnCanvas": "Pokazuj problemy na obszarze roboczym",
+ "rules": "Reguły",
+ "presetRecommended": "Zalecane",
+ "presetStrict": "Rygorystyczne",
+ "presetAccessibility": "Dostępność",
+ "ruleActions": "Działania reguły",
+ "turnOffRule": "Wyłącz regułę",
+ "turnOnRules": "Włącz wyłączone reguły: {count}",
+ "checking": "Sprawdzanie…",
+ "emptyPage": "Brak problemów na tej stronie",
+ "emptySelection": "Brak problemów w zaznaczeniu",
+ "emptyDocument": "Brak problemów w tym dokumencie",
+ "documentUnchecked": "Strony jeszcze niesprawdzone: {count}",
+ "onPage": "Na {page}",
+ "emptyDescription": "Sprawdzono regułami: {preset}.",
+ "noSelection": "Zaznacz warstwy, aby je sprawdzić",
+ "noSelectionDescription": "Tutaj pojawią się problemy w zaznaczonych warstwach.",
+ "noFilteredIssues": "Żaden problem nie pasuje do filtrów",
+ "clearFilters": "Pokaż wszystkie problemy",
+ "showMore": "Pokaż więcej: {count}",
+ "hiddenLayer": "Ukryta",
+ "missingLayer": "Usunięta warstwa",
+ "markerMore": "i jeszcze {count}",
+ "markerLayers": "Warstwy: {count}",
+ "markerHint": "Kliknij, aby przejrzeć",
+ "edgeLeft": "Poza ekranem po lewej",
+ "edgeRight": "Poza ekranem po prawej",
+ "edgeAbove": "Poza ekranem powyżej",
+ "edgeBelow": "Poza ekranem poniżej",
+ "edgeHint": "Kliknij, aby przejść do najbliższego",
+ "layerIssues": "Błędy i ostrzeżenia: {count}",
+ "layerContainsIssues": "Zawiera błędy lub ostrzeżenia",
+ "ruleColorContrast": "Niski kontrast tekstu",
+ "ruleColorContrastHelp": "Aby spełnić WCAG AA, tekst musi mieć współczynnik kontrastu z tłem co najmniej 4,5:1.",
+ "ruleTouchTargetSize": "Mały obszar dotyku",
+ "ruleTouchTargetSizeHelp": "Przyciski, linki i inne kontrolki potrzebują miejsca na dotknięcie: co najmniej 24 × 24 dla WCAG AA i 44 × 44 dla AAA.",
+ "ruleMinTextSize": "Mały tekst",
+ "ruleMinTextSizeHelp": "Tekst mniejszy niż 12 px jest trudny do odczytania na większości ekranów.",
+ "ruleConsistentSpacing": "Odstęp spoza skali",
+ "ruleConsistentSpacingHelp": "Odstępy i dopełnienia auto-layoutu powinny pochodzić ze skali odstępów lub być wielokrotnością 4.",
+ "detailSpacingGap": "Odstęp {value}",
+ "detailSpacingTop": "Dopełnienie górne {value}",
+ "detailSpacingRight": "Dopełnienie prawe {value}",
+ "detailSpacingBottom": "Dopełnienie dolne {value}",
+ "detailSpacingLeft": "Dopełnienie lewe {value}",
+ "ruleConsistentRadius": "Promień narożnika spoza skali",
+ "ruleConsistentRadiusHelp": "Promień narożnika powinien pochodzić ze skali promieni lub ze zmiennej.",
+ "ruleNoHardcodedColors": "Niepowiązany kolor",
+ "ruleNoHardcodedColorsHelp": "Ten kolor odpowiada zmiennej koloru. Powiąż go, aby zmiany motywu i palety docierały do tej warstwy.",
+ "detailStrokeColor": "Obrys: {variable}",
+ "bindVariable": "Powiąż z {variable}",
+ "bindAll": "Powiąż wszystkie ({count})",
+ "fixRoundPixels": "Zaokrąglij do pełnych pikseli",
+ "fixUseValue": "Zmień na {value}",
+ "fixFullRadius": "Użyj pełnego promienia",
+ "fixAll": "Popraw wszystkie ({count})",
+ "ruleNoDefaultNames": "Domyślna nazwa warstwy",
+ "ruleNoDefaultNamesHelp": "Opisowe nazwy ułatwiają znajdowanie, przekazywanie i ponowne użycie warstw.",
+ "rulePreferAutoLayout": "Brak auto-layoutu",
+ "rulePreferAutoLayoutHelp": "Ramki układające kilka warstw lepiej zmieniają rozmiar z auto-layoutem.",
+ "detailChildren": "Warstwy: {children}",
+ "ruleTextStyleRequired": "Niepowiązany styl tekstu",
+ "ruleTextStyleRequiredHelp": "Powiąż rozmiar lub krój czcionki ze zmienną, aby typografia była spójna.",
+ "ruleNoHiddenLayers": "Ukryta warstwa",
+ "ruleNoHiddenLayersHelp": "Ukryte warstwy to często pozostałości. Usuń je, jeśli żaden stan ich nie potrzebuje.",
+ "ruleNoDeeplyNested": "Głębokie zagnieżdżenie",
+ "ruleNoDeeplyNestedHelp": "Głęboko zagnieżdżone warstwy trudno edytować. Spłaszcz je lub wyodrębnij komponent.",
+ "detailDepth": "Poziomy: {depth}",
+ "ruleNoEmptyFrames": "Pusta ramka",
+ "ruleNoEmptyFramesHelp": "Ramki bez zawartości i wypełnienia to zwykle pozostałości.",
+ "rulePixelPerfect": "Geometria subpikselowa",
+ "rulePixelPerfectHelp": "Pozycje i rozmiary w pełnych pikselach wyświetlają się ostro.",
+ "ruleNoGroups": "Grupa",
+ "ruleNoGroupsHelp": "Ramki obsługują auto-layout i ograniczenia, a grupy nie.",
+ "ruleEffectStyleRequired": "Niewspółdzielony efekt",
+ "ruleEffectStyleRequiredHelp": "Używaj cieni i rozmyć ponownie przez współdzielone ustawienia lub zmienne.",
+ "ruleNoMixedStyles": "Mieszane style tekstu",
+ "ruleNoMixedStylesHelp": "Kilka stylów w jednej warstwie tekstu łatwo zepsuć podczas edycji.",
+ "ruleNoDetachedInstances": "Wygląda jak komponent",
+ "ruleNoDetachedInstancesHelp": "Ta ramka wygląda jak element wielokrotnego użytku. Użyj instancji komponentu."
+}
diff --git a/packages/vue/src/i18n/locales/pl/index.ts b/packages/vue/src/i18n/locales/pl/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/pl/index.ts
+++ b/packages/vue/src/i18n/locales/pl/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.json
index 12250fd22..9ff1cb933 100644
--- a/packages/vue/src/i18n/locales/pl/menu.json
+++ b/packages/vue/src/i18n/locales/pl/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Wyśrodkuj w pionie",
"arrangeAlignBottom": "Wyrównaj do dołu",
"multiplayerCursors": "Kursory wielu użytkowników",
+ "designIssues": "Problemy projektu",
"preferences": "Preferencje",
"snapToGeometry": "Przyciągaj do geometrii",
"snapToObjects": "Przyciągaj do obiektów",
diff --git a/packages/vue/src/i18n/locales/ru/design-check.json b/packages/vue/src/i18n/locales/ru/design-check.json
new file mode 100644
index 000000000..a768df05c
--- /dev/null
+++ b/packages/vue/src/i18n/locales/ru/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "Проверка",
+ "tabCount": "Ошибок и предупреждений: {count}",
+ "scope": "Область",
+ "scopePage": "Страница",
+ "scopeSelection": "Выделение",
+ "scopeDocument": "Документ",
+ "errors": "Ошибки",
+ "warnings": "Предупреждения",
+ "suggestions": "Рекомендации",
+ "filterBySeverity": "Показывать: {severity}",
+ "filterSeverities": "Фильтр по важности",
+ "showOnCanvas": "Показывать проблемы на холсте",
+ "rules": "Правила",
+ "presetRecommended": "Рекомендуемые",
+ "presetStrict": "Строгие",
+ "presetAccessibility": "Доступность",
+ "ruleActions": "Действия с правилом",
+ "turnOffRule": "Отключить правило",
+ "turnOnRules": "Включить отключённые правила: {count}",
+ "checking": "Проверка…",
+ "emptyPage": "На этой странице нет проблем",
+ "emptySelection": "В выделении нет проблем",
+ "emptyDocument": "В этом документе нет проблем",
+ "documentUnchecked": "Страницы ещё не проверены: {count}",
+ "onPage": "На странице {page}",
+ "emptyDescription": "Проверено по правилам «{preset}».",
+ "noSelection": "Выделите слои, чтобы проверить их",
+ "noSelectionDescription": "Здесь появятся проблемы внутри выделенных слоёв.",
+ "noFilteredIssues": "Нет проблем, подходящих под фильтры",
+ "clearFilters": "Показать все проблемы",
+ "showMore": "Показать ещё {count}",
+ "hiddenLayer": "Скрыт",
+ "missingLayer": "Удалённый слой",
+ "markerMore": "и ещё {count}",
+ "markerLayers": "Слоёв: {count}",
+ "markerHint": "Нажмите, чтобы посмотреть",
+ "edgeLeft": "За экраном слева",
+ "edgeRight": "За экраном справа",
+ "edgeAbove": "За экраном сверху",
+ "edgeBelow": "За экраном снизу",
+ "edgeHint": "Нажмите, чтобы перейти к ближайшему",
+ "layerIssues": "Ошибки и предупреждения: {count}",
+ "layerContainsIssues": "Содержит ошибки или предупреждения",
+ "ruleColorContrast": "Низкий контраст текста",
+ "ruleColorContrastHelp": "Для соответствия WCAG AA контраст текста с фоном должен быть не ниже 4,5:1.",
+ "ruleTouchTargetSize": "Маленькая область нажатия",
+ "ruleTouchTargetSizeHelp": "Кнопкам, ссылкам и другим элементам управления нужна область для нажатия: не меньше 24 × 24 для WCAG AA и 44 × 44 для AAA.",
+ "ruleMinTextSize": "Мелкий текст",
+ "ruleMinTextSizeHelp": "Текст меньше 12 px трудно читать на большинстве экранов.",
+ "ruleConsistentSpacing": "Отступ вне шкалы",
+ "ruleConsistentSpacingHelp": "Интервалы и внутренние отступы автораскладки должны браться из шкалы отступов или быть кратны 4.",
+ "detailSpacingGap": "Интервал {value}",
+ "detailSpacingTop": "Отступ сверху {value}",
+ "detailSpacingRight": "Отступ справа {value}",
+ "detailSpacingBottom": "Отступ снизу {value}",
+ "detailSpacingLeft": "Отступ слева {value}",
+ "ruleConsistentRadius": "Скругление вне шкалы",
+ "ruleConsistentRadiusHelp": "Радиус скругления должен браться из шкалы радиусов или переменной.",
+ "ruleNoHardcodedColors": "Цвет без переменной",
+ "ruleNoHardcodedColorsHelp": "Этот цвет совпадает с цветовой переменной. Привяжите его, чтобы изменения темы и палитры доходили до этого слоя.",
+ "detailStrokeColor": "Обводка: {variable}",
+ "bindVariable": "Привязать к {variable}",
+ "bindAll": "Привязать все ({count})",
+ "fixRoundPixels": "Округлить до целых пикселей",
+ "fixUseValue": "Изменить на {value}",
+ "fixFullRadius": "Использовать полное скругление",
+ "fixAll": "Исправить все ({count})",
+ "ruleNoDefaultNames": "Стандартное имя слоя",
+ "ruleNoDefaultNamesHelp": "Понятные имена помогают находить, передавать и переиспользовать слои.",
+ "rulePreferAutoLayout": "Без автораскладки",
+ "rulePreferAutoLayoutHelp": "Фреймы с несколькими слоями лучше меняют размер с автораскладкой.",
+ "detailChildren": "Слоёв: {children}",
+ "ruleTextStyleRequired": "Текстовый стиль без переменной",
+ "ruleTextStyleRequiredHelp": "Привяжите размер или гарнитуру шрифта к переменной, чтобы типографика оставалась единой.",
+ "ruleNoHiddenLayers": "Скрытый слой",
+ "ruleNoHiddenLayersHelp": "Скрытые слои часто остаются по ошибке. Удалите их, если они не нужны ни одному состоянию.",
+ "ruleNoDeeplyNested": "Глубокая вложенность",
+ "ruleNoDeeplyNestedHelp": "Глубоко вложенные слои сложно редактировать. Упростите структуру или вынесите компонент.",
+ "detailDepth": "Уровней: {depth}",
+ "ruleNoEmptyFrames": "Пустой фрейм",
+ "ruleNoEmptyFramesHelp": "Фреймы без содержимого и заливки обычно остаются по ошибке.",
+ "rulePixelPerfect": "Субпиксельная геометрия",
+ "rulePixelPerfectHelp": "Позиции и размеры в целых пикселях выглядят чётко.",
+ "ruleNoGroups": "Группа",
+ "ruleNoGroupsHelp": "Фреймы поддерживают автораскладку и ограничения, а группы — нет.",
+ "ruleEffectStyleRequired": "Общий эффект не используется",
+ "ruleEffectStyleRequiredHelp": "Переиспользуйте тени и размытия через общие пресеты или переменные.",
+ "ruleNoMixedStyles": "Смешанные стили текста",
+ "ruleNoMixedStylesHelp": "Несколько стилей в одном текстовом слое легко сломать при редактировании.",
+ "ruleNoDetachedInstances": "Похоже на компонент",
+ "ruleNoDetachedInstancesHelp": "Этот фрейм похож на переиспользуемый элемент. Используйте экземпляр компонента."
+}
diff --git a/packages/vue/src/i18n/locales/ru/index.ts b/packages/vue/src/i18n/locales/ru/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/ru/index.ts
+++ b/packages/vue/src/i18n/locales/ru/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.json
index 649d63347..e5d124315 100644
--- a/packages/vue/src/i18n/locales/ru/menu.json
+++ b/packages/vue/src/i18n/locales/ru/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "Выровнять по центру по вертикали",
"arrangeAlignBottom": "Выровнять по нижнему краю",
"multiplayerCursors": "Курсоры участников",
+ "designIssues": "Проблемы дизайна",
"preferences": "Настройки",
"snapToGeometry": "Привязка к геометрии",
"snapToObjects": "Привязка к объектам",
diff --git a/packages/vue/src/i18n/locales/zh-cn/design-check.json b/packages/vue/src/i18n/locales/zh-cn/design-check.json
new file mode 100644
index 000000000..a5fbf17b0
--- /dev/null
+++ b/packages/vue/src/i18n/locales/zh-cn/design-check.json
@@ -0,0 +1,93 @@
+{
+ "tab": "检查",
+ "tabCount": "{count} 个错误和警告",
+ "scope": "范围",
+ "scopePage": "页面",
+ "scopeSelection": "所选内容",
+ "scopeDocument": "文档",
+ "errors": "错误",
+ "warnings": "警告",
+ "suggestions": "建议",
+ "filterBySeverity": "显示{severity}",
+ "filterSeverities": "按严重程度筛选",
+ "showOnCanvas": "在画布上显示问题",
+ "rules": "规则",
+ "presetRecommended": "推荐",
+ "presetStrict": "严格",
+ "presetAccessibility": "无障碍",
+ "ruleActions": "规则操作",
+ "turnOffRule": "关闭规则",
+ "turnOnRules": "重新开启 {count} 条已关闭的规则",
+ "checking": "正在检查…",
+ "emptyPage": "此页面没有问题",
+ "emptySelection": "所选内容中没有问题",
+ "emptyDocument": "此文档中没有问题",
+ "documentUnchecked": "尚未检查的页面:{count}",
+ "onPage": "位于 {page}",
+ "emptyDescription": "已使用{preset}规则检查。",
+ "noSelection": "选择图层以进行检查",
+ "noSelectionDescription": "所选图层中的问题将显示在这里。",
+ "noFilteredIssues": "没有符合筛选条件的问题",
+ "clearFilters": "显示所有问题",
+ "showMore": "再显示 {count} 个",
+ "hiddenLayer": "已隐藏",
+ "missingLayer": "已删除的图层",
+ "markerMore": "另有 {count} 个",
+ "markerLayers": "{count} 个图层",
+ "markerHint": "点击查看",
+ "edgeLeft": "屏幕外左侧",
+ "edgeRight": "屏幕外右侧",
+ "edgeAbove": "屏幕外上方",
+ "edgeBelow": "屏幕外下方",
+ "edgeHint": "点击前往最近的一处",
+ "layerIssues": "错误和警告:{count}",
+ "layerContainsIssues": "包含错误或警告",
+ "ruleColorContrast": "文字对比度过低",
+ "ruleColorContrastHelp": "文字与背景的对比度至少需要 4.5:1 才能符合 WCAG AA。",
+ "ruleTouchTargetSize": "触控区域过小",
+ "ruleTouchTargetSizeHelp": "按钮、链接和其他控件需要足够的点按区域:WCAG AA 至少 24 × 24,AAA 至少 44 × 44。",
+ "ruleMinTextSize": "文字过小",
+ "ruleMinTextSizeHelp": "小于 12 px 的文字在大多数屏幕上难以阅读。",
+ "ruleConsistentSpacing": "间距不在规范内",
+ "ruleConsistentSpacingHelp": "自动布局的间距和内边距应取自间距规范或为 4 的倍数。",
+ "detailSpacingGap": "间距 {value}",
+ "detailSpacingTop": "上内边距 {value}",
+ "detailSpacingRight": "右内边距 {value}",
+ "detailSpacingBottom": "下内边距 {value}",
+ "detailSpacingLeft": "左内边距 {value}",
+ "ruleConsistentRadius": "圆角不在规范内",
+ "ruleConsistentRadiusHelp": "圆角半径应取自圆角规范或变量。",
+ "ruleNoHardcodedColors": "未绑定变量的颜色",
+ "ruleNoHardcodedColorsHelp": "此颜色与某个颜色变量一致。绑定后,主题和色板的更改会同步到此图层。",
+ "detailStrokeColor": "描边:{variable}",
+ "bindVariable": "绑定到 {variable}",
+ "bindAll": "全部绑定({count})",
+ "fixRoundPixels": "取整到整像素",
+ "fixUseValue": "改为 {value}",
+ "fixFullRadius": "使用完全圆角",
+ "fixAll": "全部修复({count})",
+ "ruleNoDefaultNames": "默认图层名称",
+ "ruleNoDefaultNamesHelp": "描述性的名称让图层更易查找、交付和复用。",
+ "rulePreferAutoLayout": "未使用自动布局",
+ "rulePreferAutoLayoutHelp": "排列多个图层的画框使用自动布局后更易调整尺寸。",
+ "detailChildren": "{children} 个图层",
+ "ruleTextStyleRequired": "未绑定变量的文字样式",
+ "ruleTextStyleRequiredHelp": "将字号或字体族绑定到变量,保持排版一致。",
+ "ruleNoHiddenLayers": "隐藏的图层",
+ "ruleNoHiddenLayersHelp": "隐藏的图层通常是遗留内容。如果没有状态需要,请删除。",
+ "ruleNoDeeplyNested": "嵌套过深",
+ "ruleNoDeeplyNestedHelp": "嵌套过深的图层难以编辑。请简化层级或提取为组件。",
+ "detailDepth": "{depth} 层",
+ "ruleNoEmptyFrames": "空画框",
+ "ruleNoEmptyFramesHelp": "没有内容和填充的画框通常是遗留内容。",
+ "rulePixelPerfect": "亚像素几何",
+ "rulePixelPerfectHelp": "位置和尺寸使用整数像素时显示更清晰。",
+ "ruleNoGroups": "编组",
+ "ruleNoGroupsHelp": "画框支持自动布局和约束,编组不支持。",
+ "ruleEffectStyleRequired": "未共享的效果",
+ "ruleEffectStyleRequiredHelp": "通过共享预设或变量复用阴影和模糊。",
+ "ruleNoMixedStyles": "混合文字样式",
+ "ruleNoMixedStylesHelp": "一个文字图层中的多种样式在编辑时容易被破坏。",
+ "ruleNoDetachedInstances": "看起来像组件",
+ "ruleNoDetachedInstancesHelp": "这个画框看起来像可复用元素。请使用组件实例。"
+}
diff --git a/packages/vue/src/i18n/locales/zh-cn/index.ts b/packages/vue/src/i18n/locales/zh-cn/index.ts
index 4ec11d8c7..f877b7541 100644
--- a/packages/vue/src/i18n/locales/zh-cn/index.ts
+++ b/packages/vue/src/i18n/locales/zh-cn/index.ts
@@ -7,6 +7,7 @@ import collaboration from './collaboration.json'
import commands from './commands.json'
import common from './common.json'
import credentials from './credentials.json'
+import designCheck from './design-check.json'
import diagnostics from './diagnostics.json'
import editor from './editor.json'
import files from './files.json'
@@ -33,6 +34,7 @@ export default {
commands,
common,
credentials,
+ designCheck,
diagnostics,
editor,
files,
diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.json
index 4c2ae4a71..f89fa56e2 100644
--- a/packages/vue/src/i18n/locales/zh-cn/menu.json
+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json
@@ -56,6 +56,7 @@
"arrangeAlignMiddle": "垂直居中",
"arrangeAlignBottom": "底部对齐",
"multiplayerCursors": "多人光标",
+ "designIssues": "设计问题",
"preferences": "偏好设置",
"snapToGeometry": "吸附到几何图形",
"snapToObjects": "吸附到对象",
diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.ts
index fac5eec96..311be2443 100644
--- a/packages/vue/src/i18n/messages.ts
+++ b/packages/vue/src/i18n/messages.ts
@@ -8,6 +8,7 @@ import {
import { commandMessageDefaults, commandMessages } from '#vue/i18n/messages/commands'
import { commonMessageDefaults, commonMessages } from '#vue/i18n/messages/common'
import { credentialsMessageDefaults, credentialsMessages } from '#vue/i18n/messages/credentials'
+import { designCheckMessageDefaults, designCheckMessages } from '#vue/i18n/messages/design-check'
import { diagnosticsMessageDefaults, diagnosticsMessages } from '#vue/i18n/messages/diagnostics'
import { editorMessageDefaults, editorMessages } from '#vue/i18n/messages/editor'
import { filesMessageDefaults, filesMessages } from '#vue/i18n/messages/files'
@@ -37,6 +38,7 @@ export {
commandMessages,
commonMessages,
credentialsMessages,
+ designCheckMessages,
diagnosticsMessages,
editorMessages,
filesMessages,
@@ -64,6 +66,7 @@ export const messageDefaults = {
commands: commandMessageDefaults,
common: commonMessageDefaults,
credentials: credentialsMessageDefaults,
+ designCheck: designCheckMessageDefaults,
diagnostics: diagnosticsMessageDefaults,
editor: editorMessageDefaults,
files: filesMessageDefaults,
diff --git a/packages/vue/src/i18n/messages/design-check.ts b/packages/vue/src/i18n/messages/design-check.ts
new file mode 100644
index 000000000..e38331370
--- /dev/null
+++ b/packages/vue/src/i18n/messages/design-check.ts
@@ -0,0 +1,106 @@
+import { params } from '@nanostores/i18n'
+
+import { i18n } from '#vue/i18n/create'
+
+export const designCheckMessageDefaults = {
+ tab: 'Lint',
+ tabCount: params('errors and warnings: {count}'),
+ scope: 'Scope',
+ scopePage: 'Page',
+ scopeSelection: 'Selection',
+ scopeDocument: 'Document',
+ errors: 'Errors',
+ warnings: 'Warnings',
+ suggestions: 'Suggestions',
+ filterBySeverity: params('Show {severity}'),
+ filterSeverities: 'Filter by severity',
+ showOnCanvas: 'Show issues on canvas',
+ rules: 'Rules',
+ presetRecommended: 'Recommended',
+ presetStrict: 'Strict',
+ presetAccessibility: 'Accessibility',
+ ruleActions: 'Rule actions',
+ turnOffRule: 'Turn off rule',
+ turnOnRules: params('Turn on {count} turned-off rules'),
+ checking: 'Checking…',
+ emptyPage: 'No issues on this page',
+ emptySelection: 'No issues in the selection',
+ emptyDocument: 'No issues in this document',
+ documentUnchecked: params('Pages not checked yet: {count}'),
+ onPage: params('On {page}'),
+ emptyDescription: params('Checked with {preset} rules.'),
+ noSelection: 'Select layers to check them',
+ noSelectionDescription: 'Issues inside the selected layers appear here.',
+ noFilteredIssues: 'No issues match the filters',
+ clearFilters: 'Show all issues',
+ showMore: params('Show {count} more'),
+ hiddenLayer: 'Hidden',
+ missingLayer: 'Deleted layer',
+ markerMore: params('+{count} more'),
+ markerLayers: params('{count} layers'),
+ markerHint: 'Click to review',
+ edgeLeft: 'Off screen to the left',
+ edgeRight: 'Off screen to the right',
+ edgeAbove: 'Off screen above',
+ edgeBelow: 'Off screen below',
+ edgeHint: 'Click to go to the nearest',
+ layerIssues: params('Errors and warnings: {count}'),
+ layerContainsIssues: 'Contains errors or warnings',
+ ruleColorContrast: 'Low text contrast',
+ ruleColorContrastHelp:
+ 'Text needs a contrast ratio of at least 4.5:1 with its background to meet WCAG AA.',
+ ruleTouchTargetSize: 'Small touch target',
+ ruleTouchTargetSizeHelp:
+ 'Buttons, links and other controls need room to tap: at least 24 × 24 for WCAG AA, 44 × 44 for AAA.',
+ ruleMinTextSize: 'Small text',
+ ruleMinTextSizeHelp: 'Text smaller than 12 px is hard to read on most screens.',
+ ruleConsistentSpacing: 'Off-scale spacing',
+ ruleConsistentSpacingHelp:
+ 'Auto layout gaps and padding should come from the spacing scale or a multiple of 4.',
+ detailSpacingGap: params('Gap {value}'),
+ detailSpacingTop: params('Top padding {value}'),
+ detailSpacingRight: params('Right padding {value}'),
+ detailSpacingBottom: params('Bottom padding {value}'),
+ detailSpacingLeft: params('Left padding {value}'),
+ ruleConsistentRadius: 'Off-scale corner radius',
+ ruleConsistentRadiusHelp: 'Corner radius should come from the radius scale or a variable.',
+ ruleNoHardcodedColors: 'Unbound color',
+ ruleNoHardcodedColorsHelp:
+ 'This color matches a color variable. Bind it so theme and palette changes reach this layer.',
+ detailStrokeColor: params('Stroke: {variable}'),
+ bindVariable: params('Bind to {variable}'),
+ bindAll: params('Bind all {count}'),
+ fixRoundPixels: 'Round to whole pixels',
+ fixUseValue: params('Change to {value}'),
+ fixFullRadius: 'Use full radius',
+ fixAll: params('Fix all {count}'),
+ ruleNoDefaultNames: 'Default layer name',
+ ruleNoDefaultNamesHelp: 'Descriptive names make layers easier to find, hand off and reuse.',
+ rulePreferAutoLayout: 'No auto layout',
+ rulePreferAutoLayoutHelp: 'Frames that stack several layers resize better with auto layout.',
+ detailChildren: params('{children} layers'),
+ ruleTextStyleRequired: 'Unbound text style',
+ ruleTextStyleRequiredHelp:
+ 'Bind font size or family to a variable to keep typography consistent.',
+ ruleNoHiddenLayers: 'Hidden layer',
+ ruleNoHiddenLayersHelp:
+ 'Hidden layers are often leftovers. Delete them unless a state needs them.',
+ ruleNoDeeplyNested: 'Deep nesting',
+ ruleNoDeeplyNestedHelp:
+ 'Deeply nested layers are hard to edit. Flatten them or extract a component.',
+ detailDepth: params('{depth} levels'),
+ ruleNoEmptyFrames: 'Empty frame',
+ ruleNoEmptyFramesHelp: 'Frames without content or fill are usually leftovers.',
+ rulePixelPerfect: 'Subpixel geometry',
+ rulePixelPerfectHelp: 'Whole-pixel positions and sizes render crisply.',
+ ruleNoGroups: 'Group',
+ ruleNoGroupsHelp: 'Frames support auto layout and constraints; groups do not.',
+ ruleEffectStyleRequired: 'Unshared effect',
+ ruleEffectStyleRequiredHelp: 'Reuse shadows and blurs through shared presets or variables.',
+ ruleNoMixedStyles: 'Mixed text styles',
+ ruleNoMixedStylesHelp: 'Several styles in one text layer are easy to break when editing.',
+ ruleNoDetachedInstances: 'Looks like a component',
+ ruleNoDetachedInstancesHelp: 'This frame looks like a reusable element. Use a component instance.'
+} as const
+
+export const designCheckMessages = i18n('designCheck', designCheckMessageDefaults)
diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.ts
index dcfc91e80..f9d9cc7cb 100644
--- a/packages/vue/src/i18n/messages/menu.ts
+++ b/packages/vue/src/i18n/messages/menu.ts
@@ -33,6 +33,7 @@ export const menuMessageDefaults = {
settings: 'Settings…',
rulers: 'Rulers',
multiplayerCursors: 'Multiplayer cursors',
+ designIssues: 'Design issues',
preferences: 'Preferences',
snapToGeometry: 'Snap to geometry',
snapToObjects: 'Snap to objects',
diff --git a/packages/vue/src/i18n/useI18n.ts b/packages/vue/src/i18n/useI18n.ts
index 3c289df58..44714d1b2 100644
--- a/packages/vue/src/i18n/useI18n.ts
+++ b/packages/vue/src/i18n/useI18n.ts
@@ -12,6 +12,7 @@ import {
commandMessages,
commonMessages,
credentialsMessages,
+ designCheckMessages,
diagnosticsMessages,
editorMessages,
filesMessages,
@@ -42,6 +43,7 @@ export const useCollaborationMessages = () => useI18nNamespace(collaborationMess
export const useCommandMessages = () => useI18nNamespace(commandMessages)
export const useCommonMessages = () => useI18nNamespace(commonMessages)
export const useCredentialMessages = () => useI18nNamespace(credentialsMessages)
+export const useDesignCheckMessages = () => useI18nNamespace(designCheckMessages)
export const useDiagnosticsMessages = () => useI18nNamespace(diagnosticsMessages)
export const useEditorMessages = () => useI18nNamespace(editorMessages)
export const useFileMessages = () => useI18nNamespace(filesMessages)
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 4ad363c0e..3edb16bd7 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -23,6 +23,8 @@ export type { PresentationColorSpace } from '#vue/canvas/surface/color-space'
export { useCanvas } from '#vue/canvas/surface/use'
export type { UseCanvasOptions } from '#vue/canvas/surface/use'
export { useCanvasInput } from '#vue/canvas/useCanvasInput'
+export { useCanvasIssueMarkers } from '#vue/canvas/issues/use'
+export type { CanvasIssueMarkerOptions } from '#vue/canvas/issues/use'
export type { CanvasLabelEdit, CanvasLabelKind } from '#vue/canvas/labels/edit'
export { useCanvasVirtualReference } from '#vue/canvas/overlays/useCanvasVirtualReference'
export { useTextEdit } from '#vue/canvas/text-edit/use'
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 80c7bbc3b..0e65d4979 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -124,8 +124,11 @@ openpencil analyze spacing design.fig --grid 8
openpencil analyze clusters design.fig --min-count 3
openpencil lint design.fig
openpencil lint design.fig --json
+openpencil lint design.fig --fix -o fixed.fig # bind matching color variables, round to whole pixels
```
+In MCP and AI chat, `lint` lists findings with their `fix` and `suggestions`; `lint_fix` applies the safe fixes, and the first suggestion of each finding with `suggestions: true`.
+
### Eval (Figma Plugin API)
Execute JavaScript against the document using a Figma Plugin API-compatible runtime:
diff --git a/src/app.css b/src/app.css
index 405d9182f..05c10cfa5 100644
--- a/src/app.css
+++ b/src/app.css
@@ -71,6 +71,9 @@
--color-primary: #60a5fa;
--color-inverted: #1f2328;
--color-error: #f87171;
+ --color-issue-error: #f24822;
+ --color-issue-warning: #ffb314;
+ --color-issue-info: #a6a6a6;
--color-error-bg: rgb(248 113 113 / 0.1);
--color-error-border: rgb(248 113 113 / 0.4);
--color-success-bg: #16a34a;
@@ -112,6 +115,9 @@ html[data-theme='light'] {
--color-warning-action: #78350f;
--color-success: #15803d;
--color-error: #b91c1c;
+ --color-issue-error: #dc3412;
+ --color-issue-warning: #b86e00;
+ --color-issue-info: #6b7280;
--color-error-bg: rgb(185 28 28 / 0.08);
--color-error-border: rgb(185 28 28 / 0.28);
--color-success-bg: #16a34a;
diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.ts
index a2d4c7937..72f08b717 100644
--- a/src/app/ai/chat/use.ts
+++ b/src/app/ai/chat/use.ts
@@ -33,7 +33,9 @@ import {
setRememberCredentials
} from '@/app/settings/credentials/media'
-const activeTab = ref<'design' | 'code' | 'ai'>('design')
+export type PropertiesTab = 'design' | 'code' | 'ai' | 'lint'
+
+const activeTab = ref<PropertiesTab>('design')
const chatSession = createChatSessionManager({
isConfigured,
diff --git a/src/app/editor/canvas/obstacles.ts b/src/app/editor/canvas/obstacles.ts
new file mode 100644
index 000000000..8548cabc7
--- /dev/null
+++ b/src/app/editor/canvas/obstacles.ts
@@ -0,0 +1,17 @@
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+/** Marks UI that floats over the canvas, such as the toolbar, for overlays to keep clear of. */
+const CANVAS_OBSTACLE_ATTRIBUTE = 'data-canvas-obstacle'
+
+/** Floating UI over a canvas, as rectangles in the canvas's CSS pixels. */
+export function canvasOverlayObstacles(canvas: HTMLElement | null): Rect[] {
+ if (!canvas) return []
+ const box = canvas.getBoundingClientRect()
+ return [...document.querySelectorAll(`[${CANVAS_OBSTACLE_ATTRIBUTE}]`)].flatMap((element) => {
+ const rect = element.getBoundingClientRect()
+ if (rect.width === 0 || rect.height === 0) return []
+ return [
+ { x: rect.left - box.left, y: rect.top - box.top, width: rect.width, height: rect.height }
+ ]
+ })
+}
diff --git a/src/app/editor/design-check/format.ts b/src/app/editor/design-check/format.ts
new file mode 100644
index 000000000..abdf54e69
--- /dev/null
+++ b/src/app/editor/design-check/format.ts
@@ -0,0 +1,202 @@
+import type { LintFix, LintFixRequest } from '@open-pencil/core/lint'
+import { locale, type useDesignCheckMessages } from '@open-pencil/vue'
+
+import type { DesignIssue } from './issues'
+
+export type DesignCheckMessages = ReturnType<typeof useDesignCheckMessages>['value']
+type Messages = DesignCheckMessages
+
+type StringKey = {
+ [Key in keyof Messages]: Messages[Key] extends string ? Key : never
+}[keyof Messages]
+
+interface RuleCopy {
+ title: StringKey
+ help: StringKey
+}
+
+const RULE_COPY: Partial<Record<string, RuleCopy>> = {
+ 'color-contrast': { title: 'ruleColorContrast', help: 'ruleColorContrastHelp' },
+ 'touch-target-size': { title: 'ruleTouchTargetSize', help: 'ruleTouchTargetSizeHelp' },
+ 'min-text-size': { title: 'ruleMinTextSize', help: 'ruleMinTextSizeHelp' },
+ 'consistent-spacing': { title: 'ruleConsistentSpacing', help: 'ruleConsistentSpacingHelp' },
+ 'consistent-radius': { title: 'ruleConsistentRadius', help: 'ruleConsistentRadiusHelp' },
+ 'no-hardcoded-colors': { title: 'ruleNoHardcodedColors', help: 'ruleNoHardcodedColorsHelp' },
+ 'no-default-names': { title: 'ruleNoDefaultNames', help: 'ruleNoDefaultNamesHelp' },
+ 'prefer-auto-layout': { title: 'rulePreferAutoLayout', help: 'rulePreferAutoLayoutHelp' },
+ 'text-style-required': { title: 'ruleTextStyleRequired', help: 'ruleTextStyleRequiredHelp' },
+ 'no-hidden-layers': { title: 'ruleNoHiddenLayers', help: 'ruleNoHiddenLayersHelp' },
+ 'no-deeply-nested': { title: 'ruleNoDeeplyNested', help: 'ruleNoDeeplyNestedHelp' },
+ 'no-empty-frames': { title: 'ruleNoEmptyFrames', help: 'ruleNoEmptyFramesHelp' },
+ 'pixel-perfect': { title: 'rulePixelPerfect', help: 'rulePixelPerfectHelp' },
+ 'no-groups': { title: 'ruleNoGroups', help: 'ruleNoGroupsHelp' },
+ 'effect-style-required': {
+ title: 'ruleEffectStyleRequired',
+ help: 'ruleEffectStyleRequiredHelp'
+ },
+ 'no-mixed-styles': { title: 'ruleNoMixedStyles', help: 'ruleNoMixedStylesHelp' },
+ 'no-detached-instances': {
+ title: 'ruleNoDetachedInstances',
+ help: 'ruleNoDetachedInstancesHelp'
+ }
+}
+
+const SPACING_DETAIL = {
+ itemSpacing: 'detailSpacingGap',
+ paddingTop: 'detailSpacingTop',
+ paddingRight: 'detailSpacingRight',
+ paddingBottom: 'detailSpacingBottom',
+ paddingLeft: 'detailSpacingLeft'
+} as const
+
+/** Figma's geometry field labels, which stay untranslated across its locales. */
+const GEOMETRY_LABELS: Record<string, string> = { x: 'X', y: 'Y', width: 'W', height: 'H' }
+
+const numberFormats = new Map<string, Intl.NumberFormat>()
+
+/** Numbers follow the app's language, not the browser's, like the rest of the panel. */
+function formatNumber(value: number): string {
+ const language = locale.get()
+ let format = numberFormats.get(language)
+ if (!format) {
+ format = new Intl.NumberFormat(language, { maximumFractionDigits: 2 })
+ numberFormats.set(language, format)
+ }
+ return format.format(value)
+}
+
+function numberAt(issue: DesignIssue, key: string): number | undefined {
+ const value = issue.data?.[key]
+ return typeof value === 'number' ? value : undefined
+}
+
+function stringAt(issue: DesignIssue, key: string): string | undefined {
+ const value = issue.data?.[key]
+ return typeof value === 'string' ? value : undefined
+}
+
+/**
+ * The last two segments of a grouped variable name: `Colors/Blue/600` reads as `Blue/600`,
+ * which is enough next to its swatch in a narrow row.
+ */
+export function shortVariableName(name: string): string {
+ const segments = name.split('/')
+ return segments.length > 2 ? segments.slice(-2).join('/') : name
+}
+
+/** Rules without copy, such as custom rules, fall back to their id and raw message. */
+export function ruleTitle(ruleId: string, messages: Messages): string {
+ const copy = RULE_COPY[ruleId]
+ return copy ? messages[copy.title] : ruleId
+}
+
+export function ruleHelp(ruleId: string, messages: Messages): string | null {
+ const copy = RULE_COPY[ruleId]
+ return copy ? messages[copy.help] : null
+}
+
+/** The value that makes this finding different from others of the same rule. */
+// One case per rule keeps each presentation next to its data contract.
+// eslint-disable-next-line complexity
+export function issueDetail(issue: DesignIssue, messages: Messages): string | null {
+ const px = (value: number | undefined) => (value === undefined ? '' : `${formatNumber(value)} px`)
+ switch (issue.ruleId) {
+ case 'color-contrast': {
+ const ratio = numberAt(issue, 'ratio')
+ return ratio === undefined ? null : `${formatNumber(ratio)}:1`
+ }
+ case 'touch-target-size': {
+ const width = numberAt(issue, 'width')
+ const height = numberAt(issue, 'height')
+ if (width === undefined || height === undefined) return null
+ return `${formatNumber(width)} × ${formatNumber(height)}`
+ }
+ case 'min-text-size':
+ return px(numberAt(issue, 'fontSize')) || null
+ case 'consistent-radius':
+ return px(numberAt(issue, 'radius')) || null
+ case 'consistent-spacing': {
+ const property = stringAt(issue, 'property')
+ const value = numberAt(issue, 'value')
+ const key =
+ property && property in SPACING_DETAIL
+ ? SPACING_DETAIL[property as keyof typeof SPACING_DETAIL]
+ : null
+ if (!key || value === undefined) return null
+ return messages[key]({ value: formatNumber(value) })
+ }
+ case 'no-hardcoded-colors': {
+ const name = stringAt(issue, 'variableName')
+ if (!name) return null
+ const variable = shortVariableName(name)
+ return stringAt(issue, 'paint') === 'stroke'
+ ? messages.detailStrokeColor({ variable })
+ : variable
+ }
+ case 'prefer-auto-layout': {
+ const children = numberAt(issue, 'children')
+ return children === undefined ? null : messages.detailChildren({ children })
+ }
+ case 'no-deeply-nested': {
+ const depth = numberAt(issue, 'depth')
+ return depth === undefined ? null : messages.detailDepth({ depth })
+ }
+ case 'pixel-perfect': {
+ const parts = Object.entries(GEOMETRY_LABELS).flatMap(([key, label]) => {
+ const value = numberAt(issue, key)
+ return value === undefined ? [] : [`${label} ${formatNumber(value)}`]
+ })
+ return parts.length > 0 ? parts.join(', ') : null
+ }
+ default:
+ return RULE_COPY[issue.ruleId] ? null : issue.message
+ }
+}
+
+export type IssueSwatch =
+ | { kind: 'color'; color: string }
+ | { kind: 'contrast'; foreground: string; background: string }
+
+/** A preview of the colors a finding is about: the paint, or text on its background. */
+export function issueSwatch(issue: DesignIssue): IssueSwatch | null {
+ if (issue.ruleId === 'no-hardcoded-colors') {
+ const color = stringAt(issue, 'color')
+ return color ? { kind: 'color', color } : null
+ }
+ if (issue.ruleId === 'color-contrast') {
+ const foreground = stringAt(issue, 'foreground')
+ const background = stringAt(issue, 'background')
+ return foreground && background ? { kind: 'contrast', foreground, background } : null
+ }
+ return null
+}
+
+/** Full radius, the pill shape Figma writes for a corner radius larger than the layer. */
+const FULL_RADIUS = 9999
+
+/** The one-step fix a row offers: the rule's safe fix, or else its first suggestion. */
+export interface IssueAction {
+ request: LintFixRequest
+ label: string
+ kind: LintFix['kind']
+}
+
+function fixLabel(fix: LintFix, messages: Messages): string {
+ if (fix.kind === 'bind-variable') {
+ return messages.bindVariable({ variable: fix.variableName })
+ }
+ const changes = Object.entries(fix.changes)
+ // Geometry changes only come from rounding to whole pixels.
+ if (changes.length !== 1 || changes.some(([property]) => property in GEOMETRY_LABELS)) {
+ return messages.fixRoundPixels
+ }
+ const [property, value] = changes[0]
+ if (property === 'cornerRadius' && value === FULL_RADIUS) return messages.fixFullRadius
+ return messages.fixUseValue({ value: `${formatNumber(value)} px` })
+}
+
+export function issueAction(issue: DesignIssue, messages: Messages): IssueAction | null {
+ const fix = issue.fix ?? issue.suggestions?.[0]
+ if (!fix) return null
+ return { request: { nodeId: issue.nodeId, fix }, label: fixLabel(fix, messages), kind: fix.kind }
+}
diff --git a/src/app/editor/design-check/issues.ts b/src/app/editor/design-check/issues.ts
new file mode 100644
index 000000000..9b6b27bfd
--- /dev/null
+++ b/src/app/editor/design-check/issues.ts
@@ -0,0 +1,134 @@
+import {
+ issueSeverityRank,
+ type DesignIssueHighlight,
+ type DesignIssueMarker,
+ type DesignIssueSeverity
+} from '@open-pencil/core/canvas'
+import type { LintMessage } from '@open-pencil/core/lint'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+export type { DesignIssueSeverity }
+
+/** A lint message with an identity that survives re-checks while the finding persists. */
+export interface DesignIssue extends LintMessage {
+ id: string
+ /** The page the layer is on. */
+ pageId: string
+}
+
+export interface DesignIssueGroup {
+ ruleId: string
+ severity: DesignIssueSeverity
+ issues: DesignIssue[]
+}
+
+export type DesignIssueCounts = Record<DesignIssueSeverity, number>
+
+export const DESIGN_ISSUE_SEVERITIES: readonly DesignIssueSeverity[] = ['error', 'warning', 'info']
+
+/** Sorts the most severe first. */
+export function compareIssueSeverity(
+ a: { severity: DesignIssueSeverity },
+ b: { severity: DesignIssueSeverity }
+): number {
+ return issueSeverityRank(b.severity) - issueSeverityRank(a.severity)
+}
+
+/**
+ * Identifies each finding by rule, layer and its position among that rule's findings on the
+ * layer, so a row keeps its hover and focus state when an unrelated edit re-runs the check.
+ */
+export function toDesignIssues(messages: readonly LintMessage[], pageId: string): DesignIssue[] {
+ const seen = new Map<string, number>()
+ return messages.map((message) => {
+ const base = `${message.ruleId}:${message.nodeId}`
+ const index = seen.get(base) ?? 0
+ seen.set(base, index + 1)
+ return { ...message, id: `${base}:${index}`, pageId }
+ })
+}
+
+export function countIssues(issues: readonly DesignIssue[]): DesignIssueCounts {
+ const counts: DesignIssueCounts = { error: 0, warning: 0, info: 0 }
+ for (const issue of issues) counts[issue.severity]++
+ return counts
+}
+
+/**
+ * One marker per layer with errors or warnings. Suggestions stay in the panel: they are
+ * common enough that marking every one would bury the problems that need attention.
+ */
+export function markersForIssues(issues: readonly DesignIssue[]): DesignIssueMarker[] {
+ const markers = new Map<string, DesignIssueMarker>()
+ for (const issue of issues) {
+ if (issue.severity === 'info') continue
+ const marker = markers.get(issue.nodeId)
+ if (!marker) {
+ markers.set(issue.nodeId, { nodeId: issue.nodeId, severity: issue.severity, count: 1 })
+ continue
+ }
+ marker.count++
+ if (compareIssueSeverity(issue, marker) < 0) {
+ marker.severity = issue.severity
+ }
+ }
+ return [...markers.values()]
+}
+
+/** Groups findings by rule, most severe and then most frequent first; rows keep layer order. */
+export function groupIssuesByRule(issues: readonly DesignIssue[]): DesignIssueGroup[] {
+ const groups = new Map<string, DesignIssueGroup>()
+ for (const issue of issues) {
+ const group = groups.get(issue.ruleId)
+ if (group) group.issues.push(issue)
+ else
+ groups.set(issue.ruleId, { ruleId: issue.ruleId, severity: issue.severity, issues: [issue] })
+ }
+ return [...groups.values()].sort(
+ (a, b) =>
+ compareIssueSeverity(a, b) ||
+ b.issues.length - a.issues.length ||
+ a.ruleId.localeCompare(b.ruleId)
+ )
+}
+
+/** Findings on the given layers or anywhere inside them. */
+export function issuesWithin(
+ issues: readonly DesignIssue[],
+ graph: Pick<SceneGraph, 'getNode'>,
+ rootIds: ReadonlySet<string>
+): DesignIssue[] {
+ if (rootIds.size === 0) return []
+ const inside = new Map<string, boolean>()
+ function isInside(nodeId: string): boolean {
+ const known = inside.get(nodeId)
+ if (known !== undefined) return known
+ const node = graph.getNode(nodeId)
+ const result = rootIds.has(nodeId) || (!!node?.parentId && isInside(node.parentId))
+ inside.set(nodeId, result)
+ return result
+ }
+ return issues.filter((issue) => isInside(issue.nodeId))
+}
+
+function numberData(issue: DesignIssue, key: string): number | undefined {
+ const value = issue.data?.[key]
+ return typeof value === 'number' ? value : undefined
+}
+
+export function highlightForIssue(issue: DesignIssue): DesignIssueHighlight {
+ const minSize = issue.ruleId === 'touch-target-size' ? numberData(issue, 'minSize') : undefined
+ return {
+ nodeId: issue.nodeId,
+ severity: issue.severity,
+ minSize: minSize ? { width: minSize, height: minSize } : undefined
+ }
+}
+
+export function mostSevereIssue(issues: readonly DesignIssue[]): DesignIssue | undefined {
+ let result: DesignIssue | undefined
+ for (const issue of issues) {
+ if (!result || compareIssueSeverity(issue, result) < 0) result = issue
+ }
+ return result
+}
diff --git a/src/app/editor/design-check/layers.ts b/src/app/editor/design-check/layers.ts
new file mode 100644
index 000000000..1c9bbce98
--- /dev/null
+++ b/src/app/editor/design-check/layers.ts
@@ -0,0 +1,55 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import {
+ compareIssueSeverity,
+ type DesignIssue,
+ type DesignIssueSeverity
+} from '@/app/editor/design-check/issues'
+
+/** What the Layers panel shows for a layer: its own issues, or issues inside it. */
+export interface LayerIssueMark {
+ /** The most severe issue on the layer itself, or inside it when it has none of its own. */
+ severity: DesignIssueSeverity
+ /** Errors and warnings on the layer itself. */
+ count: number
+ /** Whether the layer has issues of its own; otherwise they are in its descendants. */
+ own: boolean
+}
+
+function moreSevere(a: DesignIssueSeverity, b: DesignIssueSeverity): DesignIssueSeverity {
+ return compareIssueSeverity({ severity: a }, { severity: b }) <= 0 ? a : b
+}
+
+/**
+ * Marks for the Layers panel, like an IDE marks files and the folders holding them: a layer
+ * with errors or warnings is marked with the most severe, and each of its ancestors is marked
+ * as containing one. Suggestions are left to the Lint panel, as on the canvas.
+ */
+export function layerIssueMarks(
+ issues: readonly DesignIssue[],
+ graph: SceneGraph
+): Map<string, LayerIssueMark> {
+ const marks = new Map<string, LayerIssueMark>()
+ for (const issue of issues) {
+ if (issue.severity === 'info') continue
+ const mark = marks.get(issue.nodeId)
+ marks.set(issue.nodeId, {
+ severity: mark?.own ? moreSevere(mark.severity, issue.severity) : issue.severity,
+ count: (mark?.own ? mark.count : 0) + 1,
+ own: true
+ })
+ let parentId = graph.getNode(issue.nodeId)?.parentId
+ while (parentId) {
+ const parent = graph.getNode(parentId)
+ if (!parent || parent.type === 'CANVAS') break
+ const existing = marks.get(parentId)
+ if (!existing) {
+ marks.set(parentId, { severity: issue.severity, count: 0, own: false })
+ } else if (!existing.own) {
+ existing.severity = moreSevere(existing.severity, issue.severity)
+ }
+ parentId = parent.parentId
+ }
+ }
+ return marks
+}
diff --git a/src/app/editor/design-check/pages.ts b/src/app/editor/design-check/pages.ts
new file mode 100644
index 000000000..c7d58b29b
--- /dev/null
+++ b/src/app/editor/design-check/pages.ts
@@ -0,0 +1,156 @@
+import { useTimeoutFn } from '@vueuse/core'
+import { computed, ref, shallowRef } from 'vue'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { countIssues, type DesignIssue, type DesignIssueCounts } from './issues'
+
+/** Pause after an edit before other pages are checked in the background. */
+const BACKGROUND_DELAY_MS = 800
+/** Pause between two background page checks, which keeps input responsive. */
+const BACKGROUND_STEP_MS = 32
+
+export interface PageChecksOptions {
+ graph: () => SceneGraph
+ currentPageId: () => string
+ /** Pages a large `.fig` file has not loaded yet; checking them would load them. */
+ isPending: (pageId: string) => boolean
+ /** Whether an interactive edit is under way, which background checks wait out. */
+ isBusy: () => boolean
+ check: (pageId: string) => DesignIssue[]
+ /** Pauses before checking after an edit, and between pages; tests pass zero. */
+ delays?: { idle: number; step: number }
+}
+
+/** The page holding a layer, or the page itself. */
+export function pageOf(graph: SceneGraph, nodeId: string | null | undefined): string | null {
+ let node = nodeId ? graph.getNode(nodeId) : undefined
+ while (node && node.type !== 'CANVAS')
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ return node?.id ?? null
+}
+
+/**
+ * Keeps every loaded page checked, one page at a time while the editor is idle, so the page list
+ * and the Document scope can show issues beyond the current page. The current page is checked
+ * live by the session, which reports its results here. Pages not loaded yet are left out.
+ */
+export function createPageChecks(options: PageChecksOptions) {
+ const results = shallowRef<ReadonlyMap<string, readonly DesignIssue[]>>(new Map())
+ const stale = new Set<string>()
+ const active = ref(false)
+ const { idle = BACKGROUND_DELAY_MS, step: stepDelay = BACKGROUND_STEP_MS } = options.delays ?? {}
+ const delay = ref(idle)
+ const timer = useTimeoutFn(step, delay, { immediate: false })
+
+ function schedule(wait: number) {
+ if (!active.value) return
+ delay.value = wait
+ timer.start()
+ }
+
+ function store(pageId: string, issues: readonly DesignIssue[] | null) {
+ const next = new Map(results.value)
+ if (issues) next.set(pageId, issues)
+ else next.delete(pageId)
+ results.value = next
+ }
+
+ function nextPage(): string | null {
+ const graph = options.graph()
+ const current = options.currentPageId()
+ for (const pageId of stale) {
+ if (!graph.getNode(pageId)) {
+ stale.delete(pageId)
+ store(pageId, null)
+ continue
+ }
+ if (pageId !== current && !options.isPending(pageId)) return pageId
+ }
+ return null
+ }
+
+ function step() {
+ if (!active.value) return
+ if (options.isBusy()) {
+ schedule(idle)
+ return
+ }
+ const pageId = nextPage()
+ if (!pageId) return
+ stale.delete(pageId)
+ store(pageId, options.check(pageId))
+ if (nextPage()) schedule(stepDelay)
+ }
+
+ /** The live result for the current page. */
+ function report(pageId: string, issues: readonly DesignIssue[]) {
+ stale.delete(pageId)
+ store(pageId, issues)
+ }
+
+ /** A page changed: its result is out of date until it is checked again. */
+ function invalidate(pageId: string | null) {
+ if (!pageId) return
+ stale.add(pageId)
+ schedule(idle)
+ }
+
+ /** Rules or the document changed: every page is checked again. */
+ function invalidateAll() {
+ results.value = new Map()
+ stale.clear()
+ for (const page of options.graph().getPages()) stale.add(page.id)
+ schedule(idle)
+ }
+
+ function start() {
+ if (active.value) return
+ active.value = true
+ invalidateAll()
+ }
+
+ function stop() {
+ active.value = false
+ timer.stop()
+ stale.clear()
+ results.value = new Map()
+ }
+
+ /** Errors and warnings per checked page; suggestions stay in the Lint panel. */
+ const counts = computed(() => {
+ const byPage = new Map<string, DesignIssueCounts>()
+ for (const [pageId, issues] of results.value) byPage.set(pageId, countIssues(issues))
+ return byPage
+ })
+
+ const unchecked = computed(() =>
+ options
+ .graph()
+ .getPages()
+ .filter((page) => !results.value.has(page.id))
+ )
+ /** Loaded pages waiting for their check. */
+ const queued = computed(() =>
+ unchecked.value.filter((page) => !options.isPending(page.id)).map((page) => page.id)
+ )
+ /** Pages a large file has not loaded yet; they are checked once opened. */
+ const notLoaded = computed(() =>
+ unchecked.value.filter((page) => options.isPending(page.id)).map((page) => page.id)
+ )
+
+ return {
+ results,
+ counts,
+ queued,
+ notLoaded,
+ active,
+ report,
+ invalidate,
+ invalidateAll,
+ start,
+ stop
+ }
+}
+
+export type PageChecks = ReturnType<typeof createPageChecks>
diff --git a/src/app/editor/design-check/session.ts b/src/app/editor/design-check/session.ts
new file mode 100644
index 000000000..2672319a2
--- /dev/null
+++ b/src/app/editor/design-check/session.ts
@@ -0,0 +1,271 @@
+import { useTimeoutFn } from '@vueuse/core'
+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'
+
+import {
+ highlightForIssue,
+ markersForIssues,
+ mostSevereIssue,
+ toDesignIssues,
+ type DesignIssue
+} from './issues'
+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 = 48
+
+export interface DesignCheckSnapshot {
+ pageId: string
+ issues: DesignIssue[]
+}
+
+function linterConfig(preset: DesignCheckPreset, disabledRules: readonly string[]): LintConfig {
+ return {
+ extends: preset,
+ rules: Object.fromEntries(disabledRules.map((rule) => [rule, 'off' as const]))
+ }
+}
+
+/**
+ * Keeps the current page checked while the Check panel is open or canvas markers are on.
+ *
+ * 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 }
+) {
+ const scope = effectScope(true)
+ const snapshot = shallowRef<DesignCheckSnapshot | null>(null)
+ const panelVisible = ref(false)
+ const focusedIssueId = ref<string | null>(null)
+
+ const preferences = computed(() => appPreferences.value.designCheck)
+ const enabled = computed(() => panelVisible.value || preferences.value.showOnCanvas)
+ // Primitive keys keep unrelated preference changes, like toggling markers, from rebuilding rules.
+ const preset = computed(() => preferences.value.preset)
+ const disabledRules = computed(() => preferences.value.disabledRules.join('\n'))
+ const linter = computed(() =>
+ createLinter({
+ config: linterConfig(preset.value, disabledRules.value ? disabledRules.value.split('\n') : [])
+ })
+ )
+
+ function checkPage(pageId: string): DesignIssue[] {
+ return toDesignIssues(linter.value.lintGraph(editor.graph, [pageId]).messages, pageId)
+ }
+
+ /** Set while the Lint panel lists the whole document, which needs every page checked. */
+ const documentScope = ref(false)
+ // Pages beyond the current one are checked for the page list and the Document scope.
+ const pagesNeeded = computed(
+ () => enabled.value && (preferences.value.showOnCanvas || documentScope.value)
+ )
+ // Stopped in dispose, so it needs no effect scope of its own.
+ const pages = createPageChecks({
+ graph: () => editor.graph,
+ currentPageId: () => state.currentPageId,
+ isPending: (pageId) => isFigPagePending(editor.graph, pageId),
+ isBusy: () => editor.isInteractiveEditing(),
+ check: checkPage
+ })
+
+ /** Marks the pages a graph change touches as out of date. */
+ function watchGraph() {
+ const graph = editor.graph
+ const touch = (nodeId: string | null | undefined) => pages.invalidate(pageOf(graph, nodeId))
+ return graph.onNodeEvents({
+ created: (node) => touch(node.id),
+ updated: (id) => touch(id),
+ deleted: (_id, parentId) => touch(parentId),
+ reparented: (_id, oldParentId, newParentId) => {
+ touch(oldParentId)
+ touch(newParentId)
+ },
+ reordered: (_id, parentId, _index, previousParentId) => {
+ touch(parentId)
+ touch(previousParentId)
+ }
+ })
+ }
+ let unwatchGraph = watchGraph()
+
+ const delay = ref(CHECK_DELAY_MS)
+ const timer = scope.run(() => useTimeoutFn(() => run(), delay, { immediate: false }))
+
+ function cancel() {
+ timer?.stop()
+ }
+
+ function run() {
+ cancel()
+ if (!enabled.value) return
+ if (editor.isInteractiveEditing()) {
+ schedule()
+ return
+ }
+ const pageId = state.currentPageId
+ snapshot.value = { pageId, issues: checkPage(pageId) }
+ }
+
+ function schedule(wait = CHECK_DELAY_MS) {
+ delay.value = wait
+ timer?.start()
+ }
+
+ function publishMarkers() {
+ const current = snapshot.value
+ const show =
+ preferences.value.showOnCanvas && current !== null && current.pageId === state.currentPageId
+ editor.setDesignIssueMarkers(show ? markersForIssues(current.issues) : [])
+ }
+
+ scope.run(() => {
+ watch(
+ enabled,
+ (on) => {
+ if (on) {
+ run()
+ return
+ }
+ cancel()
+ snapshot.value = null
+ editor.clearDesignIssues()
+ },
+ { immediate: true }
+ )
+ watch(linter, () => {
+ if (enabled.value) run()
+ if (pagesNeeded.value) pages.invalidateAll()
+ })
+ watch(pagesNeeded, (on) => (on ? pages.start() : pages.stop()), { immediate: true })
+ watch(snapshot, (current) => current && pages.report(current.pageId, current.issues))
+ watch(
+ () => state.currentPageId,
+ () => {
+ focusedIssueId.value = null
+ editor.setDesignIssueHighlight(null)
+ if (enabled.value) run()
+ }
+ )
+ watch(
+ () => state.sceneVersion,
+ () => enabled.value && schedule()
+ )
+ watch([snapshot, () => preferences.value.showOnCanvas], publishMarkers)
+ })
+
+ const unsubscribeGraph = editor.onEditorEvent('graph:replaced', () => {
+ snapshot.value = null
+ unwatchGraph()
+ unwatchGraph = watchGraph()
+ if (pagesNeeded.value) pages.invalidateAll()
+ if (enabled.value) schedule(0)
+ })
+
+ function highlightIssue(issue: DesignIssue | null) {
+ editor.setDesignIssueHighlight(issue ? highlightForIssue(issue) : null)
+ }
+
+ function issuesOn(nodeIds: readonly string[]): DesignIssue[] {
+ const ids = new Set(nodeIds)
+ return snapshot.value?.issues.filter((issue) => ids.has(issue.nodeId)) ?? []
+ }
+
+ /** Highlights the layer behind a hovered canvas marker; a merged marker leads with its first layer. */
+ function highlightMarker(nodeIds: readonly string[] | null) {
+ const issue =
+ nodeIds && nodeIds.length > 0 ? mostSevereIssue(issuesOn([nodeIds[0]])) : undefined
+ highlightIssue(issue ?? null)
+ }
+
+ /** Selects the layers behind a clicked marker and focuses their most severe issue. */
+ function openMarker(nodeIds: readonly string[]) {
+ const present = nodeIds.filter((id) => editor.graph.getNode(id))
+ if (present.length === 0) return
+ editor.select(present)
+ 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.
+ if (issue.pageId !== state.currentPageId && editor.graph.getNode(issue.pageId)) {
+ await editor.switchPage(issue.pageId)
+ }
+ focusedIssueId.value = issue.id
+ if (!editor.graph.getNode(issue.nodeId)) return
+ editor.select([issue.nodeId])
+ revealNode(issue.nodeId)
+ }
+
+ /** Applies fixes as one undo step and re-checks right away, so fixed rows leave at once. */
+ function applyFixes(requests: readonly LintFixRequest[]) {
+ if (editor.applyLintFixes(requests) > 0) run()
+ }
+
+ function dispose() {
+ cancel()
+ unsubscribeGraph()
+ unwatchGraph()
+ pages.stop()
+ scope.stop()
+ }
+
+ return {
+ snapshot,
+ pages,
+ documentScope,
+ enabled,
+ panelVisible,
+ focusedIssueId,
+ checkNow: run,
+ highlightIssue,
+ highlightMarker,
+ openIssue,
+ openMarker,
+ revealNode,
+ applyFixes,
+ dispose
+ }
+}
+
+export type DesignCheck = ReturnType<typeof createDesignCheck>
diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.ts
index 4e898c58d..f81862289 100644
--- a/src/app/editor/session/modules.ts
+++ b/src/app/editor/session/modules.ts
@@ -7,6 +7,7 @@ import { createSelectedNodeState } from '@open-pencil/vue'
import { createDocumentExportActions } from '@/app/document/export'
import { createDocumentIOActions } from '@/app/document/io'
import type { ViewportSize } from '@/app/document/io/types'
+import { createDesignCheck } from '@/app/editor/design-check/session'
import { createFlashActions } from '@/app/editor/flash'
import { createMobileClipboardActions } from '@/app/editor/mobile-clipboard'
import { createPenActions } from '@/app/editor/pen'
@@ -65,6 +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)
return {
...flash,
@@ -89,7 +91,9 @@ export function createEditorStoreModules(
setStorageDocumentSource: documentIO.setStorageDocumentSource,
setPlannedFilePath: documentIO.setPlannedFilePath,
startWatchingCurrentFile: documentIO.startWatchingCurrentFile,
+ designCheck,
dispose: () => {
+ designCheck.dispose()
editor.releaseGraphResources()
editor.dispose()
editor.clearPageViewports()
diff --git a/src/app/settings/preferences/apply.ts b/src/app/settings/preferences/apply.ts
index 9274968b5..43edbaa9c 100644
--- a/src/app/settings/preferences/apply.ts
+++ b/src/app/settings/preferences/apply.ts
@@ -2,8 +2,13 @@ import type { SnappingPreferences } from '@open-pencil/core/editor'
import { getTabsSnapshot } from '@/app/tabs'
-import { syncNativeSnappingMenu } from './native-menu'
-import { appPreferences, updateSnappingPreferences } from './store'
+import { syncNativeDesignIssuesMenu, syncNativeSnappingMenu } from './native-menu'
+import {
+ appPreferences,
+ updateDesignCheckPreferences,
+ updateSnappingPreferences,
+ type DesignCheckPreset
+} from './store'
export function setSnappingPreference(
preference: keyof SnappingPreferences,
@@ -18,3 +23,24 @@ export function setSnappingPreference(
console.error('[Settings] Failed to synchronize native snapping preferences:', error)
})
}
+
+export function setDesignIssuesOnCanvas(showOnCanvas: boolean): void {
+ updateDesignCheckPreferences({ showOnCanvas })
+ void syncNativeDesignIssuesMenu(showOnCanvas).catch((error: unknown) => {
+ console.error('[Settings] Failed to synchronize the native design issues menu:', error)
+ })
+}
+
+export function setDesignCheckPreset(preset: DesignCheckPreset): void {
+ updateDesignCheckPreferences({ preset })
+}
+
+export function turnOffDesignCheckRule(ruleId: string): void {
+ const disabledRules = new Set(appPreferences.value.designCheck.disabledRules)
+ disabledRules.add(ruleId)
+ updateDesignCheckPreferences({ disabledRules: [...disabledRules] })
+}
+
+export function turnOnDesignCheckRules(): void {
+ updateDesignCheckPreferences({ disabledRules: [] })
+}
diff --git a/src/app/settings/preferences/native-menu.ts b/src/app/settings/preferences/native-menu.ts
index 33636a46e..ee91d53fe 100644
--- a/src/app/settings/preferences/native-menu.ts
+++ b/src/app/settings/preferences/native-menu.ts
@@ -2,6 +2,8 @@ import type { SnappingPreferences } from '@open-pencil/core/editor'
import { isTauri } from '@/app/tauri/env'
+export const DESIGN_ISSUES_MENU_ID = 'view-design-issues'
+
const SNAPPING_MENU_IDS = {
geometry: 'snap-geometry',
objects: 'snap-objects',
@@ -20,3 +22,9 @@ export async function syncNativeSnappingMenu(preferences: SnappingPreferences):
)
)
}
+
+export async function syncNativeDesignIssuesMenu(showOnCanvas: boolean): Promise<void> {
+ if (!isTauri()) return
+ const { invoke } = await import('@tauri-apps/api/core')
+ await invoke('set_native_menu_checked', { id: DESIGN_ISSUES_MENU_ID, checked: showOnCanvas })
+}
diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.ts
index c79ca04a6..d2c1ee431 100644
--- a/src/app/settings/preferences/store.ts
+++ b/src/app/settings/preferences/store.ts
@@ -14,6 +14,17 @@ export type ChangePreviewSize = (typeof CHANGE_PREVIEW_SIZES)[number]
export type CanvasRenderingMode = 'retained' | 'tiled'
+export const DESIGN_CHECK_PRESETS = ['recommended', 'strict', 'accessibility'] as const
+export type DesignCheckPreset = (typeof DESIGN_CHECK_PRESETS)[number]
+
+export interface DesignCheckPreferences {
+ /** Marks layers with errors and warnings on the canvas. */
+ showOnCanvas: boolean
+ preset: DesignCheckPreset
+ /** Rules turned off on top of the preset. */
+ disabledRules: string[]
+}
+
export interface AppPreferences {
appearance: { animations: AnimationPreference }
chat: {
@@ -31,6 +42,7 @@ export interface AppPreferences {
rendering: {
canvasMode: CanvasRenderingMode
}
+ designCheck: DesignCheckPreferences
}
export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {
@@ -45,7 +57,8 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {
editing: {
snapping: { ...DEFAULT_SNAPPING_PREFERENCES }
},
- rendering: { canvasMode: 'retained' }
+ rendering: { canvasMode: 'retained' },
+ designCheck: { showOnCanvas: true, preset: 'recommended', disabledRules: [] }
}
const STORAGE_KEY = 'open-pencil:preferences:v1'
@@ -66,6 +79,7 @@ interface StoredAppPreferences {
recovery?: { enabled?: unknown }
editing?: { snapping?: StoredSnappingPreferences }
rendering?: { canvasMode?: unknown }
+ designCheck?: { showOnCanvas?: unknown; preset?: unknown; disabledRules?: unknown }
}
function isStoredAppPreferences(value: unknown): value is StoredAppPreferences {
@@ -89,6 +103,23 @@ function normalizeChatPreferences(chat: StoredAppPreferences['chat']): AppPrefer
}
}
+function normalizeDesignCheckPreferences(
+ designCheck: StoredAppPreferences['designCheck']
+): DesignCheckPreferences {
+ const preset = DESIGN_CHECK_PRESETS.find((candidate) => candidate === designCheck?.preset)
+ const disabledRules = Array.isArray(designCheck?.disabledRules)
+ ? designCheck.disabledRules.filter((rule): rule is string => typeof rule === 'string')
+ : []
+ return {
+ showOnCanvas: booleanOrDefault(
+ designCheck?.showOnCanvas,
+ DEFAULT_APP_PREFERENCES.designCheck.showOnCanvas
+ ),
+ preset: preset ?? DEFAULT_APP_PREFERENCES.designCheck.preset,
+ disabledRules: [...new Set(disabledRules)]
+ }
+}
+
function normalizePreferences(value: unknown): AppPreferences {
const stored = isStoredAppPreferences(value) ? value : undefined
const snapping = stored?.editing?.snapping
@@ -118,7 +149,8 @@ function normalizePreferences(value: unknown): AppPreferences {
},
rendering: {
canvasMode: stored?.rendering?.canvasMode === 'tiled' ? 'tiled' : 'retained'
- }
+ },
+ designCheck: normalizeDesignCheckPreferences(stored?.designCheck)
}
}
@@ -157,3 +189,10 @@ export function updateSnappingPreferences(changes: Partial<SnappingPreferences>)
}
}
}
+
+export function updateDesignCheckPreferences(changes: Partial<DesignCheckPreferences>): void {
+ appPreferences.value = {
+ ...appPreferences.value,
+ designCheck: { ...appPreferences.value.designCheck, ...changes }
+ }
+}
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index d579b2700..b9fabd854 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -3,11 +3,12 @@ import type { Ref } from 'vue'
import { opacityFromBuffer } from '@open-pencil/core/editor'
import type { useEditorCommands, useViewportKind } from '@open-pencil/vue'
+import type { PropertiesTab } from '@/app/ai/chat/use'
import type { EditorStore } from '@/app/editor/active-store'
type KeyboardActionsOptions = {
store: EditorStore
- activeTab: Ref<'design' | 'code' | 'ai'>
+ activeTab: Ref<PropertiesTab>
isMobile: ReturnType<typeof useViewportKind>['isMobile']
runCommand: ReturnType<typeof useEditorCommands>['runCommand']
setOpacityTarget: ReturnType<typeof useEditorCommands>['setOpacityTarget']
diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.ts
index 0d58f292d..e98b0909c 100644
--- a/src/app/shell/menu/app-menu.ts
+++ b/src/app/shell/menu/app-menu.ts
@@ -21,7 +21,8 @@ import { shortcutPlatform, useEditorCommands, useI18n } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { openSettingsDialog } from '@/app/settings/dialog'
-import { setSnappingPreference } from '@/app/settings/preferences/apply'
+import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
+import { appPreferences } from '@/app/settings/preferences/store'
import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'
import { openStorageWorkspace } from '@/app/shell/menu/navigation'
import type {
@@ -110,6 +111,7 @@ export function useAppMenu() {
settings: 'settings',
'view-rulers': 'rulers',
'view-multiplayer-cursors': 'multiplayerCursors',
+ 'view-design-issues': 'designIssues',
'snap-geometry': 'snapToGeometry',
'snap-objects': 'snapToObjects',
'snap-pixel-grid': 'snapToPixelGrid',
@@ -183,6 +185,8 @@ export function useAppMenu() {
return store.state.showRulers
case 'view-multiplayer-cursors':
return store.state.showRemoteCursors
+ case 'view-design-issues':
+ return appPreferences.value.designCheck.showOnCanvas
case 'snap-geometry':
return store.state.snappingPreferences.geometry
case 'snap-objects':
@@ -216,6 +220,8 @@ export function useAppMenu() {
return (value: boolean) => {
if (store.state.showRemoteCursors !== value) itemAction(item)?.()
}
+ case 'view-design-issues':
+ return (value: boolean) => setDesignIssuesOnCanvas(value)
case 'snap-geometry':
return (value: boolean) => setSnappingPreference('geometry', value)
case 'snap-objects':
diff --git a/src/app/shell/menu/editor-actions.ts b/src/app/shell/menu/editor-actions.ts
index 781133970..076194288 100644
--- a/src/app/shell/menu/editor-actions.ts
+++ b/src/app/shell/menu/editor-actions.ts
@@ -1,7 +1,8 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { useEditorStore } from '@/app/editor/active-store'
-import { setSnappingPreference } from '@/app/settings/preferences/apply'
+import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
+import { appPreferences } from '@/app/settings/preferences/store'
type TextFormatUpdates = {
fontWeight?: number
@@ -63,6 +64,8 @@ export function createSharedEditorMenuActions(
store.state.showRemoteCursors = !store.state.showRemoteCursors
store.requestRepaint()
},
+ 'view-design-issues': () =>
+ setDesignIssuesOnCanvas(!appPreferences.value.designCheck.showOnCanvas),
'snap-geometry': () =>
setSnappingPreference('geometry', !store.state.snappingPreferences.geometry),
'snap-objects': () =>
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 4522d57a7..bd19c2c1d 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -176,6 +176,7 @@ export const APP_MENU_SCHEMA = [
{ type: 'separator' },
{ id: 'view-rulers', label: 'Rulers', checkbox: true },
{ id: 'view-multiplayer-cursors', label: 'Multiplayer Cursors', checkbox: true },
+ { id: 'view-design-issues', label: 'Design Issues', checkbox: true, handler: 'shell' },
{ type: 'separator' },
{
id: 'theme',
diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.ts
index 9743544e6..38fcf3688 100644
--- a/src/app/shell/menu/shell.ts
+++ b/src/app/shell/menu/shell.ts
@@ -2,8 +2,11 @@ import { useI18n } from '@open-pencil/vue'
import { requestAppExit } from '@/app/document/close/exit'
import { openSettingsDialog } from '@/app/settings/dialog'
-import { setSnappingPreference } from '@/app/settings/preferences/apply'
-import { syncNativeSnappingMenu } from '@/app/settings/preferences/native-menu'
+import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
+import {
+ syncNativeDesignIssuesMenu,
+ syncNativeSnappingMenu
+} from '@/app/settings/preferences/native-menu'
import { appPreferences } from '@/app/settings/preferences/store'
import { useNativeMenuEvents } from '@/app/shell/menu/native-events'
import { openStorageWorkspace } from '@/app/shell/menu/navigation'
@@ -33,6 +36,11 @@ export function useShellMenu() {
void syncNativeSnappingMenu(appPreferences.value.editing.snapping).catch((error: unknown) => {
console.error('[Menu] Failed to synchronize native snapping preferences:', error)
})
+ void syncNativeDesignIssuesMenu(appPreferences.value.designCheck.showOnCanvas).catch(
+ (error: unknown) => {
+ console.error('[Menu] Failed to synchronize the native design issues menu:', error)
+ }
+ )
const { setTheme } = useAppTheme()
const { updates } = useI18n()
@@ -53,6 +61,8 @@ export function useShellMenu() {
const current = appPreferences.value.editing.snapping.pixelGrid
setSnappingPreference('pixelGrid', !current)
},
+ 'view-design-issues': () =>
+ setDesignIssuesOnCanvas(!appPreferences.value.designCheck.showOnCanvas),
'theme-light': () => setTheme('light'),
'theme-dark': () => setTheme('dark'),
'theme-auto': () => setTheme('auto'),
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index 77dc16d56..edc43371f 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -22,16 +22,20 @@ import {
useCanvas,
useCanvasDrop,
useCanvasInput,
+ useCanvasIssueMarkers,
useCanvasVirtualReference,
useTextEdit
} from '@open-pencil/vue'
+import { useAIChat } from '@/app/ai/chat/use'
import { useCollabInjected } from '@/app/collab/use'
import { useEditorStore } from '@/app/editor/active-store'
import { useCanvasCollaborationAwareness } from '@/app/editor/canvas/collaboration-awareness'
import { createCanvasContextSelection } from '@/app/editor/canvas/context-selection'
+import { canvasOverlayObstacles } from '@/app/editor/canvas/obstacles'
import { useFollowView } from '@/app/presence/follow-view'
import { appRuntimeConfig } from '@/app/runtime/config'
+import IssueMarkerTooltip from '@/components/design-check/IssueMarkerTooltip.vue'
import PreparationOverlay from '@/components/preparation/canvas/Overlay.vue'
import FollowFrame from '@/components/presence/FollowFrame.vue'
@@ -88,19 +92,17 @@ useCanvas(sceneCanvasRef, store, {
store.state.canvasPresentation = colorSpace
}
})
-const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(
- canvasRef,
- store,
- {
+const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, hitTestIssueMarker } =
+ useCanvas(canvasRef, store, {
layer: 'overlays',
get showRulers() {
return appRuntimeConfig.showRulers && store.state.showRulers
},
+ getOverlayObstacles: () => canvasOverlayObstacles(canvasRef.value),
shouldSuspendRender,
getRenderState,
onViewportResize
- }
-)
+ })
const {
cursorOverride,
canvasLabelEdit,
@@ -128,6 +130,24 @@ watch(isActivePane, (active) => {
})
onUnmounted(cleanupInteractions)
+const { activeTab: propertiesTab } = useAIChat()
+const { detailMarker: hoveredIssueMarker, cursor: issueMarkerCursor } = useCanvasIssueMarkers(
+ canvasRef,
+ store,
+ {
+ hitTest: hitTestIssueMarker,
+ onHover: (marker) => store.designCheck.highlightMarker(marker?.nodeIds ?? null),
+ onActivate: (marker) => {
+ activatePane()
+ propertiesTab.value = 'lint'
+ // 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.nodeIds
+ store.designCheck.openMarker(nodeIds)
+ if (marker.direction && nodeIds[0]) store.designCheck.revealNode(nodeIds[0])
+ }
+ }
+)
+
useTextEdit(canvasRef, store, { isEnabled: () => isActivePane.value })
const { isDraggingOver } = useCanvasDrop(canvasRef, store, activatePane)
@@ -172,7 +192,9 @@ const paddingEditorIcon = computed(() => {
return edit ? paddingSideIcons[edit.side] : IconLucidePanelTop
})
-const cursor = computed(() => toolCursor(store.state.activeTool, cursorOverride.value))
+const cursor = computed(() =>
+ toolCursor(store.state.activeTool, issueMarkerCursor.value ?? cursorOverride.value)
+)
</script>
<template>
@@ -215,6 +237,7 @@ const cursor = computed(() => toolCursor(store.state.activeTool, cursorOverride.
class="pointer-events-none absolute inset-0 z-40 border-2 border-dashed border-accent/60 bg-accent/5"
/>
</Transition>
+ <IssueMarkerTooltip :marker="hoveredIssueMarker" :canvas="canvasRef" />
<CanvasLabelEditor
:edit="canvasLabelEdit"
:presentation="canvasLabelEditPresentation"
diff --git a/src/components/LayerTree/LayerTree.vue b/src/components/LayerTree/LayerTree.vue
index a1f25bf7b..f098aec48 100644
--- a/src/components/LayerTree/LayerTree.vue
+++ b/src/components/LayerTree/LayerTree.vue
@@ -7,7 +7,7 @@ import {
ContextMenuPortal
} from 'reka-ui'
import { tv } from 'tailwind-variants'
-import { useAttrs, watch } from 'vue'
+import { computed, useAttrs, watch } from 'vue'
import { LayerTreeRoot, LayerTreeItem, useInlineRename } from '@open-pencil/vue'
import type {
@@ -18,6 +18,8 @@ import type {
} from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
+import { layerIssueMarks } from '@/app/editor/design-check/layers'
+import { appPreferences } from '@/app/settings/preferences/store'
import layerTreeTheme from '@/theme/layer-tree'
import CanvasMenu from '../canvas/CanvasMenu.vue'
@@ -52,6 +54,14 @@ const styles = tv(layerTreeTheme)()
provideLayerTreeUI(() => ui)
const store = useEditorStore()
const rename = useInlineRename((id, name) => store.renameNode(id, name))
+
+/** Issue marks follow the canvas markers' View → Design issues toggle. */
+const issueMarks = computed(() => {
+ const snapshot = store.designCheck.snapshot.value
+ if (!appPreferences.value.designCheck.showOnCanvas) return null
+ if (!snapshot || snapshot.pageId !== store.state.currentPageId) return null
+ return layerIssueMarks(snapshot.issues, store.graph)
+})
const renameControls = {
commit: rename.commit,
onKeydown: rename.onKeydown,
@@ -218,6 +228,7 @@ function onFocusOut(event: FocusEvent, actions: LayerTreeRootActions) {
:pad-left="padLeft"
:expanded="isExpanded"
:actions="actions"
+ :issue="issueMarks?.get(node.id) ?? null"
:chrome="
chrome({
...scope,
diff --git a/src/components/LayerTree/LayerTreeNodeRow.vue b/src/components/LayerTree/LayerTreeNodeRow.vue
index 1d80b75c2..699ec50a0 100644
--- a/src/components/LayerTree/LayerTreeNodeRow.vue
+++ b/src/components/LayerTree/LayerTreeNodeRow.vue
@@ -4,7 +4,9 @@ import { computed } from 'vue'
import type { LayerNode } from '@open-pencil/vue'
+import type { LayerIssueMark as LayerIssueMarkData } from '@/app/editor/design-check/layers'
import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'
+import LayerIssueMark from '@/components/design-check/LayerIssueMark.vue'
import layerTreeTheme from '@/theme/layer-tree'
import LayerTreeActions from './LayerTreeActions.vue'
@@ -14,16 +16,19 @@ import LayerTreeRowShell from './LayerTreeRowShell.vue'
import type { LayerTreeChrome, LayerTreeItemActions } from './types'
import { useLayerTreeUI } from './ui'
-const { node, level, hasChildren, selected, padLeft, expanded, actions, chrome } = defineProps<{
- node: LayerNode
- level: number
- hasChildren: boolean
- selected: boolean
- padLeft: string
- expanded: boolean
- actions: LayerTreeItemActions
- chrome: LayerTreeChrome
-}>()
+const { node, level, hasChildren, selected, padLeft, expanded, actions, chrome, issue } =
+ defineProps<{
+ node: LayerNode
+ level: number
+ hasChildren: boolean
+ selected: boolean
+ padLeft: string
+ expanded: boolean
+ actions: LayerTreeItemActions
+ chrome: LayerTreeChrome
+ /** Design issues on the layer, or inside it, shown while it is collapsed. */
+ issue?: LayerIssueMarkData | null
+ }>()
const emit = defineEmits<{
renameStart: [id: string, name: string]
@@ -76,6 +81,7 @@ const styles = computed(() =>
<component :is="nodeIcon(node)" data-slot="icon" :class="styles.icon({ class: ui?.icon })" />
<span data-slot="label" :class="styles.label({ class: ui?.label })">{{ node.name }}</span>
+ <LayerIssueMark v-if="issue && (issue.own || !expanded)" :mark="issue" />
<LayerTreeActions
:node="node"
diff --git a/src/components/LayerTree/examples/States.vue b/src/components/LayerTree/examples/States.vue
index 2ba379e62..6670db138 100644
--- a/src/components/LayerTree/examples/States.vue
+++ b/src/components/LayerTree/examples/States.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
import type { LayerNode } from '@open-pencil/vue'
+import type { LayerIssueMark } from '@/app/editor/design-check/layers'
import LayerTreeNodeRow from '@/components/LayerTree/LayerTreeNodeRow.vue'
import LayerTreeRenameRow from '@/components/LayerTree/LayerTreeRenameRow.vue'
import type {
@@ -56,8 +57,35 @@ function chrome(overrides: Partial<LayerTreeChrome> = {}): LayerTreeChrome {
}
}
-const states = [
+const states: Array<{
+ label: string
+ node: LayerNode
+ selected: boolean
+ chrome: LayerTreeChrome
+ issue?: LayerIssueMark
+}> = [
{ label: 'Normal', node: node('Normal'), selected: false, chrome: chrome() },
+ {
+ label: 'Own error',
+ node: node('Own error'),
+ selected: false,
+ chrome: chrome(),
+ issue: { severity: 'error', count: 2, own: true }
+ },
+ {
+ label: 'Selected own warning',
+ node: node('Selected own warning'),
+ selected: true,
+ chrome: chrome({ focused: true }),
+ issue: { severity: 'warning', count: 1, own: true }
+ },
+ {
+ label: 'Contains error',
+ node: node('Contains error'),
+ selected: false,
+ chrome: chrome(),
+ issue: { severity: 'error', count: 0, own: false }
+ },
{
label: 'Selected focused',
node: node('Selected focused'),
@@ -131,6 +159,7 @@ const states = [
:expanded="state.label === 'Normal'"
:actions="actions"
:chrome="state.chrome"
+ :issue="state.issue"
/>
</div>
<div aria-label="Rename">
diff --git a/src/components/PagesPanel.vue b/src/components/PagesPanel.vue
index 872275607..82fbc6658 100644
--- a/src/components/PagesPanel.vue
+++ b/src/components/PagesPanel.vue
@@ -15,6 +15,8 @@ import { PageListRoot, useFlatReorderDrag, useI18n, useInlineRename } from '@ope
import { useActiveEditorStoreRef } from '@/app/editor/active-store'
import { presenceByPage } from '@/app/presence/registry'
+import { appPreferences } from '@/app/settings/preferences/store'
+import PageIssueBadge from '@/components/design-check/PageIssueBadge.vue'
import PresenceMarkers from '@/components/presence/PresenceMarkers.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import { useMenuUI } from '@/components/ui/menu/menu'
@@ -43,6 +45,13 @@ const storeRef = useActiveEditorStoreRef()
const pagePresence = computed(() =>
storeRef.value ? presenceByPage(storeRef.value) : new Map<string, never[]>()
)
+
+/** Errors and warnings per page, following the View → Design issues toggle like the markers. */
+function pageIssues(pageId: string) {
+ if (!appPreferences.value.designCheck.showOnCanvas) return null
+ return storeRef.value?.designCheck.pages.counts.value.get(pageId) ?? null
+}
+
const pageActions = ref<Pick<PageActions, 'rename'> | null>(null)
const currentPages = ref<readonly PageItem[]>([])
const currentMovePage = ref<PageActions['move'] | null>(null)
@@ -151,6 +160,7 @@ function setupPageRowRef(
<span :class="pageStyles(pg, currentPageId).label()">{{ pg.name }}</span>
<span :class="pageStyles(pg, currentPageId).trailing()">
<PresenceMarkers :entries="pagePresence.get(pg.id) ?? []" />
+ <PageIssueBadge :counts="pageIssues(pg.id)" />
</span>
</button>
<div
diff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vue
index ab0afa1c7..7fbe1270b 100644
--- a/src/components/PropertiesPanel.vue
+++ b/src/components/PropertiesPanel.vue
@@ -1,17 +1,34 @@
<script setup lang="ts">
import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'reka-ui'
+import { computed } from 'vue'
-import { useI18n } from '@open-pencil/vue'
+import { useDesignCheckMessages, useI18n } from '@open-pencil/vue'
import { useAIChat } from '@/app/ai/chat/use'
+import { useEditorStore } from '@/app/editor/active-store'
+import { countIssues } from '@/app/editor/design-check/issues'
+import { propertiesTabs } from '@/theme/panel/properties-tabs'
import ChatPanel from './ChatPanel.vue'
import CodePanel from './CodePanel.vue'
+import DesignCheckPanel from './design-check/DesignCheckPanel.vue'
import DesignPanel from './DesignPanel.vue'
import ZoomDropdown from './editor/ZoomDropdown.vue'
const { activeTab } = useAIChat()
const { panels } = useI18n()
+const checkMessages = useDesignCheckMessages()
+const store = useEditorStore()
+
+const tabStyles = propertiesTabs()
+
+/** Errors and warnings on the current page; suggestions do not earn an indicator. */
+const problemCount = computed(() => {
+ const snapshot = store.designCheck.snapshot.value
+ if (!snapshot || snapshot.pageId !== store.state.currentPageId) return null
+ const counts = countIssues(snapshot.issues)
+ return { total: counts.error + counts.warning, severity: counts.error > 0 ? 'error' : 'warning' }
+})
</script>
<template>
@@ -21,29 +38,39 @@ const { panels } = useI18n()
style="contain: paint layout style"
>
<TabsRoot v-model="activeTab" class="flex min-h-0 flex-1 flex-col">
- <TabsList class="flex h-10 shrink-0 items-center gap-1 border-b border-border px-2">
+ <TabsList :class="tabStyles.list()">
<TabsTrigger
value="design"
data-test-id="properties-tab-design"
- class="relative rounded px-2.5 py-1 text-[11px] text-muted hover:text-surface data-[state=active]:font-semibold data-[state=active]:text-surface after:absolute after:inset-x-2 after:-bottom-[9px] after:h-0.5 after:rounded-full after:bg-transparent data-[state=active]:after:bg-accent"
+ :class="tabStyles.trigger()"
>
{{ panels.design }}
</TabsTrigger>
- <TabsTrigger
- value="code"
- data-test-id="properties-tab-code"
- class="relative flex items-center gap-1 rounded px-2.5 py-1 text-[11px] text-muted hover:text-surface data-[state=active]:font-semibold data-[state=active]:text-surface after:absolute after:inset-x-2 after:-bottom-[9px] after:h-0.5 after:rounded-full after:bg-transparent data-[state=active]:after:bg-accent"
- >
- <icon-lucide-code class="size-3" />
- {{ panels.code }}
+ <TabsTrigger value="code" data-test-id="properties-tab-code" :class="tabStyles.trigger()">
+ <icon-lucide-code :class="tabStyles.icon()" aria-hidden="true" />
+ <span :class="tabStyles.label()">{{ panels.code }}</span>
+ </TabsTrigger>
+ <TabsTrigger value="ai" data-test-id="properties-tab-ai" :class="tabStyles.trigger()">
+ <icon-lucide-sparkles :class="tabStyles.icon()" aria-hidden="true" />
+ <span :class="tabStyles.label()">{{ panels.ai }}</span>
</TabsTrigger>
<TabsTrigger
- value="ai"
- data-test-id="properties-tab-ai"
- class="relative flex items-center gap-1 rounded px-2.5 py-1 text-[11px] text-muted hover:text-surface data-[state=active]:font-semibold data-[state=active]:text-surface after:absolute after:inset-x-2 after:-bottom-[9px] after:h-0.5 after:rounded-full after:bg-transparent data-[state=active]:after:bg-accent"
+ value="lint"
+ data-test-id="properties-tab-lint"
+ :aria-label="
+ problemCount?.total
+ ? `${checkMessages.tab}, ${checkMessages.tabCount({ count: problemCount.total })}`
+ : checkMessages.tab
+ "
+ :class="tabStyles.trigger()"
>
- <icon-lucide-sparkles class="size-3" />
- {{ panels.ai }}
+ <!-- Errors and warnings tint the icon, which costs no room in a full row. -->
+ <icon-lucide-list-checks
+ :data-severity="problemCount?.total ? problemCount.severity : undefined"
+ :class="tabStyles.icon()"
+ aria-hidden="true"
+ />
+ <span :class="tabStyles.label()">{{ checkMessages.tab }}</span>
</TabsTrigger>
<ZoomDropdown v-if="activeTab === 'design'" />
</TabsList>
@@ -66,6 +93,15 @@ const { panels } = useI18n()
<CodePanel :active="activeTab === 'code'" />
</TabsContent>
+ <TabsContent
+ value="lint"
+ class="flex min-h-0 flex-1 flex-col"
+ :force-mount="true"
+ :hidden="activeTab !== 'lint'"
+ >
+ <DesignCheckPanel :active="activeTab === 'lint'" />
+ </TabsContent>
+
<TabsContent
value="ai"
class="flex min-h-0 flex-1 flex-col"
diff --git a/src/components/Toolbar/DesktopToolbar.vue b/src/components/Toolbar/DesktopToolbar.vue
index 28624b18c..93015f8ee 100644
--- a/src/components/Toolbar/DesktopToolbar.vue
+++ b/src/components/Toolbar/DesktopToolbar.vue
@@ -32,7 +32,10 @@ const emit = defineEmits<{
</script>
<template>
- <div class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center">
+ <div
+ data-canvas-obstacle
+ class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center"
+ >
<ToolbarRoot
data-test-id="toolbar"
class="flex gap-0.5 rounded-xl bg-panel p-1 shadow-[0_8px_30px_rgb(0_0_0/0.4)]"
diff --git a/src/components/Toolbar/MobileToolbar.vue b/src/components/Toolbar/MobileToolbar.vue
index 178108084..5e1da58d8 100644
--- a/src/components/Toolbar/MobileToolbar.vue
+++ b/src/components/Toolbar/MobileToolbar.vue
@@ -78,6 +78,7 @@ function navigationClass(disabled: boolean) {
<template>
<div
data-test-id="mobile-toolbar"
+ data-canvas-obstacle
class="fixed left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5"
:style="{
maxWidth: 'calc(100vw - 2rem)',
diff --git a/src/components/design-check/DesignCheckPanel.vue b/src/components/design-check/DesignCheckPanel.vue
new file mode 100644
index 000000000..23d3089c9
--- /dev/null
+++ b/src/components/design-check/DesignCheckPanel.vue
@@ -0,0 +1,102 @@
+<script setup lang="ts">
+import { computed, useTemplateRef } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import { turnOffDesignCheckRule } from '@/app/settings/preferences/apply'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
+import { designCheck } from '@/theme/design-check'
+
+import DesignCheckRulesMenu from './DesignCheckRulesMenu.vue'
+import IssueGroup from './IssueGroup.vue'
+import SeverityFilters from './SeverityFilters.vue'
+import { useDesignCheckPanel, type DesignCheckScope } from './useDesignCheckPanel'
+
+const { active } = defineProps<{ active: boolean }>()
+
+const messages = useDesignCheckMessages()
+const styles = designCheck()
+const list = useTemplateRef<HTMLElement>('list')
+
+const {
+ check,
+ scope,
+ visibleSeverities,
+ counts,
+ groups,
+ emptyState,
+ documentNote,
+ loading,
+ isGroupOpen,
+ setGroupOpen,
+ clearFilters,
+ hoverRow
+} = useDesignCheckPanel({ active: () => active, list })
+
+const scopeOptions = computed(() => [
+ { value: 'page' satisfies DesignCheckScope, label: messages.value.scopePage },
+ { value: 'selection' satisfies DesignCheckScope, label: messages.value.scopeSelection },
+ { value: 'document' satisfies DesignCheckScope, label: messages.value.scopeDocument }
+])
+
+const scopeModel = computed({
+ get: () => scope.value,
+ set: (value: string) => {
+ if (value === 'page' || value === 'selection' || value === 'document') scope.value = value
+ }
+})
+</script>
+
+<template>
+ <section data-test-id="design-check-panel" :aria-label="messages.tab" :class="styles.root()">
+ <div :class="styles.toolbar()">
+ <SegmentedControl v-model="scopeModel" :label="messages.scope" :options="scopeOptions" />
+ <div :class="styles.toolbarRow()">
+ <SeverityFilters v-model="visibleSeverities" :counts="counts" />
+ <DesignCheckRulesMenu />
+ </div>
+ </div>
+
+ <p v-if="documentNote" :class="styles.status()" data-test-id="design-check-document-note">
+ {{ documentNote }}
+ </p>
+ <p v-if="loading" :class="styles.status()" role="status">{{ messages.checking }}</p>
+
+ <AppPlaceholder
+ v-else-if="emptyState"
+ :label="emptyState.label"
+ :description="emptyState.kind === 'filtered' ? undefined : emptyState.description"
+ :fill="false"
+ :ui="{ root: 'pt-10' }"
+ data-test-id="design-check-empty"
+ >
+ <template #icon>
+ <icon-lucide-circle-check v-if="emptyState.kind === 'clean'" class="size-4 text-success" />
+ <icon-lucide-list-filter v-else-if="emptyState.kind === 'filtered'" class="size-4" />
+ <icon-lucide-mouse-pointer-2 v-else class="size-4" />
+ </template>
+ <template v-if="emptyState.kind === 'filtered'" #action>
+ <AppButton color="primary" size="xs" @click="clearFilters">
+ {{ messages.clearFilters }}
+ </AppButton>
+ </template>
+ </AppPlaceholder>
+
+ <div v-else ref="list" :class="styles.list()" @mouseleave="hoverRow(null)">
+ <IssueGroup
+ v-for="group in groups"
+ :key="group.ruleId"
+ :group="group"
+ :open="isGroupOpen(group)"
+ @update:open="(open) => setGroupOpen(group.ruleId, open)"
+ @open-row="(row) => void check.openIssue(row.issue)"
+ @hover-row="hoverRow"
+ @fix="(row) => row.action && check.applyFixes([row.action.request])"
+ @fix-all="check.applyFixes(group.fixes)"
+ @turn-off="turnOffDesignCheckRule(group.ruleId)"
+ />
+ </div>
+ </section>
+</template>
diff --git a/src/components/design-check/DesignCheckRulesMenu.vue b/src/components/design-check/DesignCheckRulesMenu.vue
new file mode 100644
index 000000000..e6b3ab322
--- /dev/null
+++ b/src/components/design-check/DesignCheckRulesMenu.vue
@@ -0,0 +1,88 @@
+<script setup lang="ts">
+import {
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuItemIndicator,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuRoot,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import {
+ setDesignCheckPreset,
+ setDesignIssuesOnCanvas,
+ turnOnDesignCheckRules
+} from '@/app/settings/preferences/apply'
+import { appPreferences, DESIGN_CHECK_PRESETS } from '@/app/settings/preferences/store'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+
+import { usePresetLabels } from './usePresetLabels'
+
+const messages = useDesignCheckMessages()
+const presetLabels = usePresetLabels()
+const menuCls = useMenuUI({ content: 'min-w-56' })
+const itemCls = menuItem({ justify: 'start', class: 'relative pl-7' })
+const preferences = computed(() => appPreferences.value.designCheck)
+
+const presetModel = computed({
+ get: () => preferences.value.preset,
+ set: (value: string) => {
+ const preset = DESIGN_CHECK_PRESETS.find((candidate) => candidate === value)
+ if (preset) setDesignCheckPreset(preset)
+ }
+})
+</script>
+
+<template>
+ <DropdownMenuRoot :modal="false">
+ <DropdownMenuTrigger as-child>
+ <IconButton size="xs" :label="messages.rules">
+ <icon-lucide-settings-2 class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menuCls.content">
+ <DropdownMenuLabel :class="menuCls.label">{{ messages.rules }}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup v-model="presetModel">
+ <DropdownMenuRadioItem
+ v-for="preset in DESIGN_CHECK_PRESETS"
+ :key="preset"
+ :value="preset"
+ :class="itemCls"
+ >
+ <DropdownMenuItemIndicator class="absolute left-2">
+ <icon-lucide-check class="size-3.5" />
+ </DropdownMenuItemIndicator>
+ {{ presetLabels[preset] }}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <template v-if="preferences.disabledRules.length > 0">
+ <DropdownMenuSeparator :class="menuCls.separator" />
+ <DropdownMenuItem :class="itemCls" @select="turnOnDesignCheckRules">
+ {{ messages.turnOnRules({ count: preferences.disabledRules.length }) }}
+ </DropdownMenuItem>
+ </template>
+ <DropdownMenuSeparator :class="menuCls.separator" />
+ <DropdownMenuCheckboxItem
+ :model-value="preferences.showOnCanvas"
+ :class="itemCls"
+ @update:model-value="setDesignIssuesOnCanvas"
+ >
+ <DropdownMenuItemIndicator class="absolute left-2">
+ <icon-lucide-check class="size-3.5" />
+ </DropdownMenuItemIndicator>
+ {{ messages.showOnCanvas }}
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+</template>
diff --git a/src/components/design-check/IssueGroup.stories.ts b/src/components/design-check/IssueGroup.stories.ts
new file mode 100644
index 000000000..a862aa6c7
--- /dev/null
+++ b/src/components/design-check/IssueGroup.stories.ts
@@ -0,0 +1,158 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import IconCircle from '~icons/lucide/circle'
+import IconFrame from '~icons/lucide/frame'
+import IconSquare from '~icons/lucide/square'
+import IconType from '~icons/lucide/type'
+
+import type { LintFix } from '@open-pencil/core/lint'
+
+import type { IssueAction } from '@/app/editor/design-check/format'
+import type { DesignIssue } from '@/app/editor/design-check/issues'
+
+import IssueGroup from './IssueGroup.vue'
+import type { IssueGroupView, IssueRowView } from './types'
+
+function issue(ruleId: string, nodeId: string, severity: DesignIssue['severity']): DesignIssue {
+ return {
+ id: `${ruleId}:${nodeId}:0`,
+ ruleId,
+ nodeId,
+ severity,
+ message: ruleId,
+ nodeName: nodeId,
+ nodePath: [nodeId],
+ pageId: 'page'
+ }
+}
+
+function row(overrides: Partial<IssueRowView> & Pick<IssueRowView, 'issue' | 'layerName'>) {
+ return {
+ layerIcon: IconSquare,
+ detail: null,
+ swatch: null,
+ action: null,
+ hidden: false,
+ missing: false,
+ selected: false,
+ pageLabel: null,
+ ...overrides
+ } satisfies IssueRowView
+}
+
+const contrast: IssueGroupView = {
+ ruleId: 'color-contrast',
+ severity: 'error',
+ title: 'Low text contrast',
+ help: 'Text needs a contrast ratio of at least 4.5:1 with its background to meet WCAG AA.',
+ fixes: [],
+ bindsOnly: true,
+ rows: [
+ row({
+ issue: issue('color-contrast', 'caption', 'error'),
+ layerName: 'Caption',
+ layerIcon: IconType,
+ detail: '2.8:1',
+ swatch: { kind: 'contrast', foreground: '#FFFFFF', background: '#F97316' },
+ selected: true
+ })
+ ]
+}
+
+const brandFix = {
+ kind: 'bind-variable',
+ path: 'fills/0/color',
+ variableId: 'brand',
+ variableName: 'Colors/Blue/600'
+} satisfies LintFix
+
+function bindAction(nodeId: string): IssueAction {
+ return { request: { nodeId, fix: brandFix }, label: 'Bind to Blue/600', kind: 'bind-variable' }
+}
+
+const colors: IssueGroupView = {
+ ruleId: 'no-hardcoded-colors',
+ severity: 'warning',
+ title: 'Unbound color',
+ help: 'This color matches a color variable. Bind it so theme and palette changes reach this layer.',
+ fixes: [bindAction('card').request, bindAction('dot').request],
+ bindsOnly: true,
+ rows: [
+ row({
+ issue: issue('no-hardcoded-colors', 'card', 'warning'),
+ layerName: 'Pricing card with a long descriptive name',
+ layerIcon: IconFrame,
+ detail: 'Blue/600',
+ swatch: { kind: 'color', color: '#2563EB' },
+ action: bindAction('card')
+ }),
+ row({
+ issue: issue('no-hardcoded-colors', 'dot', 'warning'),
+ layerName: 'Status dot',
+ layerIcon: IconCircle,
+ detail: 'Blue/600',
+ swatch: { kind: 'color', color: '#2563EB' },
+ action: bindAction('dot'),
+ hidden: true
+ }),
+ row({
+ issue: issue('no-hardcoded-colors', 'removed', 'warning'),
+ layerName: 'Removed',
+ detail: 'Gray/800',
+ swatch: { kind: 'color', color: '#1F2937' },
+ missing: true
+ })
+ ]
+}
+
+const radius: IssueGroupView = {
+ ruleId: 'consistent-radius',
+ severity: 'info',
+ title: 'Off-scale corner radius',
+ help: 'Corner radius should come from the radius scale or a variable.',
+ fixes: [],
+ bindsOnly: true,
+ rows: [
+ row({
+ issue: issue('consistent-radius', 'card', 'info'),
+ layerName: 'Card',
+ layerIcon: IconFrame,
+ detail: '10 px',
+ action: {
+ request: { nodeId: 'card', fix: { kind: 'set', changes: { cornerRadius: 12 } } },
+ label: 'Change to 12 px',
+ kind: 'set'
+ }
+ })
+ ]
+}
+
+interface IssueGroupStoryArgs {
+ group: IssueGroupView
+ open?: boolean
+}
+
+const meta = {
+ title: 'Editor/Design Check/Issue Group',
+ component: IssueGroup,
+ args: { group: contrast },
+ render: (args) => ({
+ components: { IssueGroup },
+ setup: () => ({ args }),
+ template: `
+ <div class="w-60 bg-panel py-1">
+ <IssueGroup v-bind="args" />
+ </div>
+ `
+ })
+} satisfies Meta<IssueGroupStoryArgs>
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const ContrastError: Story = {}
+
+export const FixableColors: Story = { args: { group: colors } }
+
+export const Collapsed: Story = { args: { group: colors, open: false } }
+
+export const Suggestion: Story = { args: { group: radius } }
diff --git a/src/components/design-check/IssueGroup.vue b/src/components/design-check/IssueGroup.vue
new file mode 100644
index 000000000..5c12d58be
--- /dev/null
+++ b/src/components/design-check/IssueGroup.vue
@@ -0,0 +1,114 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+import { computed, ref } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+import Tip from '@/components/ui/overlay/Tip.vue'
+import { designCheck } from '@/theme/design-check'
+
+import IssueRow from './IssueRow.vue'
+import SeverityIcon from './SeverityIcon.vue'
+import type { IssueGroupView, IssueRowView } from './types'
+
+/** Rows rendered before a group asks to show the rest. */
+const ROW_PAGE_SIZE = 50
+
+const { group } = defineProps<{ group: IssueGroupView }>()
+const open = defineModel<boolean>('open', { default: true })
+const emit = defineEmits<{
+ openRow: [row: IssueRowView]
+ hoverRow: [row: IssueRowView | null]
+ fix: [row: IssueRowView]
+ fixAll: []
+ turnOff: []
+}>()
+
+const messages = useDesignCheckMessages()
+const styles = designCheck()
+const menuCls = useMenuUI({ content: 'min-w-40' })
+const itemCls = menuItem({ justify: 'start' })
+const menuOpen = ref(false)
+const limit = ref(ROW_PAGE_SIZE)
+
+const visibleRows = computed(() => group.rows.slice(0, limit.value))
+const hiddenCount = computed(() => group.rows.length - visibleRows.value.length)
+</script>
+
+<template>
+ <AppCollapsible
+ v-model:open="open"
+ :data-rule-id="group.ruleId"
+ :data-menu-open="menuOpen ? '' : undefined"
+ :ui="{
+ root: styles.group(),
+ header: styles.groupHeader(),
+ trigger: styles.groupTrigger(),
+ icon: styles.chevron(),
+ label: styles.groupLabel(),
+ actions: styles.groupActions()
+ }"
+ >
+ <template #label>
+ <SeverityIcon :severity="group.severity" />
+ <Tip :label="group.help ?? undefined" side="left">
+ <span :class="styles.groupTitle()">{{ group.title }}</span>
+ </Tip>
+ <span :class="styles.groupCount()">{{ group.rows.length }}</span>
+ </template>
+ <template #actions>
+ <AppButton v-if="group.fixes.length > 1" color="primary" size="xs" @click="emit('fixAll')">
+ {{
+ group.bindsOnly
+ ? messages.bindAll({ count: group.fixes.length })
+ : messages.fixAll({ count: group.fixes.length })
+ }}
+ </AppButton>
+ <DropdownMenuRoot v-model:open="menuOpen" :modal="false">
+ <DropdownMenuTrigger as-child>
+ <IconButton size="xs" :label="messages.ruleActions">
+ <icon-lucide-ellipsis class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menuCls.content">
+ <DropdownMenuItem :class="itemCls" @select="emit('turnOff')">
+ <icon-lucide-eye-off class="size-3.5 text-muted" aria-hidden="true" />
+ {{ messages.turnOffRule }}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </template>
+
+ <ul :class="styles.rows()">
+ <IssueRow
+ v-for="row in visibleRows"
+ :key="row.issue.id"
+ :row="row"
+ @open="emit('openRow', row)"
+ @hover="(hovered) => emit('hoverRow', hovered ? row : null)"
+ @fix="emit('fix', row)"
+ />
+ </ul>
+ <AppButton
+ v-if="hiddenCount > 0"
+ color="primary"
+ size="xs"
+ :class="styles.more()"
+ @click="limit += ROW_PAGE_SIZE * 4"
+ >
+ {{ messages.showMore({ count: hiddenCount }) }}
+ </AppButton>
+ </AppCollapsible>
+</template>
diff --git a/src/components/design-check/IssueMarkerTooltip.vue b/src/components/design-check/IssueMarkerTooltip.vue
new file mode 100644
index 000000000..bb783a4af
--- /dev/null
+++ b/src/components/design-check/IssueMarkerTooltip.vue
@@ -0,0 +1,154 @@
+<script setup lang="ts">
+import {
+ TooltipContent,
+ TooltipPortal,
+ TooltipProvider,
+ TooltipRoot,
+ TooltipTrigger
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import type { PlacedIssueMarker } from '@open-pencil/core/canvas'
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import { issueDetail, ruleTitle } from '@/app/editor/design-check/format'
+import { compareIssueSeverity, type DesignIssue } from '@/app/editor/design-check/issues'
+import { nodeIcon } from '@/app/editor/icons'
+import { issueTooltip } from '@/theme/design-check'
+
+import SeverityIcon from './SeverityIcon.vue'
+
+/** Issues listed before the tooltip summarizes the rest. */
+const MAX_ITEMS = 4
+
+const { marker, canvas } = defineProps<{
+ marker: PlacedIssueMarker | null
+ canvas: HTMLElement | null
+}>()
+
+const store = useEditorStore()
+
+const messages = useDesignCheckMessages()
+const styles = issueTooltip()
+
+const reference = computed(() => {
+ const current = marker
+ const element = canvas
+ if (!current || !element) return null
+ return {
+ getBoundingClientRect() {
+ const bounds = element.getBoundingClientRect()
+ const { rect } = current
+ return new DOMRect(bounds.left + rect.x, bounds.top + rect.y, rect.width, rect.height)
+ }
+ }
+})
+
+const issues = computed<DesignIssue[]>(() => {
+ if (!marker) return []
+ const nodeIds = new Set(marker.nodeIds)
+ const all = store.designCheck.snapshot.value?.issues ?? []
+ return (
+ all
+ // Suggestions do not earn a marker, so the tooltip lists what the marker counts.
+ .filter((issue) => nodeIds.has(issue.nodeId) && issue.severity !== 'info')
+ .toSorted(compareIssueSeverity)
+ )
+})
+
+const singleNode = computed(() =>
+ marker?.nodeIds.length === 1 ? store.graph.getNode(marker.nodeIds[0]) : undefined
+)
+
+const items = computed(() =>
+ issues.value.slice(0, MAX_ITEMS).map((issue) => {
+ const detail = issueDetail(issue, messages.value)
+ // The header names a single layer, except on an edge pin, where it names the direction.
+ const layer =
+ singleNode.value && !marker?.direction
+ ? null
+ : (store.graph.getNode(issue.nodeId)?.name ?? issue.nodeName)
+ return {
+ id: issue.id,
+ severity: issue.severity,
+ title: ruleTitle(issue.ruleId, messages.value),
+ detail: [layer, detail].filter(Boolean).join(' · ')
+ }
+ })
+)
+
+const remaining = computed(() => issues.value.length - items.value.length)
+
+type Side = 'top' | 'right' | 'bottom' | 'left'
+
+/** The side an edge pin points to, by its stronger axis; the tooltip opens the other way. */
+const edgeSide = computed<Side | null>(() => {
+ const direction = marker?.direction
+ if (!direction) return null
+ if (Math.abs(direction.x) >= Math.abs(direction.y)) return direction.x < 0 ? 'left' : 'right'
+ return direction.y < 0 ? 'top' : 'bottom'
+})
+
+const OPPOSITE: Record<Side, Side> = { top: 'bottom', right: 'left', bottom: 'top', left: 'right' }
+
+const edgeHeading = computed(() => {
+ const side = edgeSide.value
+ if (!side) return null
+ const headings = {
+ left: messages.value.edgeLeft,
+ right: messages.value.edgeRight,
+ top: messages.value.edgeAbove,
+ bottom: messages.value.edgeBelow
+ }
+ return headings[side]
+})
+</script>
+
+<template>
+ <TooltipProvider :delay-duration="0" disable-hoverable-content>
+ <TooltipRoot :open="!!marker && items.length > 0">
+ <TooltipTrigger v-if="reference" as-child :reference="reference">
+ <span class="hidden" />
+ </TooltipTrigger>
+ <TooltipPortal>
+ <TooltipContent
+ :side="edgeSide ? OPPOSITE[edgeSide] : 'right'"
+ align="start"
+ :side-offset="8"
+ :collision-padding="8"
+ :class="styles.content()"
+ data-test-id="issue-marker-tooltip"
+ >
+ <div :class="styles.header()">
+ <span v-if="edgeHeading" :class="styles.headerText()">{{ edgeHeading }}</span>
+ <template v-else-if="singleNode">
+ <component
+ :is="nodeIcon(singleNode)"
+ :class="styles.headerIcon()"
+ aria-hidden="true"
+ />
+ <span :class="styles.headerText()">{{ singleNode.name }}</span>
+ </template>
+ <span v-else :class="styles.headerText()">
+ {{ messages.markerLayers({ count: marker?.nodeIds.length ?? 0 }) }}
+ </span>
+ </div>
+ <div v-for="item in items" :key="item.id" :class="styles.item()">
+ <SeverityIcon :severity="item.severity" :class="styles.itemIcon()" />
+ <div :class="styles.itemBody()">
+ <div :class="styles.itemTitle()">{{ item.title }}</div>
+ <div v-if="item.detail" :class="styles.itemDetail()">{{ item.detail }}</div>
+ </div>
+ </div>
+ <div v-if="remaining > 0" :class="styles.more()">
+ {{ messages.markerMore({ count: remaining }) }}
+ </div>
+ <div :class="styles.hint()">
+ {{ edgeSide ? messages.edgeHint : messages.markerHint }}
+ </div>
+ </TooltipContent>
+ </TooltipPortal>
+ </TooltipRoot>
+ </TooltipProvider>
+</template>
diff --git a/src/components/design-check/IssueRow.vue b/src/components/design-check/IssueRow.vue
new file mode 100644
index 000000000..8ec252764
--- /dev/null
+++ b/src/components/design-check/IssueRow.vue
@@ -0,0 +1,81 @@
+<script setup lang="ts">
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import Tip from '@/components/ui/overlay/Tip.vue'
+import { designCheck } from '@/theme/design-check'
+
+import type { IssueRowView } from './types'
+
+const { row } = defineProps<{ row: IssueRowView }>()
+const emit = defineEmits<{
+ open: []
+ hover: [hovered: boolean]
+ fix: []
+}>()
+
+const messages = useDesignCheckMessages()
+const styles = designCheck()
+</script>
+
+<template>
+ <!-- The row and its fix are sibling buttons: interactive controls must not nest. -->
+ <li
+ :class="styles.rowItem()"
+ @mouseenter="emit('hover', true)"
+ @mouseleave="emit('hover', false)"
+ @focusin="emit('hover', true)"
+ @focusout="emit('hover', false)"
+ >
+ <button
+ type="button"
+ :data-issue-id="row.issue.id"
+ :data-node-id="row.issue.nodeId"
+ :data-selected="row.selected ? '' : undefined"
+ :data-missing="row.missing ? '' : undefined"
+ :aria-current="row.selected ? 'true' : undefined"
+ :class="styles.row()"
+ @click="emit('open')"
+ >
+ <component :is="row.layerIcon" :class="styles.rowIcon()" aria-hidden="true" />
+ <span :class="styles.rowName()">{{
+ row.missing ? messages.missingLayer : row.layerName
+ }}</span>
+ <span v-if="row.hidden" :class="styles.rowTag()">{{ messages.hiddenLayer }}</span>
+ <span v-if="row.pageLabel" :class="styles.rowTag()" data-slot="page">{{
+ row.pageLabel
+ }}</span>
+ <span v-if="row.detail" :class="styles.rowDetail()">
+ <span
+ v-if="row.swatch?.kind === 'color'"
+ :class="styles.swatch()"
+ :style="{ backgroundColor: row.swatch.color }"
+ aria-hidden="true"
+ />
+ <span
+ v-else-if="row.swatch?.kind === 'contrast'"
+ :class="styles.contrastSwatch()"
+ :style="{ backgroundColor: row.swatch.background, color: row.swatch.foreground }"
+ aria-hidden="true"
+ >
+ Aa
+ </span>
+ <span :class="styles.rowDetailText()">{{ row.detail }}</span>
+ </span>
+ </button>
+ <Tip v-if="row.action" as-child :label="row.action.label">
+ <button
+ type="button"
+ :aria-label="row.action.label"
+ :class="styles.rowAction()"
+ @click="emit('fix')"
+ >
+ <icon-lucide-link
+ v-if="row.action.kind === 'bind-variable'"
+ class="size-3"
+ aria-hidden="true"
+ />
+ <icon-lucide-wand-sparkles v-else class="size-3" aria-hidden="true" />
+ </button>
+ </Tip>
+ </li>
+</template>
diff --git a/src/components/design-check/LayerIssueMark.vue b/src/components/design-check/LayerIssueMark.vue
new file mode 100644
index 000000000..8775e6fde
--- /dev/null
+++ b/src/components/design-check/LayerIssueMark.vue
@@ -0,0 +1,35 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import type { LayerIssueMark } from '@/app/editor/design-check/layers'
+import Tip from '@/components/ui/overlay/Tip.vue'
+import { layerIssueMark } from '@/theme/design-check'
+
+import SeverityIcon from './SeverityIcon.vue'
+
+/** A layer's own issues show as their severity icon; issues inside it as a dot. */
+const { mark } = defineProps<{ mark: LayerIssueMark }>()
+
+const messages = useDesignCheckMessages()
+const styles = computed(() => layerIssueMark({ severity: mark.severity }))
+const label = computed(() =>
+ mark.own ? messages.value.layerIssues({ count: mark.count }) : messages.value.layerContainsIssues
+)
+</script>
+
+<template>
+ <Tip :label="label">
+ <span
+ role="img"
+ :aria-label="label"
+ :data-issue-severity="mark.severity"
+ :data-issue-own="mark.own || undefined"
+ :class="styles.root()"
+ >
+ <SeverityIcon v-if="mark.own" :severity="mark.severity" />
+ <span v-else :class="styles.dot()" />
+ </span>
+ </Tip>
+</template>
diff --git a/src/components/design-check/PageIssueBadge.vue b/src/components/design-check/PageIssueBadge.vue
new file mode 100644
index 000000000..ea2ed8fde
--- /dev/null
+++ b/src/components/design-check/PageIssueBadge.vue
@@ -0,0 +1,38 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import type { DesignIssueCounts } from '@/app/editor/design-check/issues'
+import Tip from '@/components/ui/overlay/Tip.vue'
+import { pageIssueBadge } from '@/theme/design-check'
+
+/**
+ * Errors and warnings on a page, like the problem count an IDE shows next to a file. Nothing
+ * shows for a page without them, or one not checked yet (`null`).
+ */
+const { counts } = defineProps<{ counts: DesignIssueCounts | null }>()
+
+const messages = useDesignCheckMessages()
+const errors = computed(() => counts?.error ?? 0)
+const warnings = computed(() => counts?.warning ?? 0)
+const total = computed(() => errors.value + warnings.value)
+const severity = computed(() => (errors.value > 0 ? 'error' : 'warning'))
+const styles = computed(() => pageIssueBadge({ severity: severity.value }))
+const label = computed(() =>
+ [
+ errors.value > 0 ? `${messages.value.errors}: ${errors.value}` : null,
+ warnings.value > 0 ? `${messages.value.warnings}: ${warnings.value}` : null
+ ]
+ .filter(Boolean)
+ .join(', ')
+)
+</script>
+
+<template>
+ <Tip v-if="total > 0" :label="label">
+ <span role="img" :aria-label="label" :data-issue-severity="severity" :class="styles">
+ {{ total > 99 ? '99+' : total }}
+ </span>
+ </Tip>
+</template>
diff --git a/src/components/design-check/SeverityFilters.vue b/src/components/design-check/SeverityFilters.vue
new file mode 100644
index 000000000..a9f33fe3f
--- /dev/null
+++ b/src/components/design-check/SeverityFilters.vue
@@ -0,0 +1,60 @@
+<script setup lang="ts">
+import { ToggleGroupItem, ToggleGroupRoot } from 'reka-ui'
+import { computed } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import {
+ DESIGN_ISSUE_SEVERITIES,
+ type DesignIssueCounts,
+ type DesignIssueSeverity
+} from '@/app/editor/design-check/issues'
+import Tip from '@/components/ui/overlay/Tip.vue'
+import { designCheck } from '@/theme/design-check'
+
+import SeverityIcon from './SeverityIcon.vue'
+
+const { counts } = defineProps<{ counts: DesignIssueCounts }>()
+/** Severities whose issues are listed; toggling one hides or shows its issues. */
+const visible = defineModel<DesignIssueSeverity[]>({ required: true })
+
+const messages = useDesignCheckMessages()
+const styles = designCheck()
+
+const labels = computed<Record<DesignIssueSeverity, string>>(() => ({
+ error: messages.value.errors,
+ warning: messages.value.warnings,
+ info: messages.value.suggestions
+}))
+
+function update(value: unknown) {
+ const selected: unknown[] = Array.isArray(value) ? value : []
+ visible.value = DESIGN_ISSUE_SEVERITIES.filter((severity) => selected.includes(severity))
+}
+</script>
+
+<template>
+ <ToggleGroupRoot
+ type="multiple"
+ :model-value="visible"
+ :aria-label="messages.filterSeverities"
+ :class="styles.filters()"
+ @update:model-value="update"
+ >
+ <Tip
+ v-for="severity in DESIGN_ISSUE_SEVERITIES"
+ :key="severity"
+ as-child
+ :label="messages.filterBySeverity({ severity: labels[severity] })"
+ >
+ <ToggleGroupItem
+ :value="severity"
+ :aria-label="`${labels[severity]}: ${counts[severity]}`"
+ :class="styles.filter()"
+ >
+ <SeverityIcon :severity="severity" />
+ {{ counts[severity] }}
+ </ToggleGroupItem>
+ </Tip>
+ </ToggleGroupRoot>
+</template>
diff --git a/src/components/design-check/SeverityIcon.vue b/src/components/design-check/SeverityIcon.vue
new file mode 100644
index 000000000..6a9e6355e
--- /dev/null
+++ b/src/components/design-check/SeverityIcon.vue
@@ -0,0 +1,27 @@
+<script setup lang="ts">
+import type { DesignIssueSeverity } from '@/app/editor/design-check/issues'
+import { severityIcon } from '@/theme/design-check'
+
+const { severity, class: className } = defineProps<{
+ severity: DesignIssueSeverity
+ class?: string
+}>()
+</script>
+
+<template>
+ <icon-lucide-circle-alert
+ v-if="severity === 'error'"
+ aria-hidden="true"
+ :class="severityIcon({ severity, class: className })"
+ />
+ <icon-lucide-triangle-alert
+ v-else-if="severity === 'warning'"
+ aria-hidden="true"
+ :class="severityIcon({ severity, class: className })"
+ />
+ <icon-lucide-lightbulb
+ v-else
+ aria-hidden="true"
+ :class="severityIcon({ severity, class: className })"
+ />
+</template>
diff --git a/src/components/design-check/types.ts b/src/components/design-check/types.ts
new file mode 100644
index 000000000..181c35749
--- /dev/null
+++ b/src/components/design-check/types.ts
@@ -0,0 +1,32 @@
+import type { Component } from 'vue'
+
+import type { LintFixRequest } from '@open-pencil/core/lint'
+
+import type { IssueAction, IssueSwatch } from '@/app/editor/design-check/format'
+import type { DesignIssue, DesignIssueSeverity } from '@/app/editor/design-check/issues'
+
+export interface IssueRowView {
+ issue: DesignIssue
+ layerName: string
+ layerIcon: Component
+ detail: string | null
+ swatch: IssueSwatch | null
+ action: IssueAction | null
+ hidden: boolean
+ missing: boolean
+ selected: boolean
+ /** The page the layer is on, shown when it is not the current page. */
+ pageLabel: string | null
+}
+
+export interface IssueGroupView {
+ ruleId: string
+ severity: DesignIssueSeverity
+ title: string
+ help: string | null
+ rows: IssueRowView[]
+ /** Safe fixes of the rows, which the group applies together. */
+ fixes: LintFixRequest[]
+ /** Whether every safe fix binds a variable, which the group button names. */
+ bindsOnly: boolean
+}
diff --git a/src/components/design-check/useDesignCheckPanel.ts b/src/components/design-check/useDesignCheckPanel.ts
new file mode 100644
index 000000000..d1d2caee6
--- /dev/null
+++ b/src/components/design-check/useDesignCheckPanel.ts
@@ -0,0 +1,248 @@
+import { computed, nextTick, onBeforeUnmount, reactive, ref, watch, type Ref } from 'vue'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import {
+ issueDetail,
+ issueAction,
+ issueSwatch,
+ ruleHelp,
+ ruleTitle
+} from '@/app/editor/design-check/format'
+import {
+ countIssues,
+ DESIGN_ISSUE_SEVERITIES,
+ groupIssuesByRule,
+ issuesWithin,
+ type DesignIssue,
+ type DesignIssueSeverity
+} from '@/app/editor/design-check/issues'
+import { nodeIcon } from '@/app/editor/icons'
+import { appPreferences } from '@/app/settings/preferences/store'
+
+import type { IssueGroupView, IssueRowView } from './types'
+import { usePresetLabels } from './usePresetLabels'
+
+export type DesignCheckScope = 'page' | 'selection' | 'document'
+
+export type DesignCheckEmptyState =
+ | { kind: 'no-selection'; label: string; description: string }
+ | { kind: 'filtered'; label: string }
+ | { kind: 'clean'; label: string; description: string }
+
+function isHidden(graph: SceneGraph, nodeId: string): boolean {
+ let node = graph.getNode(nodeId)
+ while (node) {
+ if (!node.visible) return true
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ return false
+}
+
+/**
+ * State of the Lint panel: scope, filters, grouped rows and empty states. While the panel is
+ * shown it keeps the design check running and brings focused issues into view in `list`.
+ */
+export function useDesignCheckPanel(options: {
+ active: () => boolean
+ list: Readonly<Ref<HTMLElement | null>>
+}) {
+ const store = useEditorStore()
+ const messages = useDesignCheckMessages()
+ const presetLabels = usePresetLabels()
+ const check = store.designCheck
+
+ const scope = ref<DesignCheckScope>('page')
+ const visibleSeverities = ref<DesignIssueSeverity[]>([...DESIGN_ISSUE_SEVERITIES])
+ /** Explicit open state per rule; suggestions start collapsed, problems start open. */
+ const openGroups = reactive(new Map<string, boolean>())
+
+ const snapshot = computed(() => {
+ const current = check.snapshot.value
+ return current?.pageId === store.state.currentPageId ? current : null
+ })
+ const selectedIds = computed(() => store.state.selectedIds)
+
+ /** Every checked page's issues, in page order, the current page from its live check. */
+ const documentIssues = computed<DesignIssue[]>(() => {
+ const results = check.pages.results.value
+ return store.graph
+ .getPages()
+ .flatMap((page) =>
+ page.id === store.state.currentPageId
+ ? (snapshot.value?.issues ?? [])
+ : (results.get(page.id) ?? [])
+ )
+ })
+
+ const scopedIssues = computed<DesignIssue[]>(() => {
+ const issues = snapshot.value?.issues ?? []
+ if (scope.value === 'page') return issues
+ if (scope.value === 'document') return documentIssues.value
+ return issuesWithin(issues, store.graph, selectedIds.value)
+ })
+ const counts = computed(() => countIssues(scopedIssues.value))
+ const filtersActive = computed(
+ () => visibleSeverities.value.length < DESIGN_ISSUE_SEVERITIES.length
+ )
+
+ function rowView(issue: DesignIssue): IssueRowView {
+ void store.state.sceneVersion
+ const node = store.graph.getNode(issue.nodeId)
+ return {
+ issue,
+ layerName: node?.name ?? issue.nodeName,
+ layerIcon: nodeIcon(node ?? { type: 'FRAME', layoutMode: 'NONE' }),
+ detail: issueDetail(issue, messages.value),
+ swatch: issueSwatch(issue),
+ action: node ? issueAction(issue, messages.value) : null,
+ hidden: node ? isHidden(store.graph, node.id) : false,
+ missing: !node,
+ selected: selectedIds.value.has(issue.nodeId),
+ pageLabel:
+ issue.pageId === store.state.currentPageId
+ ? null
+ : messages.value.onPage({ page: store.graph.getNode(issue.pageId)?.name ?? '' })
+ }
+ }
+
+ const groups = computed<IssueGroupView[]>(() =>
+ groupIssuesByRule(
+ scopedIssues.value.filter((issue) => visibleSeverities.value.includes(issue.severity))
+ ).map((group) => {
+ const rows = group.issues.map(rowView)
+ const fixes = rows.flatMap(({ issue, missing }) =>
+ issue.fix && !missing ? [{ nodeId: issue.nodeId, fix: issue.fix }] : []
+ )
+ return {
+ ruleId: group.ruleId,
+ severity: group.severity,
+ title: ruleTitle(group.ruleId, messages.value),
+ help: ruleHelp(group.ruleId, messages.value),
+ rows,
+ fixes,
+ bindsOnly: fixes.every(({ fix }) => fix.kind === 'bind-variable')
+ }
+ })
+ )
+
+ /** Pages still waiting for their background check, while the document is listed. */
+ const checkingDocument = computed(
+ () => scope.value === 'document' && check.pages.queued.value.length > 0
+ )
+
+ /** Pages a large file has not loaded yet, which the document list cannot include. */
+ const documentNote = computed(() => {
+ const count = check.pages.notLoaded.value.length
+ return scope.value === 'document' && count > 0
+ ? messages.value.documentUnchecked({ count })
+ : null
+ })
+
+ const emptyState = computed<DesignCheckEmptyState | null>(() => {
+ if (!snapshot.value) return null
+ if (checkingDocument.value && groups.value.length === 0) return null
+ if (scope.value === 'selection' && selectedIds.value.size === 0) {
+ return {
+ kind: 'no-selection',
+ label: messages.value.noSelection,
+ description: messages.value.noSelectionDescription
+ }
+ }
+ if (groups.value.length > 0) return null
+ if (filtersActive.value && scopedIssues.value.length > 0) {
+ return { kind: 'filtered', label: messages.value.noFilteredIssues }
+ }
+ const emptyLabels: Record<DesignCheckScope, string> = {
+ page: messages.value.emptyPage,
+ selection: messages.value.emptySelection,
+ document: messages.value.emptyDocument
+ }
+ return {
+ kind: 'clean',
+ label: emptyLabels[scope.value],
+ description: messages.value.emptyDescription({
+ preset: presetLabels.value[appPreferences.value.designCheck.preset]
+ })
+ }
+ })
+
+ function isGroupOpen(group: IssueGroupView): boolean {
+ return openGroups.get(group.ruleId) ?? group.severity !== 'info'
+ }
+
+ function setGroupOpen(ruleId: string, open: boolean) {
+ openGroups.set(ruleId, open)
+ }
+
+ function clearFilters() {
+ visibleSeverities.value = [...DESIGN_ISSUE_SEVERITIES]
+ }
+
+ /** Highlights a row's layer on the canvas; layers on other pages are not on screen. */
+ function hoverRow(row: IssueRowView | null) {
+ const onCanvas = row && !row.missing && row.issue.pageId === store.state.currentPageId
+ check.highlightIssue(onCanvas ? row.issue : null)
+ }
+
+ watch(
+ options.active,
+ (visible) => {
+ check.panelVisible.value = visible
+ if (!visible) check.highlightIssue(null)
+ },
+ { immediate: true }
+ )
+
+ watch(
+ () => options.active() && scope.value === 'document',
+ (listing) => {
+ check.documentScope.value = listing
+ },
+ { immediate: true }
+ )
+
+ onBeforeUnmount(() => {
+ check.panelVisible.value = false
+ check.documentScope.value = false
+ check.highlightIssue(null)
+ })
+
+ /** Shows the focused issue's row, e.g. after a canvas marker click: unfiltered, open, in view. */
+ watch(
+ [check.focusedIssueId, groups],
+ async ([issueId], [previousId]) => {
+ if (!issueId || issueId === previousId) return
+ const issue = check.snapshot.value?.issues.find((candidate) => candidate.id === issueId)
+ if (!issue) return
+ if (!visibleSeverities.value.includes(issue.severity)) {
+ visibleSeverities.value = [...visibleSeverities.value, issue.severity]
+ }
+ openGroups.set(issue.ruleId, true)
+ await nextTick()
+ options.list.value
+ ?.querySelector(`[data-issue-id="${CSS.escape(issueId)}"]`)
+ ?.scrollIntoView({ block: 'center' })
+ },
+ { flush: 'post' }
+ )
+
+ return {
+ check,
+ scope,
+ visibleSeverities,
+ counts,
+ groups,
+ emptyState,
+ documentNote,
+ loading: computed(
+ () => snapshot.value === null || (checkingDocument.value && groups.value.length === 0)
+ ),
+ isGroupOpen,
+ setGroupOpen,
+ clearFilters,
+ hoverRow
+ }
+}
diff --git a/src/components/design-check/usePresetLabels.ts b/src/components/design-check/usePresetLabels.ts
new file mode 100644
index 000000000..43cbbd76e
--- /dev/null
+++ b/src/components/design-check/usePresetLabels.ts
@@ -0,0 +1,15 @@
+import { computed } from 'vue'
+
+import { useDesignCheckMessages } from '@open-pencil/vue'
+
+import type { DesignCheckPreset } from '@/app/settings/preferences/store'
+
+/** Localized names of the rule presets, shared by the rules menu and empty states. */
+export function usePresetLabels() {
+ const messages = useDesignCheckMessages()
+ return computed<Record<DesignCheckPreset, string>>(() => ({
+ recommended: messages.value.presetRecommended,
+ strict: messages.value.presetStrict,
+ accessibility: messages.value.presetAccessibility
+ }))
+}
diff --git a/src/components/editor/ZoomDropdown.vue b/src/components/editor/ZoomDropdown.vue
index 70d5b90fb..2a199e239 100644
--- a/src/components/editor/ZoomDropdown.vue
+++ b/src/components/editor/ZoomDropdown.vue
@@ -12,6 +12,8 @@ import { nextTick, ref, watch } from 'vue'
import { useEditorCommands, useI18n, formatShortcut } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
+import { setDesignIssuesOnCanvas } from '@/app/settings/preferences/apply'
+import { appPreferences } from '@/app/settings/preferences/store'
import { appMenuShortcut, appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'
import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
@@ -165,6 +167,16 @@ watch(open, (v) => {
/>
<span class="flex-1">{{ panels.multiplayerCursors }}</span>
</DropdownMenuItem>
+ <DropdownMenuItem
+ :class="itemCls"
+ @select.prevent="setDesignIssuesOnCanvas(!appPreferences.designCheck.showOnCanvas)"
+ >
+ <icon-lucide-check
+ v-if="appPreferences.designCheck.showOnCanvas"
+ class="absolute left-2 size-3.5"
+ />
+ <span class="flex-1">{{ menuText.designIssues }}</span>
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenuRoot>
diff --git a/src/components/ui/menu/menu.ts b/src/components/ui/menu/menu.ts
index 19028cc42..5b3980887 100644
--- a/src/components/ui/menu/menu.ts
+++ b/src/components/ui/menu/menu.ts
@@ -5,6 +5,7 @@ export const menu = tv({
content: 'z-50 rounded-xl bg-panel p-1 shadow-[0_8px_30px_rgb(0_0_0/0.4)]',
item: 'flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-[11px] outline-none select-none data-[disabled]:cursor-default data-[disabled]:text-muted/50 data-[highlighted]:bg-hover',
separator: 'mx-1 my-1 h-px bg-border',
+ label: 'px-2 pt-1.5 pb-1 text-[11px] text-muted select-none',
shortcut: 'text-[11px] text-muted',
icon: 'size-3 text-muted',
subTrigger:
@@ -41,6 +42,7 @@ interface MenuUI {
content?: string
item?: string
separator?: string
+ label?: string
shortcut?: string
icon?: string
subTrigger?: string
@@ -52,6 +54,7 @@ export function useMenuUI(ui?: MenuUI) {
content: cls.content({ class: ui?.content }),
item: cls.item({ class: ui?.item }),
separator: cls.separator({ class: ui?.separator }),
+ label: cls.label({ class: ui?.label }),
shortcut: cls.shortcut({ class: ui?.shortcut }),
icon: cls.icon({ class: ui?.icon }),
subTrigger: cls.subTrigger({ class: ui?.subTrigger })
diff --git a/src/theme/design-check.ts b/src/theme/design-check.ts
new file mode 100644
index 000000000..4c9cf4e48
--- /dev/null
+++ b/src/theme/design-check.ts
@@ -0,0 +1,94 @@
+import { tv } from 'tailwind-variants'
+
+export const designCheck = tv({
+ slots: {
+ root: 'flex min-h-0 flex-1 flex-col',
+ toolbar: 'flex shrink-0 flex-col gap-2 border-b border-border px-3 pt-2 pb-2',
+ toolbarRow: 'flex min-w-0 items-center gap-1',
+ filters: 'flex min-w-0 flex-1 items-center gap-0.5',
+ filter:
+ 'flex h-6 cursor-pointer items-center gap-1 rounded px-1.5 text-[11px] text-surface tabular-nums outline-none hover:bg-hover focus-visible:ring-1 focus-visible:ring-panel-focus data-[state=off]:text-muted data-[state=off]:[&_svg]:opacity-50',
+ list: 'scrollbar-thin min-h-0 flex-1 overflow-x-hidden overflow-y-auto pb-2',
+ status: 'px-3 py-2 text-[11px] text-muted',
+ // Group slots override the matching AppCollapsible slots.
+ group: 'group/issue border-b border-border/60 last:border-b-0',
+ groupHeader: 'group/header relative h-8 gap-0 pr-2 pl-1.5',
+ groupTrigger:
+ 'h-7 cursor-pointer gap-1.5 rounded pr-1 text-[11px] focus-visible:ring-1 focus-visible:ring-panel-focus',
+ chevron: 'size-3 text-muted',
+ groupLabel: 'flex min-w-0 flex-1 items-center gap-1.5',
+ groupTitle: 'block min-w-0 truncate font-semibold',
+ groupCount:
+ 'ml-auto shrink-0 pr-1 text-muted tabular-nums group-focus-within/header:invisible group-hover/header:invisible group-data-[menu-open]/issue:invisible',
+ groupActions:
+ 'invisible absolute inset-y-0 right-1.5 flex items-center gap-0.5 group-focus-within/header:visible group-hover/header:visible group-data-[menu-open]/issue:visible',
+ rows: 'pb-1',
+ rowItem: 'group/row relative',
+ row: 'flex h-7 w-full cursor-default items-center gap-2 pr-2 pl-7 text-left text-[11px] text-surface outline-none hover:bg-hover focus-visible:bg-hover data-[selected]:bg-panel-selected-muted data-[missing]:text-muted',
+ rowIcon: 'size-3 shrink-0 text-muted',
+ rowName: 'min-w-0 flex-1 truncate',
+ rowTag: 'shrink-0 text-[10px] text-muted',
+ rowDetail: 'flex max-w-[50%] min-w-0 shrink items-center gap-1.5 text-muted tabular-nums',
+ rowDetailText: 'truncate',
+ rowAction:
+ 'absolute top-1/2 right-1.5 hidden h-5 -translate-y-1/2 cursor-pointer items-center rounded bg-panel px-1.5 text-accent shadow-[0_0_0_1px_var(--color-border)] outline-none group-focus-within/row:flex group-hover/row:flex hover:bg-hover focus-visible:ring-1 focus-visible:ring-panel-focus',
+ contrastSwatch:
+ 'flex h-3.5 shrink-0 items-center rounded-[3px] px-[3px] text-[9px] leading-none font-semibold shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)]',
+ swatch: 'size-2.5 shrink-0 rounded-[3px] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)]',
+ more: 'mb-1 ml-6'
+ }
+})
+
+export const severityIcon = tv({
+ base: 'size-3 shrink-0',
+ variants: {
+ severity: {
+ error: 'text-issue-error',
+ warning: 'text-issue-warning',
+ info: 'text-issue-info'
+ }
+ }
+})
+
+/** The Layers panel mark: a severity icon on a layer, a dot on a collapsed layer holding issues. */
+export const layerIssueMark = tv({
+ slots: {
+ root: 'flex size-4 shrink-0 items-center justify-center',
+ dot: 'size-1.5 rounded-full'
+ },
+ variants: {
+ severity: {
+ error: { dot: 'bg-issue-error' },
+ warning: { dot: 'bg-issue-warning' },
+ info: { dot: 'bg-issue-info' }
+ }
+ }
+})
+
+/** The page list badge: the count of errors and warnings, in the most severe color. */
+export const pageIssueBadge = tv({
+ base: 'flex h-3.5 min-w-3.5 shrink-0 items-center justify-center rounded-full px-1 text-[9px] leading-none font-semibold tabular-nums',
+ variants: {
+ severity: {
+ error: 'bg-issue-error text-white',
+ warning: 'bg-issue-warning text-black'
+ }
+ }
+})
+
+export const issueTooltip = tv({
+ slots: {
+ content:
+ 'pointer-events-none z-50 w-64 rounded-lg bg-panel py-1.5 text-[11px] text-surface shadow-[0_0_0_1px_var(--color-border),0_8px_30px_rgb(0_0_0/0.35)]',
+ header: 'flex items-center gap-1.5 px-2.5 pt-0.5 pb-1 font-semibold',
+ headerIcon: 'size-3 shrink-0 text-muted',
+ headerText: 'min-w-0 truncate',
+ item: 'flex items-start gap-1.5 px-2.5 py-1',
+ itemIcon: 'mt-px',
+ itemBody: 'min-w-0 flex-1',
+ itemTitle: 'truncate',
+ itemDetail: 'truncate text-muted tabular-nums',
+ more: 'px-2.5 py-1 pl-7 text-muted',
+ hint: 'mt-1 border-t border-border px-2.5 pt-1.5 text-muted'
+ }
+})
diff --git a/src/theme/panel/properties-tabs.ts b/src/theme/panel/properties-tabs.ts
new file mode 100644
index 000000000..2e71e6528
--- /dev/null
+++ b/src/theme/panel/properties-tabs.ts
@@ -0,0 +1,16 @@
+import { tv } from 'tailwind-variants'
+
+/**
+ * Tabs across the top of the right panel. Tabs with icons show their labels whenever the whole row
+ * fits and drop them together when it does not; labels stay available to screen readers. The row
+ * clips horizontally rather than scrolls, so focusing a control never shifts the panel.
+ */
+export const propertiesTabs = tv({
+ slots: {
+ list: '@container/tabs flex h-10 shrink-0 items-center gap-0.5 overflow-x-clip border-b border-border px-2',
+ trigger:
+ 'relative flex shrink-0 items-center gap-1 rounded px-1.5 py-1 text-[11px] text-muted outline-none hover:text-surface focus-visible:ring-1 focus-visible:ring-panel-focus data-[state=active]:font-semibold data-[state=active]:text-surface after:absolute after:inset-x-1.5 after:-bottom-[9px] after:h-0.5 after:rounded-full after:bg-transparent data-[state=active]:after:bg-accent',
+ icon: 'size-3 shrink-0 data-[severity=error]:text-issue-error data-[severity=warning]:text-issue-warning',
+ label: 'sr-only @[240px]/tabs:not-sr-only'
+ }
+})
diff --git a/tests/app/editor/design-check/issues.test.ts b/tests/app/editor/design-check/issues.test.ts
new file mode 100644
index 000000000..2426e528a
--- /dev/null
+++ b/tests/app/editor/design-check/issues.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { LintMessage } from '@open-pencil/core/lint'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import {
+ countIssues,
+ groupIssuesByRule,
+ highlightForIssue,
+ issuesWithin,
+ markersForIssues,
+ mostSevereIssue,
+ toDesignIssues
+} from '@/app/editor/design-check/issues'
+
+function message(
+ ruleId: string,
+ nodeId: string,
+ severity: LintMessage['severity'],
+ data?: LintMessage['data']
+): LintMessage {
+ return { ruleId, nodeId, severity, message: ruleId, nodeName: nodeId, nodePath: [nodeId], data }
+}
+
+describe('design issues', () => {
+ test('keep their identity across re-checks, even with several findings per layer', () => {
+ const messages = [
+ message('consistent-spacing', 'card', 'warning'),
+ message('consistent-spacing', 'card', 'warning'),
+ message('no-groups', 'card', 'info')
+ ]
+
+ const first = toDesignIssues(messages, 'page').map((issue) => issue.id)
+ const second = toDesignIssues(messages, 'page').map((issue) => issue.id)
+
+ expect(first).toEqual([
+ 'consistent-spacing:card:0',
+ 'consistent-spacing:card:1',
+ 'no-groups:card:0'
+ ])
+ expect(second).toEqual(first)
+ })
+
+ test('mark each layer once, by its most severe problem, and leave suggestions to the panel', () => {
+ const issues = toDesignIssues(
+ [
+ message('consistent-spacing', 'card', 'warning'),
+ message('color-contrast', 'card', 'error'),
+ message('no-groups', 'group', 'info')
+ ],
+ 'page'
+ )
+
+ expect(markersForIssues(issues)).toEqual([{ nodeId: 'card', severity: 'error', count: 2 }])
+ expect(countIssues(issues)).toEqual({ error: 1, warning: 1, info: 1 })
+ expect(mostSevereIssue(issues)?.ruleId).toBe('color-contrast')
+ })
+
+ test('group by rule, most severe and most frequent first', () => {
+ const issues = toDesignIssues(
+ [
+ message('no-default-names', 'a', 'info'),
+ message('consistent-spacing', 'a', 'warning'),
+ message('no-hardcoded-colors', 'b', 'warning'),
+ message('no-hardcoded-colors', 'c', 'warning'),
+ message('color-contrast', 'd', 'error')
+ ],
+ 'page'
+ )
+
+ expect(groupIssuesByRule(issues).map((group) => [group.ruleId, group.issues.length])).toEqual([
+ ['color-contrast', 1],
+ ['no-hardcoded-colors', 2],
+ ['consistent-spacing', 1],
+ ['no-default-names', 1]
+ ])
+ })
+
+ test('narrow to the selected layers and everything inside them', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const card = graph.createNode('FRAME', pageId, { name: 'Card' })
+ const label = graph.createNode('TEXT', card.id, { name: 'Label' })
+ const other = graph.createNode('FRAME', pageId, { name: 'Other' })
+ const issues = toDesignIssues(
+ [
+ message('color-contrast', label.id, 'error'),
+ message('no-groups', other.id, 'info'),
+ message('consistent-spacing', card.id, 'warning')
+ ],
+ 'page'
+ )
+
+ const inside = issuesWithin(issues, graph, new Set([card.id]))
+
+ expect(inside.map((issue) => issue.nodeId)).toEqual([label.id, card.id])
+ expect(issuesWithin(issues, graph, new Set())).toEqual([])
+ })
+
+ test('highlight touch targets with the size they should reach', () => {
+ const [target, text] = toDesignIssues(
+ [
+ message('touch-target-size', 'chip', 'warning', { width: 60, height: 24, minSize: 44 }),
+ message('min-text-size', 'caption', 'warning', { fontSize: 10, minSize: 12 })
+ ],
+ 'page'
+ )
+
+ expect(highlightForIssue(target)).toEqual({
+ nodeId: 'chip',
+ severity: 'warning',
+ minSize: { width: 44, height: 44 }
+ })
+ expect(highlightForIssue(text).minSize).toBeUndefined()
+ })
+})
diff --git a/tests/app/editor/design-check/layers.test.ts b/tests/app/editor/design-check/layers.test.ts
new file mode 100644
index 000000000..78bcc4dd3
--- /dev/null
+++ b/tests/app/editor/design-check/layers.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { LintMessage } from '@open-pencil/core/lint'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { toDesignIssues } from '@/app/editor/design-check/issues'
+import { layerIssueMarks } from '@/app/editor/design-check/layers'
+
+function message(ruleId: string, nodeId: string, severity: LintMessage['severity']): LintMessage {
+ return { ruleId, nodeId, severity, message: ruleId, nodeName: nodeId, nodePath: [nodeId] }
+}
+
+describe('layer issue marks', () => {
+ test('mark layers with errors and warnings and the ancestors that contain them', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const card = graph.createNode('FRAME', pageId, { name: 'Card' })
+ const row = graph.createNode('FRAME', card.id, { name: 'Row' })
+ const label = graph.createNode('TEXT', row.id, { name: 'Label' })
+ const icon = graph.createNode('VECTOR', card.id, { name: 'Icon' })
+
+ const marks = layerIssueMarks(
+ toDesignIssues(
+ [
+ message('color-contrast', label.id, 'error'),
+ message('touch-target-size', icon.id, 'warning'),
+ message('min-text-size', label.id, 'warning'),
+ message('no-groups', card.id, 'info')
+ ],
+ 'page'
+ ),
+ graph
+ )
+
+ expect(marks.get(label.id)).toEqual({ severity: 'error', count: 2, own: true })
+ expect(marks.get(icon.id)).toEqual({ severity: 'warning', count: 1, own: true })
+ expect(marks.get(row.id)).toEqual({ severity: 'error', count: 0, own: false })
+ // A suggestion on the card is left to the Lint panel; it still contains an error.
+ expect(marks.get(card.id)).toEqual({ severity: 'error', count: 0, own: false })
+ expect(marks.has(pageId)).toBe(false)
+ })
+})
diff --git a/tests/app/editor/design-check/pages.test.ts b/tests/app/editor/design-check/pages.test.ts
new file mode 100644
index 000000000..ffb21b244
--- /dev/null
+++ b/tests/app/editor/design-check/pages.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import type { DesignIssue } from '@/app/editor/design-check/issues'
+import { createPageChecks, pageOf } from '@/app/editor/design-check/pages'
+
+/** Lets every scheduled zero-delay check run. */
+async function settle() {
+ for (let i = 0; i < 10; i++) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0)
+ })
+ }
+}
+
+function issue(nodeId: string, pageId: string, severity: DesignIssue['severity']): DesignIssue {
+ return {
+ id: `rule:${nodeId}:0`,
+ ruleId: 'rule',
+ nodeId,
+ pageId,
+ severity,
+ message: 'rule',
+ nodeName: nodeId,
+ nodePath: [nodeId]
+ }
+}
+
+/** `pendingNames`: pages a large file has not loaded yet, by name. */
+function setup(pendingNames: string[] = []) {
+ const graph = new SceneGraph()
+ const first = graph.getPages()[0]
+ const second = graph.addPage('Second')
+ const third = graph.addPage('Third')
+ const checked: string[] = []
+ const checks = createPageChecks({
+ graph: () => graph,
+ currentPageId: () => first.id,
+ isPending: (pageId) => pendingNames.includes(graph.getNode(pageId)?.name ?? ''),
+ isBusy: () => false,
+ check: (pageId) => {
+ checked.push(pageId)
+ return [issue(`layer-on-${pageId}`, pageId, 'error')]
+ },
+ delays: { idle: 0, step: 0 }
+ })
+ return { graph, first, second, third, checked, checks }
+}
+
+describe('background page checks', () => {
+ test('check every other loaded page once, and take the current page from the live check', async () => {
+ const { first, second, third, checked, checks } = setup()
+
+ checks.start()
+ checks.report(first.id, [issue('live', first.id, 'warning')])
+ await settle()
+
+ expect(checked.toSorted()).toEqual([second.id, third.id].toSorted())
+ expect(checks.counts.value.get(first.id)).toEqual({ error: 0, warning: 1, info: 0 })
+ expect(checks.counts.value.get(second.id)).toEqual({ error: 1, warning: 0, info: 0 })
+ expect(checks.queued.value).toEqual([])
+ checks.stop()
+ })
+
+ test('check again only the page an edit touched', async () => {
+ const { graph, second, third, checked, checks } = setup()
+ checks.start()
+ await settle()
+ checked.length = 0
+
+ const layer = graph.createNode('FRAME', third.id, { name: 'Card' })
+ checks.invalidate(pageOf(graph, layer.id))
+ await settle()
+
+ expect(checked).toEqual([third.id])
+ expect(checked).not.toContain(second.id)
+ checks.stop()
+ })
+
+ test('leave pages a large file has not loaded unchecked', async () => {
+ const { first, second, third, checked, checks } = setup(['Third'])
+
+ checks.start()
+ checks.report(first.id, [])
+ await settle()
+
+ expect(checked).toEqual([second.id])
+ expect(checks.notLoaded.value).toEqual([third.id])
+ expect(checks.queued.value).toEqual([])
+ checks.stop()
+ })
+})
+
+describe('pageOf', () => {
+ test('finds the page of a nested layer, and a page is its own page', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const frame = graph.createNode('FRAME', page.id)
+ const child = graph.createNode('RECTANGLE', frame.id)
+
+ expect(pageOf(graph, child.id)).toBe(page.id)
+ expect(pageOf(graph, page.id)).toBe(page.id)
+ expect(pageOf(graph, null)).toBeNull()
+ })
+})
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png
index a6d0d054a..c4e466ae7 100644
Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png
index 7c1c5102f..88a4d6df7 100644
Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png differ
diff --git a/tests/e2e/design-check/design-check.spec.ts b/tests/e2e/design-check/design-check.spec.ts
new file mode 100644
index 000000000..1b7622b17
--- /dev/null
+++ b/tests/e2e/design-check/design-check.spec.ts
@@ -0,0 +1,417 @@
+import type { Page } from '@playwright/test'
+
+import type { Vector } from '@open-pencil/core'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-rulers')
+
+const CARD = { x: 80, y: 120, width: 320, height: 200 }
+/** Where the Close button's marker sits at zoom 1: just outside its top-right corner. */
+const CLOSE_BUTTON = { x: 340, y: 140, width: 24, height: 20 }
+const CLOSE_MARKER = {
+ x: CARD.x + CLOSE_BUTTON.x + CLOSE_BUTTON.width + 12,
+ y: CARD.y + CLOSE_BUTTON.y - 12
+}
+
+interface Scene {
+ cardId: string
+ captionId: string
+ closeId: string
+ swatchId: string
+}
+
+function buildScene(page: Page): Promise<Scene> {
+ return page.evaluate(
+ ({ card, close }) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.zoom = 1
+ store.state.panX = 0
+ store.state.panY = 0
+ const pageId = store.state.currentPageId
+ const white = { r: 1, g: 1, b: 1, a: 1 }
+ const brand = { r: 0.23, g: 0.51, b: 0.96, a: 1 }
+ store.graph.addCollection({
+ id: 'check-colors',
+ name: 'Colors',
+ modes: [{ modeId: 'light', name: 'Light' }],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ store.graph.addVariable({
+ id: 'check-brand',
+ name: 'Colors/Brand/500',
+ type: 'COLOR',
+ collectionId: 'check-colors',
+ valuesByMode: { light: brand },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ const frame = store.graph.createNode('FRAME', pageId, {
+ name: 'Card',
+ ...card,
+ fills: [{ type: 'SOLID', color: white, visible: true, opacity: 1 }]
+ })
+ const caption = store.graph.createNode('TEXT', frame.id, {
+ name: 'Caption',
+ x: 24,
+ y: 24,
+ width: 200,
+ height: 24,
+ text: 'Pale caption',
+ fontSize: 16,
+ fills: [
+ { type: 'SOLID', color: { r: 0.82, g: 0.82, b: 0.82, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ const swatch = store.graph.createNode('RECTANGLE', frame.id, {
+ name: 'Swatch',
+ x: 24,
+ y: 80,
+ width: 96,
+ height: 64,
+ fills: [{ type: 'SOLID', color: brand, visible: true, opacity: 1 }]
+ })
+ const closeButton = store.graph.createNode('FRAME', frame.id, {
+ name: 'Close button',
+ ...close,
+ fills: [{ type: 'SOLID', color: white, visible: true, opacity: 1 }]
+ })
+ store.clearSelection()
+ store.requestRender()
+ return {
+ cardId: frame.id,
+ captionId: caption.id,
+ closeId: closeButton.id,
+ swatchId: swatch.id
+ }
+ },
+ { card: CARD, close: CLOSE_BUTTON }
+ )
+}
+
+function lintPanel(page: Page) {
+ return page.getByRole('region', { name: 'Lint' })
+}
+
+async function openLint(page: Page) {
+ await page.getByRole('tab', { name: /^Lint/ }).click()
+ await expect(lintPanel(page).getByText('Low text contrast')).toBeVisible()
+}
+
+function highlightedNode(page: Page) {
+ return page.evaluate(
+ () => window.openPencil?.getStore?.().state.designIssues?.highlight?.nodeId ?? null
+ )
+}
+
+/** Checks settle shortly after edits; markers exist once the check has published them. */
+async function waitForMarkers(page: Page) {
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.openPencil?.getStore?.().state.designIssues?.markers.length ?? 0)
+ )
+ .toBeGreaterThan(0)
+ await page.evaluate(() => new Promise(requestAnimationFrame))
+}
+
+/**
+ * Markers are drawn a frame after the check publishes them, so the pointer keeps moving over the
+ * marker, as a person's would, until the canvas reports it under the pointer.
+ */
+async function hoverMarker(point: Vector) {
+ let nudge = 0
+ await expect
+ .poll(async () => {
+ nudge = nudge === 0 ? 1 : 0
+ await editor.canvas.hover(point.x + nudge, point.y)
+ return editor.page.evaluate(
+ () => window.openPencil?.getStore?.().state.designIssues?.hoveredMarkerKey ?? null
+ )
+ })
+ .not.toBeNull()
+}
+
+function selectedIds(page: Page) {
+ return page.evaluate(() => [...(window.openPencil?.getStore?.().state.selectedIds ?? [])])
+}
+
+test.afterEach(async () => {
+ await editor.page.getByRole('tab', { name: 'Design' }).click()
+})
+
+test('Lint lists issues by rule and connects rows to the canvas', async () => {
+ const scene = await buildScene(editor.page)
+ await openLint(editor.page)
+ const panel = lintPanel(editor.page)
+
+ await expect(panel.getByText('Small touch target')).toBeVisible()
+ await expect(panel.getByText('Unbound color')).toBeVisible()
+ const captionRow = panel.locator(`[data-node-id="${scene.captionId}"]`)
+ await expect(captionRow).toContainText('Caption')
+ await expect(captionRow).toContainText(':1')
+
+ await captionRow.hover()
+ await expect.poll(() => highlightedNode(editor.page)).toBe(scene.captionId)
+
+ await captionRow.click()
+ await expect.poll(() => selectedIds(editor.page)).toEqual([scene.captionId])
+ await expect(captionRow).toHaveAttribute('aria-current', 'true')
+
+ await panel.getByRole('button', { name: 'Rules' }).first().hover()
+ await expect.poll(() => highlightedNode(editor.page)).toBeNull()
+})
+
+test('Binding a suggested variable resolves the issue and undoes in one step', async () => {
+ const scene = await buildScene(editor.page)
+ await openLint(editor.page)
+ const panel = lintPanel(editor.page)
+ // Suggestions start collapsed; binding tokens is one of them.
+ await panel.getByText('Unbound color').click()
+ const swatchRow = panel.locator(`[data-node-id="${scene.swatchId}"]`)
+ await expect(swatchRow).toContainText('Brand/500')
+
+ // The fix is a sibling of the row button, in the same list item.
+ const swatchItem = panel
+ .getByRole('listitem')
+ .filter({ has: editor.page.locator(`[data-node-id="${scene.swatchId}"]`) })
+ await swatchItem.hover()
+ await swatchItem.getByRole('button', { name: 'Bind to Colors/Brand/500' }).click()
+
+ await expect(panel.getByText('Unbound color')).toHaveCount(0)
+ await expect
+ .poll(() =>
+ editor.page.evaluate(
+ (id) => window.openPencil?.getStore?.().graph.getNode(id)?.boundVariables['fills/0/color'],
+ scene.swatchId
+ )
+ )
+ .toBe('check-brand')
+
+ await editor.page.keyboard.press('ControlOrMeta+z')
+ await expect(panel.getByText('Unbound color')).toBeVisible()
+})
+
+test('A suggestion applies to its row only', async () => {
+ const scene = await buildScene(editor.page)
+ const noteId = await editor.page.evaluate((cardId) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return store.graph.createNode('TEXT', cardId, {
+ name: 'Footnote',
+ x: 24,
+ y: 160,
+ width: 200,
+ height: 14,
+ text: 'Small print',
+ fontSize: 10,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]
+ }).id
+ }, scene.cardId)
+ await openLint(editor.page)
+ const panel = lintPanel(editor.page)
+ const noteItem = panel
+ .getByRole('listitem')
+ .filter({ has: editor.page.locator(`[data-node-id="${noteId}"]`) })
+
+ await noteItem.hover()
+ await noteItem.getByRole('button', { name: 'Change to 12 px' }).click()
+
+ await expect(panel.getByText('Small text')).toHaveCount(0)
+ await expect
+ .poll(() =>
+ editor.page.evaluate(
+ (id) => window.openPencil?.getStore?.().graph.getNode(id)?.fontSize,
+ noteId
+ )
+ )
+ .toBe(12)
+})
+
+test('A rule can be turned off from its group and turned back on from the rules menu', async () => {
+ await buildScene(editor.page)
+ await openLint(editor.page)
+ const panel = lintPanel(editor.page)
+ const group = panel.locator('[data-rule-id="touch-target-size"]')
+
+ await group.getByText('Small touch target').hover()
+ await group.getByRole('button', { name: 'Rule actions' }).click()
+ await editor.page.getByRole('menuitem', { name: 'Turn off rule' }).click()
+ await expect(panel.getByText('Small touch target')).toHaveCount(0)
+
+ await panel.getByRole('button', { name: 'Rules' }).first().click()
+ await editor.page.getByRole('menuitem', { name: 'Turn on 1 turned-off rules' }).click()
+ await expect(panel.getByText('Small touch target')).toBeVisible()
+})
+
+test('Canvas markers explain themselves on hover and open Lint on click', async () => {
+ const scene = await buildScene(editor.page)
+ await waitForMarkers(editor.page)
+
+ await hoverMarker(CLOSE_MARKER)
+ const tooltip = editor.page.getByTestId('issue-marker-tooltip')
+ await expect(tooltip).toContainText('Close button')
+ await expect(tooltip).toContainText('Small touch target')
+ await expect.poll(() => highlightedNode(editor.page)).toBe(scene.closeId)
+ 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 + 100, width: 640, height: 260 }
+ })
+ ).toMatchSnapshot('design-check-marker-hover.png')
+
+ await editor.canvas.click(CLOSE_MARKER.x, CLOSE_MARKER.y)
+ await expect(tooltip).toHaveCount(0)
+ await expect.poll(() => selectedIds(editor.page)).toEqual([scene.closeId])
+ await expect(editor.page.getByRole('tab', { name: /^Lint/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ await expect(lintPanel(editor.page).locator(`[data-node-id="${scene.closeId}"]`)).toBeVisible()
+})
+
+/** Edge pins sit this far inside the canvas, leaving room for the chevron they point with. */
+const EDGE_PIN_INSET = 12
+
+/**
+ * Where the edge pin for a layer off screen sits, following the canvas: the ray from the
+ * viewport center toward the layer, where it leaves the inset viewport.
+ */
+function edgePinCenter(width: number, height: number, target: Vector): Vector {
+ const center = { x: width / 2, y: height / 2 }
+ const dx = target.x - center.x
+ const dy = target.y - center.y
+ const length = Math.hypot(dx, dy)
+ const halfWidth = width / 2 - EDGE_PIN_INSET
+ const halfHeight = height / 2 - EDGE_PIN_INSET
+ const t = Math.min(
+ dx === 0 ? Infinity : (halfWidth * length) / Math.abs(dx),
+ dy === 0 ? Infinity : (halfHeight * length) / Math.abs(dy)
+ )
+ const point = { x: center.x + (dx / length) * t, y: center.y + (dy / length) * t }
+ // The pill is 16px wide and stays inside the inset viewport.
+ return {
+ x: Math.min(Math.max(point.x, EDGE_PIN_INSET + 8), width - EDGE_PIN_INSET - 8),
+ y: Math.min(Math.max(point.y, EDGE_PIN_INSET + 8), height - EDGE_PIN_INSET - 8)
+ }
+}
+
+test('Issues off screen are pinned to the canvas edge and lead to the nearest most severe one', async () => {
+ const scene = await buildScene(editor.page)
+ await openLint(editor.page)
+ const canvas = await editor.canvas.canvas.boundingBox()
+ if (!canvas) throw new Error('Canvas has no bounding box')
+ // Pan the card off the left edge; the caption's contrast error is the most severe issue.
+ const panX = -1000
+ await editor.page.evaluate((x) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.panX = x
+ store.requestRender()
+ }, panX)
+ await waitForMarkers(editor.page)
+ const caption = { x: CARD.x + 24 + 100 + panX, y: CARD.y + 24 + 12 }
+ const pin = edgePinCenter(canvas.width, canvas.height, caption)
+
+ await hoverMarker(pin)
+ const tooltip = editor.page.getByTestId('issue-marker-tooltip')
+ await expect(tooltip).toContainText('Off screen to the left')
+ await expect(tooltip).toContainText('Low text contrast')
+ await editor.canvas.waitForRender()
+ expect(
+ await editor.page.screenshot({
+ clip: { x: canvas.x, y: canvas.y + pin.y - 20, width: 33, height: 40 }
+ })
+ ).toMatchSnapshot('design-check-edge-pin-hover.png')
+
+ await editor.canvas.click(pin.x, pin.y)
+ await expect.poll(() => selectedIds(editor.page)).toEqual([scene.captionId])
+ await expect
+ .poll(() => editor.page.evaluate(() => window.openPencil?.getStore?.().state.panX ?? 0))
+ .toBeGreaterThan(panX)
+ await expect(lintPanel(editor.page).locator(`[data-node-id="${scene.captionId}"]`)).toBeVisible()
+})
+
+test('Other pages are checked for the page list and the Document scope', async () => {
+ await buildScene(editor.page)
+ const cartCaptionId = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const checkout = store.graph.addPage('Checkout')
+ const cart = store.graph.createNode('FRAME', checkout.id, {
+ name: 'Cart',
+ width: 300,
+ height: 160,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
+ })
+ return store.graph.createNode('TEXT', cart.id, {
+ name: 'Cart caption',
+ x: 20,
+ y: 20,
+ width: 200,
+ height: 24,
+ text: 'Pale',
+ fontSize: 16,
+ fills: [
+ { type: 'SOLID', color: { r: 0.85, g: 0.85, b: 0.85, a: 1 }, visible: true, opacity: 1 }
+ ]
+ }).id
+ })
+
+ const checkoutBadge = editor.page
+ .getByTestId('pages-item')
+ .filter({ hasText: 'Checkout' })
+ .locator('[data-issue-severity="error"]')
+ await expect(checkoutBadge).toHaveText('1')
+ await expect(checkoutBadge).toHaveAccessibleName('Errors: 1')
+
+ await openLint(editor.page)
+ const panel = lintPanel(editor.page)
+ await panel.getByRole('button', { name: 'Document' }).click()
+ const cartRow = panel.locator(`[data-node-id="${cartCaptionId}"]`)
+ await expect(cartRow).toContainText('On Checkout')
+
+ await cartRow.click()
+ await expect
+ .poll(() =>
+ editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return store ? store.graph.getNode(store.state.currentPageId)?.name : null
+ })
+ )
+ .toBe('Checkout')
+ await expect.poll(() => selectedIds(editor.page)).toEqual([cartCaptionId])
+})
+
+test('Canvas markers and Layers panel marks can be turned off from the View menu', async () => {
+ await buildScene(editor.page)
+ await waitForMarkers(editor.page)
+ // The card is collapsed in the Layers panel, so it shows the error inside it as a dot.
+ const cardMark = editor.page
+ .getByTestId('layers-item')
+ .filter({ hasText: 'Card' })
+ .locator('[data-issue-severity="error"]')
+ await expect(cardMark).toBeVisible()
+ await expect(cardMark).toHaveAccessibleName('Contains errors or warnings')
+ const markerCount = () =>
+ editor.page.evaluate(
+ () => window.openPencil?.getStore?.().state.designIssues?.markers.length ?? 0
+ )
+
+ await editor.page.getByRole('menuitem', { name: 'View' }).click()
+ const toggle = editor.page.getByRole('menuitemcheckbox', { name: 'Design issues' })
+ await expect(toggle).toHaveAttribute('aria-checked', 'true')
+ await toggle.click()
+ await expect.poll(markerCount).toBe(0)
+ await expect(cardMark).toHaveCount(0)
+
+ await editor.canvas.hover(CLOSE_MARKER.x + 1, CLOSE_MARKER.y)
+ await expect(editor.page.getByTestId('issue-marker-tooltip')).toHaveCount(0)
+
+ await editor.page.getByRole('menuitem', { name: 'View' }).click()
+ await editor.page.getByRole('menuitemcheckbox', { name: 'Design issues' }).click()
+ await expect.poll(markerCount).toBeGreaterThan(0)
+})
diff --git a/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-edge-pin-hover-openpencil-darwin.png b/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-edge-pin-hover-openpencil-darwin.png
new file mode 100644
index 000000000..50ca3a099
Binary files /dev/null and b/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-edge-pin-hover-openpencil-darwin.png differ
diff --git a/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-marker-hover-openpencil-darwin.png b/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-marker-hover-openpencil-darwin.png
new file mode 100644
index 000000000..b14c9e40e
Binary files /dev/null and b/tests/e2e/design-check/design-check.spec.ts-snapshots/design-check-marker-hover-openpencil-darwin.png differ
diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.ts
index b5547d79e..39f1d561b 100644
--- a/tests/engine/app/shell/menu/schema.test.ts
+++ b/tests/engine/app/shell/menu/schema.test.ts
@@ -50,6 +50,7 @@ describe('APP_MENU_SCHEMA', () => {
expect(shellEntries.map((entry) => ('type' in entry ? '' : entry.id))).toEqual([
'open-storage-workspace',
+ 'view-design-issues',
'theme-light',
'theme-dark',
'theme-auto',
diff --git a/tests/engine/lint/variable-binding-validation.test.ts b/tests/engine/lint/variable-binding-validation.test.ts
index 8f7e8b259..e409c4472 100644
--- a/tests/engine/lint/variable-binding-validation.test.ts
+++ b/tests/engine/lint/variable-binding-validation.test.ts
@@ -56,6 +56,12 @@ describe('bindVariable emits node:updated event', () => {
// ─── 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 = {
@@ -70,6 +76,12 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {
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,
@@ -88,6 +100,7 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {
const messages: Array<{ message: string }> = []
const context = {
+ variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
@@ -112,6 +125,12 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {
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,
@@ -130,6 +149,7 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {
const messages: Array<{ message: string }> = []
const context = {
+ variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 41dea47c2..c38e2f2f2 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -71,6 +71,9 @@ ja:commands.paletteDescription
ja:credentials.apiKey
ja:credentials.getAPIKey
ja:credentials.rememberDevice
+ja:designCheck.ruleColorContrastHelp
+ja:designCheck.ruleMinTextSizeHelp
+ja:designCheck.ruleTouchTargetSizeHelp
ja:diagnostics.acpFailed
ja:diagnostics.chatCompleted
ja:diagnostics.chatFailed
@@ -207,6 +210,9 @@ zh-cn:commands.paletteDescription
zh-cn:credentials.apiKey
zh-cn:credentials.getAPIKey
zh-cn:credentials.rememberDevice
+zh-cn:designCheck.ruleColorContrastHelp
+zh-cn:designCheck.ruleMinTextSizeHelp
+zh-cn:designCheck.ruleTouchTargetSizeHelp
zh-cn:diagnostics.acpFailed
zh-cn:diagnostics.chatCompleted
zh-cn:diagnostics.chatFailed
diff --git a/tools/checks/i18n/src/check-locales.ts b/tools/checks/i18n/src/check-locales.ts
index a27498668..8fa4aa11f 100644
--- a/tools/checks/i18n/src/check-locales.ts
+++ b/tools/checks/i18n/src/check-locales.ts
@@ -14,6 +14,7 @@ import { hasMixedLatinAndCjk, placeholders } from './quality'
const LOCALES_DIR = 'packages/vue/src/i18n/locales'
const LOCALE_FILE_NAMES: Record<string, string> = {
+ designCheck: 'design-check',
variableTypes: 'variable-types'
}
const REQUIRED_INDEX_FILE = 'index.ts'
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index bd19cc699..21c9e76b4 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -96,6 +96,9 @@ fr:code.sourceDesignJSX
fr:code.sourceHTMLCSS
fr:code.sourceTailwindJSX
fr:common.ok
+fr:designCheck.scopeDocument
+fr:designCheck.scopePage
+fr:designCheck.suggestions
fr:diagnostics.title
fr:pages.pageName
fr:pages.pages