AI-native design editor. Open-source Figma alternative.
perf: build Lint rows only while the panel is shown (#1274)
Danila Poyarkovfec159c02e86
diff --git a/changes/1274/performance.md b/changes/1274/performance.mdnew file mode 100644index 000000000..7c4a71b96--- /dev/null+++ b/changes/1274/performance.md@@ -0,0 +1 @@+- Switching pages in a document with many design-check issues no longer builds the hidden Lint panel's rows.diff --git a/src/components/design-check/DesignCheckPanel.vue b/src/components/design-check/DesignCheckPanel.vueindex 541febe5f..89dd63243 100644--- a/src/components/design-check/DesignCheckPanel.vue+++ b/src/components/design-check/DesignCheckPanel.vue@@ -12,7 +12,8 @@ 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'+import type { DesignCheckScope } from './types'+import { useDesignCheckPanel } from './useDesignCheckPanel'const { active, initialScope = 'page' } = defineProps<{active: boolean@@ -93,6 +94,7 @@ const scopeModel = computed({v-for="group in groups":key="group.ruleId":group="group"+ :focused-issue-id="check.focusedIssueId.value":open="isGroupOpen(group)"@update:open="(open) => setGroupOpen(group.ruleId, open)"@open-row="(row) => void check.openIssue(row.issue)"diff --git a/src/components/design-check/IssueGroup.stories.ts b/src/components/design-check/IssueGroup.stories.tsindex 207d27d94..ef7e4e6ef 100644--- a/src/components/design-check/IssueGroup.stories.ts+++ b/src/components/design-check/IssueGroup.stories.ts@@ -46,6 +46,7 @@ const contrast: IssueGroupView = {help: 'Text needs a contrast ratio of at least 4.5:1 with its background to meet WCAG AA.',fixes: [],bindsOnly: true,+ count: 1,rows: [row({issue: issue('color-contrast', 'caption', 'error'),@@ -76,6 +77,7 @@ const colors: IssueGroupView = {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,+ count: 3,rows: [row({issue: issue('no-hardcoded-colors', 'card', 'warning'),@@ -111,6 +113,7 @@ const radius: IssueGroupView = {help: 'Corner radius should come from the radius scale or a variable.',fixes: [],bindsOnly: true,+ count: 1,rows: [row({issue: issue('consistent-radius', 'card', 'info'),diff --git a/src/components/design-check/IssueGroup.vue b/src/components/design-check/IssueGroup.vueindex 610d38b5d..aecbc8f0e 100644--- a/src/components/design-check/IssueGroup.vue+++ b/src/components/design-check/IssueGroup.vue@@ -6,7 +6,7 @@ import {DropdownMenuRoot,DropdownMenuTrigger} from 'reka-ui'-import { computed, ref } from 'vue'+import { computed, ref, watch } from 'vue'import { useDesignCheckMessages } from '@open-pencil/vue'@@ -25,7 +25,10 @@ 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 { group, focusedIssueId = null } = defineProps<{+ group: IssueGroupView+ focusedIssueId?: string | null+}>()const open = defineModel<boolean>('open', { default: true })const emit = defineEmits<{openRow: [row: IssueRowView]@@ -42,6 +45,15 @@ const itemCls = menuItem({ justify: 'start' })const menuOpen = ref(false)const limit = ref(ROW_PAGE_SIZE)+// A focused row past the ones shown, such as one a canvas marker opened, shows its page too.+watch(+ () => (focusedIssueId ? group.rows.findIndex((row) => row.issue.id === focusedIssueId) : -1),+ (index) => {+ if (index >= limit.value) limit.value = Math.ceil((index + 1) / ROW_PAGE_SIZE) * ROW_PAGE_SIZE+ },+ { immediate: true }+)+const visibleRows = computed(() => group.rows.slice(0, limit.value))const hiddenCount = computed(() => group.rows.length - visibleRows.value.length)</script>@@ -65,7 +77,7 @@ const hiddenCount = computed(() => group.rows.length - visibleRows.value.length)<Tip :label="group.help ?? undefined" side="left"><span :class="styles.groupTitle()">{{ group.title }}</span></Tip>- <span :class="styles.groupCount()">{{ group.rows.length }}</span>+ <span :class="styles.groupCount()">{{ group.count }}</span></template><template #actions><AppButton v-if="group.fixes.length > 1" color="primary" size="xs" @click="emit('fixAll')">diff --git a/src/components/design-check/empty-state.ts b/src/components/design-check/empty-state.tsnew file mode 100644index 000000000..2f674ff56--- /dev/null+++ b/src/components/design-check/empty-state.ts@@ -0,0 +1,42 @@+import type { DesignCheckMessages } from '@/app/editor/design-check/format'++import type { DesignCheckEmptyState, DesignCheckScope } from './types'++/** What the Lint panel lists, as far as choosing its empty state goes. */+export interface ListingState {+ scope: DesignCheckScope+ hasSelection: boolean+ /** Issues in scope before the severity filters, and the groups left after them. */+ issueCount: number+ groupCount: number+ filtersActive: boolean+ presetLabel: string+}++/** Why the panel lists nothing, or null when it lists something. */+export function emptyState(+ state: ListingState,+ messages: DesignCheckMessages+): DesignCheckEmptyState | null {+ if (state.scope === 'selection' && !state.hasSelection) {+ return {+ kind: 'no-selection',+ label: messages.noSelection,+ description: messages.noSelectionDescription+ }+ }+ if (state.groupCount > 0) return null+ if (state.filtersActive && state.issueCount > 0) {+ return { kind: 'filtered', label: messages.noFilteredIssues }+ }+ const labels: Record<DesignCheckScope, string> = {+ page: messages.emptyPage,+ selection: messages.emptySelection,+ document: messages.emptyDocument+ }+ return {+ kind: 'clean',+ label: labels[state.scope],+ description: messages.emptyDescription({ preset: state.presetLabel })+ }+}diff --git a/src/components/design-check/rows.ts b/src/components/design-check/rows.tsnew file mode 100644index 000000000..1edc72efb--- /dev/null+++ b/src/components/design-check/rows.ts@@ -0,0 +1,76 @@+import type { SceneGraph } from '@open-pencil/scene-graph'++import {+ issueAction,+ issueDetail,+ issueSwatch,+ ruleHelp,+ ruleTitle,+ type DesignCheckMessages+} from '@/app/editor/design-check/format'+import type { DesignIssue, DesignIssueGroup } from '@/app/editor/design-check/issues'+import { IconFrame, sceneNodeIcon } from '@/app/editor/icons'++import type { IssueGroupView, IssueRowView } from './types'++/** What a row reads besides its issue: the document as it is now, and who is looking. */+export interface RowContext {+ graph: SceneGraph+ messages: DesignCheckMessages+ currentPageId: string+ selectedIds: ReadonlySet<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+}++/** An issue's row, with its layer as it is now; a layer deleted since the check shows as missing. */+export function issueRowView(issue: DesignIssue, context: RowContext): IssueRowView {+ const { graph, messages } = context+ const node = graph.getNode(issue.nodeId)+ const onOtherPage = issue.pageId !== context.currentPageId+ return {+ issue,+ layerName: node?.name ?? issue.nodeName,+ layerIcon: node ? sceneNodeIcon(node) : IconFrame,+ detail: issueDetail(issue, messages),+ swatch: issueSwatch(issue),+ action: node ? issueAction(issue, messages) : null,+ hidden: node ? isHidden(graph, node.id) : false,+ missing: !node,+ selected: context.selectedIds.has(issue.nodeId),+ pageLabel: onOtherPage+ ? messages.onPage({ page: graph.getNode(issue.pageId)?.name ?? '' })+ : null+ }+}++/**+ * A rule's group. Rows are built only when it is open, since each reads its layer and a large+ * page has thousands of issues; fixes skip layers deleted since the check either way.+ */+export function issueGroupView(+ group: DesignIssueGroup,+ open: boolean,+ context: RowContext+): IssueGroupView {+ const fixes = group.issues.flatMap(({ nodeId, fix }) =>+ fix && context.graph.getNode(nodeId) ? [{ nodeId, fix }] : []+ )+ return {+ ruleId: group.ruleId,+ severity: group.severity,+ title: ruleTitle(group.ruleId, context.messages),+ help: ruleHelp(group.ruleId, context.messages),+ count: group.issues.length,+ rows: open ? group.issues.map((issue) => issueRowView(issue, context)) : [],+ fixes,+ bindsOnly: fixes.every(({ fix }) => fix.kind === 'bind-variable')+ }+}diff --git a/src/components/design-check/types.ts b/src/components/design-check/types.tsindex 181c35749..54085cd51 100644--- a/src/components/design-check/types.ts+++ b/src/components/design-check/types.ts@@ -24,9 +24,19 @@ export interface IssueGroupView {severity: DesignIssueSeveritytitle: stringhelp: string | null+ /** How many issues the group lists, whether or not its rows are built. */+ count: number+ /** The rows of an open group; a collapsed group builds none. */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}++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 }diff --git a/src/components/design-check/useDesignCheckPanel.ts b/src/components/design-check/useDesignCheckPanel.tsindex f69b41051..660b2fbf7 100644--- a/src/components/design-check/useDesignCheckPanel.ts+++ b/src/components/design-check/useDesignCheckPanel.ts@@ -1,16 +1,8 @@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,@@ -19,28 +11,14 @@ import {type DesignIssue,type DesignIssueSeverity} from '@/app/editor/design-check/issues'-import { IconFrame, sceneNodeIcon } from '@/app/editor/icons'+import type { DesignCheck } from '@/app/editor/design-check/session'import { appPreferences } from '@/app/settings/preferences/store'-import type { IssueGroupView, IssueRowView } from './types'+import { emptyState } from './empty-state'+import { issueGroupView, type RowContext } from './rows'+import type { DesignCheckScope, 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`.@@ -60,14 +38,25 @@ export function useDesignCheckPanel(options: {/** Explicit open state per rule; suggestions start collapsed, problems start open. */const openGroups = reactive(new Map<string, boolean>())+ // Issues in scope++ /** The current page's check, once it has caught up with a page switch. */const snapshot = computed(() => {const current = check.snapshot.valuereturn current?.pageId === store.state.currentPageId ? current : null})- const selectedIds = computed(() => store.state.selectedIds)++ const scopedIssues = computed<DesignIssue[]>(() => {+ const pageIssues = snapshot.value?.issues ?? []+ if (scope.value === 'page') return pageIssues+ if (scope.value === 'selection') {+ return issuesWithin(pageIssues, store.graph, store.state.selectedIds)+ }+ return documentIssues()+ })/** Every checked page's issues, in page order, the current page from its live check. */- const documentIssues = computed<DesignIssue[]>(() => {+ function documentIssues(): DesignIssue[] {const results = check.pages.results.valuereturn store.graph.getPages()@@ -76,64 +65,65 @@ export function useDesignCheckPanel(options: {? (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))++ // Groups and rows+const filtersActive = computed(() => visibleSeverities.value.length < DESIGN_ISSUE_SEVERITIES.length)- function rowView(issue: DesignIssue): IssueRowView {+ /** Empty while the panel is hidden: rows read every issue's layer, which nobody would see. */+ const groups = computed<IssueGroupView[]>(() => {+ if (!options.active()) return []+ const context = rowContext()+ const shown = scopedIssues.value.filter((issue) =>+ visibleSeverities.value.includes(issue.severity)+ )+ return groupIssuesByRule(shown).map((group) =>+ issueGroupView(group, isGroupOpen(group), context)+ )+ })++ /**+ * Rows show layers as they are now, which Vue cannot track in the graph; the scene version+ * changes with them, so reading it here rebuilds the rows after an edit.+ */+ function rowContext(): RowContext {void store.state.sceneVersion- const node = store.graph.getNode(issue.nodeId)return {- issue,- layerName: node?.name ?? issue.nodeName,- layerIcon: node ? sceneNodeIcon(node) : IconFrame,- 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 ?? '' })+ graph: store.graph,+ messages: messages.value,+ currentPageId: store.state.currentPageId,+ selectedIds: store.state.selectedIds}}- 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')- }- })- )+ function isGroupOpen(group: Pick<IssueGroupView, 'ruleId' | 'severity'>): 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]+ }++ // Status/** Pages still waiting for their background check, while the document is listed. */const checkingDocument = computed(() => scope.value === 'document' && check.pages.queued.value.length > 0)+ const loading = computed(+ () => snapshot.value === null || (checkingDocument.value && groups.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@@ -142,45 +132,23 @@ export function useDesignCheckPanel(options: {: 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)- }+ const empty = computed(() =>+ loading.value+ ? null+ : emptyState(+ {+ scope: scope.value,+ hasSelection: store.state.selectedIds.size > 0,+ issueCount: scopedIssues.value.length,+ groupCount: groups.value.length,+ filtersActive: filtersActive.value,+ presetLabel: presetLabels.value[appPreferences.value.designCheck.preset]+ },+ messages.value+ )+ )- function clearFilters() {- visibleSeverities.value = [...DESIGN_ISSUE_SEVERITIES]- }+ // Canvas and focus/** Highlights a row's layer on the canvas; layers on other pages are not on screen. */function hoverRow(row: IssueRowView | null) {@@ -188,62 +156,74 @@ export function useDesignCheckPanel(options: {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 a focused issue's row, such as after a canvas marker click: unfiltered, open, in view. */+ async function revealIssue(issueId: string) {+ const issue = check.snapshot.value?.issues.find(({ id }) => 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' })+ }- /** Shows the focused issue's row, e.g. after a canvas marker click: unfiltered, open, in view. */+ // A hidden panel has no rows, so an issue focused meanwhile is revealed once the panel opens.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' })+ () => (options.active() ? check.focusedIssueId.value : null),+ (issueId) => {+ if (issueId) void revealIssue(issueId)},{ flush: 'post' })+ useCheckFollowsPanel(check, options.active, scope)+return {check,scope,visibleSeverities,counts,groups,- emptyState,+ emptyState: empty,documentNote,- loading: computed(- () => snapshot.value === null || (checkingDocument.value && groups.value.length === 0)- ),+ loading,isGroupOpen,setGroupOpen,clearFilters,hoverRow}}++/**+ * Keeps the design check running while the panel is shown, and every page checked while it lists+ * the document; a hidden or closed panel leaves no layer highlighted.+ */+function useCheckFollowsPanel(+ check: DesignCheck,+ active: () => boolean,+ scope: Readonly<Ref<DesignCheckScope>>+) {+ watch(+ active,+ (shown) => {+ check.panelVisible.value = shown+ if (!shown) check.highlightIssue(null)+ },+ { immediate: true }+ )+ watch(+ () => active() && scope.value === 'document',+ (listing) => {+ check.documentScope.value = listing+ },+ { immediate: true }+ )+ onBeforeUnmount(() => {+ check.panelVisible.value = false+ check.documentScope.value = false+ check.highlightIssue(null)+ })+}diff --git a/tests/e2e/design-check/design-check.spec.ts b/tests/e2e/design-check/design-check.spec.tsindex f5ec81313..527f34a24 100644--- a/tests/e2e/design-check/design-check.spec.ts+++ b/tests/e2e/design-check/design-check.spec.ts@@ -415,3 +415,45 @@ test('Canvas markers and Layers panel marks can be turned off from the View menuawait editor.page.getByRole('menuitemcheckbox', { name: 'Design issues' }).click()await expect.poll(markerCount).toBeGreaterThan(0)})++/** Sixty small notes in a grid, far enough apart that each one's marker can be clicked. */+const NOTE = { columns: 6, gapX: 100, gapY: 50, width: 40, height: 10, left: 40, top: 60 }++test('A marker opens an issue past the rows its group shows at first', async () => {+ const lastNoteId = await editor.page.evaluate((note) => {+ 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+ let last = ''+ for (let index = 0; index < 60; index++) {+ last = store.graph.createNode('TEXT', store.state.currentPageId, {+ name: `Note ${index + 1}`,+ text: 'Note',+ fontSize: 8,+ x: note.left + (index % note.columns) * note.gapX,+ y: note.top + Math.floor(index / note.columns) * note.gapY,+ width: note.width,+ height: note.height+ }).id+ }+ return last+ }, NOTE)+ await waitForMarkers(editor.page)++ // The sixtieth note's row is past the fifty its group lists at first.+ const last = 59+ const marker = {+ x: NOTE.left + (last % NOTE.columns) * NOTE.gapX + NOTE.width + 12,+ y: NOTE.top + Math.floor(last / NOTE.columns) * NOTE.gapY - 12+ }+ await hoverMarker(marker)+ await editor.canvas.click(marker.x, marker.y)++ await expect(editor.page.getByRole('tab', { name: /^Lint/ })).toHaveAttribute(+ 'aria-selected',+ 'true'+ )+ await expect(lintPanel(editor.page).locator(`[data-node-id="${lastNoteId}"]`)).toBeInViewport()+})