AI-native design editor. Open-source Figma alternative.
fix(lint): composite translucent fills in color-contrast (#1400)
Roman Purtov38b6a04b7b7e
diff --git a/changes/1400/fixed.md b/changes/1400/fixed.mdnew file mode 100644index 000000000..1ef85760a--- /dev/null+++ b/changes/1400/fixed.md@@ -0,0 +1 @@+- The color contrast lint rule measures text against what it sits on: every visible solid fill of the ancestors and of the text, composited in paint order. It skips fully transparent text, text with no opaque background, and text where a gradient or image shows in its fills or its background.diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.tsindex a0a946f45..7a78389cc 100644--- a/packages/core/src/lint/rules/color-contrast.ts+++ b/packages/core/src/lint/rules/color-contrast.ts@@ -1,6 +1,8 @@-import { colorToHex, contrastRatio } from '@open-pencil/scene-graph/color'+import { colorToHex, compositeOver, contrastRatio } from '@open-pencil/scene-graph/color'+import type { Color } from '@open-pencil/scene-graph/primitives'import { defineRule } from '#core/lint/rule'+import type { LintNode, RuleContext } from '#core/lint/types'/** WCAG AA: 4.5:1 for text, 3:1 for large text, which is 24px, or 18.66px when bold. */const MIN_CONTRAST = 4.5@@ -25,6 +27,45 @@ function requiredContrast(node: {return Math.max(...styles.map(minContrast))}+type SolidPaint = LintNode['fills'][number] & {+ color: NonNullable<LintNode['fills'][number]['color']>+}++function isSolidPaint(fill: LintNode['fills'][number]): fill is SolidPaint {+ return fill.type === 'SOLID' && fill.visible && fill.color != null+}++function opaque(color: Pick<Color, 'r' | 'g' | 'b'>): Color {+ return { ...color, a: 1 }+}++/**+ * 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.+ */+function backdrop(node: LintNode, context: RuleContext): Color | undefined {+ const layers: SolidPaint[] = []+ for (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)+ }+ }+ return undefined+}+export default defineRule({meta: {id: 'color-contrast',@@ -34,29 +75,33 @@ export default defineRule({},match: ['TEXT'],check(node, context) {- const textColor = node.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.color- if (textColor == null) return- let parent = context.getParent(node)- while (parent) {- const bg = parent.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.color- if (bg) {- const ratio = contrastRatio(textColor, bg)- const minRatio = requiredContrast(node)- if (ratio < minRatio)- context.report({- node,- message: `Contrast ratio ${ratio.toFixed(2)}:1 is below WCAG AA`,- suggest: 'Increase contrast between text and background',- data: {- ratio: Math.floor(ratio * 100) / 100,- minRatio,- foreground: colorToHex({ ...textColor, a: 1 }),- background: colorToHex({ ...bg, a: 1 })- }- })- return- }- parent = context.getParent(parent)- }+ // Paints under the topmost opaque solid fill are covered by it.+ const base = node.fills.findLastIndex((paint) => isSolidPaint(paint) && paint.opacity >= 1)+ const visible = node.fills.slice(Math.max(base, 0))+ // Gradients and images are not composited yet, so a stack showing one has no single color.+ if (visible.some((paint) => paint.visible && paint.type !== 'SOLID' && paint.opacity > 0))+ return+ const text = visible.filter(isSolidPaint)+ if (!text.some((paint) => paint.opacity > 0)) return+ const bg = backdrop(node, context)+ if (!bg) return+ const fg = text.reduce(+ (color, paint) => compositeOver(opaque(paint.color), color, paint.opacity),+ bg+ )+ const ratio = contrastRatio(fg, bg)+ const minRatio = requiredContrast(node)+ if (ratio < minRatio)+ context.report({+ node,+ message: `Contrast ratio ${ratio.toFixed(2)}:1 is below WCAG AA`,+ suggest: 'Increase contrast between text and background',+ data: {+ ratio: Math.floor(ratio * 100) / 100,+ minRatio,+ foreground: colorToHex(fg),+ background: colorToHex(bg)+ }+ })}})diff --git a/packages/core/tests/lint/rules.test.ts b/packages/core/tests/lint/rules.test.tsindex edc8ba48e..1370f989f 100644--- a/packages/core/tests/lint/rules.test.ts+++ b/packages/core/tests/lint/rules.test.ts@@ -96,7 +96,13 @@ describe('color-contrast', () => {// 3.2:1 against white.const grey = { r: 0.55, g: 0.55, b: 0.55, a: 1 }const text = (name: string, fontSize: number, fontWeight: number) =>- graph.createNode('TEXT', card.id, { name, text: name, fontSize, fontWeight, fills: solid(grey) })+ graph.createNode('TEXT', card.id, {+ name,+ text: name,+ fontSize,+ fontWeight,+ fills: solid(grey)+ })const body = text('Body', 16, 400)const boldBody = text('Bold body', 18, 700)text('Display', 24, 400)@@ -138,6 +144,117 @@ describe('color-contrast', () => {})})+describe('color-contrast over translucent fills', () => {+ const DARK = { r: 0.1, g: 0.1, b: 0.1, a: 1 }+ const tint = (opacity: number): SceneNode['fills'] => [+ { type: 'SOLID', visible: true, opacity, color: WHITE }+ ]++ function textOn(layers: SceneNode['fills'][], text: SceneNode['fills']) {+ const graph = new SceneGraph()+ let parentId = graph.getPages()[0].id+ for (const fills of layers) parentId = graph.createNode('FRAME', parentId, { fills }).id+ const label = graph.createNode('TEXT', parentId, { name: 'Label', text: 'Hi', fills: text })+ return { graph, label }+ }++ test('composites a translucent card over the opaque fill below it', () => {+ // A 10% white tint over a dark page stays dark: white text on it reads well.+ const { graph } = textOn([solid(DARK), tint(0.1)], solid(WHITE))++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('reports against the composited background', () => {+ // A 90% white tint over a dark page is nearly white: white text on it does not read.+ const { graph, label } = textOn([solid(DARK), tint(0.9)], solid(WHITE))+ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([label.id])+ expect(messages[0]?.data?.background).not.toBe('#FFFFFF')+ })++ test('composites translucent text over its background', () => {+ const faint: SceneNode['fills'] = [+ { type: 'SOLID', visible: true, opacity: 0.2, color: { r: 0, g: 0, b: 0, a: 1 } }+ ]+ const { graph, label } = textOn([solid(WHITE)], faint)++ expect(lint(graph, 'color-contrast').map((message) => message.nodeId)).toEqual([label.id])+ })++ test('skips text whose only backdrop is translucent', () => {+ const { graph } = textOn([tint(0.1)], solid(WHITE))++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('composites a translucent fill over an opaque fill on the same frame', () => {+ // The frame paints white, then a 10% dark tint over it: dark gray text on it does not read.+ const frame: SceneNode['fills'] = [+ ...solid(WHITE),+ { type: 'SOLID', visible: true, opacity: 0.1, color: DARK }+ ]+ const gray = solid({ r: 0.75, g: 0.75, b: 0.75, a: 1 })+ const { graph, label } = textOn([solid(DARK), frame], gray)+ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([label.id])+ expect(messages[0]?.data?.background).toBe('#E8E8E8')+ })++ test('composites every text fill in paint order', () => {+ // Half-white over black paints mid gray; the other way round, black would cover the white.+ const text: SceneNode['fills'] = [+ ...solid({ r: 0, g: 0, b: 0, a: 1 }),+ { type: 'SOLID', visible: true, opacity: 0.5, color: WHITE }+ ]+ const { graph, label } = textOn([solid(DARK)], text)+ const messages = lint(graph, 'color-contrast')++ expect(messages.map((message) => message.nodeId)).toEqual([label.id])+ expect(messages[0]?.data?.foreground).toBe('#808080')+ })++ test('skips text with a gradient in its fills', () => {+ const text: SceneNode['fills'] = [+ { type: 'GRADIENT_LINEAR', visible: true, opacity: 1, color: WHITE },+ { type: 'SOLID', visible: true, opacity: 0.5, color: WHITE }+ ]+ const { graph } = textOn([solid(WHITE)], text)++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('measures text whose gradient is covered by an opaque fill', () => {+ const text: SceneNode['fills'] = [+ { type: 'GRADIENT_LINEAR', visible: true, opacity: 1, color: WHITE },+ ...solid(WHITE)+ ]+ const { graph, label } = textOn([solid(WHITE)], text)++ expect(lint(graph, 'color-contrast').map((message) => message.nodeId)).toEqual([label.id])+ })++ test('skips text under a gradient that covers the opaque fill', () => {+ // A light gradient covers the dark fill: dark text on it is not dark on dark.+ const frame: SceneNode['fills'] = [+ ...solid(DARK),+ { type: 'GRADIENT_LINEAR', visible: true, opacity: 1, color: WHITE }+ ]+ const { graph } = textOn([frame], solid({ r: 0.15, g: 0.15, b: 0.15, a: 1 }))++ expect(lint(graph, 'color-contrast')).toEqual([])+ })++ test('skips fully transparent text', () => {+ const hidden: SceneNode['fills'] = [{ type: 'SOLID', visible: true, opacity: 0, color: WHITE }]+ const { graph } = textOn([solid(WHITE)], hidden)++ expect(lint(graph, 'color-contrast')).toEqual([])+ })+})+describe('no-deeply-nested', () => {test('reports only the layer that crosses the depth limit', () => {const graph = new SceneGraph()