AI-native design editor. Open-source Figma alternative.
perf: copy only checked layers for lint and check once per page switch (#1276)
Danila Poyarkov840219073ab4
diff --git a/changes/1276/performance.md b/changes/1276/performance.mdnew file mode 100644index 000000000..102d5daa9--- /dev/null+++ b/changes/1276/performance.md@@ -0,0 +1 @@+- The design check copies only the layers it checks and runs once per page switch, after the page is shown, so large pages switch and recheck faster.diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.tsindex 93ce82b8b..4b5a7a50a 100644--- a/packages/core/src/lint/linter.ts+++ b/packages/core/src/lint/linter.ts@@ -1,3 +1,5 @@+import { uniq } from 'es-toolkit'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { colorToHex } from '@open-pencil/scene-graph/color'@@ -30,6 +32,9 @@ export class Linter {private rules = new Map<string, Rule>()private ruleConfigs = new Map<string, { severity: Severity; options?: Record<string, unknown> }>()private messages: LintMessage[] = []+ private graph: SceneGraph | null = null+ /** The enabled rules with their contexts, made once per run rather than once per layer. */+ private checks: { rule: Rule; context: RuleContext }[] = []private nodes = new Map<string, LintNode>()private variables: LintVariables = {counts: { COLOR: 0, FLOAT: 0, STRING: 0, BOOLEAN: 0 },@@ -63,10 +68,13 @@ export class Linter {lintGraph(graph: SceneGraph, rootIds?: string[]): LintResult {this.messages = []this.nodes.clear()+ this.graph = graphthis.variables = describeVariables(graph)+ this.checks = this.ruleChecks()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)+ for (const id of outermostRoots(graph, roots)) this.lintNode(id, undefined)+ this.graph = null+ this.checks = []return {messages: this.messages,errorCount: this.messages.filter((m) => m.severity === 'error').length,@@ -75,13 +83,19 @@ export class Linter {}}- private capture(graph: SceneGraph, id: string, parent?: LintNode) {- const raw = graph.getNode(id)- if (!raw) return- const node = this.toLintNode(graph, raw)+ /**+ * The rules' view of `id`, made the first time the walk or a rule reaches it. Instance sublayers+ * are never linted, so on a page made of instances most layers are never converted at all.+ */+ private nodeFor(id: string, parent: LintNode | undefined): LintNode | undefined {+ const cached = this.nodes.get(id)+ if (cached) return cached+ const raw = this.graph?.getNode(id)+ if (!this.graph || !raw) return undefined+ const node = this.toLintNode(this.graph, raw)node.parent = parentthis.nodes.set(id, node)- for (const childId of raw.childIds) this.capture(graph, childId, node)+ return node}private toLintNode(graph: SceneGraph, raw: SceneNode): LintNode {@@ -144,45 +158,71 @@ export class Linter {}}- private lintNode(id: string) {- const node = this.nodes.get(id)- if (!node) return+ private ruleChecks(): { rule: Rule; context: RuleContext }[] {+ const checks: { rule: Rule; context: RuleContext }[] = []for (const [ruleId, rule] of this.rules) {- if (rule.match && !rule.match.includes(node.type)) continueconst config = this.ruleConfigs.get(ruleId)if (!config || config.severity === 'off') continue- const context: RuleContext = {- variables: this.variables,- report: ({ node, message, suggest, data, fix, suggestions }) => {- this.messages.push({- ruleId,- severity: config.severity as Exclude<Severity, 'off'>,- message,- nodeId: node.id,- nodeName: node.name,- nodePath: getNodePath(this.nodes.get(node.id) ?? node),- suggest,- data,- fix,- suggestions- })- },- getConfig: () => config.options,- getParent: (node) => this.nodes.get(node.id)?.parent ?? null,- getChildren: (node) =>- node.childIds- .map((childId) => this.nodes.get(childId))- .filter((child): child is LintNode => !!child)- }+ const severity = config.severity+ checks.push({+ rule,+ context: {+ variables: this.variables,+ report: ({ node, message, suggest, data, fix, suggestions }) => {+ this.messages.push({+ ruleId,+ severity,+ message,+ nodeId: node.id,+ nodeName: node.name,+ nodePath: getNodePath(this.nodes.get(node.id) ?? node),+ suggest,+ data,+ fix,+ suggestions+ })+ },+ getConfig: () => config.options,+ getParent: (node) => this.nodes.get(node.id)?.parent ?? null,+ getChildren: (node) =>+ node.childIds+ .map((childId) => this.nodeFor(childId, this.nodes.get(node.id)))+ .filter((child): child is LintNode => !!child)+ }+ })+ }+ return checks+ }++ private lintNode(id: string, parent: LintNode | undefined) {+ const node = this.nodeFor(id, parent)+ if (!node) return+ for (const { rule, context } of this.checks) {+ if (rule.match && !rule.match.includes(node.type)) continuerule.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)+ for (const childId of node.childIds) this.lintNode(childId, node)}}+/**+ * The roots no other root contains, each once. A layer inside another root is linted with it,+ * so it has its real parents and reports once.+ */+function outermostRoots(graph: SceneGraph, ids: readonly string[]): string[] {+ const requested = new Set(ids)+ return uniq(ids).filter((id) => {+ for (let parentId = graph.getNode(id)?.parentId; parentId;) {+ if (requested.has(parentId)) return false+ parentId = graph.getNode(parentId)?.parentId+ }+ return true+ })+}+function describeVariables(graph: SceneGraph): LintVariables {const counts = { COLOR: 0, FLOAT: 0, STRING: 0, BOOLEAN: 0 }const colorsByHex = new Map<string, { id: string; name: string }>()diff --git a/packages/core/tests/lint/linter.test.ts b/packages/core/tests/lint/linter.test.tsnew file mode 100644index 000000000..f0111eb7f--- /dev/null+++ b/packages/core/tests/lint/linter.test.ts@@ -0,0 +1,24 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createLinter } from '#core/lint'++describe('lintGraph roots', () => {+ test('lints a layer inside another root once, with its real parents', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const card = graph.createNode('FRAME', page.id, { name: 'Card', width: 200, height: 100 })+ const inner = graph.createNode('FRAME', card.id, { name: 'Frame 1', width: 50, height: 50 })+ const lint = (roots: string[]) =>+ createLinter({ rules: ['no-default-names'], config: { rules: { 'no-default-names': 'warning' } } })+ .lintGraph(graph, roots)+ .messages.map(({ nodeId, nodePath }) => ({ nodeId, nodePath }))++ const fromPage = lint([page.id])++ expect(fromPage.find(({ nodeId }) => nodeId === inner.id)?.nodePath).toContain('Card')+ // Listed before its page, the inner frame still reports once and under its parents.+ expect(lint([inner.id, page.id])).toEqual(fromPage)+ })+})diff --git a/src/app/editor/design-check/session.ts b/src/app/editor/design-check/session.tsindex a2142e6fb..0b2ec8964 100644--- a/src/app/editor/design-check/session.ts+++ b/src/app/editor/design-check/session.ts@@ -144,19 +144,23 @@ export function createDesignCheck(editor: Editor, state: AppEditorState) {})watch(pagesNeeded, (on) => (on ? pages.start() : pages.stop()), { immediate: true })watch(snapshot, (current) => current && pages.report(current.pageId, current.issues))+ // The switch itself settles the new page's layout, which changes the scene again, so the+ // check waits for that instead of running once inside the switch and once after it.watch(() => state.currentPageId,() => {focusedIssueId.value = nulleditor.setDesignIssueHighlight(null)- if (enabled.value) run()+ publishMarkers()+ if (enabled.value) schedule()})watch(() => state.sceneVersion,() => enabled.value && schedule())- watch([snapshot, () => preferences.value.showOnCanvas], publishMarkers)+ // Immediate: the first check runs before this watcher exists, while `enabled` starts up.+ watch([snapshot, () => preferences.value.showOnCanvas], publishMarkers, { immediate: true })})const unsubscribeGraph = editor.onEditorEvent('graph:replaced', () => {@@ -196,6 +200,8 @@ export function createDesignCheck(editor: Editor, state: AppEditorState) {// 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)+ // The row to focus belongs to the new page's check, which would otherwise come later.+ run()}focusedIssueId.value = issue.idif (!editor.graph.getNode(issue.nodeId)) returndiff --git a/tests/app/editor/design-check/session.test.ts b/tests/app/editor/design-check/session.test.tsnew file mode 100644index 000000000..197fc2d78--- /dev/null+++ b/tests/app/editor/design-check/session.test.ts@@ -0,0 +1,81 @@+import { afterEach, describe, expect, jest, test } from 'bun:test'++import { nextTick, watch } from 'vue'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createEditorStore } from '@/app/editor/session'++const stores: ReturnType<typeof createEditorStore>[] = []+afterEach(() => {+ for (const store of stores.splice(0)) store.dispose()+ jest.useRealTimers()+})++/** Two pages, each with text small enough for the design check to mark on the canvas. */+function twoPagesWithIssues() {+ const graph = new SceneGraph()+ const first = graph.getPages()[0]+ const second = graph.addPage('Second')+ const [firstText, secondText] = [first, second].map((page) =>+ graph.createNode('TEXT', page.id, { name: 'Caption', text: 'Caption', fontSize: 8 })+ )+ const store = createEditorStore(graph)+ stores.push(store)+ const checkedPages: string[] = []+ watch(+ store.designCheck.snapshot,+ (snapshot) => {+ if (snapshot) checkedPages.push(snapshot.pageId)+ },+ { flush: 'sync' }+ )+ const markedNodes = () => (store.state.designIssues?.markers ?? []).map((m) => m.nodeId)+ return { store, first, second, firstText, secondText, checkedPages, markedNodes }+}++describe('the design check across a page switch', () => {+ test('checks the new page once, after the switch', async () => {+ jest.useFakeTimers()+ const { store, first, second, firstText, secondText, checkedPages, markedNodes } =+ twoPagesWithIssues()+ expect(store.designCheck.snapshot.value?.pageId).toBe(first.id)+ expect(markedNodes()).toEqual([firstText.id])++ // The editor's own switch; the app's adds a progress overlay with timers of its own.+ const prepared = await store.preparePage(second.id)+ if (prepared) store.commitPageSwitch(prepared)+ expect(store.state.currentPageId).toBe(second.id)+ await nextTick()+ // The previous page's markers would point at layers that are no longer shown.+ expect(markedNodes()).toEqual([])+ expect(checkedPages).toEqual([])++ jest.advanceTimersByTime(1000)+ await nextTick()+ expect(checkedPages).toEqual([second.id])+ expect(markedNodes()).toEqual([secondText.id])+ })++ test('opening an issue on another page checks that page right away', async () => {+ jest.useFakeTimers()+ const { store, second, secondText, checkedPages } = twoPagesWithIssues()+ const issue = {+ id: `min-text-size:${secondText.id}:0`,+ ruleId: 'min-text-size',+ nodeId: secondText.id,+ pageId: second.id,+ severity: 'warning' as const,+ message: '',+ nodeName: 'Caption',+ nodePath: ['Caption']+ }++ await store.designCheck.openIssue(issue)++ // The Lint panel focuses the issue's row, which needs the new page's issues already.+ expect(checkedPages).toEqual([second.id])+ expect(store.designCheck.snapshot.value?.issues.map(({ id }) => id)).toContain(issue.id)+ expect(store.designCheck.focusedIssueId.value).toBe(issue.id)+ })+})