AI-native design editor. Open-source Figma alternative.
fix: convert document colour profiles, keep text edits live, and fix .fig exports (#716)
Danila Poyarkov899fecf845ef
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 595fe09b7..93d47cd4c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@### Changed+- Create new documents with the sRGB colour profile, so Display P3 is reserved for documents that declare it.- Export diagnostics from Settings only. AI requests and tool activity now carry conversation and request identifiers, while chat no longer offers a separate diagnostic log or includes transcript content.### Fixed@@ -18,10 +19,19 @@- Find a globally installed `@open-pencil/mcp` when the desktop app is launched from the system shell, by searching the common global binary directories that a graphical launch omits from `PATH`.- Mark unsaved documents and ask whether to save before closing a tab, the desktop window, or the application, rather than relying on recovery alone.- Defer AI provider connections and system credential reads until you send a message or use a connected feature, so opening documents and browsing chat history no longer trigger unexpected credential prompts.+- Save and recover documents whose text uses disabled numeric, fraction, or small-caps OpenType features, which previously failed to write a `.fig` file.+- Update instance text properties on the canvas while typing, with grouped undo for rapid edits.+- Keep Display-P3 documents rendering correctly in wide gamut where the browser supports it and in sRGB elsewhere, fixing the black rectangles and incorrect blend colors, with a dismissible notice when wide gamut is unavailable.+- Convert colours between a document's colour profile and the display's, so a Display-P3 document no longer looks different on an sRGB display than on a wide-gamut one.- Point Homebrew installation instructions to the official `openpencil` cask and document separate CLI installation.- Let the desktop app use an MCP server you started yourself by allowing the app's own origin by default, instead of requiring `OPENPENCIL_MCP_CORS_ORIGIN`.- Reach the custom model option in the model picker for providers with large model catalogs instead of requiring a search for it.+### Performance++- Reduce editor pauses while generating recovery snapshots and exporting text-heavy `.fig` documents.+- Recompute layout only for the pages an edit affects, instead of every page, when editing a component or its instances.+## 0.15.0 — 2026-09-16### Breaking changesdiff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 8493d4b54..9a7ecf98c 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -3,7 +3,7 @@ import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { SnapGuide } from '@open-pencil/scene-graph/snap'import { decodeBase64 } from '#core/bytes'-import type { ResolvedRenderColor } from '#core/color/management'+import type { RenderColorSpace, ResolvedRenderColor } from '#core/color/management'/* eslint-disable max-lines -- SkiaRenderer facade owns CanvasKit state and delegates domain drawing */import {SELECTION_COLOR,@@ -127,6 +127,8 @@ export class SkiaRenderer {navigationGeneration = 0tiledSceneEnabled = falsetracksSceneSettlement = true+ /** Colour space this renderer's surface presents; colours convert into it when painting. */+ presentationColorSpace: RenderColorSpace = 'srgb'tiledScenePending = falsetiledSceneCovered = falselastSceneViewport: { panX: number; panY: number; zoom: number } | null = null@@ -663,11 +665,17 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): ResolvedRenderColor {- return RenderColors.resolveFillColorInfo(fill, fillIndex, node, graph)+ return RenderColors.resolveFillColorInfo(+ fill,+ fillIndex,+ node,+ graph,+ this.presentationColorSpace+ )}resolveFillColor(fill: Fill, fillIndex: number, node: SceneNode, graph: SceneGraph): Color {- return RenderColors.resolveFillColor(fill, fillIndex, node, graph)+ return RenderColors.resolveFillColor(fill, fillIndex, node, graph, this.presentationColorSpace)}resolveStrokeColorInfo(@@ -676,7 +684,13 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): ResolvedRenderColor {- return RenderColors.resolveStrokeColorInfo(stroke, strokeIndex, node, graph)+ return RenderColors.resolveStrokeColorInfo(+ stroke,+ strokeIndex,+ node,+ graph,+ this.presentationColorSpace+ )}resolveStrokeColor(@@ -685,7 +699,13 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): Color {- return RenderColors.resolveStrokeColor(stroke, strokeIndex, node, graph)+ return RenderColors.resolveStrokeColor(+ stroke,+ strokeIndex,+ node,+ graph,+ this.presentationColorSpace+ )}screenToCanvas(sx: number, sy: number): Vector {diff --git a/packages/core/src/canvas/renderer/colors.ts b/packages/core/src/canvas/renderer/colors.tsindex 62521d156..1a9f8054c 100644--- a/packages/core/src/canvas/renderer/colors.ts+++ b/packages/core/src/canvas/renderer/colors.ts@@ -1,18 +1,26 @@import type { Fill, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'-import { resolveNodeFillColor, resolveNodeStrokeColor } from '#core/color/management'-import type { ResolvedRenderColor } from '#core/color/management'+import {+ resolveNodeFillColor,+ resolveNodeStrokeColor,+ resolveRGBAForPreview+} from '#core/color/management'+import type { RenderColorSpace, ResolvedRenderColor } from '#core/color/management'import { normalizeColor } from '#core/color/normalize'import { getFillOkHCL, getStrokeOkHCL } from '#core/color/okhcl'-function resolvedVariableColor(color: Color, graph: SceneGraph): ResolvedRenderColor {+function resolvedVariableColor(+ color: Color,+ graph: SceneGraph,+ presentation: RenderColorSpace+): ResolvedRenderColor {return {- color,- cssColor: '',- sourceSpace: 'srgb',- targetSpace: graph.documentColorSpace,- clipped: false+ ...resolveRGBAForPreview(color, {+ documentColorSpace: graph.documentColorSpace,+ colorSpace: presentation+ }),+ cssColor: ''}}@@ -20,15 +28,17 @@ export function resolveFillColorInfo(fill: Fill,fillIndex: number,node: SceneNode,- graph: SceneGraph+ graph: SceneGraph,+ presentation: RenderColorSpace): ResolvedRenderColor {const varId = node.boundVariables[`fills/${fillIndex}/color`]if (varId) {const resolved = graph.resolveColorVariableForNode(node.id, varId)- if (resolved) return resolvedVariableColor(resolved, graph)+ if (resolved) return resolvedVariableColor(resolved, graph, presentation)}return resolveNodeFillColor(fill, fillIndex, node, {- documentColorSpace: graph.documentColorSpace+ documentColorSpace: graph.documentColorSpace,+ colorSpace: presentation})}@@ -36,26 +46,29 @@ export function resolveFillColor(fill: Fill,fillIndex: number,node: SceneNode,- graph: SceneGraph+ graph: SceneGraph,+ presentation: RenderColorSpace): Color {const varId = node.boundVariables[`fills/${fillIndex}/color`]if (!varId && !getFillOkHCL(node, fillIndex)) return normalizeColor(fill.color)- return resolveFillColorInfo(fill, fillIndex, node, graph).color+ return resolveFillColorInfo(fill, fillIndex, node, graph, presentation).color}export function resolveStrokeColorInfo(stroke: Stroke,strokeIndex: number,node: SceneNode,- graph: SceneGraph+ graph: SceneGraph,+ presentation: RenderColorSpace): ResolvedRenderColor {const varId = node.boundVariables[`strokes/${strokeIndex}/color`]if (varId) {const resolved = graph.resolveColorVariableForNode(node.id, varId)- if (resolved) return resolvedVariableColor(resolved, graph)+ if (resolved) return resolvedVariableColor(resolved, graph, presentation)}return resolveNodeStrokeColor(stroke, strokeIndex, node, {- documentColorSpace: graph.documentColorSpace+ documentColorSpace: graph.documentColorSpace,+ colorSpace: presentation})}@@ -63,9 +76,10 @@ export function resolveStrokeColor(stroke: Stroke,strokeIndex: number,node: SceneNode,- graph: SceneGraph+ graph: SceneGraph,+ presentation: RenderColorSpace): Color {const varId = node.boundVariables[`strokes/${strokeIndex}/color`]if (!varId && !getStrokeOkHCL(node, strokeIndex)) return normalizeColor(stroke.color)- return resolveStrokeColorInfo(stroke, strokeIndex, node, graph).color+ return resolveStrokeColorInfo(stroke, strokeIndex, node, graph, presentation).color}diff --git a/packages/core/src/color/management.ts b/packages/core/src/color/management.tsindex 56110c361..7b6f2a6f4 100644--- a/packages/core/src/color/management.ts+++ b/packages/core/src/color/management.ts@@ -22,7 +22,7 @@ export interface ResolvedRenderColor {clipped: boolean}-const DEFAULT_COLOR_SPACE: RenderColorSpace = 'display-p3'+const DEFAULT_COLOR_SPACE: RenderColorSpace = 'srgb'const toRGB = converter('rgb')const toP3 = converter('p3')@@ -42,6 +42,32 @@ function normalizeOkLCH(color: OkHCLColor) {}}+/**+ * Numbers are stored in the document's profile, so painting into a surface with a different+ * profile has to convert them. Same profile means no work, which is the common case.+ */+function convertComponents(color: Color, from: RenderColorSpace, to: RenderColorSpace): Color {+ if (from === to) return color+ const source =+ from === 'display-p3'+ ? { mode: 'p3' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }+ : { mode: 'rgb' as const, r: color.r, g: color.g, b: color.b, alpha: color.a }+ const converted = to === 'display-p3' ? toP3(source) : toRGB(source)+ return normalizeColor({+ r: converted.r,+ g: converted.g,+ b: converted.b,+ a: converted.alpha ?? color.a+ })+}++function isOutsideGamut(color: Color, space: RenderColorSpace): boolean {+ if (space === 'display-p3') {+ return !isDisplayableP3({ mode: 'p3', r: color.r, g: color.g, b: color.b, alpha: color.a })+ }+ return !isDisplayableRGB({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })+}+function resolveTargetSpace(options?: ColorPreviewOptions): RenderColorSpace {return options?.colorSpace ?? options?.documentColorSpace ?? DEFAULT_COLOR_SPACE}@@ -77,12 +103,12 @@ export function resolveOkHCLForPreview(if (targetSpace === 'display-p3') {const clipped = !isDisplayableP3(oklch)const p3 = toP3(toDisplayableP3(oklch))- const rgb = toRGB({ mode: 'p3', r: p3.r, g: p3.g, b: p3.b, alpha: p3.alpha ?? oklch.alpha })+ // P3 coordinates, because the caller asked for a P3 target.const resolved = normalizeColor({- r: rgb.r,- g: rgb.g,- b: rgb.b,- a: rgb.alpha ?? oklch.alpha+ r: p3.r,+ g: p3.g,+ b: p3.b,+ a: p3.alpha ?? oklch.alpha})return {@@ -128,14 +154,15 @@ export function resolveRGBAForPreview(color: Color,options?: ColorPreviewOptions): ResolvedRenderColor {- const resolved = normalizeColor(color)- const targetSpace = resolveTargetSpace(options)+ const documentColorSpace = options?.documentColorSpace ?? DEFAULT_COLOR_SPACE+ const targetSpace = options?.colorSpace ?? documentColorSpace+ const resolved = convertComponents(normalizeColor(color), documentColorSpace, targetSpace)return {color: resolved,cssColor: formatCSSForTarget(resolved, targetSpace),sourceSpace: 'srgb',targetSpace,- clipped: false+ clipped: targetSpace !== documentColorSpace && isOutsideGamut(resolved, targetSpace)}}diff --git a/packages/core/src/editor/color-space.ts b/packages/core/src/editor/color-space.tsindex 7a73be7e0..68036fe71 100644--- a/packages/core/src/editor/color-space.ts+++ b/packages/core/src/editor/color-space.ts@@ -83,6 +83,7 @@ export function createColorSpaceActions(ctx: EditorContext) {}ctx.graph.documentColorSpace = colorSpace+ ctx.emitEditorEvent('document:color-space-changed', colorSpace)ctx.requestRender()}diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.tsindex de121e572..5b60a0ef6 100644--- a/packages/core/src/editor/component-sync.ts+++ b/packages/core/src/editor/component-sync.ts@@ -2,9 +2,45 @@ import type { SceneGraph } from '@open-pencil/scene-graph'import { computeAllLayouts } from '#core/layout'+type ComputeLayouts = (graph: SceneGraph, scopeId?: string) => void++/** Pages are `CANVAS` nodes; layout recomputation is scoped to them. */+function pageIdOf(graph: SceneGraph, nodeId: string): string | null {+ let current = graph.getNode(nodeId)+ while (current) {+ if (current.type === 'CANVAS') return current.id+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ }+ return null+}++/**+ * Only the pages that actually changed need layout work: the edited subtrees, the components+ * they belong to, and every instance of those components, which may sit on another page.+ */+function affectedPageIds(+ graph: SceneGraph,+ editedIds: Iterable<string>,+ componentIds: Iterable<string>+): Set<string> {+ const pageIds = new Set<string>()+ const addPageOf = (nodeId: string) => {+ const pageId = pageIdOf(graph, nodeId)+ if (pageId) pageIds.add(pageId)+ }++ for (const id of editedIds) addPageOf(id)+ for (const componentId of componentIds) {+ addPageOf(componentId)+ for (const instance of graph.getInstances(componentId)) addPageOf(instance.id)+ }+ return pageIds+}+export function createComponentSyncScheduler(getGraph: () => SceneGraph,- requestRender: () => void+ requestRender: () => void,+ computeLayouts: ComputeLayouts = computeAllLayouts) {let pendingComponentSync: Set<string> | null = nulllet isFlushingComponentSync = false@@ -31,7 +67,9 @@ export function createComponentSyncScheduler(graph.syncInstances(compId)}if (componentIds.size > 0) {- computeAllLayouts(graph)+ const pageIds = affectedPageIds(graph, ids, componentIds)+ if (pageIds.size === 0) computeLayouts(graph)+ else for (const pageId of pageIds) computeLayouts(graph, pageId)requestRender()}} finally {diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 3e90c2adf..7c32269c9 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -1,6 +1,7 @@import type { CanvasKit } from 'canvaskit-wasm'import type {+ DocumentColorSpace,SceneGraph,SceneGraphEvents,SceneNode,@@ -123,6 +124,7 @@ export interface EditorEvents extends SceneGraphEvents {'render:requested': (versions: { renderVersion: number; sceneVersion: number }) => void'repaint:requested': (versions: { renderVersion: number; sceneVersion: number }) => void'graph:replaced': (graph: SceneGraph) => void+ 'document:color-space-changed': (colorSpace: DocumentColorSpace) => void'history:changed': () => void'selection:changed': (selectedIds: string[], previousIds: string[]) => void'rotation:preview-changed': (preview: RotationPreview | null) => voiddiff --git a/packages/docs/programmable/sdk/api/composables/use-component-properties.md b/packages/docs/programmable/sdk/api/composables/use-component-properties.mdindex e289a5578..cf1b45cbb 100644--- a/packages/docs/programmable/sdk/api/composables/use-component-properties.md+++ b/packages/docs/programmable/sdk/api/composables/use-component-properties.md@@ -27,6 +27,10 @@ Each item in `controls` contains:`active` is true only when every selected node is an instance and each instance exposes the sameordered property IDs and types. Compatible multi-selection changes are grouped into one undo entry.+For live text inputs, call `setTextValue(propertyId, value)` on each model update and `flush()` on+blur or Enter. Text appears immediately, while rapid changes share an undo entry. Batches also finish+after an idle pause, a selection/page change, or scope disposal. `setValue()` remains a discrete edit.+Text and boolean properties update the referenced instance descendant. Instance-swap propertiesreplace the referenced nested instance. Variant changes swap the main component and then reapplynon-variant assignments, so custom labels, visibility, and nested swaps survive the change and itsdiff --git a/packages/fig/src/node-change/font/features.ts b/packages/fig/src/node-change/font/features.tsindex cffb1db09..b8737c800 100644--- a/packages/fig/src/node-change/font/features.ts+++ b/packages/fig/src/node-change/font/features.ts@@ -1,6 +1,19 @@+import { figmaSchema } from '@open-pencil/kiwi/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import type { FontFeature } from '@open-pencil/scene-graph'+/**+ * `toggledOn/OffOTFeatures` are typed as `OpenTypeFeature[]`, so only tags Figma's schema+ * can encode belong there. Everything else has to map to a typed text field, or the encoder+ * rejects the tag and the whole `.fig` export fails.+ */+const OT_FEATURE_TAGS: ReadonlySet<string> = new Set(+ (+ figmaSchema.definitions.find((definition) => definition.name === 'OpenTypeFeature')?.fields ??+ []+ ).map((field) => field.name)+)+const BOOLEAN_FEATURES = [['fontVariantCommonLigatures', 'LIGA'],['fontVariantContextualLigatures', 'CALT'],@@ -76,7 +89,8 @@ function applyFontFeatureToKiwi(tag: string,enabled: boolean,toggledOn: string[],- toggledOff: string[]+ toggledOff: string[],+ clearedAxes: Map<string, 'NORMAL'>): void {const booleanField = BOOLEAN_FEATURE_EXPORT[tag]if (booleanField) {@@ -85,11 +99,22 @@ function applyFontFeatureToKiwi(}const enumField = ENUM_FEATURE_EXPORT[tag]- if (enabled && enumField) {- nc[enumField.field] = enumField.value+ if (enumField) {+ // Each axis holds one value, so a disabled toggle clears it to the neutral value rather+ // than inventing the opposite. An enabled tag for the same axis wins over a disabled one,+ // because text such as "TNUM on, PNUM off" describes that one state.+ if (enabled) {+ nc[enumField.field] = enumField.value+ clearedAxes.delete(enumField.field)+ } else if (nc[enumField.field] === undefined) {+ clearedAxes.set(enumField.field, 'NORMAL')+ }return}+ // A tag the schema cannot express is dropped rather than written as an invalid enum member.+ if (!OT_FEATURE_TAGS.has(tag)) return+if (enabled) toggledOn.push(tag)else toggledOff.push(tag)}@@ -97,10 +122,20 @@ function applyFontFeatureToKiwi(export function applyFontFeaturesToKiwi(nc: NodeChange, features: FontFeature[]): void {const toggledOn: string[] = []const toggledOff: string[] = []+ // Applied after the loop so a later enabled tag can cancel a pending clear.+ const clearedAxes = new Map<string, 'NORMAL'>()for (const feature of features) {- applyFontFeatureToKiwi(nc, feature.tag.toUpperCase(), feature.enabled, toggledOn, toggledOff)+ applyFontFeatureToKiwi(+ nc,+ feature.tag.toUpperCase(),+ feature.enabled,+ toggledOn,+ toggledOff,+ clearedAxes+ )}+ for (const field of clearedAxes.keys()) nc[field] = 'NORMAL'if (toggledOn.length > 0) nc.toggledOnOTFeatures = toggledOnif (toggledOff.length > 0) nc.toggledOffOTFeatures = toggledOffdiff --git a/packages/fig/src/node-change/path/commands.ts b/packages/fig/src/node-change/path/commands.tsindex ba9729bf4..417765bff 100644--- a/packages/fig/src/node-change/path/commands.ts+++ b/packages/fig/src/node-change/path/commands.ts@@ -14,12 +14,32 @@ const CMD_MOVE_TO = 1const CMD_LINE_TO = 2const CMD_CUBIC_TO = 4+function commandByteLength(type: string): number {+ switch (type) {+ case 'M':+ case 'L':+ return 1 + 2 * Float32Array.BYTES_PER_ELEMENT+ case 'C':+ case 'Q':+ return 1 + 6 * Float32Array.BYTES_PER_ELEMENT+ case 'Z':+ return 1+ default:+ return 0+ }+}+export function encodePathCommandsBlob(commands: OutlineCommand[], scale = 1): Uint8Array {- const bytes: number[] = []+ const byteLength = commands.reduce(+ (length, command) => length + commandByteLength(command.type),+ 0+ )+ const bytes = new Uint8Array(byteLength)+ const view = new DataView(bytes.buffer)+ let offset = 0const pushFloat = (value: number | undefined) => {- const buf = new ArrayBuffer(4)- new DataView(buf).setFloat32(0, (value ?? 0) / scale, true)- bytes.push(...new Uint8Array(buf))+ view.setFloat32(offset, (value ?? 0) / scale, true)+ offset += Float32Array.BYTES_PER_ELEMENT}const negY = (v: number | undefined) => (v === undefined ? undefined : -v)@@ -29,21 +49,21 @@ export function encodePathCommandsBlob(commands: OutlineCommand[], scale = 1): Ufor (const command of commands) {switch (command.type) {case 'M':- bytes.push(CMD_MOVE_TO)+ bytes[offset++] = CMD_MOVE_TOpushFloat(command.x)pushFloat(negY(command.y))curX = command.x ?? 0curY = command.y ?? 0breakcase 'L':- bytes.push(CMD_LINE_TO)+ bytes[offset++] = CMD_LINE_TOpushFloat(command.x)pushFloat(negY(command.y))curX = command.x ?? 0curY = command.y ?? 0breakcase 'C':- bytes.push(CMD_CUBIC_TO)+ bytes[offset++] = CMD_CUBIC_TOpushFloat(command.x1)pushFloat(negY(command.y1))pushFloat(command.x2)@@ -58,7 +78,7 @@ export function encodePathCommandsBlob(commands: OutlineCommand[], scale = 1): Uconst qy1 = command.y1 ?? 0const qx = command.x ?? 0const qy = command.y ?? 0- bytes.push(CMD_CUBIC_TO)+ bytes[offset++] = CMD_CUBIC_TOpushFloat(curX + (2 / 3) * (qx1 - curX))pushFloat(negY(curY + (2 / 3) * (qy1 - curY)))pushFloat(qx + (2 / 3) * (qx1 - qx))@@ -70,12 +90,12 @@ export function encodePathCommandsBlob(commands: OutlineCommand[], scale = 1): Ubreak}case 'Z':- bytes.push(CMD_CLOSE)+ bytes[offset++] = CMD_CLOSEbreak}}- return new Uint8Array(bytes)+ return bytes}/**diff --git a/packages/fig/tests/font-features.test.ts b/packages/fig/tests/font-features.test.tsnew file mode 100644index 000000000..c0f700efb--- /dev/null+++ b/packages/fig/tests/font-features.test.ts@@ -0,0 +1,85 @@+import { expect, test } from 'bun:test'++import type { NodeChange } from '@open-pencil/kiwi/fig/codec'++import { applyFontFeaturesToKiwi, convertFontFeatures } from '../src/node-change/font/features'++function apply(features: { tag: string; enabled: boolean }[]) {+ const nc: NodeChange = { type: 'TEXT' }+ applyFontFeaturesToKiwi(nc, features)+ return nc+}++test('enabled numeric features set their typed axis', () => {+ expect(apply([{ tag: 'TNUM', enabled: true }]).fontVariantNumericSpacing).toBe('TABULAR')+ expect(apply([{ tag: 'LNUM', enabled: true }]).fontVariantNumericFigure).toBe('LINING')+ expect(apply([{ tag: 'AFRC', enabled: true }]).fontVariantNumericFraction).toBe('STACKED')+ expect(apply([{ tag: 'SMCP', enabled: true }]).fontVariantCaps).toBe('SMALL')+})++test('disabled numeric features clear their axis instead of writing an unknown enum member', () => {+ // The regression: PNUM/TNUM/LNUM/ONUM/FRAC are absent from the schema's OpenTypeFeature+ // enum, so emitting them as raw tags made every affected export throw.+ for (const tag of ['PNUM', 'TNUM', 'LNUM', 'ONUM', 'FRAC', 'AFRC', 'SMCP', 'C2SC']) {+ const nc = apply([{ tag, enabled: false }])+ expect([nc.toggledOnOTFeatures, nc.toggledOffOTFeatures]).toEqual([undefined, undefined])+ }+ expect(apply([{ tag: 'PNUM', enabled: false }]).fontVariantNumericSpacing).toBe('NORMAL')+ expect(apply([{ tag: 'SMCP', enabled: false }]).fontVariantCaps).toBe('NORMAL')+})++test('an enabled tag on an axis wins over a disabled sibling tag', () => {+ // "TNUM on, PNUM off" describes tabular figures; the disabled sibling must not clear it.+ expect(+ apply([+ { tag: 'TNUM', enabled: true },+ { tag: 'PNUM', enabled: false }+ ]).fontVariantNumericSpacing+ ).toBe('TABULAR')+ expect(+ apply([+ { tag: 'PNUM', enabled: false },+ { tag: 'TNUM', enabled: true }+ ]).fontVariantNumericSpacing+ ).toBe('TABULAR')+ expect(+ apply([+ { tag: 'SMCP', enabled: true },+ { tag: 'C2SC', enabled: false }+ ]).fontVariantCaps+ ).toBe('SMALL')+})++test('raw tags survive only when the schema can encode them', () => {+ const known = apply([+ { tag: 'CASE', enabled: true },+ { tag: 'KERN', enabled: false }+ ])+ expect(known.toggledOnOTFeatures).toEqual(['CASE'])+ expect(known.toggledOffOTFeatures).toEqual(['KERN'])++ const unknown = apply([+ { tag: 'ZZZZ', enabled: true },+ { tag: 'YYYY', enabled: false }+ ])+ expect(unknown.toggledOnOTFeatures).toBeUndefined()+ expect(unknown.toggledOffOTFeatures).toBeUndefined()+})++test('boolean features map in both directions', () => {+ expect(apply([{ tag: 'LIGA', enabled: false }]).fontVariantCommonLigatures).toBe(false)+ expect(apply([{ tag: 'LIGA', enabled: true }]).fontVariantCommonLigatures).toBe(true)+})++test('the feature model round-trips through the Kiwi fields', () => {+ const nc = apply([+ { tag: 'TNUM', enabled: true },+ { tag: 'LIGA', enabled: false },+ { tag: 'CASE', enabled: true }+ ])+ expect(convertFontFeatures(nc)).toEqual([+ { tag: 'LIGA', enabled: false },+ { tag: 'TNUM', enabled: true },+ { tag: 'CASE', enabled: true }+ ])+})diff --git a/packages/fig/tests/node-change/path/commands.test.ts b/packages/fig/tests/node-change/path/commands.test.tsnew file mode 100644index 000000000..5417d1a43--- /dev/null+++ b/packages/fig/tests/node-change/path/commands.test.ts@@ -0,0 +1,52 @@+import { expect, test } from 'bun:test'++import { encodePathCommandsBlob, type OutlineCommand } from '@open-pencil/fig/node-change'++const outline: OutlineCommand[] = [+ { type: 'M', x: 2, y: 4 },+ { type: 'L', x: 6, y: -8 },+ { type: 'C', x1: 2, y1: -4, x2: 6, y2: 8, x: 10, y: 12 },+ { type: 'Q', x1: 16, y1: 18, x: 22, y: 24 },+ { type: 'Z' }+]++test('preserves little-endian glyph bytes, scaling, Y inversion, and quadratic conversion', () => {+ const bytes = encodePathCommandsBlob(outline, 2)+ expect(Buffer.from(bytes).toString('hex')).toBe(+ '010000803f000000c0020000404000008040040000803f0000004000004040000080c00000a0400000c0c0040000e040000000c100001041000020c100003041000040c100'+ )+})++test('preserves missing-coordinate defaults and signed zero', () => {+ const bytes = encodePathCommandsBlob(+ [{ type: 'M' }, { type: 'C' }, { type: 'Q' }, { type: 'Z' }],+ 2+ )+ expect(Buffer.from(bytes).toString('hex')).toBe(+ '010000000000000000040000000000000000000000000000000000000000000000000400000000000000800000000000000080000000000000008000'+ )+})++test('ignores unsupported commands without reserving bytes or changing the current point', () => {+ expect(encodePathCommandsBlob([])).toEqual(new Uint8Array())+ expect(encodePathCommandsBlob([{ type: 'unsupported' }])).toEqual(new Uint8Array())+ expect(+ encodePathCommandsBlob(+ [...outline.slice(0, 3), { type: 'unknown', x: 999 }, ...outline.slice(3)],+ 2+ )+ ).toEqual(encodePathCommandsBlob(outline, 2))+})++test('packs repeated contours exactly and owns each returned buffer', () => {+ const contour = encodePathCommandsBlob(outline, 2)+ const copies = 1000+ const bytes = encodePathCommandsBlob(Array.from({ length: copies }, () => outline).flat(), 2)+ expect(bytes.length).toBe(copies * contour.length)+ for (let index = 0; index < copies; index++) {+ expect(bytes.subarray(index * contour.length, (index + 1) * contour.length)).toEqual(contour)+ }+ const another = encodePathCommandsBlob(outline, 2)+ another.fill(0)+ expect(bytes.subarray(0, contour.length)).toEqual(contour)+})diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 189658a8c..d5fe00ab2 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -107,7 +107,7 @@ export class SceneGraph {figKiwiVersion: number | null = null/** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */figSchemaDeflated: Uint8Array | null = null- documentColorSpace: DocumentColorSpace = 'display-p3'+ documentColorSpace: DocumentColorSpace = 'srgb'enabledLibraries = new Map<string, EnabledLibraryBinding>()readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()private absPosCache = new Map<string, Vector>()diff --git a/packages/vue/src/canvas/surface/color-space.ts b/packages/vue/src/canvas/surface/color-space.tsindex 3de278b1d..bff2ea979 100644--- a/packages/vue/src/canvas/surface/color-space.ts+++ b/packages/vue/src/canvas/surface/color-space.ts@@ -1,20 +1,158 @@+import { IS_BROWSER } from '@open-pencil/core/constants'import type { DocumentColorSpace } from '@open-pencil/scene-graph'-type ColorManagedContext = Partial<Pick<WebGLRenderingContext, 'drawingBufferColorSpace'>>+export type PresentationColorSpace = 'srgb' | 'display-p3'-/** Keep Skia's surface encoding aligned with the browser's actual presentation buffer. */-export function configureDrawingBufferColorSpace(+/** The drawing-buffer storage API is not in the installed DOM lib yet (Chromium 122+). */+interface ColorManagedContext {+ drawingBufferColorSpace?: 'srgb' | 'display-p3'+ drawingBufferFormat?: number+ drawingBufferWidth?: number+ drawingBufferHeight?: number+ drawingBufferStorage?: (format: number, width: number, height: number) => void+ RGBA8?: number+ RGBA16F?: number+ getExtension?: (name: string) => { loseContext?: () => void } | null+ getParameter?: (name: number) => unknown+}++const UNMASKED_RENDERER_WEBGL = 0x9246++export interface PresentationRequest {+ documentColorSpace: DocumentColorSpace+ wideGamutDisplay: boolean+ width: number+ height: number+}++/** Software rasterizers advertise the float extensions but cannot render offscreen float targets. */+const SOFTWARE_RENDERER = /swiftshader|llvmpipe|softpipe|software|basic render/i++export function isHardwareRenderer(renderer: string | null | undefined): boolean {+ if (typeof renderer !== 'string' || renderer.length === 0) return false+ return !SOFTWARE_RENDERER.test(renderer)+}++function hasFloatDrawingBuffer(context: ColorManagedContext): boolean {+ if (typeof context.drawingBufferStorage !== 'function') return false+ if (context.RGBA16F === undefined) return false+ // WebGL methods require their context as `this`, so never call them unbound.+ if (!context.getExtension) return false+ return (+ context.getExtension('EXT_color_buffer_float') != null &&+ context.getExtension('EXT_float_blend') != null+ )+}++/** Read the buffer back instead of trusting a write TS narrowed to the requested value. */+function readColorSpace(context: ColorManagedContext): string {+ return context.drawingBufferColorSpace ?? 'srgb'+}++/** Reinstall the drawing buffer only when its format or size drifted. */+function installDrawingBuffer(+ context: ColorManagedContext,+ format: number,+ request: PresentationRequest+): boolean {+ const matches =+ context.drawingBufferFormat === format &&+ context.drawingBufferWidth === request.width &&+ context.drawingBufferHeight === request.height+ if (matches) return true+ if (typeof context.drawingBufferStorage !== 'function') return false+ try {+ context.drawingBufferStorage(format, request.width, request.height)+ } catch {+ return false+ }+ return context.drawingBufferFormat === format+}++/**+ * CanvasKit 0.41 wraps sRGB on-screen surfaces as RGBA_8888 but every other color+ * space as RGBA_F16 — the pixel format is not configurable (Skia's+ * `modules/canvaskit/canvaskit_bindings.cpp`, `ColorSettings`). A Display-P3 surface+ * therefore only matches the browser buffer when that buffer is floating point, which+ * `drawingBufferStorage` provides on Chromium 122+; WebKit and Firefox have no+ * implementation. Presenting P3 over the default 8-bit buffer produces invalid+ * destination copies and broken blend modes, so it falls back to sRGB.+ *+ * Returns the space actually configured, or null when the buffer cannot be made+ * consistent with the requested surface.+ */+export function configurePresentation(context: ColorManagedContext | null,- documentColorSpace: DocumentColorSpace,- wideGamut: boolean-): DocumentColorSpace {+ request: PresentationRequest+): PresentationColorSpace | null {if (!context?.drawingBufferColorSpace) return 'srgb'- const requested = wideGamut && documentColorSpace === 'display-p3' ? 'display-p3' : 'srgb'- if (context.drawingBufferColorSpace === requested) return requestedtry {- context.drawingBufferColorSpace = requested- } catch (error) {- console.warn('Canvas color-space request is unavailable; keeping the current buffer.', error)+ if (+ request.documentColorSpace === 'display-p3' &&+ request.wideGamutDisplay &&+ hasFloatDrawingBuffer(context) &&+ context.RGBA16F !== undefined &&+ installDrawingBuffer(context, context.RGBA16F, request)+ ) {+ context.drawingBufferColorSpace = 'display-p3'+ if (readColorSpace(context) === 'display-p3') return 'display-p3'+ }+ // 8-bit is already the browser default, so sRGB only has to undo a float buffer we+ // installed earlier. Reallocating the default buffer on every resize would decouple it+ // from the canvas size. Browsers without drawingBufferStorage never need this.+ if (+ context.RGBA8 !== undefined &&+ context.drawingBufferFormat !== undefined &&+ context.drawingBufferFormat !== context.RGBA8 &&+ !installDrawingBuffer(context, context.RGBA8, request)+ ) {+ return null+ }+ if (context.drawingBufferColorSpace !== 'srgb') context.drawingBufferColorSpace = 'srgb'+ return readColorSpace(context) === 'srgb' ? 'srgb' : null+ } catch {+ return null}- return context.drawingBufferColorSpace === 'display-p3' ? 'display-p3' : 'srgb'+}++let wideGamutSupport: boolean | null = null++/**+ * Whether this browser can present a Display-P3 canvas at all: a P3 display plus the+ * floating-point drawing buffer CanvasKit's P3 on-screen surface requires.+ */+function rendererName(context: ColorManagedContext): string | null {+ const info = context.getExtension?.('WEBGL_debug_renderer_info')+ if (!info || !context.getParameter) return null+ const renderer = context.getParameter(UNMASKED_RENDERER_WEBGL)+ return typeof renderer === 'string' ? renderer : null+}++function probeDrawingBufferContext(): ColorManagedContext | null {+ const probe = document.createElement('canvas')+ probe.width = 1+ probe.height = 1+ return probe.getContext('webgl2') ?? probe.getContext('webgl')+}++function detectWideGamutSupport(): boolean {+ if (!IS_BROWSER) return false+ if (!window.matchMedia('(color-gamut: p3)').matches) return false+ const context = probeDrawingBufferContext()+ if (!context) return false+ // Software renderers cannot render the offscreen float targets Skia needs once the+ // drawing buffer is float, and a software compositor has no wide-gamut output either.+ const supported = isHardwareRenderer(rendererName(context)) && hasFloatDrawingBuffer(context)+ context.getExtension?.('WEBGL_lose_context')?.loseContext?.()+ return supported+}++/**+ * Whether this browser can present a Display-P3 canvas: a P3 display, a hardware+ * renderer, and the floating-point drawing buffer CanvasKit's P3 on-screen surface+ * requires (Chromium 122+; WebKit and Firefox have no drawingBufferStorage).+ */+export function supportsWideGamutPresentation(): boolean {+ wideGamutSupport ??= detectWideGamutSupport()+ return wideGamutSupport}diff --git a/packages/vue/src/canvas/surface/gl-surface.ts b/packages/vue/src/canvas/surface/gl-surface.tsindex 89daa82ce..5d7fc84eb 100644--- a/packages/vue/src/canvas/surface/gl-surface.ts+++ b/packages/vue/src/canvas/surface/gl-surface.ts@@ -2,10 +2,15 @@ import type { CanvasKit, Surface } from 'canvaskit-wasm'import { IS_BROWSER } from '@open-pencil/core/constants'import type { Editor } from '@open-pencil/core/editor'+import type { DocumentColorSpace } from '@open-pencil/scene-graph'import type { UseCanvasOptions } from '#vue/canvas/surface/types'-import { configureDrawingBufferColorSpace } from './color-space'+import {+ configurePresentation,+ supportsWideGamutPresentation,+ type PresentationColorSpace+} from './color-space'type GLContext = ReturnType<CanvasKit['MakeGrContext']>@@ -31,37 +36,41 @@ export function sizeCanvas(export function makeGLSurface(ck: CanvasKit,canvas: HTMLCanvasElement,- editor: Editor,options: UseCanvasOptions | undefined,+ glContext: GLContext | null,+ documentColorSpace: DocumentColorSpace+): {+ surface: Surface | nullglContext: GLContext | null-): { surface: Surface | null; glContext: GLContext | null } {+ presentation: PresentationColorSpace | null+} {let context = glContextconst glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefinedconst handle = context ? null : ck.GetWebGLContext(canvas, glAttrs)- if (!context && !handle) return { surface: null, glContext: context }+ if (!context && !handle) return { surface: null, glContext: context, presentation: null }const buffer = canvas.getContext('webgl2') ?? canvas.getContext('webgl')- const wideGamut = IS_BROWSER && window.matchMedia('(color-gamut: p3)').matches- const actualSpace = configureDrawingBufferColorSpace(- buffer,- editor.graph.documentColorSpace,- wideGamut- )+ const presentation = configurePresentation(buffer, {+ documentColorSpace,+ wideGamutDisplay: IS_BROWSER && supportsWideGamutPresentation(),+ width: canvas.width,+ height: canvas.height+ })+ if (!presentation) {+ if (handle) ck.deleteContext(handle)+ return { surface: null, glContext: context, presentation: null }+ }if (!context && handle) context = ck.MakeGrContext(handle)- if (!context) return { surface: null, glContext: context }-- const colorSpace = actualSpace === 'display-p3' ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB- const surface = ck.MakeOnScreenGLSurface(context, canvas.width, canvas.height, colorSpace)- if (surface) return { surface, glContext: context }+ if (!context) return { surface: null, glContext: context, presentation: null }- if (- actualSpace === 'display-p3' &&- configureDrawingBufferColorSpace(buffer, 'srgb', false) === 'srgb'- ) {- return {- surface: ck.MakeOnScreenGLSurface(context, canvas.width, canvas.height, ck.ColorSpace.SRGB),- glContext: context- }+ return {+ surface: ck.MakeOnScreenGLSurface(+ context,+ canvas.width,+ canvas.height,+ presentation === 'display-p3' ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB+ ),+ glContext: context,+ presentation}- return { surface: null, glContext: context }}diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.tsindex 4d1f90882..9835ec44f 100644--- a/packages/vue/src/canvas/surface/lifecycle.ts+++ b/packages/vue/src/canvas/surface/lifecycle.ts@@ -5,6 +5,10 @@ import type { Ref } from 'vue'import { SkiaRenderer } from '@open-pencil/core/canvas'import type { Editor } from '@open-pencil/core/editor'+import {+ supportsWideGamutPresentation,+ type PresentationColorSpace+} from '#vue/canvas/surface/color-space'import { makeGLSurface, sizeCanvas, type CanvasGLContext } from '#vue/canvas/surface/gl-surface'import { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'@@ -14,6 +18,7 @@ import type { UseCanvasOptions } from '#vue/canvas/surface/types'type SurfaceManagerState = {renderer: SkiaRenderer | nullglContext: CanvasGLContext | null+ presentation: PresentationColorSpace | null}export function createCanvasSurfaceManager({@@ -31,7 +36,7 @@ export function createCanvasSurfaceManager({isDestroyed: () => booleanshouldShowRulers: () => boolean}) {- const state: SurfaceManagerState = { renderer: null, glContext: null }+ const state: SurfaceManagerState = { renderer: null, glContext: null, presentation: null }let sceneBackingRenderTimer: ReturnType<typeof setTimeout> | null = nullfunction clearSceneBackingRenderTimer() {@@ -55,8 +60,16 @@ export function createCanvasSurfaceManager({sizeCanvas(canvas, editor, options?.onViewportResize)- const result = makeGLSurface(ck, canvas, editor, options, state.glContext)+ const result = makeGLSurface(+ ck,+ canvas,+ options,+ state.glContext,+ editor.graph.documentColorSpace+ )state.glContext = result.glContext+ state.presentation = result.presentation+ options?.onPresentation?.(result.presentation)const surface = result.surfaceif (!surface) {canvas.dataset.surfaceError = 'webgl'@@ -65,6 +78,7 @@ export function createCanvasSurfaceManager({const glCtx = canvas.getContext('webgl2') ?? nullstate.renderer = new SkiaRenderer(ck, surface, glCtx)+ state.renderer.presentationColorSpace = result.presentation ?? 'srgb'state.renderer.tracksSceneSettlement = options?.layer !== 'overlays'state.renderer.tiledSceneEnabled = options?.sceneRenderer === 'tiled'editor.setCanvasKit(ck, state.renderer)@@ -128,19 +142,48 @@ export function createCanvasSurfaceManager({sizeCanvas(canvas, editor, options?.onViewportResize)- const result = makeGLSurface(ck, canvas, editor, options, state.glContext)+ const result = makeGLSurface(+ ck,+ canvas,+ options,+ state.glContext,+ editor.graph.documentColorSpace+ )state.glContext = result.glContext+ state.presentation = result.presentation+ options?.onPresentation?.(result.presentation)const surface = result.surfaceif (!surface) {console.warn('Falling back to full surface recreation after resize')createSurface(canvas, { reloadFonts: true })return}+ state.renderer.presentationColorSpace = result.presentation ?? 'srgb'state.renderer.replaceSurface(surface)renderNow()}+ const wantsWideGamut = () =>+ editor.graph.documentColorSpace === 'display-p3' && supportsWideGamutPresentation()++ /** A P3 document needs the P3 surface, and vice versa; documents arrive after mount. */+ function refreshPresentation() {+ if (isDestroyed()) return+ const canvas = canvasRef.value+ if (!canvas) return+ if (wantsWideGamut() === (state.presentation === 'display-p3')) return+ createSurface(canvas, { reloadFonts: true })+ }++ const stopPresentationRefresh = editor.onEditorEvent('graph:replaced', refreshPresentation)+ const stopColorSpaceRefresh = editor.onEditorEvent(+ 'document:color-space-changed',+ refreshPresentation+ )+function destroy() {+ stopPresentationRefresh()+ stopColorSpaceRefresh()clearSceneBackingRenderTimer()renderLoop.pause()if (state.renderer) editor.removeCanvasRenderer(state.renderer)@@ -154,7 +197,8 @@ export function createCanvasSurfaceManager({renderNow,destroy,markDirty: () => renderLoop.markDirty(),- getRenderer: () => state.renderer+ getRenderer: () => state.renderer,+ getPresentation: () => state.presentation}}diff --git a/packages/vue/src/canvas/surface/types.ts b/packages/vue/src/canvas/surface/types.tsindex 035bfdcae..2c7b4e74b 100644--- a/packages/vue/src/canvas/surface/types.ts+++ b/packages/vue/src/canvas/surface/types.ts@@ -1,5 +1,7 @@import type { EditorState } from '@open-pencil/core/editor'+import type { PresentationColorSpace } from '#vue/canvas/surface/color-space'+/*** Options for {@link useCanvas}.*/@@ -33,6 +35,11 @@ export interface UseCanvasOptions {* Called once the rendering surface is ready.*/onReady?: () => void+ /**+ * Reports the color space the canvas actually presents, including fallbacks, or null+ * when no surface could be configured.+ */+ onPresentation?: (colorSpace: PresentationColorSpace | null) => void/*** Supplies the view state rendered by this canvas. Defaults to `editor.state`.*diff --git a/packages/vue/src/controls/component-props/model.ts b/packages/vue/src/controls/component-props/model.tsindex 22728e9c3..8b75f082a 100644--- a/packages/vue/src/controls/component-props/model.ts+++ b/packages/vue/src/controls/component-props/model.ts@@ -1,3 +1,4 @@+import type { Editor } from '@open-pencil/core/editor'import type {ComponentPropertyDefinition,ComponentPropertyType,@@ -61,3 +62,17 @@ export function instanceSwapOptions(}return options}++export function variantOptions(+ editor: Editor,+ instance: SceneNode,+ propertyName: string+): ComponentPropertyOption[] {+ return editor+ .getVariantOptionAvailability(instance.id, propertyName)+ .map(({ value, available }) => ({+ value,+ label: value,+ disabled: !available+ }))+}diff --git a/packages/vue/src/controls/component-props/use.ts b/packages/vue/src/controls/component-props/use.tsindex a2fb8ef6e..bd08a8f70 100644--- a/packages/vue/src/controls/component-props/use.ts+++ b/packages/vue/src/controls/component-props/use.ts@@ -1,50 +1,66 @@-import { computed } from 'vue'+import { computed, watch } from 'vue'-import type { SceneNode } from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'import {compatibleComponentPropertyDefinitions,instanceSwapOptions,mergedComponentPropertyValue,+ variantOptions,type ComponentPropertyControl,type ComponentPropertyOption} from '#vue/controls/component-props/model'import { MIXED } from '#vue/controls/node-props/helpers'+import { useUndoBatch } from '#vue/controls/undo-batch/use'import { useEditor } from '#vue/editor/context'import { useSceneComputed } from '#vue/internal/scene-computed/use'+import { useRetainedActivity } from '#vue/lifecycle/retention/context'-function variantOptions(editor: ReturnType<typeof useEditor>, instance: SceneNode, name: string) {- return editor.getVariantOptionAvailability(instance.id, name).map(({ value, available }) => ({- value,- label: value,- disabled: !available- }))+interface ResolvedEdit {+ definition: ComponentPropertyDefinition+ targets: SceneNode[]+ label: string+}++/** One batch per property and target set, so a new selection starts a new entry. */+function batchKey(propertyId: string, targets: SceneNode[]): string {+ return [propertyId, ...targets.map((node) => node.id)].join(':')}export function useComponentProperties() {const editor = useEditor()- const instances = useSceneComputed(() => {- void editor.state.sceneVersion- return editor.getSelectedNodes().filter((node) => node.type === 'INSTANCE')+ const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)+ const retainedActivity = useRetainedActivity()+ // A batch never spans a page change, a new selection, or a paused retained scope.+ watch([() => editor.state.currentPageId, () => editor.state.selectedIds], batch.flush, {+ flush: 'sync'})- const selectedCount = computed(() => editor.state.selectedIds.size)- const definitionSets = useSceneComputed(() => {- void editor.state.sceneVersion- return instances.value.map((instance) =>- editor.getInstanceComponentPropertyDefinitions(instance.id)+ if (retainedActivity) {+ watch(+ retainedActivity,+ (active) => {+ if (!active) batch.flush()+ },+ { flush: 'sync' })- })- const definitions = computed(() => compatibleComponentPropertyDefinitions(definitionSets.value))- const active = computed(- () =>- instances.value.length > 0 &&- instances.value.length === selectedCount.value &&- definitions.value.length > 0+ }+ const instances = useSceneComputed(() =>+ editor.getSelectedNodes().filter((node) => node.type === 'INSTANCE'))+ const selectedCount = computed(() => editor.state.selectedIds.size)+ const allSelectedAreInstances = computed(+ () => instances.value.length > 0 && instances.value.length === selectedCount.value+ )+ const definitionSets = useSceneComputed(() =>+ instances.value.map((instance) => editor.getInstanceComponentPropertyDefinitions(instance.id))+ )+ const definitions = computed(() => compatibleComponentPropertyDefinitions(definitionSets.value))+ const active = computed(() => allSelectedAreInstances.value && definitions.value.length > 0)const controls = useSceneComputed<ComponentPropertyControl[]>(() => {- void editor.state.sceneVersionif (!active.value || instances.value.length === 0) return []const firstInstance = instances.value[0]+ // Swap options scan the graph, so resolve that list once for every swap control.+ let componentNodes: SceneNode[] | null = nullreturn definitions.value.map((definition) => {const values = instances.value.map((instance) =>editor.getInstanceComponentPropertyValue(instance.id, definition)@@ -54,11 +70,8 @@ export function useComponentProperties() {if (definition.type === 'VARIANT') {options = variantOptions(editor, firstInstance, definition.name)} else if (definition.type === 'INSTANCE_SWAP') {- options = instanceSwapOptions(- [...editor.graph.getAllNodes()],- definition,- value === MIXED ? '' : value- )+ componentNodes ??= [...editor.graph.getAllNodes()]+ options = instanceSwapOptions(componentNodes, definition, value === MIXED ? '' : value)}return {id: definition.id,@@ -70,20 +83,51 @@ export function useComponentProperties() {})})- function setValue(propertyId: string, value: string) {- if (!active.value) return- const targets = [...instances.value]+ function resolveEdit(propertyId: string): ResolvedEdit | null {+ if (!active.value) return nullconst definition = definitions.value.find((item) => item.id === propertyId)- if (!definition) return- const label = `Change ${definition.name}`- const run = () => {- for (const instance of targets) {+ if (!definition) return null+ return { definition, targets: [...instances.value], label: `Change ${definition.name}` }+ }++ function commitToInstances(edit: ResolvedEdit, propertyId: string, value: string) {+ const apply = () => {+ for (const instance of edit.targets) {editor.setInstanceComponentProperty(instance.id, propertyId, value)}}- if (targets.length > 1) editor.undo.runBatch(label, run)- else run()+ if (edit.targets.length > 1) editor.undo.runBatch(edit.label, apply)+ else apply()+ }++ function applyDiscrete(edit: ResolvedEdit, propertyId: string, value: string) {+ batch.flush()+ commitToInstances(edit, propertyId, value)+ }++ function hasValueEverywhere(edit: ResolvedEdit, value: string): boolean {+ return edit.targets.every(+ (instance) => editor.getInstanceComponentPropertyValue(instance.id, edit.definition) === value+ )+ }++ function setValue(propertyId: string, value: string) {+ const edit = resolveEdit(propertyId)+ if (edit) applyDiscrete(edit, propertyId, value)+ }++ /** Apply typing immediately, grouping rapid changes until blur, Enter, or idle. */+ function setTextValue(propertyId: string, value: string) {+ const edit = resolveEdit(propertyId)+ if (!edit) return+ if (edit.definition.type !== 'TEXT') {+ applyDiscrete(edit, propertyId, value)+ return+ }+ if (hasValueEverywhere(edit, value)) return+ batch.ensure(batchKey(propertyId, edit.targets), edit.label)+ commitToInstances(edit, propertyId, value)}- return { active, controls, setValue }+ return { active, controls, setValue, setTextValue, flush: batch.flush }}diff --git a/packages/vue/src/i18n/locales/de/common.json b/packages/vue/src/i18n/locales/de/common.jsonindex 9187aec5f..3c3c9f7aa 100644--- a/packages/vue/src/i18n/locales/de/common.json+++ b/packages/vue/src/i18n/locales/de/common.json@@ -36,5 +36,6 @@"unsupported": "Nicht unterstützt","tokens": "Token","clear": "Löschen",- "dismiss": "Schließen"+ "dismiss": "Schließen",+ "browserSupport": "Browser-Unterstützung prüfen"}diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.jsonindex 0b5a37dec..e4d97cde5 100644--- a/packages/vue/src/i18n/locales/de/files.json+++ b/packages/vue/src/i18n/locales/de/files.json@@ -25,7 +25,5 @@"newDesign": "Neues Design","noMatchingFiles": "Keine Dateien entsprechen „{query}“.","saveAsPrompt": "Speichern unter:",- "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden.",- "useChrome": "Chrome verwenden",- "orEdgeForFullSupport": "oder Edge für vollständige Unterstützung."+ "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden."}diff --git a/packages/vue/src/i18n/locales/de/rendering.json b/packages/vue/src/i18n/locales/de/rendering.jsonindex ed2a4b14a..246116491 100644--- a/packages/vue/src/i18n/locales/de/rendering.json+++ b/packages/vue/src/i18n/locales/de/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Progressives Rendering","progressiveTiledDescription": "Aktualisiert große Zeichenflächen beim Navigieren in kleineren Kacheln.","reloadRequired": "Lade OpenPencil neu, um diese Änderung anzuwenden.",+ "wideGamutUnavailable": "Dieses Display oder dieser Browser kann Display-P3-Farben nicht darstellen, daher zeigt die Zeichenfläche sie in sRGB an. Das Dokument behält seinen Farbraum.","urlOverride": "Der Renderer dieser Sitzung wird durch einen URL-Parameter gesteuert. Deine gespeicherte Einstellung gilt, sobald der Parameter entfernt wird.","experimental": "Experimentell"}diff --git a/packages/vue/src/i18n/locales/es/common.json b/packages/vue/src/i18n/locales/es/common.jsonindex d78167d37..d984b80ff 100644--- a/packages/vue/src/i18n/locales/es/common.json+++ b/packages/vue/src/i18n/locales/es/common.json@@ -36,5 +36,6 @@"unsupported": "No compatible","tokens": "tokens","clear": "Limpiar",- "dismiss": "Descartar"+ "dismiss": "Descartar",+ "browserSupport": "Consultar compatibilidad"}diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.jsonindex 839b1f366..7f318bd51 100644--- a/packages/vue/src/i18n/locales/es/files.json+++ b/packages/vue/src/i18n/locales/es/files.json@@ -25,7 +25,5 @@"newDesign": "Nuevo diseño","noMatchingFiles": "Ningún archivo coincide con «{query}».","saveAsPrompt": "Guardar como:",- "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar.",- "useChrome": "Usar Chrome",- "orEdgeForFullSupport": "o Edge para disponer de compatibilidad completa."+ "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar."}diff --git a/packages/vue/src/i18n/locales/es/rendering.json b/packages/vue/src/i18n/locales/es/rendering.jsonindex 20174fad8..b83e49bb2 100644--- a/packages/vue/src/i18n/locales/es/rendering.json+++ b/packages/vue/src/i18n/locales/es/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Renderizado progresivo","progressiveTiledDescription": "Actualiza los lienzos grandes en mosaicos más pequeños mientras navegas.","reloadRequired": "Recarga OpenPencil para aplicar este cambio.",+ "wideGamutUnavailable": "Esta pantalla o este navegador no pueden mostrar colores Display-P3, así que el lienzo los previsualiza en sRGB. El documento conserva su espacio de color.","urlOverride": "El renderizador de esta sesión está controlado por un parámetro de URL. Tu preferencia guardada se aplicará al eliminarlo.","experimental": "Experimental"}diff --git a/packages/vue/src/i18n/locales/fr/common.json b/packages/vue/src/i18n/locales/fr/common.jsonindex ea7db94f3..18af7f0a2 100644--- a/packages/vue/src/i18n/locales/fr/common.json+++ b/packages/vue/src/i18n/locales/fr/common.json@@ -36,5 +36,6 @@"unsupported": "Non pris en charge","tokens": "jetons","clear": "Effacer",- "dismiss": "Ignorer"+ "dismiss": "Ignorer",+ "browserSupport": "Vérifier la compatibilité"}diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.jsonindex 1b9bd6e1a..58435d75c 100644--- a/packages/vue/src/i18n/locales/fr/files.json+++ b/packages/vue/src/i18n/locales/fr/files.json@@ -25,7 +25,5 @@"newDesign": "Nouveau design","noMatchingFiles": "Aucun fichier ne correspond à « {query} ».","saveAsPrompt": "Enregistrer sous :",- "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place.",- "useChrome": "Utiliser Chrome",- "orEdgeForFullSupport": "ou Edge pour une prise en charge complète."+ "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place."}diff --git a/packages/vue/src/i18n/locales/fr/rendering.json b/packages/vue/src/i18n/locales/fr/rendering.jsonindex 0e70ec748..2c5cbb38c 100644--- a/packages/vue/src/i18n/locales/fr/rendering.json+++ b/packages/vue/src/i18n/locales/fr/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Rendu progressif","progressiveTiledDescription": "Actualise les grands canevas par petites tuiles pendant la navigation.","reloadRequired": "Rechargez OpenPencil pour appliquer cette modification.",+ "wideGamutUnavailable": "Cet écran ou ce navigateur ne peut pas afficher les couleurs Display-P3 ; le canevas les prévisualise donc en sRGB. Le document conserve son espace colorimétrique.","urlOverride": "Le rendu de cette session est contrôlé par un paramètre d’URL. Votre préférence enregistrée s’appliquera après sa suppression.","experimental": "Expérimental"}diff --git a/packages/vue/src/i18n/locales/it/common.json b/packages/vue/src/i18n/locales/it/common.jsonindex d3e01a7cc..73f0003a1 100644--- a/packages/vue/src/i18n/locales/it/common.json+++ b/packages/vue/src/i18n/locales/it/common.json@@ -36,5 +36,6 @@"unsupported": "Non supportato","tokens": "token","clear": "Cancella",- "dismiss": "Chiudi"+ "dismiss": "Chiudi",+ "browserSupport": "Verifica il supporto"}diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.jsonindex d92ab1a78..d48e3cd68 100644--- a/packages/vue/src/i18n/locales/it/files.json+++ b/packages/vue/src/i18n/locales/it/files.json@@ -25,7 +25,5 @@"newDesign": "Nuovo design","noMatchingFiles": "Nessun file corrisponde a «{query}».","saveAsPrompt": "Salva con nome:",- "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente.",- "useChrome": "Usa Chrome",- "orEdgeForFullSupport": "o Edge per il supporto completo."+ "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente."}diff --git a/packages/vue/src/i18n/locales/it/rendering.json b/packages/vue/src/i18n/locales/it/rendering.jsonindex 67be91e06..d727472f9 100644--- a/packages/vue/src/i18n/locales/it/rendering.json+++ b/packages/vue/src/i18n/locales/it/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Rendering progressivo","progressiveTiledDescription": "Aggiorna le tele di grandi dimensioni in riquadri più piccoli durante la navigazione.","reloadRequired": "Ricarica OpenPencil per applicare questa modifica.",+ "wideGamutUnavailable": "Questo schermo o browser non può mostrare i colori Display-P3, quindi la tela li visualizza in sRGB. Il documento mantiene il suo spazio colore.","urlOverride": "Il renderer della sessione corrente è controllato da un parametro URL. La preferenza salvata verrà applicata quando il parametro sarà rimosso.","experimental": "Sperimentale"}diff --git a/packages/vue/src/i18n/locales/ja/common.json b/packages/vue/src/i18n/locales/ja/common.jsonindex ca672fdee..e3251b3c6 100644--- a/packages/vue/src/i18n/locales/ja/common.json+++ b/packages/vue/src/i18n/locales/ja/common.json@@ -36,5 +36,6 @@"unsupported": "非対応","tokens": "トークン","clear": "クリア",- "dismiss": "閉じる"+ "dismiss": "閉じる",+ "browserSupport": "ブラウザーの対応状況を確認"}diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.jsonindex b5f8251bc..7fbc163c8 100644--- a/packages/vue/src/i18n/locales/ja/files.json+++ b/packages/vue/src/i18n/locales/ja/files.json@@ -25,7 +25,5 @@"newDesign": "新しいデザイン","noMatchingFiles": "「{query}」に一致するファイルはありません。","saveAsPrompt": "名前を付けて保存:",- "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。",- "useChrome": "Chromeを使用",- "orEdgeForFullSupport": "またはEdgeを使用するとすべての機能を利用できます。"+ "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。"}diff --git a/packages/vue/src/i18n/locales/ja/rendering.json b/packages/vue/src/i18n/locales/ja/rendering.jsonindex 49eed7faa..f809179d3 100644--- a/packages/vue/src/i18n/locales/ja/rendering.json+++ b/packages/vue/src/i18n/locales/ja/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "段階的な描画","progressiveTiledDescription": "移動中に大きなキャンバスを小さなタイルに分けて更新します。","reloadRequired": "この変更を適用するには OpenPencil を再読み込みしてください。",+ "wideGamutUnavailable": "このディスプレイまたはブラウザーは Display-P3 の色を表示できないため、キャンバスでは sRGB でプレビューします。ドキュメントのカラースペースは保持されます。","urlOverride": "現在のセッションのレンダラーは URL パラメーターで指定されています。保存した設定はパラメーターを削除すると適用されます。","experimental": "試験的機能"}diff --git a/packages/vue/src/i18n/locales/pl/common.json b/packages/vue/src/i18n/locales/pl/common.jsonindex f1bea56f4..9a3823c86 100644--- a/packages/vue/src/i18n/locales/pl/common.json+++ b/packages/vue/src/i18n/locales/pl/common.json@@ -36,5 +36,6 @@"unsupported": "Nieobsługiwane","tokens": "tokenów","clear": "Wyczyść",- "dismiss": "Zamknij"+ "dismiss": "Zamknij",+ "browserSupport": "Sprawdź obsługę w przeglądarkach"}diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.jsonindex a38360bb5..a5c897258 100644--- a/packages/vue/src/i18n/locales/pl/files.json+++ b/packages/vue/src/i18n/locales/pl/files.json@@ -25,7 +25,5 @@"newDesign": "Nowy projekt","noMatchingFiles": "Brak plików pasujących do „{query}”.","saveAsPrompt": "Zapisz jako:",- "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu.",- "useChrome": "Użyj Chrome",- "orEdgeForFullSupport": "lub Edge, aby uzyskać pełną obsługę."+ "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu."}diff --git a/packages/vue/src/i18n/locales/pl/rendering.json b/packages/vue/src/i18n/locales/pl/rendering.jsonindex cf1e970a7..9eb13e4a3 100644--- a/packages/vue/src/i18n/locales/pl/rendering.json+++ b/packages/vue/src/i18n/locales/pl/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Renderowanie progresywne","progressiveTiledDescription": "Aktualizuje duże płótna w mniejszych kafelkach podczas nawigacji.","reloadRequired": "Wczytaj ponownie OpenPencil, aby zastosować tę zmianę.",+ "wideGamutUnavailable": "Ten ekran lub przeglądarka nie obsługuje kolorów Display-P3, więc kanwa wyświetla je w sRGB. Dokument zachowuje swoją przestrzeń kolorów.","urlOverride": "Renderer bieżącej sesji jest kontrolowany przez parametr URL. Zapisana preferencja zostanie użyta po usunięciu parametru.","experimental": "Eksperymentalne"}diff --git a/packages/vue/src/i18n/locales/ru/common.json b/packages/vue/src/i18n/locales/ru/common.jsonindex 690900761..0b8e04a9a 100644--- a/packages/vue/src/i18n/locales/ru/common.json+++ b/packages/vue/src/i18n/locales/ru/common.json@@ -36,5 +36,6 @@"unsupported": "Не поддерживается","tokens": "токенов","clear": "Очистить",- "dismiss": "Закрыть"+ "dismiss": "Закрыть",+ "browserSupport": "Проверить поддержку в браузерах"}diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.jsonindex 032d55612..9352f5d21 100644--- a/packages/vue/src/i18n/locales/ru/files.json+++ b/packages/vue/src/i18n/locales/ru/files.json@@ -25,7 +25,5 @@"newDesign": "Новый дизайн","noMatchingFiles": "Нет файлов по запросу «{query}».","saveAsPrompt": "Сохранить как:",- "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться.",- "useChrome": "Использовать Chrome",- "orEdgeForFullSupport": "или Edge для полной поддержки."+ "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться."}diff --git a/packages/vue/src/i18n/locales/ru/rendering.json b/packages/vue/src/i18n/locales/ru/rendering.jsonindex 6be58e56e..24b99d319 100644--- a/packages/vue/src/i18n/locales/ru/rendering.json+++ b/packages/vue/src/i18n/locales/ru/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "Поэтапная отрисовка","progressiveTiledDescription": "Обновляет большие холсты небольшими плитками во время навигации.","reloadRequired": "Перезагрузите OpenPencil, чтобы применить изменение.",+ "wideGamutUnavailable": "Этот дисплей или браузер не поддерживает цвета Display-P3, поэтому холст показывает их в sRGB. Цветовое пространство документа сохраняется.","urlOverride": "Режим отрисовки текущего сеанса задан параметром URL. Сохранённая настройка применится после удаления параметра.","experimental": "Экспериментально"}diff --git a/packages/vue/src/i18n/locales/zh-cn/common.json b/packages/vue/src/i18n/locales/zh-cn/common.jsonindex eb287479a..7a5414a31 100644--- a/packages/vue/src/i18n/locales/zh-cn/common.json+++ b/packages/vue/src/i18n/locales/zh-cn/common.json@@ -36,5 +36,6 @@"unsupported": "不支持","tokens": "token","clear": "清除",- "dismiss": "关闭"+ "dismiss": "关闭",+ "browserSupport": "查看浏览器支持情况"}diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.jsonindex 6a8b816b6..345936a58 100644--- a/packages/vue/src/i18n/locales/zh-cn/files.json+++ b/packages/vue/src/i18n/locales/zh-cn/files.json@@ -25,7 +25,5 @@"newDesign": "新建设计","noMatchingFiles": "没有与“{query}”匹配的文件。","saveAsPrompt": "另存为:",- "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。",- "useChrome": "使用 Chrome",- "orEdgeForFullSupport": "或使用 Edge 以获得完整支持。"+ "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/rendering.json b/packages/vue/src/i18n/locales/zh-cn/rendering.jsonindex d03769f8d..4a79755fa 100644--- a/packages/vue/src/i18n/locales/zh-cn/rendering.json+++ b/packages/vue/src/i18n/locales/zh-cn/rendering.json@@ -4,6 +4,7 @@"progressiveTiled": "渐进式渲染","progressiveTiledDescription": "导航时将大型画布分成较小的图块进行更新。","reloadRequired": "重新加载 OpenPencil 以应用此更改。",+ "wideGamutUnavailable": "此显示器或浏览器无法显示 Display-P3 颜色,因此画布以 sRGB 预览。文档的色彩空间保持不变.","urlOverride": "当前会话的渲染器由 URL 参数控制。移除该参数后将应用已保存的偏好设置。","experimental": "实验性功能"}diff --git a/packages/vue/src/i18n/messages/common.ts b/packages/vue/src/i18n/messages/common.tsindex b283a6352..1bb13f4bd 100644--- a/packages/vue/src/i18n/messages/common.ts+++ b/packages/vue/src/i18n/messages/common.ts@@ -38,7 +38,8 @@ export const commonMessageDefaults = {unsupported: 'Not supported',tokens: 'tokens',clear: 'Clear',- dismiss: 'Dismiss'+ dismiss: 'Dismiss',+ browserSupport: 'Check browser support'} as constexport const commonMessages = i18n('common', commonMessageDefaults)diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.tsindex f75c8b4ec..d12fa54f1 100644--- a/packages/vue/src/i18n/messages/files.ts+++ b/packages/vue/src/i18n/messages/files.ts@@ -36,9 +36,7 @@ export const filesMessageDefaults = {noMatchingFiles: params('No files match “{query}”.'),saveAsPrompt: 'Save as:',browserFileAPINotSupported:- "Your browser doesn't support the local file API. Files will be downloaded instead of saved in place.",- useChrome: 'Use Chrome',- orEdgeForFullSupport: 'or Edge for full support.'+ "Your browser doesn't support the local file API. Files will be downloaded instead of saved in place."} as constexport const filesMessages = i18n('files', filesMessageDefaults)diff --git a/packages/vue/src/i18n/messages/rendering.ts b/packages/vue/src/i18n/messages/rendering.tsindex bfc6a8613..8928818d5 100644--- a/packages/vue/src/i18n/messages/rendering.ts+++ b/packages/vue/src/i18n/messages/rendering.ts@@ -7,6 +7,8 @@ export const renderingMessageDefaults = {progressiveTiledDescription: 'Updates large canvases in smaller tiles as you navigate.',experimental: 'Experimental',reloadRequired: 'Reload OpenPencil to apply this change.',+ wideGamutUnavailable:+ 'This display or browser cannot show Display-P3 colors, so the canvas previews them in sRGB. The document keeps its color space.',urlOverride:'The current session renderer is controlled by a URL override. Your saved preference applies when the override is removed.'} as constdiff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex baa1da451..9f56d9a84 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -18,6 +18,8 @@ export { createEditor, EDITOR_TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/edexport { provideEditor, useEditor, EDITOR_KEY } from '#vue/editor/context'/** Canvas and input integration composables. */+export { supportsWideGamutPresentation } from '#vue/canvas/surface/color-space'+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'diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.tsindex f459f67a8..738e004ee 100644--- a/src/app/document/export/files.ts+++ b/src/app/document/export/files.ts@@ -11,6 +11,7 @@ import { renderNodesToImage } from '@open-pencil/core/io/formats/raster'import type { SceneGraph } from '@open-pencil/scene-graph'import type { ExportOptions } from '@/app/document/export/types'+import { pickBrowserSaveFile, supportsFileSystemAccess } from '@/app/document/io/capability'import { isTauri } from '@/app/tauri/env'type ExportData = string | ArrayBuffer | Uint8Array@@ -158,9 +159,9 @@ export async function saveExportedFile(return}- if (window.showSaveFilePicker) {+ if (supportsFileSystemAccess()) {try {- const handle = await window.showSaveFilePicker({+ const handle = await pickBrowserSaveFile({suggestedName: fileName,types: [{@@ -169,9 +170,11 @@ export async function saveExportedFile(}]})- const writable = await handle.createWritable()- await writable.write(new Uint8Array(data))- await writable.close()+ if (handle) {+ const writable = await handle.createWritable()+ await writable.write(new Uint8Array(data))+ await writable.close()+ }return} catch (e) {if ((e as Error).name === 'AbortError') returndiff --git a/src/app/document/io/capability.ts b/src/app/document/io/capability.tsnew file mode 100644index 000000000..d081521e7--- /dev/null+++ b/src/app/document/io/capability.ts@@ -0,0 +1,21 @@+import { IS_BROWSER } from '@/constants'++/**+ * File System Access is Chromium-only today; other browsers download instead. This module is+ * the one place that touches the API, so callers cannot drift on the availability check.+ */+export function supportsFileSystemAccess(): boolean {+ return IS_BROWSER && typeof window.showSaveFilePicker === 'function'+}++/**+ * Opens the browser save picker. Resolves to null when the browser has no picker, and rejects+ * with `AbortError` when the user cancels so callers can keep cancel and failure distinct.+ */+export async function pickBrowserSaveFile(+ options: FilePickerOptions+): Promise<FileSystemFileHandle | null> {+ // Checked inline rather than through the predicate so TypeScript narrows the method.+ if (!IS_BROWSER || typeof window.showSaveFilePicker !== 'function') return null+ return window.showSaveFilePicker(options)+}diff --git a/src/app/document/io/save-targets.ts b/src/app/document/io/save-targets.tsindex 643109d94..f0d650cce 100644--- a/src/app/document/io/save-targets.ts+++ b/src/app/document/io/save-targets.ts@@ -1,3 +1,5 @@+import { pickBrowserSaveFile } from '@/app/document/io/capability'+export async function chooseTauriFigSavePath() {const { save } = await import('@tauri-apps/plugin-dialog')return save({@@ -7,9 +9,8 @@ export async function chooseTauriFigSavePath() {}export async function chooseBrowserFigSaveHandle() {- if (!window.showSaveFilePicker) return nulltry {- return await window.showSaveFilePicker({+ return await pickBrowserSaveFile({suggestedName: 'Untitled.fig',types: [{diff --git a/src/app/document/io/save.ts b/src/app/document/io/save.tsindex 60be4128d..0e09ffdf1 100644--- a/src/app/document/io/save.ts+++ b/src/app/document/io/save.ts@@ -87,9 +87,9 @@ export function createSaveActions({return wrote}- if (window.showSaveFilePicker) {- const handle = await chooseBrowserFigSaveHandle()- if (!handle) return false+ // The picker helper returns null when the browser has no File System Access API.+ const handle = await chooseBrowserFigSaveHandle()+ if (handle) {setStorageBinding(null)setFileHandle(handle)setFilePath(null)diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.tsindex 1e75d8fcd..4c7ef7a04 100644--- a/src/app/editor/session/create.ts+++ b/src/app/editor/session/create.ts@@ -66,6 +66,17 @@ export function createEditorStore(initialGraph?: SceneGraph) {editor,state)+ // Mirror the document color space into app state so UI can react to it.+ const syncDocumentColorSpace = () => {+ state.documentColorSpace = editor.graph.documentColorSpace+ }+ syncDocumentColorSpace()+ const stopColorSpaceSync = editor.onEditorEvent(+ 'document:color-space-changed',+ syncDocumentColorSpace+ )+ editor.onEditorEvent('graph:replaced', syncDocumentColorSpace)+const preparationEvents = createEditorPreparationEvents()const preparationLifecycle = new Map<number,@@ -220,6 +231,7 @@ export function createEditorStore(initialGraph?: SceneGraph) {// App-specific overrides and additions...modules,dispose() {+ stopColorSpaceSync()disposeSelection()modules.dispose()}diff --git a/src/app/editor/session/types.ts b/src/app/editor/session/types.tsindex b7ade4ef7..f4a227f72 100644--- a/src/app/editor/session/types.ts+++ b/src/app/editor/session/types.ts@@ -1,4 +1,6 @@import { createDefaultEditorState, type EditorState } from '@open-pencil/core/editor'+import type { DocumentColorSpace } from '@open-pencil/scene-graph'+import type { PresentationColorSpace } from '@open-pencil/vue'import type { EditorPreparation } from '@/app/editor/preparation/types'import type { NodeEditState } from '@/app/editor/vector/types'@@ -22,7 +24,9 @@ export function createInitialAppEditorState(pageId: string): AppEditorState {renameSelectionOpen: false,renameNodeId: null,numberFieldFocused: false,- preparation: null+ preparation: null,+ canvasPresentation: null,+ documentColorSpace: 'srgb'}}@@ -42,4 +46,8 @@ export type AppEditorState = EditorState & {renameNodeId: string | nullnumberFieldFocused: booleanpreparation: EditorPreparation | null+ /** Color space the canvas is presenting, reported by the surface. */+ canvasPresentation: PresentationColorSpace | null+ /** Mirror of the document's color space, kept reactive for UI. */+ documentColorSpace: DocumentColorSpace}diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 9e6b33b08..3f901662b 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -80,7 +80,10 @@ useCanvas(sceneCanvasRef, store, {getRenderState,onViewportResize,onPresented: ({ sceneVersion }) =>- store.preparationController.acknowledgePresentation(sceneVersion)+ store.preparationController.acknowledgePresentation(sceneVersion),+ onPresentation: (colorSpace) => {+ store.state.canvasPresentation = colorSpace+ }})const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(canvasRef,diff --git a/src/components/FileApiBanner.vue b/src/components/FileApiBanner.vuenew file mode 100644index 000000000..2ac537d41--- /dev/null+++ b/src/components/FileApiBanner.vue@@ -0,0 +1,22 @@+<script setup lang="ts">+import { useI18n } from '@open-pencil/vue'++import { supportsFileSystemAccess } from '@/app/document/io/capability'+import ExternalLink from '@/components/links/ExternalLink.vue'+import AppBanner from '@/components/ui/feedback/AppBanner.vue'+import { IS_TAURI } from '@/constants'++/** Neutral capability reference: the File System Access API support table. */+const supportURL = 'https://caniuse.com/native-filesystem-api'++const { files, common } = useI18n()+const show = !IS_TAURI && !supportsFileSystemAccess()+</script>++<template>+ <AppBanner v-if="show" test-id="safari-banner" storage-key="safari-banner-dismissed">+ {{ files.browserFileAPINotSupported }}+ <ExternalLink :href="supportURL" class="ml-1">{{ common.browserSupport }}</ExternalLink>+ <template #dismiss>{{ common.dismiss }}</template>+ </AppBanner>+</template>diff --git a/src/components/SafariBanner.vue b/src/components/SafariBanner.vuedeleted file mode 100644index d8a0e73ac..000000000--- a/src/components/SafariBanner.vue+++ /dev/null@@ -1,34 +0,0 @@-<script setup lang="ts">-import { useLocalStorage } from '@vueuse/core'--import { useI18n } from '@open-pencil/vue'--import { IS_BROWSER, IS_TAURI } from '@/constants'--const { files, common } = useI18n()-const dismissed = useLocalStorage('safari-banner-dismissed', false)-const show = !IS_TAURI && IS_BROWSER && !window.showSaveFilePicker-</script>--<template>- <div- v-if="show && !dismissed"- data-test-id="safari-banner"- class="flex items-center gap-2 border-b border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] px-3 py-1.5 text-xs text-[var(--color-warning-text)]"- >- <span class="flex-1">- {{ files.browserFileAPINotSupported }}- <a href="https://www.google.com/chrome/" target="_blank" class="font-medium underline">- {{ files.useChrome }}- </a>- {{ files.orEdgeForFullSupport }}- </span>- <button- data-test-id="safari-banner-dismiss"- class="shrink-0 rounded px-1.5 py-0.5 font-medium text-[var(--color-warning-action)] transition-colors hover:bg-amber-500/20"- @click="dismissed = true"- >- {{ common.dismiss }}- </button>- </div>-</template>diff --git a/src/components/canvas/ColorSpaceBanner.vue b/src/components/canvas/ColorSpaceBanner.vuenew file mode 100644index 000000000..96af3db49--- /dev/null+++ b/src/components/canvas/ColorSpaceBanner.vue@@ -0,0 +1,34 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { activeTab } from '@/app/tabs'+import ExternalLink from '@/components/links/ExternalLink.vue'+import AppBanner from '@/components/ui/feedback/AppBanner.vue'++/** Neutral capability reference: the floating-point drawing buffer support table. */+const supportURL = 'https://caniuse.com/mdn-api_webglrenderingcontext_drawingbufferstorage'++const { rendering, common } = useI18n()++// The surface reports what it actually presents, so this notice appears only when a+// Display-P3 document really is being shown in sRGB.+const show = computed(() => {+ const state = activeTab.value?.store.state+ // Both fields are read unconditionally so the computed keeps depending on each of them.+ const presentation = state?.canvasPresentation+ const documentColorSpace = state?.documentColorSpace+ return presentation === 'srgb' && documentColorSpace === 'display-p3'+})++const message = computed(() => rendering.value.wideGamutUnavailable)+</script>++<template>+ <AppBanner v-if="show" test-id="wide-gamut-banner" storage-key="wide-gamut-banner-dismissed">+ {{ message }}+ <ExternalLink :href="supportURL" class="ml-1">{{ common.browserSupport }}</ExternalLink>+ <template #dismiss>{{ common.dismiss }}</template>+ </AppBanner>+</template>diff --git a/src/components/links/ExternalLink.vue b/src/components/links/ExternalLink.vuenew file mode 100644index 000000000..d523744b1--- /dev/null+++ b/src/components/links/ExternalLink.vue@@ -0,0 +1,36 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'+import { computed } from 'vue'++import { openExternalLink } from '@/app/shell/ui'+import type { ComponentUI } from '@/components/ui/types'+import { IS_TAURI } from '@/constants'+import linkTheme from '@/theme/link'++const { href, ui } = defineProps<{+ href: string+ ui?: ComponentUI<typeof linkTheme>+}>()++const styles = computed(() => {+ const theme = tv(linkTheme)()+ return {+ base: theme.base({ class: ui?.base }),+ icon: theme.icon({ class: ui?.icon })+ }+})++/** Desktop WebViews cannot open external pages themselves, so route them to the system browser. */+function navigate(event: MouseEvent) {+ if (!IS_TAURI) return+ event.preventDefault()+ void openExternalLink(href)+}+</script>++<template>+ <a :href="href" target="_blank" rel="noopener noreferrer" :class="styles.base" @click="navigate">+ <slot />+ <icon-lucide-external-link :class="styles.icon" aria-hidden="true" />+ </a>+</template>diff --git a/src/components/properties/component-properties/ComponentPropertiesSection.vue b/src/components/properties/component-properties/ComponentPropertiesSection.vueindex 8d949cfc6..34922df53 100644--- a/src/components/properties/component-properties/ComponentPropertiesSection.vue+++ b/src/components/properties/component-properties/ComponentPropertiesSection.vue@@ -10,7 +10,7 @@ import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'import ComponentPropertyTextField from './ComponentPropertyTextField.vue'-const { active, controls, setValue } = useComponentProperties()+const { active, controls, setValue, setTextValue, flush } = useComponentProperties()const { panels } = useI18n()const componentSectionUI = { title: 'text-component' }@@ -48,7 +48,8 @@ const sectionLabel = computed(() =>:value="control.value":label="control.name":data-property="control.id"- @commit="setValue(control.id, $event)"+ @update="setTextValue(control.id, $event)"+ @commit="flush"/><div v-else-if="control.type === 'BOOLEAN'" class="flex h-field items-center"><AppSwitchdiff --git a/src/components/properties/component-properties/ComponentPropertyTextField.vue b/src/components/properties/component-properties/ComponentPropertyTextField.vueindex 61f27b268..5729541f2 100644--- a/src/components/properties/component-properties/ComponentPropertyTextField.vue+++ b/src/components/properties/component-properties/ComponentPropertyTextField.vue@@ -1,31 +1,22 @@<script setup lang="ts">-import { ref, watch } from 'vue'-import { MIXED, type MixedValue } from '@open-pencil/vue'import AppInput from '@/components/ui/input/AppInput.vue'const { value, label } = defineProps<{ value: MixedValue<string>; label: string }>()-const emit = defineEmits<{ commit: [value: string] }>()-const draft = ref('')--watch(- () => value,- (next) => {- draft.value = next === MIXED ? '' : next- },- { immediate: true }-)+const emit = defineEmits<{ update: [value: string]; commit: [] }>()</script><template><AppInput- v-model="draft"+ :model-value="value === MIXED ? '' : value"tone="panel"size="sm":state="value === MIXED ? 'mixed' : 'idle'":placeholder="value === MIXED ? '—' : undefined":aria-label="label"- @change="emit('commit', draft)"+ @update:model-value="emit('update', String($event))"+ @blur="emit('commit')"+ @enter="emit('commit')"/></template>diff --git a/src/components/settings/layout/SettingsLink.vue b/src/components/settings/layout/SettingsLink.vueindex 83f132150..2fc2fee59 100644--- a/src/components/settings/layout/SettingsLink.vue+++ b/src/components/settings/layout/SettingsLink.vue@@ -1,24 +1,9 @@<script setup lang="ts">-import { tv } from 'tailwind-variants'--import { IS_TAURI } from '@open-pencil/core/constants'--import { openExternalLink } from '@/app/shell/ui'-import settingsLinkTheme from '@/theme/settings/link'+import ExternalLink from '@/components/links/ExternalLink.vue'const { href } = defineProps<{ href: string }>()-const styles = tv(settingsLinkTheme)--function navigate(event: MouseEvent) {- if (!IS_TAURI) return- event.preventDefault()- void openExternalLink(href)-}</script><template>- <a :href="href" target="_blank" rel="noopener noreferrer" :class="styles()" @click="navigate">- <slot />- <icon-lucide-external-link class="size-3 shrink-0" aria-hidden="true" />- </a>+ <ExternalLink :href="href" class="text-[11px]"><slot /></ExternalLink></template>diff --git a/src/components/ui/feedback/AppBanner.stories.ts b/src/components/ui/feedback/AppBanner.stories.tsnew file mode 100644index 000000000..4e892ee0c--- /dev/null+++ b/src/components/ui/feedback/AppBanner.stories.ts@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'++import AppBanner from './AppBanner.vue'++const meta = {+ title: 'Design System/Banner',+ component: AppBanner,+ parameters: { layout: 'fullscreen' }+} satisfies Meta<typeof AppBanner>++export default meta+type Story = StoryObj<typeof meta>++export const Dismissible: Story = {+ render: () => ({+ components: { AppBanner },+ template: `+ <AppBanner storage-key="storybook-banner-dismissed" test-id="app-banner">+ This display or browser cannot show Display-P3 colors, so the canvas previews them in sRGB.+ <template #dismiss>Dismiss</template>+ </AppBanner>+ `+ })+}++export const Persistent: Story = {+ render: () => ({+ components: { AppBanner },+ template: `<AppBanner>This banner cannot be dismissed.</AppBanner>`+ })+}diff --git a/src/components/ui/feedback/AppBanner.vue b/src/components/ui/feedback/AppBanner.vuenew file mode 100644index 000000000..924afb7a9--- /dev/null+++ b/src/components/ui/feedback/AppBanner.vue@@ -0,0 +1,32 @@+<script setup lang="ts">+import { useLocalStorage } from '@vueuse/core'+import { computed } from 'vue'++import { banner, type BannerProps } from './banner'++const { storageKey, testId, ui } = defineProps<BannerProps>()++const dismissed = storageKey ? useLocalStorage(storageKey, false) : null+const styles = computed(() => {+ const theme = banner()+ return {+ root: theme.root({ class: ui?.root }),+ content: theme.content({ class: ui?.content }),+ dismiss: theme.dismiss({ class: ui?.dismiss })+ }+})+</script>++<template>+ <div v-if="!dismissed" :data-test-id="testId" :class="styles.root">+ <span :class="styles.content"><slot /></span>+ <button+ v-if="storageKey"+ :data-test-id="testId ? `${testId}-dismiss` : undefined"+ :class="styles.dismiss"+ @click="dismissed = true"+ >+ <slot name="dismiss" />+ </button>+ </div>+</template>diff --git a/src/components/ui/feedback/banner.ts b/src/components/ui/feedback/banner.tsnew file mode 100644index 000000000..f79d5664f--- /dev/null+++ b/src/components/ui/feedback/banner.ts@@ -0,0 +1,14 @@+import { tv } from 'tailwind-variants'++import type { ComponentUI } from '@/components/ui/types'+import bannerTheme from '@/theme/feedback/banner'++export const banner = tv(bannerTheme)+export type BannerUI = ComponentUI<typeof bannerTheme>++export interface BannerProps {+ /** Persist dismissal under this key; omit to keep the banner permanently visible. */+ storageKey?: string+ testId?: string+ ui?: BannerUI+}diff --git a/src/theme/feedback/banner.ts b/src/theme/feedback/banner.tsnew file mode 100644index 000000000..e132b6e3e--- /dev/null+++ b/src/theme/feedback/banner.ts@@ -0,0 +1,10 @@+const bannerTheme = {+ slots: {+ root: 'flex items-center gap-2 border-b border-warning-border bg-warning-bg px-3 py-1.5 text-xs text-warning-text',+ content: 'flex-1',+ dismiss:+ 'shrink-0 rounded px-1.5 py-0.5 font-medium text-warning-action transition-colors hover:bg-amber-500/20'+ }+}++export default bannerThemediff --git a/src/theme/link.ts b/src/theme/link.tsnew file mode 100644index 000000000..b4d9ed1d0--- /dev/null+++ b/src/theme/link.ts@@ -0,0 +1,8 @@+const linkTheme = {+ slots: {+ base: 'inline-flex w-fit cursor-pointer items-center gap-1 rounded-sm font-medium text-surface underline decoration-muted/60 underline-offset-2 hover:decoration-current focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',+ icon: 'size-3 shrink-0'+ }+}++export default linkThemediff --git a/src/theme/settings/link.ts b/src/theme/settings/link.tsdeleted file mode 100644index 5abf696b7..000000000--- a/src/theme/settings/link.ts+++ /dev/null@@ -1,3 +0,0 @@-export default {- base: 'inline-flex w-fit cursor-pointer items-center gap-1 rounded-sm text-[11px] font-medium text-surface underline decoration-muted/60 underline-offset-2 hover:decoration-current focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'-} as constdiff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex e665c5e83..8d75e4248 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -21,11 +21,12 @@ import {tabCount} from '@/app/tabs'import { isTauri } from '@/app/tauri/env'+import ColorSpaceBanner from '@/components/canvas/ColorSpaceBanner.vue'import CommandPalette from '@/components/commands/CommandPalette.vue'import EditorWorkspace from '@/components/editor/EditorWorkspace.vue'+import FileApiBanner from '@/components/FileApiBanner.vue'import FontStatusBanner from '@/components/font-status/FontStatusBanner.vue'import HomeWorkspace from '@/components/home/HomeWorkspace.vue'-import SafariBanner from '@/components/SafariBanner.vue'import RenameSelectionDialog from '@/components/selection/RenameSelectionDialog.vue'import TabBar from '@/components/TabBar.vue'@@ -103,7 +104,8 @@ onUnmounted(() => {<template><div data-test-id="editor-root" class="flex h-screen w-screen flex-col">- <SafariBanner />+ <FileApiBanner />+ <ColorSpaceBanner /><FontStatusBanner /><RenameSelectionDialog /><CommandPalette />diff --git a/tests/e2e/canvas/color-space.webkit.spec.ts b/tests/e2e/canvas/color-space.webkit.spec.tsnew file mode 100644index 000000000..df5d1878f--- /dev/null+++ b/tests/e2e/canvas/color-space.webkit.spec.ts@@ -0,0 +1,74 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import {+ dismissWideGamutBanner,+ emulateWideGamutDisplay,+ focusPaintEffects,+ sceneBufferState,+ waitForSettledScene+} from '#tests/helpers/canvas/color-space'++test.use({ viewport: { width: 1200, height: 900 } })++test('P3 paint blends and masks survive pan, zoom, and surface resize', async ({ page }) => {+ await emulateWideGamutDisplay(page)+ await page.goto('/demo?no-chrome&no-rulers')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ await focusPaintEffects(page)+ // The notice appears once the document is Display P3, and dismissing it keeps the canvas+ // at a fixed offset for the snapshot.+ await dismissWideGamutBanner(page)+ await waitForSettledScene(page)++ async function expectEffects() {+ const buffer = await sceneBufferState(page)+ expect(buffer).toEqual({ colorSpace: 'srgb', documentColorSpace: 'display-p3', error: 0 })+ expect(await canvas.screenshotCanvas()).toMatchSnapshot('paint-effects.png')+ canvas.assertNoErrors()+ }+ await expectEffects()++ await canvas.canvas.hover()+ await page.mouse.wheel(80, 40)+ await page.keyboard.down('Control')+ try {+ await page.mouse.wheel(0, -120)+ } finally {+ await page.keyboard.up('Control')+ }+ await waitForSettledScene(page)+ expect((await sceneBufferState(page)).error).toBe(0)++ await page.setViewportSize({ width: 1320, height: 960 })+ await waitForSettledScene(page)+ expect((await sceneBufferState(page)).error).toBe(0)+ await page.setViewportSize({ width: 1200, height: 900 })+ await focusPaintEffects(page)+ await waitForSettledScene(page)+ await expectEffects()+})++test('warns when a Display-P3 document cannot be presented in wide gamut', async ({ page }) => {+ await page.goto('/demo?no-chrome&no-rulers')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()++ // New documents are sRGB, so this notice only applies once a document declares Display P3.+ const banner = page.getByTestId('wide-gamut-banner')+ await expect(banner).toBeHidden()+ expect(await sceneBufferState(page)).toMatchObject({+ colorSpace: 'srgb',+ documentColorSpace: 'srgb'+ })++ // This project renders through SwiftShader or WebKit, so wide gamut is unavailable and an+ // sRGB buffer is what a Display-P3 document gets.+ await page.evaluate(() => window.openPencil?.getStore?.()?.setDocumentColorSpace('display-p3'))+ await expect(banner).toBeVisible()+ await expect(banner).toContainText('Display-P3')++ await page.evaluate(() => window.openPencil?.getStore?.()?.setDocumentColorSpace('srgb'))+ await expect(banner).toBeHidden()+})diff --git a/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.pngnew file mode 100644index 000000000..da24bae65Binary files /dev/null and b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-webkit-darwin.png b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-webkit-darwin.pngnew file mode 100644index 000000000..91360e716Binary files /dev/null and b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-webkit-darwin.png differdiff --git a/tests/e2e/color-picker/demo-card.spec.ts b/tests/e2e/color-picker/demo-card.spec.tsindex b220fab29..e809b5e14 100644--- a/tests/e2e/color-picker/demo-card.spec.ts+++ b/tests/e2e/color-picker/demo-card.spec.ts@@ -1,7 +1,7 @@import { expect, test } from '@playwright/test'import { CanvasHelper } from '#tests/helpers/canvas'-import { selectDemoReferencePage } from '#tests/helpers/demo'+import { waitForDemo } from '#tests/helpers/demo'async function dragSlider(page: Parameters<typeof test>[0]['page'],@@ -25,15 +25,21 @@ async function dragSlider(async function selectDemoCard(page: Parameters<typeof test>[0]['page'], canvas: CanvasHelper) {await page.goto('/demo')await canvas.waitForInit()- await selectDemoReferencePage(page)+ await waitForDemo(page)- await page.evaluate(() => {+ await page.evaluate(async () => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')const nodes = Array.from(store.graph.nodes.values())const card =nodes.find((node) => node.name === 'Card' && node.type === 'COMPONENT') ??nodes.find((node) => node.name === 'Card')+ // The card lives on whichever page the demo keeps its component library on.+ let owner = card+ while (owner && owner.type !== 'CANVAS') {+ owner = owner.parentId ? store.graph.getNode(owner.parentId) : undefined+ }+ if (owner && owner.id !== store.state.currentPageId) await store.switchPage(owner.id)if (!card)throw new Error(`Card not found. Available: ${nodesdiff --git a/tests/e2e/properties/component-properties.spec.ts b/tests/e2e/properties/component-properties.spec.tsindex 46ca4625d..6a3261799 100644--- a/tests/e2e/properties/component-properties.spec.ts+++ b/tests/e2e/properties/component-properties.spec.ts@@ -93,6 +93,29 @@ test.afterAll(async () => {await page.close()})+test('updates text while typing and undoes a burst as one edit', async () => {+ const text = propertySection(page, 'Component properties').getByRole('textbox', { name: 'Label' })+ const before = await canvas.screenshotCanvas()+ await text.fill('Live')+ await expect(text).toBeFocused()+ await expect.poll(instanceState).toMatchObject({ label: 'Live' })+ await expect.poll(async () => (await canvas.screenshotCanvas()).equals(before)).toBe(false)+ await text.blur()++ await text.focus()+ await text.pressSequentially(' typing')+ await expect(text).toBeFocused()+ await expect.poll(instanceState).toMatchObject({ label: 'Live typing' })+ await text.press('Enter')+ await text.blur()+ await canvas.pressKey('Meta+z')+ await expect.poll(instanceState).toMatchObject({ label: 'Live' })+ await expect(text).toHaveValue('Live')+ await canvas.pressKey('Meta+z')+ await expect.poll(instanceState).toMatchObject({ label: 'Default label' })+ await expect(text).toHaveValue('Default label')+})+test('renders and applies all component property control types', async () => {const section = propertySection(page, 'Component properties')await expect(section).toBeVisible()@@ -148,6 +171,18 @@ test('batches compatible mixed selection and undo', async () => {expect(await instanceState(instanceId)).toMatchObject({ badgeVisible: false })expect(await instanceState(secondId)).toMatchObject({ badgeVisible: true })+ const text = propertySection(page, 'Component properties').getByRole('textbox', { name: 'Label' })+ const originalLabels = [(await instanceState())?.label, (await instanceState(secondId))?.label]+ await text.fill('Shared text')+ await expect(text).toBeFocused()+ await expect.poll(instanceState).toMatchObject({ label: 'Shared text' })+ await expect.poll(() => instanceState(secondId)).toMatchObject({ label: 'Shared text' })+ await text.blur()+ await canvas.pressKey('Meta+z')+ await expect+ .poll(async () => [(await instanceState())?.label, (await instanceState(secondId))?.label])+ .toEqual(originalLabels)+await page.evaluate((id) => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')diff --git a/tests/e2e/stroke-picker/basic.spec.ts b/tests/e2e/stroke-picker/basic.spec.tsindex 30bcefcc2..6d7f52396 100644--- a/tests/e2e/stroke-picker/basic.spec.ts+++ b/tests/e2e/stroke-picker/basic.spec.ts@@ -1,7 +1,7 @@import { expect, test, type Page } from '@playwright/test'import { CanvasHelper } from '#tests/helpers/canvas'-import { selectDemoReferencePage } from '#tests/helpers/demo'+import { waitForDemo } from '#tests/helpers/demo'import { propertyItems, propertySection } from '#tests/helpers/properties'async function dragSlider(page: Page, canvas: CanvasHelper, testId: string, ratio: number) {@@ -86,9 +86,9 @@ test('stroke picker hsb saturation and brightness sliders update stroke color onconst canvas = new CanvasHelper(page)await page.goto('/demo')await canvas.waitForInit()- await selectDemoReferencePage(page)+ await waitForDemo(page)- await page.evaluate(() => {+ await page.evaluate(async () => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')const nodes = Array.from(store.graph.nodes.values())@@ -96,6 +96,11 @@ test('stroke picker hsb saturation and brightness sliders update stroke color onnodes.find((node) => node.name === 'Card' && node.type === 'COMPONENT') ??nodes.find((node) => node.name === 'Card')if (!card) throw new Error('Card not found')+ let owner = card+ while (owner && owner.type !== 'CANVAS') {+ owner = owner.parentId ? store.graph.getNode(owner.parentId) : undefined+ }+ if (owner && owner.id !== store.state.currentPageId) await store.switchPage(owner.id)const stroke = {color: { r: 0.9, g: 0.9, b: 0.92, a: 1 },weight: 1,diff --git a/tests/engine/color/document-space-conversion.test.ts b/tests/engine/color/document-space-conversion.test.tsnew file mode 100644index 000000000..09ed599a5--- /dev/null+++ b/tests/engine/color/document-space-conversion.test.ts@@ -0,0 +1,70 @@+import { describe, expect, test } from 'bun:test'++import { resolveOkHCLForPreview, resolveRGBAForPreview } from '#core/color/management'++/** #2563EB as authored in an sRGB document. */+const BLUE = { r: 0.1450980392156863, g: 0.38823529411764707, b: 0.9215686274509803, a: 1 }+/** Saturated P3 red, far outside sRGB. */+const P3_RED = { r: 1, g: 0, b: 0, a: 1 }++describe('document colour profile conversion', () => {+ test('an sRGB document painting into an sRGB surface keeps its numbers', () => {+ const resolved = resolveRGBAForPreview(BLUE, {+ documentColorSpace: 'srgb',+ colorSpace: 'srgb'+ })+ expect(resolved.color.r).toBeCloseTo(BLUE.r, 5)+ expect(resolved.color.b).toBeCloseTo(BLUE.b, 5)+ expect(resolved.clipped).toBe(false)+ })++ test('a P3 document painting into a P3 surface keeps its numbers', () => {+ const resolved = resolveRGBAForPreview(P3_RED, {+ documentColorSpace: 'display-p3',+ colorSpace: 'display-p3'+ })+ expect(resolved.color).toEqual(P3_RED)+ expect(resolved.clipped).toBe(false)+ })++ test('a P3 document converts into an sRGB surface and reports clipping', () => {+ const resolved = resolveRGBAForPreview(P3_RED, {+ documentColorSpace: 'display-p3',+ colorSpace: 'srgb'+ })+ // P3 red is outside sRGB: the coordinates go out of range and the surface clamps them+ // when painting, which is the "closest approximate colour" the profile change documents.+ expect(resolved.color.r).toBeGreaterThan(1)+ expect(resolved.color.g).toBeLessThan(0)+ expect(resolved.color.b).toBeLessThan(0)+ expect(resolved.clipped).toBe(true)+ expect(resolved.cssColor).toBe('rgb(255, 0, 0)')+ })++ test('an sRGB document converts into a P3 surface', () => {+ const resolved = resolveRGBAForPreview(BLUE, {+ documentColorSpace: 'srgb',+ colorSpace: 'display-p3'+ })+ // The same colour, expressed in P3 coordinates: slightly different numbers.+ expect(resolved.color).not.toEqual(BLUE)+ expect(resolved.color.b).toBeCloseTo(0.89, 2)+ expect(resolved.clipped).toBe(false)+ })++ test('recognised document colours report their own space when no target is requested', () => {+ const resolved = resolveRGBAForPreview(BLUE, { documentColorSpace: 'display-p3' })+ expect(resolved.targetSpace).toBe('display-p3')+ expect(resolved.color).toEqual(BLUE)+ })++ test('OKHCL colours resolve into the requested target space', () => {+ const okhcl = { l: 0.6, c: 0.3, h: 20, a: 1 }+ const srgb = resolveOkHCLForPreview(okhcl, { colorSpace: 'srgb' })+ const p3 = resolveOkHCLForPreview(okhcl, { colorSpace: 'display-p3' })+ expect(srgb.targetSpace).toBe('srgb')+ expect(p3.targetSpace).toBe('display-p3')+ // P3 is the wider space, so the same colour needs fewer of its primaries.+ expect(p3.color.r).toBeLessThan(srgb.color.r)+ })+})diff --git a/tests/engine/editor/components/sync-layout-scope.test.ts b/tests/engine/editor/components/sync-layout-scope.test.tsnew file mode 100644index 000000000..b80cbc7d8--- /dev/null+++ b/tests/engine/editor/components/sync-layout-scope.test.ts@@ -0,0 +1,109 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createComponentSyncScheduler } from '#core/editor/component-sync'+import { computeAllLayouts } from '#core/layout'++function createGraph() {+ const graph = new SceneGraph()+ const componentPage = graph.getPages()[0]+ const instancePage = graph.addPage('Instances')+ const unrelatedPage = graph.addPage('Unrelated')++ const component = graph.createNode('COMPONENT', componentPage.id, {+ name: 'Button',+ width: 200,+ height: 40,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 8,+ paddingLeft: 16+ })+ const label = graph.createNode('TEXT', component.id, { name: 'Label', text: 'Label', x: 0, y: 0 })+ const instance = graph.createInstance(component.id, instancePage.id, { x: 0, y: 0 })+ const unrelated = graph.createNode('FRAME', unrelatedPage.id, {+ name: 'Dashboard',+ width: 300,+ height: 200,+ layoutMode: 'VERTICAL',+ itemSpacing: 4+ })+ graph.createNode('TEXT', unrelated.id, { name: 'Title', text: 'Title', x: 0, y: 0 })++ return {+ graph,+ componentPage,+ instancePage,+ unrelatedPage,+ component,+ label,+ instance,+ unrelated+ }+}++describe('component sync layout scope', () => {+ test('recomputes only the pages that changed, including cross-page instances', async () => {+ const { graph, componentPage, instancePage, unrelatedPage, label } = createGraph()+ const scopes: (string | undefined)[] = []+ const { scheduleComponentSync } = createComponentSyncScheduler(+ () => graph,+ () => undefined,+ (innerGraph, scopeId) => {+ scopes.push(scopeId)+ computeAllLayouts(innerGraph, scopeId)+ }+ )++ graph.updateNode(label.id, { text: 'Renamed label' })+ scheduleComponentSync(label.id)++ await Promise.resolve()+ expect([...scopes].sort()).toEqual([componentPage.id, instancePage.id].sort())+ expect(scopes).not.toContain(unrelatedPage.id)+ expect(scopes).not.toContain(undefined)+ })++ test('an edit outside any component does no layout work', async () => {+ const { graph, unrelated } = createGraph()+ const scopes: (string | undefined)[] = []+ const { scheduleComponentSync } = createComponentSyncScheduler(+ () => graph,+ () => undefined,+ (innerGraph, scopeId) => {+ scopes.push(scopeId)+ computeAllLayouts(innerGraph, scopeId)+ }+ )++ graph.updateNode(unrelated.id, { width: 400 })+ scheduleComponentSync(unrelated.id)++ await Promise.resolve()+ expect(scopes).toEqual([])+ })++ test('a cross-page instance still receives the component layout', async () => {+ const { graph, instance, component } = createGraph()+ const { scheduleComponentSync } = createComponentSyncScheduler(+ () => graph,+ () => undefined,+ computeAllLayouts+ )++ // Widen the component's padding, which moves its label; the instance must follow.+ const label = graph.getChildren(component.id)[0]+ if (!label) throw new Error('Expected a component child')+ graph.updateNode(label.id, { text: 'A much longer label' })+ scheduleComponentSync(label.id)++ await Promise.resolve()+ const instanceLabel = graph.getChildren(instance.id)[0]+ const componentLabel = graph.getChildren(component.id)[0]+ expect(instanceLabel).toBeDefined()+ expect(instanceLabel?.x).toBe(componentLabel?.x)+ expect(instanceLabel?.width).toBe(componentLabel?.width)+ })+})diff --git a/tests/engine/io/fig/export/font-feature-encoding.test.ts b/tests/engine/io/fig/export/font-feature-encoding.test.tsnew file mode 100644index 000000000..d5259dab3--- /dev/null+++ b/tests/engine/io/fig/export/font-feature-encoding.test.ts@@ -0,0 +1,57 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'++import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'++/**+ * Regression: disabled numeric and caps features (PNUM, TNUM, LNUM, ONUM, FRAC, SMCP, …) are+ * absent from the schema's `OpenTypeFeature` enum, so emitting them as raw toggled tags made+ * `.fig` export throw `Invalid value "PNUM" for enum "OpenTypeFeature"`. Save and recovery+ * snapshots failed for any document using them.+ */+describe('OpenType feature encoding', () => {+ beforeAll(+ async () => {+ await initCodec()+ },+ { timeout: HEAVY_TEST_TIMEOUT_MS }+ )++ test(+ 'exports and reimports text with disabled numeric features',+ { timeout: HEAVY_TEST_TIMEOUT_MS },+ async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.createNode('TEXT', page.id, {+ text: '1,111.00 / 8,888.00',+ fontFeatures: [+ { tag: 'TNUM', enabled: true },+ { tag: 'PNUM', enabled: false },+ { tag: 'SMCP', enabled: false },+ // A tag with no Kiwi representation at all must not poison the export either.+ { tag: 'ZZZZ', enabled: true }+ ]+ })++ const exported = await exportFigFile(graph)+ expect(exported.length).toBeGreaterThan(100)++ const reimported = await parseFigFile(+ exported.buffer.slice(+ exported.byteOffset,+ exported.byteOffset + exported.byteLength+ ) as ArrayBuffer+ )+ const text = [...reimported.getAllNodes()].find((node) => node.type === 'TEXT')+ // The numeric axis survives; the unencodable tags and cleared caps axis do not.+ expect(text?.fontFeatures).toEqual([+ { tag: 'LIGA', enabled: true },+ { tag: 'CALT', enabled: true },+ { tag: 'TNUM', enabled: true }+ ])+ }+ )+})diff --git a/tests/engine/vue/canvas/color-space.test.ts b/tests/engine/vue/canvas/color-space.test.tsindex d132ed469..1074307fc 100644--- a/tests/engine/vue/canvas/color-space.test.ts+++ b/tests/engine/vue/canvas/color-space.test.ts@@ -1,35 +1,134 @@import { expect, test } from 'bun:test'-import { configureDrawingBufferColorSpace } from '#vue/canvas/surface/color-space'+import {+ configurePresentation,+ isHardwareRenderer,+ type PresentationColorSpace+} from '#vue/canvas/surface/color-space'-for (const wideGamut of [false, true]) {- for (const documentSpace of ['srgb', 'display-p3'] as const) {- test(`buffer space matches ${documentSpace}, wide gamut ${wideGamut}`, () => {- const context: Pick<WebGLRenderingContext, 'drawingBufferColorSpace'> = {- drawingBufferColorSpace: 'srgb'+const RGBA8 = 32856+const RGBA16F = 34842++interface FakeContextOptions {+ colorSpace?: PresentationColorSpace+ format?: number+ size?: [number, number]+ /** Model renderers that accept the call but keep the previous pixel format. */+ acceptFloatStorage?: boolean+ ignoreColorSpaceSetter?: boolean+ extensions?: string[]+}++function fakeContext(options: FakeContextOptions = {}) {+ const extensions = new Set(options.extensions ?? ['EXT_color_buffer_float', 'EXT_float_blend'])+ const size = options.size ?? [800, 600]+ const context = {+ drawingBufferColorSpace: (options.colorSpace ?? 'srgb') as PresentationColorSpace,+ drawingBufferFormat: options.format ?? RGBA8,+ RGBA8,+ RGBA16F,+ drawingBufferWidth: size[0],+ drawingBufferHeight: size[1],+ storageCalls: [] as { format: number; width: number; height: number }[],+ getExtension(name: string) {+ return extensions.has(name) ? { loseContext: () => undefined } : null+ },+ drawingBufferStorage(format: number, width: number, height: number) {+ context.storageCalls.push({ format, width, height })+ const accepted = format !== RGBA16F || options.acceptFloatStorage !== false+ if (accepted) {+ context.drawingBufferFormat = format+ context.drawingBufferWidth = width+ context.drawingBufferHeight = height+ }+ }+ }+ if (options.ignoreColorSpaceSetter) {+ // Model a browser that keeps its P3 buffer when asked for sRGB.+ Object.defineProperty(context, 'drawingBufferColorSpace', {+ get: () => 'display-p3' as PresentationColorSpace,+ set: () => {+ /* ignored */}- const expected = wideGamut && documentSpace === 'display-p3' ? 'display-p3' : 'srgb'- expect(configureDrawingBufferColorSpace(context, documentSpace, wideGamut)).toBe(expected)- expect(context.drawingBufferColorSpace).toBe(expected)})}+ return context}-test('unsupported and read-only contexts retain their actual sRGB buffer', () => {- expect(configureDrawingBufferColorSpace(null, 'display-p3', true)).toBe('srgb')- expect(configureDrawingBufferColorSpace({}, 'display-p3', true)).toBe('srgb')- const readOnly = {- get drawingBufferColorSpace(): PredefinedColorSpace {- return 'srgb'- }- }- expect(configureDrawingBufferColorSpace(readOnly, 'display-p3', true)).toBe('srgb')+function requestFor(documentColorSpace: 'srgb' | 'display-p3', wideGamutDisplay = true) {+ return { documentColorSpace, wideGamutDisplay, width: 800, height: 600 }+}++test('an sRGB document presents in sRGB without touching storage', () => {+ const context = fakeContext()+ expect(configurePresentation(context, requestFor('srgb'))).toBe('srgb')+ expect(context.storageCalls).toEqual([])})-test('switching away from P3 resets a retained context to sRGB', () => {- const context: Pick<WebGLRenderingContext, 'drawingBufferColorSpace'> = {- drawingBufferColorSpace: 'display-p3'- }- expect(configureDrawingBufferColorSpace(context, 'srgb', true)).toBe('srgb')- expect(context.drawingBufferColorSpace).toBe('srgb')+test('a P3 document on a wide-gamut display uses a float buffer and P3 presentation', () => {+ const context = fakeContext({ format: RGBA8 })+ expect(configurePresentation(context, requestFor('display-p3'))).toBe('display-p3')+ expect(context.storageCalls).toEqual([{ format: RGBA16F, width: 800, height: 600 }])+ expect(context.drawingBufferFormat).toBe(RGBA16F)+})++test('a P3 document stays sRGB when the display is not wide gamut', () => {+ const context = fakeContext()+ expect(configurePresentation(context, requestFor('display-p3', false))).toBe('srgb')+ expect(context.storageCalls).toEqual([])+})++test('browsers without drawingBufferStorage keep their default sRGB buffer', () => {+ const context = fakeContext({ format: RGBA8 })+ // WebKit exposes drawingBufferColorSpace but no storage API at all.+ Object.assign(context, { drawingBufferStorage: undefined })+ expect(configurePresentation(context, requestFor('display-p3'))).toBe('srgb')+})++test('a renderer that rejects the float format stays on the sRGB buffer', () => {+ // Renderers that accept the call but draw incorrectly cannot be detected here; those+ // are excluded by isHardwareRenderer, which this suite covers separately.+ const context = fakeContext({ acceptFloatStorage: false })+ expect(configurePresentation(context, requestFor('display-p3'))).toBe('srgb')+ expect(context.storageCalls).toEqual([{ format: RGBA16F, width: 800, height: 600 }])+ expect(context.drawingBufferFormat).toBe(RGBA8)+})++test('an unchanged size and format does not reallocate the drawing buffer', () => {+ const context = fakeContext({ format: RGBA16F })+ expect(configurePresentation(context, requestFor('display-p3'))).toBe('display-p3')+ expect(context.storageCalls).toEqual([])+})++test('a renderer without the float extensions stays on the sRGB path', () => {+ const context = fakeContext({ extensions: [] })+ expect(configurePresentation(context, requestFor('display-p3'))).toBe('srgb')+ expect(context.storageCalls).toEqual([])+})++test('a browser that ignores the color-space request cannot be presented consistently', () => {+ const context = fakeContext({ ignoreColorSpaceSetter: true })+ expect(configurePresentation(context, requestFor('srgb'))).toBe(null)+})++test('browsers without color-space control use their default sRGB buffer', () => {+ expect(configurePresentation(null, requestFor('display-p3'))).toBe('srgb')+ expect(configurePresentation({}, requestFor('display-p3'))).toBe('srgb')+})++test('software rasterizers are not treated as hardware renderers', () => {+ expect(+ isHardwareRenderer(+ 'ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (LLVM 10.0.0) (0x0000C0DE)), SwiftShader driver)'+ )+ ).toBe(false)+ expect(isHardwareRenderer('Mesa/X.org, llvmpipe (LLVM 15.0.7, 256 bits)')).toBe(false)+ expect(isHardwareRenderer('Microsoft Basic Render Driver')).toBe(false)+ expect(+ isHardwareRenderer('ANGLE (Apple, ANGLE Metal Renderer: Apple M5, Unspecified Version)')+ ).toBe(true)+ expect(isHardwareRenderer('Adreno (TM) 740')).toBe(true)+ // An unknown renderer must not be assumed to be hardware.+ expect(isHardwareRenderer(null)).toBe(false)+ expect(isHardwareRenderer('')).toBe(false)})diff --git a/tests/helpers/canvas/color-space.ts b/tests/helpers/canvas/color-space.tsnew file mode 100644index 000000000..b1c79374d--- /dev/null+++ b/tests/helpers/canvas/color-space.ts@@ -0,0 +1,69 @@+import type { Page } from '@playwright/test'++/** Exercise the P3 surface negotiation even on an sRGB CI display. */+export async function emulateWideGamutDisplay(page: Page) {+ await page.addInitScript(() => {+ const matchMedia = window.matchMedia.bind(window)+ window.matchMedia = (query) => {+ const result = matchMedia(query)+ if (query === '(color-gamut: p3)') Object.defineProperty(result, 'matches', { value: true })+ return result+ }+ })+}++/** Keep the wide-gamut notice from resizing the canvas in rendering-fidelity tests. */+export async function dismissWideGamutBanner(page: Page) {+ const banner = page.getByTestId('wide-gamut-banner')+ await banner.waitFor({ state: 'visible', timeout: 5_000 }).catch(() => undefined)+ if (await banner.isVisible()) await page.getByTestId('wide-gamut-banner-dismiss').click()+}++/** Focus the demo's paint and effects page, where blends and masks live. */+export async function focusPaintEffects(page: Page) {+ await page.evaluate(async () => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ const paintPage = store.graph.getPages().find((candidate) => candidate.name.startsWith('03'))+ if (!paintPage) throw new Error('Demo paint page unavailable')+ store.setDocumentColorSpace('display-p3')+ if (store.state.currentPageId !== paintPage.id) await store.switchPage(paintPage.id)+ })+ await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ const subject = store.graph.getChildren(store.state.currentPageId)[0]+ if (!subject) throw new Error('Demo paint page is empty')+ store.select([subject.id])+ store.zoomToSelection()+ store.clearSelection()+ })+}++export async function waitForSettledScene(page: Page) {+ await page.waitForFunction(() => {+ const store = window.openPencil?.getStore?.()+ const renderer = store?.canvasRenderers.find((r) => r.tracksSceneSettlement)+ return (+ store?.state.navigation.phase === 'idle' &&+ renderer &&+ !renderer.sceneBackingNeedsCrispRender &&+ !renderer.sceneBackingBuild+ )+ })+}++export async function sceneBufferState(page: Page) {+ return page.evaluate(() => {+ const canvas = document.querySelector<HTMLCanvasElement>(+ '[data-test-id="scene-canvas-element"]'+ )+ const gl = canvas?.getContext('webgl2')+ if (!gl) throw new Error('Scene WebGL context unavailable')+ return {+ colorSpace: gl.drawingBufferColorSpace,+ documentColorSpace: window.openPencil?.getStore?.().graph.documentColorSpace,+ error: gl.getError()+ }+ })+}diff --git a/tests/helpers/demo.ts b/tests/helpers/demo.tsindex f4f1bbafa..a0b17c366 100644--- a/tests/helpers/demo.ts+++ b/tests/helpers/demo.ts@@ -9,16 +9,3 @@ export async function waitForDemo(page: Page) {)})}--export async function selectDemoReferencePage(page: Page) {- await waitForDemo(page)- await page.evaluate(async () => {- const store = window.openPencil?.getStore?.()- if (!store) throw new Error('OpenPencil store not initialized')- const reference = store.graph- .getPages()- .find((page) => page.name === 'Reference · original examples')- if (!reference) throw new Error('Demo reference page not found')- await store.switchPage(reference.id)- })-}diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txtindex 770896ea4..4bd4899c9 100644--- a/tools/i18n/mixed-script-baseline.txt+++ b/tools/i18n/mixed-script-baseline.txt@@ -87,8 +87,6 @@ ja:files.clipboardImagesFetchFailedja:files.importFailedja:files.importHTMLCSSja:files.importHTMLCSSDescription-ja:files.orEdgeForFullSupport-ja:files.useChromeja:fonts.downloadFallbackPacksDescriptionja:media.getPexelsAPIKeyja:media.getUnsplashAccessKey@@ -120,6 +118,7 @@ ja:recovery.dialogDescriptionja:rendering.reloadRequiredja:rendering.settingsDescriptionja:rendering.urlOverride+ja:rendering.wideGamutUnavailableja:settings.aiAndAgentsja:settings.baseURLHintja:settings.invalidURL@@ -222,8 +221,6 @@ zh-cn:files.clipboardImagesFetchFailedzh-cn:files.importFailedzh-cn:files.importHTMLCSSzh-cn:files.importHTMLCSSDescription-zh-cn:files.orEdgeForFullSupport-zh-cn:files.useChromezh-cn:fonts.downloadFallbackPacksDescriptionzh-cn:media.getPexelsAPIKeyzh-cn:media.getUnsplashAccessKey@@ -254,6 +251,7 @@ zh-cn:recovery.dialogDescriptionzh-cn:rendering.reloadRequiredzh-cn:rendering.settingsDescriptionzh-cn:rendering.urlOverride+zh-cn:rendering.wideGamutUnavailablezh-cn:settings.aiAndAgentszh-cn:settings.baseURLHintzh-cn:settings.invalidURL