AI-native design editor. Open-source Figma alternative.
fix(canvas): preserve paint geometry and color fidelity
Danila Poyarkov3220fd179844
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 170ca76f4..ed9dde2ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -59,6 +59,7 @@### Fixed+- Render four-point diamond gradients, preserve text layout across fill types, and keep image colors accurate on sRGB displays.- Keep newly created and edited objects visible during zoom instead of replaying outdated scene content.- Keep property fields and paint previews live during editing, rotated selection labels readable and aligned, and object edges stable when previews settle.- Show compact bordered section labels with inset nested titles and clearer hover feedback.diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.tsindex 7e27ea938..9d422e2f9 100644--- a/packages/core/src/canvas/fills.ts+++ b/packages/core/src/canvas/fills.ts@@ -4,6 +4,7 @@ import type { SceneNode, SceneGraph, Fill } from '@open-pencil/scene-graph'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import { figmaBlendModeToSkia } from './blend'+import { makeDiamondGradient } from './gradients/diamond'import type { SkiaRenderer } from './renderer'import { makeSmoothRRectPath, nodeHasSmoothCorners } from './shapes'@@ -354,7 +355,14 @@ export function applyGradientFill(r.ck.TileMode.Clamp)r.fillPaint.setShader(shader)- } else if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {+ } else if (fill.type === 'GRADIENT_DIAMOND') {+ const shader = makeDiamondGradient(r, colors, positions, makeGradientLocalMatrix(r, w, h, t))+ try {+ r.fillPaint.setShader(shader)+ } finally {+ shader.delete()+ }+ } else if (fill.type === 'GRADIENT_RADIAL') {// Figma's gradientTransform maps gradient space (center 0.5,0.5, radius 0.5)// to the node's normalized [0,1] coordinate space. The full local matrix// converts to pixel coordinates: scale(w, h) * gradientTransform.diff --git a/packages/core/src/canvas/gradients/diamond.ts b/packages/core/src/canvas/gradients/diamond.tsnew file mode 100644index 000000000..8775defa6--- /dev/null+++ b/packages/core/src/canvas/gradients/diamond.ts@@ -0,0 +1,40 @@+import type { InputMatrix, Shader } from 'canvaskit-wasm'++import type { SkiaRenderer } from '#core/canvas/renderer'++const DIAMOND_GRADIENT = `+uniform shader ramp;+half4 main(float2 position) {+ float2 distance = abs(position - float2(0.5));+ return ramp.eval(float2(2.0 * (distance.x + distance.y), 0.0));+}+`++/** Use Skia's ordinary gradient ramp for stop interpolation and color management. */+export function makeDiamondGradient(+ r: SkiaRenderer,+ colors: Float32Array[],+ positions: number[],+ localMatrix: InputMatrix+): Shader {+ if (!r.diamondGradientEffect) {+ let error = ''+ const effect = r.ck.RuntimeEffect.Make(DIAMOND_GRADIENT, (message) => {+ error = message+ })+ if (!effect) throw new Error(`Cannot compile diamond gradient: ${error}`)+ r.diamondGradientEffect = effect+ }+ const ramp = r.ck.Shader.MakeLinearGradient(+ [0, 0],+ [1, 0],+ colors,+ positions,+ r.ck.TileMode.Clamp+ )+ try {+ return r.diamondGradientEffect.makeShaderWithChildren([], [ramp], localMatrix)+ } finally {+ ramp.delete()+ }+}diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 1ac2a7bbe..8493d4b54 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -49,6 +49,7 @@ import type {SkPicture,ImageFilter,MaskFilter,+ RuntimeEffect,Paragraph} from 'canvaskit-wasm'@@ -73,6 +74,7 @@ export class SkiaRenderer {ck: CanvasKitsurface: Surfacedeclare fillPaint: Paint+ diamondGradientEffect: RuntimeEffect | null = nulldeclare strokePaint: Paintdeclare selectionPaint: Paintdeclare parentOutlinePaint: Paint@@ -650,7 +652,7 @@ export class SkiaRenderer {buildParagraph(node: SceneNode,color?: Float32Array,- opts?: { halfLeading?: boolean }+ opts?: RenderText.ParagraphBuildOptions): Paragraph {return RenderText.buildParagraph(this, node, color, opts)}diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.tsindex 71174714a..c418e5fca 100644--- a/packages/core/src/canvas/renderer/lifecycle.ts+++ b/packages/core/src/canvas/renderer/lifecycle.ts@@ -34,6 +34,8 @@ export function destroyRenderer(r: SkiaRenderer): void {r.imageCache.clear()disposePathCaches(r)r.fillPaint.delete()+ r.diamondGradientEffect?.delete()+ r.diamondGradientEffect = nullr.strokePaint.delete()r.selectionPaint.delete()r.parentOutlinePaint.delete()diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex f51ee486f..bdadc8b1e 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -45,7 +45,6 @@ import {drawReflowedPathTextSilhouettes,isReflowedPathText} from './text/derived'-import { textNodeToOutlinePath } from './text/outlines'function drawVisibleFills(r: SkiaRenderer,@@ -876,11 +875,7 @@ export function renderShapeUncached(r.renderEffects(canvas, node, rect, hasRadius, 'front', shadowChild)}-function isGradientFill(fill?: Fill): boolean {- return fill?.type.startsWith('GRADIENT') === true-}--function shouldRenderTextAsOutline(fill?: Fill): boolean {+function hasComplexTextFill(fill?: Fill): boolean {return fill !== undefined && fill.type !== 'SOLID'}@@ -891,53 +886,22 @@ export function textVerticalOffset(node: SceneNode, contentHeight: number): numbreturn 0}-function drawOutlinedText(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- paragraphY: number-): boolean {- const outlineNode =- node.textCase === 'ORIGINAL'- ? node- : { ...node, text: transformTextCase(node.text, node.textCase), styleRuns: [] }- const path = textNodeToOutlinePath(r, outlineNode)- if (!path) return false- canvas.save()- canvas.translate(0, paragraphY)- canvas.drawPath(path, r.fillPaint)- canvas.restore()- path.delete()- return true-}--function drawGradientText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {+function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {if (!r.fontsLoaded || !r.fontProvider) return false-- const paragraph = r.buildParagraph(node, r.ck.Color4f(0, 0, 0, 1), {- halfLeading: true- })- try {- const paragraphY = textVerticalOffset(node, paragraph.getHeight())- r.effectLayerPaint.setImageFilter(null)- r.effectLayerPaint.setColorFilter(null)- r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)- const bounds = r.ck.LTRBRect(0, paragraphY, node.width, paragraphY + node.height)- canvas.saveLayer(r.effectLayerPaint, bounds)- canvas.drawParagraph(paragraph, 0, paragraphY)-- r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcIn)- canvas.saveLayer(r.effectLayerPaint, bounds)- canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.fillPaint)- canvas.restore()- canvas.restore()- return true- } finally {- paragraph.delete()- r.effectLayerPaint.setImageFilter(null)- r.effectLayerPaint.setColorFilter(null)- r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)- }+ // Apply the shader directly to native glyphs: coverage layers add another rounding pass.+ return withTextParagraph(+ r,+ node,+ r.ck.Color4f(0, 0, 0, 1),+ {+ halfLeading: true,+ foregroundPaint: r.fillPaint+ },+ (paragraph) => {+ canvas.drawParagraph(paragraph, 0, textVerticalOffset(node, paragraph.getHeight()))+ return true+ }+ )}function shouldClipTextToLayoutBox(node: SceneNode): boolean {@@ -994,21 +958,7 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, filcanvas.restore()return}- if (shouldRenderTextAsOutline(fill)) {- let paragraphY = 0- if (node.textAlignVertical !== 'TOP') {- const paragraph = r.buildParagraph(node, r.ck.Color4f(0, 0, 0, 1), {- halfLeading: true- })- paragraphY = textVerticalOffset(node, paragraph.getHeight())- paragraph.delete()- }- if (drawOutlinedText(r, canvas, node, paragraphY)) {- canvas.restore()- return- }- }- if (isGradientFill(fill) && drawGradientText(r, canvas, node)) {+ if (hasComplexTextFill(fill) && drawPaintedText(r, canvas, node)) {canvas.restore()return}diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.tsindex 169f9ef00..a21635793 100644--- a/packages/core/src/canvas/text/index.ts+++ b/packages/core/src/canvas/text/index.ts@@ -1,6 +1,7 @@import type {CanvasKit,FontWeight,+ Paint,Paragraph,TextFontFeatures,TextFontVariations,@@ -25,8 +26,12 @@ import {} from '#core/text/resolver'import { resolveParagraphFontFamilies } from './font-families'+import { pushParagraphStyle, type ParagraphPaintStyle, type ParagraphBuildOptions } from './paint'+import { withPreparedText } from './prepared'+export { withTextParagraph } from './prepared'+export type { ParagraphBuildOptions } from './paint'import type { ParagraphNode } from './paragraph-inputs'-import type { PreparedText, TextPreparationCache } from './preparation-cache'+import type { TextPreparationCache } from './preparation-cache'interface FontReadinessRenderer {textPreparationCache?: TextPreparationCache@@ -370,46 +375,45 @@ function pushStyleRun(baseColor: Float32Array,baseFontSize: number,fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],- halfLeading: boolean+ halfLeading: boolean,+ paintStyle?: ParagraphPaintStyle): void {const ck = r.ckconst style = run.styleconst runLineHeight = style.lineHeight !== undefined ? style.lineHeight : node.lineHeightconst runFontSize = style.fontSize ?? baseFontSize- builder.pushStyle(- new ck.TextStyle({- color: styleRunColor(ck, style, baseColor),- fontFamilies: fontFamilies(- style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),- style.fontWeight ?? node.fontWeight,- style.italic ?? node.italic- ),- fontSize: runFontSize,- locale: styleRunLanguage(style, node),- fontStyle: {- weight: { value: style.fontWeight ?? node.fontWeight } as FontWeight,- slant: (style.italic ?? node.italic) ? ck.FontSlant.Italic : ck.FontSlant.Upright- },- fontVariations: textFontVariations(style.fontVariations ?? node.fontVariations),- fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),- letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),- decoration: textDecorationValue(ck, style.textDecoration ?? node.textDecoration),- decorationStyle: textDecorationStyleValue(- ck,- style.textDecorationStyle ?? node.textDecorationStyle- ),- decorationThickness:- style.textDecorationThickness ?? node.textDecorationThickness ?? undefined,- decorationColor: textDecorationColor(- ck,- style.textDecorationFills ?? node.textDecorationFills,- baseColor- ),- heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,- halfLeading- })- )+ const textStyle = new ck.TextStyle({+ color: styleRunColor(ck, style, baseColor),+ fontFamilies: fontFamilies(+ style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY),+ style.fontWeight ?? node.fontWeight,+ style.italic ?? node.italic+ ),+ fontSize: runFontSize,+ locale: styleRunLanguage(style, node),+ fontStyle: {+ weight: { value: style.fontWeight ?? node.fontWeight } as FontWeight,+ slant: (style.italic ?? node.italic) ? ck.FontSlant.Italic : ck.FontSlant.Upright+ },+ fontVariations: textFontVariations(style.fontVariations ?? node.fontVariations),+ fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),+ letterSpacing: style.letterSpacing ?? (node.letterSpacing || 0),+ decoration: textDecorationValue(ck, style.textDecoration ?? node.textDecoration),+ decorationStyle: textDecorationStyleValue(+ ck,+ style.textDecorationStyle ?? node.textDecorationStyle+ ),+ decorationThickness: style.textDecorationThickness ?? node.textDecorationThickness ?? undefined,+ decorationColor: textDecorationColor(+ ck,+ style.textDecorationFills ?? node.textDecorationFills,+ baseColor+ ),+ heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,+ halfLeading+ })+ pushParagraphStyle(builder, textStyle, paintStyle)}function addParagraphText(@@ -427,14 +431,25 @@ function addStyledRuns(baseColor: Float32Array,baseFontSize: number,fontFamilies: (primary: string, weight: number, italic?: boolean) => string[],- halfLeading: boolean+ halfLeading: boolean,+ paintStyle?: ParagraphPaintStyle): void {const text = node.textlet pos = 0for (const run of node.styleRuns) {if (pos < run.start) addParagraphText(builder, node, text.slice(pos, run.start))- pushStyleRun(r, builder, node, run, baseColor, baseFontSize, fontFamilies, halfLeading)+ pushStyleRun(+ r,+ builder,+ node,+ run,+ baseColor,+ baseFontSize,+ fontFamilies,+ halfLeading,+ paintStyle+ )addParagraphText(builder, node, text.slice(run.start, run.start + run.length))builder.pop()pos = run.start + run.length@@ -443,59 +458,11 @@ function addStyledRuns(if (pos < text.length) addParagraphText(builder, node, text.slice(pos))}-function withPreparedText<T>(- r: FontReadinessRenderer,- node: SceneNode,- variant: string,- build: () => Paragraph,- consume: (prepared: PreparedText) => T-): T {- if (r.textPreparationCache && r.fontProvider) {- return r.textPreparationCache.use(- node,- variant,- fontManager.generation(),- r.fontProvider,- build,- consume- )- }- const paragraph = build()- try {- return consume({ paragraph })- } finally {- paragraph.delete()- }-}--/** Draw from a borrowed paragraph without transferring native resource ownership. */-export function withTextParagraph<T>(- r: FontReadinessRenderer & {- buildParagraph: (- node: SceneNode,- color: Float32Array,- options: { halfLeading?: boolean }- ) => Paragraph- },- node: SceneNode,- color: Float32Array,- options: { halfLeading?: boolean },- draw: (paragraph: Paragraph) => T-): T {- return withPreparedText(- r,- node,- `draw:${Boolean(options.halfLeading)}:${color.join(',')}`,- () => r.buildParagraph(node, color, options),- (prepared) => draw(prepared.paragraph)- )-}-export function buildParagraph(r: TextRenderer,node: ParagraphNode,color?: Float32Array,- { halfLeading = false }: { halfLeading?: boolean } = {}+ { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {}): Paragraph {const ck = r.ckconst baseColor = color ?? ck.BLACK@@ -514,52 +481,79 @@ export function buildParagraph(cjkFallbacks)+ const baseTextStyle = {+ color: baseColor,+ fontFamilies: fontFamilies(+ node.fontFamily || DEFAULT_FONT_FAMILY,+ node.fontWeight,+ node.italic+ ),+ fontSize: baseFontSize,+ locale: node.textLanguage ?? undefined,+ fontStyle: {+ weight: { value: node.fontWeight } as FontWeight,+ slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright+ },+ fontVariations: textFontVariations(node.fontVariations),+ fontFeatures: textFontFeatures(node.fontFeatures),+ letterSpacing: node.letterSpacing || 0,+ decoration: textDecorationValue(ck, node.textDecoration),+ decorationStyle: textDecorationStyleValue(ck, node.textDecorationStyle),+ decorationThickness: node.textDecorationThickness ?? undefined,+ decorationColor: textDecorationColor(ck, node.textDecorationFills, baseColor),+ heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,+ halfLeading+ }const paraStyle = new ck.ParagraphStyle({textAlign: getParagraphTextAlign(ck, node),textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,textHeightBehavior: textHeightBehaviorValue(ck, node.leadingTrim),...truncateOpts,- textStyle: {- color: baseColor,- fontFamilies: fontFamilies(- node.fontFamily || DEFAULT_FONT_FAMILY,- node.fontWeight,- node.italic- ),- fontSize: baseFontSize,- locale: node.textLanguage ?? undefined,- fontStyle: {- weight: { value: node.fontWeight } as FontWeight,- slant: node.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright- },- fontVariations: textFontVariations(node.fontVariations),- fontFeatures: textFontFeatures(node.fontFeatures),- letterSpacing: node.letterSpacing || 0,- decoration: textDecorationValue(ck, node.textDecoration),- decorationStyle: textDecorationStyleValue(ck, node.textDecorationStyle),- decorationThickness: node.textDecorationThickness ?? undefined,- decorationColor: textDecorationColor(ck, node.textDecorationFills, baseColor),- heightMultiplier: node.lineHeight ? node.lineHeight / baseFontSize : undefined,- halfLeading- }+ textStyle: baseTextStyle})if (!r.fontProvider) throw new Error('Font provider not initialized')const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, r.fontProvider)- if (node.styleRuns.length === 0) {- addParagraphText(builder, node, node.text)- } else {- addStyledRuns(r, builder, node, baseColor, baseFontSize, fontFamilies, halfLeading)- }+ let background: Paint | undefined+ try {+ let paintStyle: ParagraphPaintStyle | undefined+ if (foregroundPaint) {+ background = new ck.Paint()+ background.setColor(ck.TRANSPARENT)+ paintStyle = { foreground: foregroundPaint, background }+ builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)+ }+ if (node.styleRuns.length === 0) {+ addParagraphText(builder, node, node.text)+ } else {+ addStyledRuns(+ r,+ builder,+ node,+ baseColor,+ baseFontSize,+ fontFamilies,+ halfLeading,+ paintStyle+ )+ }- const paragraph = builder.build()- if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {- paragraph.layout(1e6)- paragraph.layout(Math.max(node.width || 1, Math.ceil(paragraph.getLongestLine())))- } else {- paragraph.layout(resolveParagraphLayoutWidth(node))+ const paragraph = builder.build()+ try {+ if (node.textAutoResize === 'WIDTH_AND_HEIGHT') {+ paragraph.layout(1e6)+ paragraph.layout(Math.max(node.width || 1, Math.ceil(paragraph.getLongestLine())))+ } else {+ paragraph.layout(resolveParagraphLayoutWidth(node))+ }+ return paragraph+ } catch (error) {+ paragraph.delete()+ throw error+ }+ } finally {+ builder.delete()+ background?.delete()}- builder.delete()- return paragraph}diff --git a/packages/core/src/canvas/text/paint.ts b/packages/core/src/canvas/text/paint.tsnew file mode 100644index 000000000..c9c1cf688--- /dev/null+++ b/packages/core/src/canvas/text/paint.ts@@ -0,0 +1,20 @@+import type { Paint, ParagraphBuilder, TextStyle } from 'canvaskit-wasm'++export interface ParagraphBuildOptions {+ halfLeading?: boolean+ foregroundPaint?: Paint+}++export interface ParagraphPaintStyle {+ foreground: Paint+ background: Paint+}++export function pushParagraphStyle(+ builder: ParagraphBuilder,+ style: TextStyle,+ paints?: ParagraphPaintStyle+): void {+ if (paints) builder.pushPaintStyle(style, paints.foreground, paints.background)+ else builder.pushStyle(style)+}diff --git a/packages/core/src/canvas/text/prepared.ts b/packages/core/src/canvas/text/prepared.tsnew file mode 100644index 000000000..7d4238b7d--- /dev/null+++ b/packages/core/src/canvas/text/prepared.ts@@ -0,0 +1,63 @@+import type { Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'++import type { SceneNode } from '@open-pencil/scene-graph'++import { fontManager } from '#core/text/fonts'++import type { ParagraphBuildOptions } from './paint'+import type { PreparedText, TextPreparationCache } from './preparation-cache'++interface PreparationRenderer {+ textPreparationCache?: TextPreparationCache+ fontProvider?: TypefaceFontProvider | null+}++export function withPreparedText<T>(+ r: PreparationRenderer,+ node: SceneNode,+ variant: string,+ build: () => Paragraph,+ consume: (prepared: PreparedText) => T,+ cacheAllowed = true+): T {+ if (cacheAllowed && r.textPreparationCache && r.fontProvider) {+ return r.textPreparationCache.use(+ node,+ variant,+ fontManager.generation(),+ r.fontProvider,+ build,+ consume+ )+ }+ const paragraph = build()+ try {+ return consume({ paragraph })+ } finally {+ paragraph.delete()+ }+}++/** Borrow native text without caching mutable foreground shaders or transferring resource ownership. */+export function withTextParagraph<T>(+ r: PreparationRenderer & {+ buildParagraph: (+ node: SceneNode,+ color: Float32Array,+ options: ParagraphBuildOptions+ ) => Paragraph+ },+ node: SceneNode,+ color: Float32Array,+ options: ParagraphBuildOptions,+ draw: (paragraph: Paragraph) => T+): T {+ return withPreparedText(+ r,+ node,+ `draw:${Boolean(options.halfLeading)}:${color.join(',')}`,+ () => r.buildParagraph(node, color, options),+ (prepared) => draw(prepared.paragraph),+ !options.foregroundPaint+ )+}diff --git a/packages/vue/src/canvas/surface/color-space.ts b/packages/vue/src/canvas/surface/color-space.tsnew file mode 100644index 000000000..3de278b1d--- /dev/null+++ b/packages/vue/src/canvas/surface/color-space.ts@@ -0,0 +1,20 @@+import type { DocumentColorSpace } from '@open-pencil/scene-graph'++type ColorManagedContext = Partial<Pick<WebGLRenderingContext, 'drawingBufferColorSpace'>>++/** Keep Skia's surface encoding aligned with the browser's actual presentation buffer. */+export function configureDrawingBufferColorSpace(+ context: ColorManagedContext | null,+ documentColorSpace: DocumentColorSpace,+ wideGamut: boolean+): DocumentColorSpace {+ if (!context?.drawingBufferColorSpace) return 'srgb'+ const requested = wideGamut && documentColorSpace === 'display-p3' ? 'display-p3' : 'srgb'+ if (context.drawingBufferColorSpace === requested) return requested+ try {+ context.drawingBufferColorSpace = requested+ } catch (error) {+ console.warn('Canvas color-space request is unavailable; keeping the current buffer.', error)+ }+ return context.drawingBufferColorSpace === 'display-p3' ? 'display-p3' : 'srgb'+}diff --git a/packages/vue/src/canvas/surface/gl-surface.ts b/packages/vue/src/canvas/surface/gl-surface.tsindex 7db0d30da..89daa82ce 100644--- a/packages/vue/src/canvas/surface/gl-surface.ts+++ b/packages/vue/src/canvas/surface/gl-surface.ts@@ -5,6 +5,8 @@ import type { Editor } from '@open-pencil/core/editor'import type { UseCanvasOptions } from '#vue/canvas/surface/types'+import { configureDrawingBufferColorSpace } from './color-space'+type GLContext = ReturnType<CanvasKit['MakeGrContext']>export type CanvasGLContext = GLContext@@ -34,24 +36,32 @@ export function makeGLSurface(glContext: GLContext | null): { surface: Surface | null; glContext: GLContext | null } {let context = glContext- if (!context) {- const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined- const handle = ck.GetWebGLContext(canvas, glAttrs)- if (!handle) return { surface: null, glContext: context }- context = ck.MakeGrContext(handle)- }+ const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined+ const handle = context ? null : ck.GetWebGLContext(canvas, glAttrs)+ if (!context && !handle) return { surface: null, glContext: context }++ 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+ )+ if (!context && handle) context = ck.MakeGrContext(handle)if (!context) return { surface: null, glContext: context }- const preferredSpace = editor.graph.documentColorSpace- const colorSpaces =- preferredSpace === 'display-p3'- ? [ck.ColorSpace.DISPLAY_P3, ck.ColorSpace.SRGB]- : [ck.ColorSpace.SRGB]+ 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 }- for (const colorSpace of colorSpaces) {- const surface = ck.MakeOnScreenGLSurface(context, canvas.width, canvas.height, colorSpace)- if (surface) return { surface, glContext: context }+ 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: null, glContext: context }}diff --git a/tests/e2e/canvas/color-space.spec.ts b/tests/e2e/canvas/color-space.spec.tsnew file mode 100644index 000000000..1a4d9ad12--- /dev/null+++ b/tests/e2e/canvas/color-space.spec.ts@@ -0,0 +1,74 @@+import { expect, test } from '#tests/e2e/fixtures'+import { CanvasHelper } from '#tests/helpers/canvas'+import { readScenePixels } from '#tests/helpers/canvas/pixels'++for (const colorSpace of ['srgb', 'display-p3'] as const) {+ test(`sRGB bitmap colors survive a ${colorSpace} document on an sRGB display`, async ({+ page+ }) => {+ await page.goto('/?test&no-chrome&no-rulers')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ await canvas.clearCanvas()+ test.skip(+ await page.evaluate(() => matchMedia('(color-gamut: p3)').matches),+ 'Requires an sRGB display'+ )+ const samples = [+ [248, 130, 29],+ [17, 181, 143],+ [65, 117, 235]+ ]+ await page.evaluate(+ async ({ colorSpace, samples }) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ store.setDocumentColorSpace(colorSpace)+ const source = document.createElement('canvas')+ source.width = 96+ source.height = 32+ const context = source.getContext('2d', { colorSpace: 'srgb' })+ if (!context) throw new Error('sRGB canvas unavailable')+ const data = context.createImageData(source.width, source.height)+ for (let pixel = 0; pixel < source.width * source.height; pixel++) {+ const rgb = samples[Math.floor((pixel % source.width) / 32)]+ data.data.set([...rgb, 255], pixel * 4)+ }+ context.putImageData(data, 0, 0)+ const blob = await new Promise<Blob>((resolve, reject) => {+ source.toBlob((value) => {+ if (value) resolve(value)+ else reject(new Error('Cannot encode bitmap'))+ })+ })+ const imageHash = store.storeImage(new Uint8Array(await blob.arrayBuffer()))+ store.graph.createNode('RECTANGLE', store.state.currentPageId, {+ x: 40,+ y: 40,+ width: 96,+ height: 32,+ fills: [+ {+ type: 'IMAGE',+ imageHash,+ imageScaleMode: 'FIT',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ })+ store.requestRender()+ },+ { colorSpace, samples }+ )+ await canvas.waitForRender()+ expect(+ await readScenePixels(+ page,+ samples.map((_, index) => ({ x: 56 + index * 32, y: 56 }))+ )+ ).toEqual(samples.map((rgb) => [...rgb, 255]))+ canvas.assertNoErrors()+ })+}diff --git a/tests/e2e/canvas/painted-text.spec.ts b/tests/e2e/canvas/painted-text.spec.tsnew file mode 100644index 000000000..d009e3d6d--- /dev/null+++ b/tests/e2e/canvas/painted-text.spec.ts@@ -0,0 +1,65 @@+import { writeFile } from 'node:fs/promises'++import { expect, test } from '#tests/e2e/fixtures'+import { CanvasHelper } from '#tests/helpers/canvas'+import { readScenePixels } from '#tests/helpers/canvas/pixels'++test('changing only the text paint preserves native glyph pixels', async ({ page }) => {+ await page.goto('/?test&no-chrome&no-rulers')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ await canvas.clearCanvas()+ const id = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('Editor unavailable')+ const black = { r: 0, g: 0, b: 0, a: 1 }+ const node = store.graph.createNode('TEXT', store.state.currentPageId, {+ x: 80,+ y: 80,+ width: 560,+ height: 96,+ text: 'OPEN',+ fontFamily: 'Inter',+ fontSize: 88,+ fontWeight: 400,+ textAutoResize: 'NONE',+ fills: [+ {+ type: 'GRADIENT_LINEAR',+ color: black,+ opacity: 1,+ visible: true,+ gradientStops: [+ { position: 0, color: black },+ { position: 1, color: black }+ ],+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ ]+ })+ store.requestRender()+ return node.id+ })+ await canvas.waitForRender()+ const pixels = await readScenePixels(+ page,+ Array.from({ length: 8 }, (_, x) =>+ Array.from({ length: 6 }, (_, y) => ({ x: 90 + x * 30, y: 100 + y * 10 }))+ ).flat()+ )+ expect(pixels.some(([r, g, b, a]) => r < 32 && g < 32 && b < 32 && a === 255)).toBe(true)+ const gradient = await canvas.screenshotCanvasRegion()+ await page.evaluate((id) => {+ window.openPencil?.getStore?.().updateNode(id, {+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ })+ }, id)+ await canvas.waitForRender()+ const solid = await canvas.screenshotCanvasRegion()+ if (!solid.equals(gradient)) {+ await writeFile(test.info().outputPath('gradient.png'), gradient)+ await writeFile(test.info().outputPath('solid.png'), solid)+ }+ expect(solid.equals(gradient)).toBe(true)+ canvas.assertNoErrors()+})diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts b/tests/e2e/canvas/renderer-visuals.spec.tsindex c451b8eb5..3373bb6f0 100644--- a/tests/e2e/canvas/renderer-visuals.spec.ts+++ b/tests/e2e/canvas/renderer-visuals.spec.ts@@ -1,6 +1,7 @@import { readFile } from 'node:fs/promises'import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { readScenePixels } from '#tests/helpers/canvas/pixels'const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')@@ -180,7 +181,14 @@ test('gradients and image fill modes', async () => {height: 72,cornerRadius: 16,fills: [- { type, color: { r: 0, g: 0, b: 0, a: 1 }, visible: true, opacity: 1, gradientStops }+ {+ type,+ color: { r: 0, g: 0, b: 0, a: 1 },+ visible: true,+ opacity: 1,+ gradientStops,+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }]})}@@ -242,10 +250,19 @@ test('gradients and image fill modes', async () => {store.requestRender()})await editor.canvas.waitForRender()+ const gradientPixels = await readScenePixels(+ editor.page,+ [0, 1, 2, 3].map((index) => ({ x: 130 + index * 116, y: 120 }))+ )+ for (const [r, g, b, a] of gradientPixels) {+ expect(a).toBe(255)+ expect(Math.min(r, g, b)).toBeLessThan(200)+ }+ await editor.canvas.waitForRender()await expectCanvas('gradients-and-image-fill-modes')})-test('complex text fills render as glyph outlines', async () => {+test('complex text fills preserve native paragraph layout', async () => {await editor.page.evaluate(async () => {const store = window.openPencil?.getStore?.()if (!store) throw new Error('OpenPencil store not initialized')diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.pngindex 4e5a1d96f..227580ccb 100644Binary files a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png and b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.pngindex 7bb87930b..f5cea5815 100644Binary files a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png and b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.pngindex b0aaee097..38e2f8390 100644Binary files a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png and b/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png differdiff --git a/tests/engine/render/canvas/diamond-gradient.test.ts b/tests/engine/render/canvas/diamond-gradient.test.tsnew file mode 100644index 000000000..2e51c74ac--- /dev/null+++ b/tests/engine/render/canvas/diamond-gradient.test.ts@@ -0,0 +1,119 @@+import { expect, test } from 'bun:test'++import type { Fill } from '@open-pencil/scene-graph'+import { SceneGraph } from '@open-pencil/scene-graph'++import { initCanvasKit } from '#cli/headless'+import { SkiaRenderer } from '#core/canvas/renderer'++import { expectDefined } from '#tests/helpers/assert'++test('diamond contours use Manhattan distance and dispose their retained program', async () => {+ const ck = await initCanvasKit()+ const surface = expectDefined(ck.MakeSurface(101, 101), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'page')+ const fill: Fill = {+ type: 'GRADIENT_DIAMOND',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ gradientStops: [+ { position: 0, color: { r: 0, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 1, g: 1, b: 1, a: 1 } }+ ],+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ const node = graph.createNode('RECTANGLE', page.id, { width: 101, height: 101, fills: [fill] })+ let effect = renderer.diamondGradientEffect+ try {+ const draw = () => {+ const canvas = surface.getCanvas()+ canvas.clear(ck.TRANSPARENT)+ renderer.renderShape(canvas, node, graph)+ surface.flush()+ }+ draw()+ effect = renderer.diamondGradientEffect+ draw()+ expect(renderer.diamondGradientEffect).toBe(effect)+ const image = surface.makeImageSnapshot()+ try {+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ width: 101,+ height: 101,+ colorType: ck.ColorType.RGBA_8888,+ alphaType: ck.AlphaType.Unpremul,+ colorSpace: ck.ColorSpace.SRGB+ }),+ 'pixels'+ )+ const red = (x: number, y: number) => pixels[(y * 101 + x) * 4]+ expect(red(50, 50)).toBe(0)+ expect(red(75, 75)).toBe(red(100, 50))+ expect(red(75, 75)).toBeGreaterThan(245)+ expect(red(0, 0)).toBe(255)+ effect = expectDefined(effect, 'compiled effect')+ } finally {+ image.delete()+ }+ } finally {+ renderer.destroy()+ }+ expect(effect?.isDeleted()).toBe(true)+ expect(renderer.diamondGradientEffect).toBeNull()+})++test('diamond gradients preserve transformed contours and intermediate stops', async () => {+ const ck = await initCanvasKit()+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(100, 100), 'surface'))+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'page')+ const black = { r: 0, g: 0, b: 0, a: 1 }+ const fill: Fill = {+ type: 'GRADIENT_DIAMOND',+ color: black,+ opacity: 1,+ visible: true,+ gradientTransform: { m00: 0, m01: -1, m02: 1.005, m10: 0.5, m11: 0, m12: 0.255 },+ gradientStops: [+ { position: 0, color: black },+ { position: 0.5, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 1, g: 1, b: 1, a: 1 } }+ ]+ }+ const node = graph.createNode('RECTANGLE', page.id, { width: 100, height: 100, fills: [fill] })+ try {+ const canvas = renderer.surface.getCanvas()+ canvas.clear(ck.TRANSPARENT)+ renderer.renderShape(canvas, node, graph)+ renderer.surface.flush()+ const image = renderer.surface.makeImageSnapshot()+ try {+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ width: 100,+ height: 100,+ colorType: ck.ColorType.RGBA_8888,+ alphaType: ck.AlphaType.Unpremul,+ colorSpace: ck.ColorSpace.SRGB+ }),+ 'pixels'+ )+ const pixel = (x: number, y: number) =>+ Array.from(pixels.slice((y * 100 + x) * 4, (y * 100 + x) * 4 + 4))+ expect(pixel(50, 50)).toEqual([0, 0, 0, 255])+ expect(pixel(50, 56)).toEqual([122, 0, 0, 255])+ expect(pixel(62, 50)).toEqual(pixel(50, 56))+ expect(pixel(50, 63)).toEqual([255, 10, 10, 255])+ expect(pixel(76, 50)).toEqual(pixel(50, 63))+ expect(pixel(50, 75)).toEqual([255, 255, 255, 255])+ } finally {+ image.delete()+ }+ } finally {+ renderer.destroy()+ }+})diff --git a/tests/engine/render/canvas/painted-text.test.ts b/tests/engine/render/canvas/painted-text.test.tsnew file mode 100644index 000000000..c326e7bfe--- /dev/null+++ b/tests/engine/render/canvas/painted-text.test.ts@@ -0,0 +1,114 @@+import { expect, test } from 'bun:test'++import type { Paragraph } from 'canvaskit-wasm'++import type { Fill } from '@open-pencil/scene-graph'+import { SceneGraph } from '@open-pencil/scene-graph'++import { initCanvasKit } from '#cli/headless'+import { SkiaRenderer } from '#core/canvas/renderer'+import { withTextParagraph } from '#core/canvas/text'++import { expectDefined } from '#tests/helpers/assert'++const solid: Fill = { type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }+const gradient: Fill = {+ ...solid,+ type: 'GRADIENT_LINEAR',+ gradientStops: [+ { position: 0, color: solid.color },+ { position: 1, color: solid.color }+ ],+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+}++test('mutable foreground paints never enter the paragraph cache, including on errors', async () => {+ const ck = await initCanvasKit()+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(100, 100), 'surface'))+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'page')+ const node = graph.createNode('TEXT', page.id, {+ text: 'Paint',+ fontFamily: 'Inter',+ width: 100,+ height: 100+ })+ let borrowed: Paragraph | undefined+ try {+ await renderer.loadFonts()+ expect(() =>+ withTextParagraph(+ renderer,+ node,+ ck.BLACK,+ { halfLeading: true, foregroundPaint: renderer.fillPaint },+ (paragraph) => {+ borrowed = paragraph+ throw new Error('paint failed')+ }+ )+ ).toThrow('paint failed')+ expect(borrowed?.isDeleted()).toBe(true)+ } finally {+ renderer.destroy()+ }+})++for (const textAlignVertical of ['TOP', 'CENTER', 'BOTTOM'] as const) {+ for (const fixture of [+ { text: 'OPEN', fontSize: 88, width: 560, height: 96 },+ { text: 'office AV\nOPEN', fontSize: 32, width: 130, height: 180 },+ {+ text: 'Bold AV\noffice',+ fontSize: 32,+ width: 130,+ height: 180,+ styleRuns: [{ start: 0, length: 4, style: { fontSize: 40, fontWeight: 600 } }]+ }+ ]) {+ test(`complex paint preserves paragraph coverage: ${textAlignVertical} ${fixture.text}`, async () => {+ const ck = await initCanvasKit()+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'page')+ const node = graph.createNode('TEXT', page.id, {+ ...fixture,+ fontFamily: 'Inter',+ fontWeight: 400,+ textAlignVertical,+ textAutoResize: 'NONE',+ fills: [solid]+ })+ const surface = expectDefined(ck.MakeSurface(fixture.width, fixture.height), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ try {+ await renderer.loadFonts()+ const draw = (fill: Fill) => {+ graph.updateNode(node.id, { fills: [fill] })+ const canvas = surface.getCanvas()+ canvas.clear(ck.WHITE)+ renderer.renderShape(canvas, node, graph)+ surface.flush()+ const image = surface.makeImageSnapshot()+ try {+ const pixels = image.readPixels(0, 0, {+ width: fixture.width,+ height: fixture.height,+ colorType: ck.ColorType.RGBA_8888,+ alphaType: ck.AlphaType.Unpremul,+ colorSpace: ck.ColorSpace.SRGB+ })+ if (!(pixels instanceof Uint8Array)) throw new Error('RGBA bytes unavailable')+ return pixels.slice()+ } finally {+ image.delete()+ }+ }+ const reference = draw(solid)+ expect(reference.some((value, index) => index % 4 !== 3 && value < 128)).toBe(true)+ expect(draw(gradient)).toEqual(reference)+ } finally {+ renderer.destroy()+ }+ })+ }+}diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.tsindex 9072813b3..454c12400 100644--- a/tests/engine/render/canvas/text.test.ts+++ b/tests/engine/render/canvas/text.test.ts@@ -159,7 +159,7 @@ describe('renderText', () => {expect(canvas.drawText).not.toHaveBeenCalled()})- test('renders gradient text through a paragraph mask without outline font data', () => {+ test('paints gradients through native paragraphs without outline font data', () => {const r = createMockRenderer()const canvas = createMockCanvas()@@ -172,16 +172,16 @@ describe('renderText', () => {})expect(r.buildParagraph).toHaveBeenCalledWith(expect.anything(), expect.anything(), {- halfLeading: true+ halfLeading: true,+ foregroundPaint: r.fillPaint})- expect(canvas.saveLayer).toHaveBeenCalledTimes(2)+ expect(canvas.saveLayer).not.toHaveBeenCalled()expect(canvas.drawParagraph).toHaveBeenCalledTimes(1)- expect(canvas.drawRect).toHaveBeenCalledTimes(1)- expect(r.effectLayerPaint.setBlendMode).toHaveBeenCalledWith(r.ck.BlendMode.SrcIn)+ expect(canvas.drawRect).not.toHaveBeenCalled()expect(r._paragraph.delete).toHaveBeenCalledTimes(1)})- test('renders non-solid text fills as vector outlines when outline font data is available', async () => {+ test('keeps native paragraph layout even when outline font data is available', async () => {const interData = await Bun.file(repoPath('public/Inter-Regular.ttf')).arrayBuffer()fontManager.markLoaded('Inter', 'Regular', interData)const r = createMockRenderer()@@ -200,8 +200,8 @@ describe('renderText', () => {})- expect(canvas.drawPath).toHaveBeenCalledTimes(1)- expect(r.buildParagraph).not.toHaveBeenCalled()+ expect(canvas.drawPath).not.toHaveBeenCalled()+ expect(r.buildParagraph).toHaveBeenCalledTimes(1)expect(canvas.saveLayer).not.toHaveBeenCalled()})diff --git a/tests/engine/vue/canvas/color-space.test.ts b/tests/engine/vue/canvas/color-space.test.tsnew file mode 100644index 000000000..d132ed469--- /dev/null+++ b/tests/engine/vue/canvas/color-space.test.ts@@ -0,0 +1,35 @@+import { expect, test } from 'bun:test'++import { configureDrawingBufferColorSpace } 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 expected = wideGamut && documentSpace === 'display-p3' ? 'display-p3' : 'srgb'+ expect(configureDrawingBufferColorSpace(context, documentSpace, wideGamut)).toBe(expected)+ expect(context.drawingBufferColorSpace).toBe(expected)+ })+ }+}++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')+})++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')+})diff --git a/tests/helpers/canvas/pixels.ts b/tests/helpers/canvas/pixels.tsnew file mode 100644index 000000000..e534c03d5--- /dev/null+++ b/tests/helpers/canvas/pixels.ts@@ -0,0 +1,43 @@+import type { Page } from '@playwright/test'++import type { Vector } from '@open-pencil/scene-graph'++/** Read freshly painted scene pixels in sRGB, before WebGL discards its drawing buffer. */+export async function readScenePixels(page: Page, points: readonly Vector[]): Promise<number[][]> {+ return page.evaluate((points) => {+ const store = window.openPencil?.getStore?.()+ const renderer = store?.canvasRenderers.find((candidate) => candidate.tracksSceneSettlement)+ const source = document.querySelector<HTMLCanvasElement>(+ '[data-test-id="scene-canvas-element"]'+ )+ if (!store || !renderer || !source) throw new Error('Scene canvas unavailable')+ const copy = document.createElement('canvas')+ copy.width = source.width+ copy.height = source.height+ const context = copy.getContext('2d', { colorSpace: 'srgb' })+ if (!context) throw new Error('sRGB canvas unavailable')+ renderer.renderFromEditorState(+ store.state,+ store.graph,+ store.textEditor,+ renderer.viewportWidth,+ renderer.viewportHeight,+ false,+ 'scene',+ true+ )+ context.drawImage(source, 0, 0)+ const pixels = points.map((point) =>+ Array.from(+ context.getImageData(+ Math.floor(point.x * devicePixelRatio),+ Math.floor(point.y * devicePixelRatio),+ 1,+ 1+ ).data+ )+ )+ store.requestRepaint()+ return pixels+ }, points)+}