AI-native design editor. Open-source Figma alternative.
fix(core): avoid parent-only contrast reports over siblings (#1396)
Danny Ward6d7556be3555
diff --git a/changes/1396/fixed.md b/changes/1396/fixed.mdnew file mode 100644index 000000000..2dde1a67f--- /dev/null+++ b/changes/1396/fixed.md@@ -0,0 +1 @@+- The color contrast lint rule measures text against the layers painted under it, such as a background shape beside the frame that holds the text, instead of the nearest filled ancestor, and skips text such a layer covers only in part.diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.tsindex 4b5a7a50a..0b8380ee4 100644--- a/packages/core/src/lint/linter.ts+++ b/packages/core/src/lint/linter.ts@@ -119,6 +119,7 @@ export class Linter {rotation: raw.rotation,visible: raw.visible,locked: raw.locked,+ opacity: raw.opacity,layoutMode: raw.layoutMode,layoutPositioning: raw.layoutPositioning,layoutGrow: raw.layoutGrow,diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.tsindex 7a78389cc..e143cdd01 100644--- a/packages/core/src/lint/rules/color-contrast.ts+++ b/packages/core/src/lint/rules/color-contrast.ts@@ -1,5 +1,12 @@import { colorToHex, compositeOver, contrastRatio } from '@open-pencil/scene-graph/color'-import type { Color } from '@open-pencil/scene-graph/primitives'+import { BLACK } from '@open-pencil/scene-graph/constants'+import {+ clipPolygon,+ degToRad,+ rotatedCorners,+ rotatePoint+} from '@open-pencil/scene-graph/geometry'+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'import { defineRule } from '#core/lint/rule'import type { LintNode, RuleContext } from '#core/lint/types'@@ -39,29 +46,136 @@ function opaque(color: Pick<Color, 'r' | 'g' | 'b'>): Color {return { ...color, a: 1 }}+/** Layers whose box is painted edge to edge, so their fills cover whatever their box covers. */+const BOX_TYPES = new Set(['FRAME', 'RECTANGLE', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE'])++/** The corners of a layer's box in its parent's space; layers turn around their centre. */+function boxCorners(node: LintNode): Vector[] {+ const halfWidth = node.width / 2+ const halfHeight = node.height / 2+ return rotatedCorners(+ node.x + halfWidth,+ node.y + halfHeight,+ halfWidth,+ halfHeight,+ node.rotation+ )+}++/** `points` in `container`'s space, moved to its parent's space. */+function toParentSpace(points: Vector[], container: LintNode): Vector[] {+ const rad = degToRad(container.rotation)+ return points.map((point) => {+ const turned = rotatePoint(point.x, point.y, container.width / 2, container.height / 2, rad)+ return { x: turned.x + container.x, y: turned.y + container.y }+ })+}++function area(polygon: Vector[]): number {+ let twice = 0+ for (const [index, point] of polygon.entries()) {+ const next = polygon[(index + 1) % polygon.length]+ twice += point.x * next.y - next.x * point.y+ }+ return Math.abs(twice) / 2+}++/** How much of the text's quad `layer` covers: none, all of it, or part. */+function coverage(text: Vector[], layer: LintNode): 'none' | 'all' | 'part' {+ const covered = area(clipPolygon(text, boxCorners(layer)) ?? [])+ if (covered <= 0) return 'none'+ return covered >= area(text) - 1e-6 ? 'all' : 'part'+}++interface Coat {+ color: Color+ /** How much of what lies under it the coat hides: 1 for opaque. */+ alpha: number+}++/**+ * A layer's fills composited over nothing, in paint order, as the renderer draws them before+ * applying the layer's opacity; null when a gradient or image shows, since those are not+ * composited yet.+ */+function flatten(paints: LintNode['fills']): Coat | null {+ let coat: Coat = { color: { ...BLACK }, alpha: 0 }+ let unresolved = false+ for (const paint of paints) {+ if (!paint.visible || paint.opacity <= 0) continue+ if (!isSolidPaint(paint)) {+ unresolved ||= paint.type !== 'SOLID'+ continue+ }+ if (paint.opacity >= 1) {+ coat = { color: opaque(paint.color), alpha: 1 }+ unresolved = false+ continue+ }+ // Over a partly covered coat the paint's share of the result is its opacity over the total.+ const alpha = paint.opacity + coat.alpha * (1 - paint.opacity)+ coat = { color: compositeOver(opaque(paint.color), coat.color, paint.opacity / alpha), alpha }+ }+ return unresolved ? null : coat+}++/**+ * Puts a layer's fills, at the layer's `opacity`, under the translucent `coats` collected so+ * far: the backdrop once that completes it with something opaque, `null` when a gradient or+ * image shows, and `undefined` while everything collected is translucent.+ */+function coatUnder(+ coats: Coat[],+ paints: LintNode['fills'],+ opacity: number+): Color | null | undefined {+ const coat = flatten(paints)+ if (!coat) return null+ const alpha = coat.alpha * opacity+ if (alpha <= 0) return undefined+ if (alpha < 1) {+ coats.push({ color: coat.color, alpha })+ return undefined+ }+ return coats.reduceRight((bg, layer) => compositeOver(layer.color, bg, layer.alpha), coat.color)+}++/** The children of `parent` painted before `child`, topmost first. */+function layersBelow(parent: LintNode, child: LintNode, context: RuleContext): LintNode[] {+ const siblings = context.getChildren(parent)+ const index = siblings.findIndex((sibling) => sibling.id === child.id)+ return siblings.slice(0, Math.max(index, 0)).toReversed()+}+/**- * What the text sits on: the fills of its ancestors in paint order, translucent solid ones- * composited over the nearest opaque one, which may sit under them on the same ancestor.- * Undefined when no ancestor has an opaque fill, since what shows through a translucent fill- * then is not part of the design, or when a gradient or image shows above it, since those are- * not composited yet.+ * What the text sits on, in paint order: at each ancestor, the layers painted before the+ * branch holding the text, topmost first, then the ancestor's own fills. Translucent solid+ * fills are composited over the nearest opaque one. Undefined when nothing opaque is under the+ * text, since what shows through a translucent fill then is not part of the design; when a+ * gradient or image shows above it; and when a layer under the text covers only part of it or+ * is not a box, since the text then has more than one background.*/function backdrop(node: LintNode, context: RuleContext): Color | undefined {- const layers: SolidPaint[] = []+ const coats: Coat[] = []+ let text = boxCorners(node)+ let branch = nodefor (let parent = context.getParent(node); parent; parent = context.getParent(parent)) {- // Fills paint in array order, so the last one is on top.- for (const paint of parent.fills.toReversed()) {- if (!paint.visible || paint.opacity <= 0) continue- if (paint.type !== 'SOLID') return undefined- if (!isSolidPaint(paint)) continue- if (paint.opacity >= 1) {- return layers.reduceRight(- (bg, layer) => compositeOver(opaque(layer.color), bg, layer.opacity),- opaque(paint.color)- )- }- layers.push(paint)+ for (const layer of layersBelow(parent, branch, context)) {+ if (!layer.visible || layer.opacity <= 0 || layer.type === 'TEXT') continue+ const paints = layer.fills.some((paint) => paint.visible && paint.opacity > 0)+ // A layer that paints nothing itself and holds no layers leaves the text as it was.+ if (!paints && layer.childIds.length === 0) continue+ const covers = coverage(text, layer)+ if (covers === 'none') continue+ if (covers === 'part' || !BOX_TYPES.has(layer.type) || layer.childIds.length > 0)+ return undefined+ const result = coatUnder(coats, layer.fills, layer.opacity)+ if (result !== undefined) return result ?? undefined}+ const result = coatUnder(coats, parent.fills, 1)+ if (result !== undefined) return result ?? undefined+ text = toParentSpace(text, parent)+ branch = parent}return undefined}diff --git a/packages/core/src/lint/types.ts b/packages/core/src/lint/types.tsindex 9c423f885..f45af278c 100644--- a/packages/core/src/lint/types.ts+++ b/packages/core/src/lint/types.ts@@ -83,6 +83,7 @@ export interface LintNode {rotation: numbervisible: booleanlocked: boolean+ opacity: numberlayoutMode: stringlayoutPositioning: 'AUTO' | 'ABSOLUTE'layoutGrow: numberdiff --git a/packages/core/tests/lint/rules.test.ts b/packages/core/tests/lint/rules.test.tsindex 1370f989f..48579ae81 100644--- a/packages/core/tests/lint/rules.test.ts+++ b/packages/core/tests/lint/rules.test.ts@@ -6,6 +6,7 @@ import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'const WHITE = { r: 1, g: 1, b: 1, a: 1 }const BLUE = { r: 0.23, g: 0.51, b: 0.96, a: 1 }const LIGHT_GRAY = { r: 0.8, g: 0.8, b: 0.8, a: 1 }+const DARK_GREEN = { r: 25 / 255, g: 62 / 255, b: 51 / 255, a: 1 }function solid(color: SceneNode['fills'][number]['color']): SceneNode['fills'] {return [{ type: 'SOLID', visible: true, opacity: 1, color }]@@ -142,6 +143,173 @@ describe('color-contrast', () => {expect(messages.map((message) => message.nodeId)).toEqual([mixed.id])expect(messages[0]?.data?.minRatio).toBe(4.5)})++ test('does not use an ancestor fill when a filled sibling overlaps the text', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, { name: 'Card', fills: solid(WHITE) })+ graph.createNode('VECTOR', card.id, {+ name: 'Background',+ width: 240,+ height: 120,+ fills: solid(DARK_GREEN)+ })+ graph.createNode('TEXT', card.id, {+ name: 'Label',+ text: 'Hello',+ x: 24,+ y: 46,+ width: 120,+ height: 30,+ fills: solid(WHITE)+ })++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('uses the ancestor fill when rotated sibling bounds overlap but the shapes do not', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, {+ name: 'Card',+ width: 320,+ height: 320,+ fills: solid(WHITE)+ })+ graph.createNode('VECTOR', card.id, {+ name: 'Disjoint rotated background',+ x: 170,+ y: 170,+ width: 100,+ height: 100,+ rotation: -45,+ fills: solid(DARK_GREEN)+ })+ const label = graph.createNode('TEXT', card.id, {+ name: 'Label',+ text: 'Hello',+ x: 50,+ y: 50,+ width: 100,+ height: 100,+ rotation: 45,+ fills: solid(WHITE)+ })++ expect(lint(graph, 'color-contrast').map((message) => message.nodeId)).toEqual([label.id])+ })++ test('uses the ancestor fill when sibling fills do not affect the text background', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, {+ name: 'Card',+ width: 240,+ height: 120,+ fills: solid(WHITE)+ })+ graph.createNode('VECTOR', card.id, {+ name: 'Non-overlapping background',+ width: 10,+ height: 10,+ fills: solid(DARK_GREEN)+ })+ const label = graph.createNode('TEXT', card.id, {+ name: 'Label',+ text: 'Hello',+ x: 24,+ y: 46,+ width: 120,+ height: 30,+ fills: solid(WHITE)+ })++ graph.createNode('VECTOR', card.id, {+ name: 'Overlay',+ width: 240,+ height: 120,+ fills: solid(DARK_GREEN)+ })++ expect(lint(graph, 'color-contrast').map((message) => message.nodeId)).toEqual([label.id])+ })+})++describe('color-contrast over layers under the text', () => {+ const BLACK = { r: 0, g: 0, b: 0, a: 1 }++ /** A white card holding a dark background and, in a frame of its own, a label. */+ function card(background: Partial<SceneNode>, label: SceneNode['fills']) {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const card = graph.createNode('FRAME', pageId, {+ name: 'Card',+ width: 240,+ height: 120,+ fills: solid(WHITE)+ })+ graph.createNode('RECTANGLE', card.id, {+ name: 'Background',+ width: 240,+ height: 120,+ fills: solid(DARK_GREEN),+ ...background+ })+ const content = graph.createNode('FRAME', card.id, {+ name: 'Content',+ x: 24,+ y: 24,+ width: 192,+ height: 72+ })+ const text = graph.createNode('TEXT', content.id, {+ name: 'Label',+ text: 'Hello',+ width: 120,+ height: 30,+ fills: label+ })+ return { graph, text }+ }++ test('measures text against a layer under the frame that holds it', () => {+ expect(lint(card({}, solid(WHITE)).graph, 'color-contrast')).toEqual([])++ const { graph, text } = card({}, solid(BLACK))+ const messages = lint(graph, 'color-contrast')+ expect(messages.map((message) => message.nodeId)).toEqual([text.id])+ expect(messages[0]?.data?.background).toBe('#193E33')+ })++ test('skips text a layer under it covers only in part', () => {+ const { graph } = card({ width: 60 }, solid(WHITE))++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('composites a translucent layer under the text over the card', () => {+ const { graph, text } = card({ opacity: 0.1 }, solid(WHITE))+ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([text.id])+ expect(messages[0]?.data?.background).toBe('#E8ECEB')+ })++ test('applies a layer\'s opacity after compositing its fills', () => {+ // Black over white at half opacity is mid gray, not each fill at half strength.+ const fills = [...solid(WHITE), ...solid(BLACK)]+ const { graph, text } = card({ fills, opacity: 0.5 }, solid(WHITE))+ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([text.id])+ expect(messages[0]?.data?.background).toBe('#808080')+ })++ test('ignores a layer under the text that paints nothing', () => {+ const { graph, text } = card({ width: 60, fills: [] }, solid(WHITE))++ expect(lint(graph, 'color-contrast').map((message) => message.nodeId)).toEqual([text.id])+ })})describe('color-contrast over translucent fills', () => {diff --git a/tests/engine/lint/variable-binding-validation.test.ts b/tests/engine/lint/variable-binding-validation.test.tsindex 5666bfff0..56212d070 100644--- a/tests/engine/lint/variable-binding-validation.test.ts+++ b/tests/engine/lint/variable-binding-validation.test.ts@@ -77,6 +77,7 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {rotation: 0,visible: true,locked: false,+ opacity: 1,layoutMode: 'NONE',layoutPositioning: 'AUTO' as const,layoutGrow: 0,@@ -126,6 +127,7 @@ describe('no-hardcoded-colors lint checks indexed bindings', () => {rotation: 0,visible: true,locked: false,+ opacity: 1,layoutMode: 'NONE',layoutPositioning: 'AUTO' as const,layoutGrow: 0,