From 1975d8747ffda96d03b4b00e3f5411bb5e130464 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 17 Nov 2026 11:55:15 -0600 Subject: [PATCH] Support inline style declarations --- .changeset/dom-inline-styles.md | 5 + packages/ui/package.json | 4 +- packages/ui/src/dom.ts | 3 + packages/ui/src/index.ts | 9 + packages/ui/src/style.test.ts | 366 ++++++++++++++++++++++++++ packages/ui/src/style.ts | 451 ++++++++++++++++++++++++++++++++ packages/ui/wpt.config.ts | 52 ++++ pnpm-lock.yaml | 11 + 8 files changed, 900 insertions(+), 1 deletion(-) create mode 100644 .changeset/dom-inline-styles.md create mode 100644 packages/ui/src/style.test.ts create mode 100644 packages/ui/src/style.ts diff --git a/.changeset/dom-inline-styles.md b/.changeset/dom-inline-styles.md new file mode 100644 index 0000000..158a636 --- /dev/null +++ b/.changeset/dom-inline-styles.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': patch +--- + +Add inline style declarations with shared camelCase, dashed, and setProperty access, supported CSS value parsing, and change notifications. diff --git a/packages/ui/package.json b/packages/ui/package.json index dc2e2f0..e83f331 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -37,7 +37,9 @@ }, "dependencies": { "@bomb.sh/tty": "catalog:", - "css-select": "^7.0.0" + "css-select": "^7.0.0", + "@standard-schema/spec": "^1.1.0", + "hueful": "^0.8.1" }, "devEngines": { "packageManager": { diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 971806d..dfd0241 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -4,6 +4,7 @@ import { querySelector } from './css-select.ts'; import { asciiUppercase, asciiLowercase } from './ascii.ts'; import { NamedNodeMap } from './named-node-map.ts'; import { HTMLCollection } from './html-collection.ts'; +import { StyleDeclaration } from './style.ts'; import { validateElementName, validateElementNamespace, @@ -522,6 +523,7 @@ export interface EventListener { export class Element extends Node { declare readonly ownerDocument: Document; + readonly style: StyleDeclaration; readonly localName: string; readonly nodeName: string; readonly namespaceURI: string | null; @@ -536,6 +538,7 @@ export class Element extends Node { { namespaceURI = HTML_NS, prefix = null }: Partial = {}, ) { super(owner, notify); + this.style = new StyleDeclaration(this.notify); this.localName = localName; this.namespaceURI = namespaceURI; this.prefix = prefix; diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 25180f0..8196b76 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -10,3 +10,12 @@ export { HTMLTitleElement, HTMLUnknownElement, } from './dom.ts'; + +export type { + ColorValue, + BorderWidthValue, + FlexDirectionValue, + DisplayValue, + LengthValue, + BorderStyleValue, +} from './style.ts'; diff --git a/packages/ui/src/style.test.ts b/packages/ui/src/style.test.ts new file mode 100644 index 0000000..95f437c --- /dev/null +++ b/packages/ui/src/style.test.ts @@ -0,0 +1,366 @@ +// Independent tests for our terminal style subset; upstream coverage runs through WPT. +import { describe, expect, expectTypeOf, it } from 'vitest'; +import { createHTMLDocument, Document } from './dom.ts'; +import { StyleDeclaration, type ColorValue } from './style.ts'; + +describe('inline style declarations', () => { + // These checks cover the shared declaration and terminal notification behavior. + it('shares declarations between camelCase, dashed aliases, and setProperty', () => { + const style = new StyleDeclaration(); + const properties = [ + ['flexDirection', 'flex-direction', 'row', 'column'], + ['paddingTop', 'padding-top', '1px', '2px'], + ['paddingRight', 'padding-right', '1px', '2px'], + ['paddingBottom', 'padding-bottom', '1px', '2px'], + ['paddingLeft', 'padding-left', '1px', '2px'], + ['borderTopWidth', 'border-top-width', '0px', '1px'], + ['borderRightWidth', 'border-right-width', '0px', '1px'], + ['borderBottomWidth', 'border-bottom-width', '0px', '1px'], + ['borderLeftWidth', 'border-left-width', '0px', '1px'], + ['borderStyle', 'border-style', 'none', 'solid'], + ['borderColor', 'border-color', 'red', 'blue'], + ] as const; + for (const [camel, dashed, first, second] of properties) { + Reflect.set(style, camel, first); + expect(style[dashed], dashed).toBe(first); + Reflect.set(style, dashed, second); + expect(style[camel], camel).toBe(second); + expect(style.getPropertyValue(dashed), dashed).toBe(second); + style.setProperty(dashed, first); + expect(style[camel], camel).toBe(first); + expect(style[dashed], dashed).toBe(first); + style.setProperty(dashed, ''); + expect(style[camel], camel).toBe(''); + } + }); + + it('commits values and priorities together before notifying the terminal', () => { + const changes: [string, string][] = []; + const style = new StyleDeclaration(() => { + changes.push([style.paddingTop, style.getPropertyPriority('padding-top')]); + }); + style.setProperty('PADDING-TOP', '2px', 'IMPORTANT'); + expect(changes).toEqual([['2px', 'important']]); + + style.setProperty('padding-top', '-1px'); + style.setProperty('padding-top', ' \t\n'); + style.setProperty('padding-top', '3px', ' important '); + style.setProperty('paddingTop', '3px'); + style.setProperty(' padding-top ', '3px'); + expect(changes).toEqual([['2px', 'important']]); + expect(style.paddingTop).toBe('2px'); + expect(style.getPropertyPriority('padding-top')).toBe('important'); + + style['padding-top'] = '2px'; + expect(changes).toEqual([ + ['2px', 'important'], + ['2px', ''], + ]); + style.setProperty('padding-top', '1px', 'important'); + style.setProperty('padding-top', '', 'invalid'); + expect(changes.at(-1)).toEqual(['', '']); + }); + + it('converts setProperty arguments and clears declarations assigned null', () => { + const style = new StyleDeclaration(); + style.color = 'white'; + Reflect.apply(style.setProperty, style, ['color', undefined]); + expect(style.color).toBe('white'); + style.setProperty('color', 'red', undefined); + expect(style.color).toBe('red'); + expect(style.getPropertyPriority('color')).toBe(''); + style.setProperty('color', 'blue', null); + expect(style.color).toBe('blue'); + style.setProperty('color', null); + expect(style.color).toBe(''); + style.color = 'red'; + Reflect.set(style, 'color', null); + expect(style.color).toBe(''); + Reflect.apply(style.setProperty, style, ['padding-left', { toString: () => '2px' }]); + expect(style.paddingLeft).toBe('2px'); + expect(() => Reflect.apply(style.setProperty, style, ['padding-left'])).toThrow(TypeError); + expect(() => Reflect.apply(style.setProperty, style, ['unknown', Symbol()])).toThrow(TypeError); + }); + + it('keeps a stable style object for each element', () => { + const document = new Document(() => {}); + const first = document.createElement('div'); + const second = document.createElement('span'); + const style = first.style; + + expect(style).toBeDefined(); + expect(first.style).toBe(style); + expect(second.style).not.toBe(style); + + style.color = 'green'; + + expect(first.style).toBe(style); + expect(second.style.color).toBe(''); + }); + + it('reads undeclared properties as empty strings, including element defaults', () => { + const document = createHTMLDocument(() => {}); + const documentElement = document.documentElement!; + + expect(documentElement.style.display, `${documentElement.tagName}.style.display`).toBe(''); + expect( + documentElement.style.flexDirection, + `${documentElement.tagName}.style.flexDirection`, + ).toBe(''); + expect(documentElement.style.gap, `${documentElement.tagName}.style.gap`).toBe(''); + expect(documentElement.style.paddingTop, `${documentElement.tagName}.style.paddingTop`).toBe( + '', + ); + expect( + documentElement.style.paddingRight, + `${documentElement.tagName}.style.paddingRight`, + ).toBe(''); + expect( + documentElement.style.paddingBottom, + `${documentElement.tagName}.style.paddingBottom`, + ).toBe(''); + expect(documentElement.style.paddingLeft, `${documentElement.tagName}.style.paddingLeft`).toBe( + '', + ); + expect(documentElement.style.borderStyle, `${documentElement.tagName}.style.borderStyle`).toBe( + '', + ); + expect( + documentElement.style.borderTopWidth, + `${documentElement.tagName}.style.borderTopWidth`, + ).toBe(''); + expect( + documentElement.style.borderRightWidth, + `${documentElement.tagName}.style.borderRightWidth`, + ).toBe(''); + expect( + documentElement.style.borderBottomWidth, + `${documentElement.tagName}.style.borderBottomWidth`, + ).toBe(''); + expect( + documentElement.style.borderLeftWidth, + `${documentElement.tagName}.style.borderLeftWidth`, + ).toBe(''); + expect(documentElement.style.borderColor, `${documentElement.tagName}.style.borderColor`).toBe( + '', + ); + expect(documentElement.style.color, `${documentElement.tagName}.style.color`).toBe(''); + + const div = document.createElement('div'); + + expect(div.style.display, `${div.tagName}.style.display`).toBe(''); + expect(div.style.flexDirection, `${div.tagName}.style.flexDirection`).toBe(''); + expect(div.style.gap, `${div.tagName}.style.gap`).toBe(''); + expect(div.style.paddingTop, `${div.tagName}.style.paddingTop`).toBe(''); + expect(div.style.paddingRight, `${div.tagName}.style.paddingRight`).toBe(''); + expect(div.style.paddingBottom, `${div.tagName}.style.paddingBottom`).toBe(''); + expect(div.style.paddingLeft, `${div.tagName}.style.paddingLeft`).toBe(''); + expect(div.style.borderStyle, `${div.tagName}.style.borderStyle`).toBe(''); + expect(div.style.borderTopWidth, `${div.tagName}.style.borderTopWidth`).toBe(''); + expect(div.style.borderRightWidth, `${div.tagName}.style.borderRightWidth`).toBe(''); + expect(div.style.borderBottomWidth, `${div.tagName}.style.borderBottomWidth`).toBe(''); + expect(div.style.borderLeftWidth, `${div.tagName}.style.borderLeftWidth`).toBe(''); + expect(div.style.borderColor, `${div.tagName}.style.borderColor`).toBe(''); + expect(div.style.color, `${div.tagName}.style.color`).toBe(''); + + const span = document.createElement('span'); + + expect(span.style.display, `${span.tagName}.style.display`).toBe(''); + expect(span.style.flexDirection, `${span.tagName}.style.flexDirection`).toBe(''); + expect(span.style.gap, `${span.tagName}.style.gap`).toBe(''); + expect(span.style.paddingTop, `${span.tagName}.style.paddingTop`).toBe(''); + expect(span.style.paddingRight, `${span.tagName}.style.paddingRight`).toBe(''); + expect(span.style.paddingBottom, `${span.tagName}.style.paddingBottom`).toBe(''); + expect(span.style.paddingLeft, `${span.tagName}.style.paddingLeft`).toBe(''); + expect(span.style.borderStyle, `${span.tagName}.style.borderStyle`).toBe(''); + expect(span.style.borderTopWidth, `${span.tagName}.style.borderTopWidth`).toBe(''); + expect(span.style.borderRightWidth, `${span.tagName}.style.borderRightWidth`).toBe(''); + expect(span.style.borderBottomWidth, `${span.tagName}.style.borderBottomWidth`).toBe(''); + expect(span.style.borderLeftWidth, `${span.tagName}.style.borderLeftWidth`).toBe(''); + expect(span.style.borderColor, `${span.tagName}.style.borderColor`).toBe(''); + expect(span.style.color, `${span.tagName}.style.color`).toBe(''); + }); + + it('accepts direct display and flexDirection assignments', () => { + const style = new Document(() => {}).createElement('div').style; + + style.display = 'inline'; + style.flexDirection = 'column'; + expect(style.display).toBe('inline'); + expect(style.flexDirection).toBe('column'); + + style.display = 'flex'; + style.flexDirection = 'row'; + expect(style.display).toBe('flex'); + expect(style.flexDirection).toBe('row'); + }); + + it('ignores unsupported display and flexDirection values', () => { + const style = new Document(() => {}).createElement('div').style; + style.display = 'inline'; + style.flexDirection = 'column'; + + Reflect.set(style, 'display', 'grid'); + Reflect.set(style, 'flexDirection', 'row-reverse'); + + expect(style.display).toBe('inline'); + expect(style.flexDirection).toBe('column'); + }); + + it('accepts nonnegative whole-cell px lengths for gap and each padding side', () => { + const style = new Document(() => {}).createElement('div').style; + style.gap = '0px'; + style.paddingTop = '1px'; + style.paddingRight = '2px'; + style.paddingBottom = '3px'; + style.paddingLeft = '4px'; + + expect(style.gap).toBe('0px'); + expect(style.paddingTop).toBe('1px'); + expect(style.paddingRight).toBe('2px'); + expect(style.paddingBottom).toBe('3px'); + expect(style.paddingLeft).toBe('4px'); + }); + + it('types gap and padding as px strings or empty declarations', () => { + const style = new Document(() => {}).createElement('div').style; + + expectTypeOf(style.gap).toEqualTypeOf<`${number}px` | ''>(); + expectTypeOf(style.paddingTop).toEqualTypeOf<`${number}px` | ''>(); + expectTypeOf(style.paddingRight).toEqualTypeOf<`${number}px` | ''>(); + expectTypeOf(style.paddingBottom).toEqualTypeOf<`${number}px` | ''>(); + expectTypeOf(style.paddingLeft).toEqualTypeOf<`${number}px` | ''>(); + }); + + it('preserves previous lengths after invalid assignments', () => { + const style = new Document(() => {}).createElement('div').style; + + for (const property of [ + 'gap', + 'paddingTop', + 'paddingRight', + 'paddingBottom', + 'paddingLeft', + ] as const) { + style[property] = '2px'; + + for (const value of ['-1px', '1.5px', '1ch', '2', 'auto', 'NaNpx', 2]) { + Reflect.set(style, property, value); + expect(style[property], `${property} after ${String(value)}`).toBe('2px'); + } + } + }); + + it('accepts zero or one cell for each border width and preserves other sides', () => { + const style = new Document(() => {}).createElement('div').style; + style.borderTopWidth = '0px'; + style.borderRightWidth = '1px'; + style.borderBottomWidth = '0px'; + style.borderLeftWidth = '1px'; + + expect(style.borderTopWidth).toBe('0px'); + expect(style.borderRightWidth).toBe('1px'); + expect(style.borderBottomWidth).toBe('0px'); + expect(style.borderLeftWidth).toBe('1px'); + }); + + it('preserves previous border widths after unsupported assignments', () => { + const style = new Document(() => {}).createElement('div').style; + + for (const property of [ + 'borderTopWidth', + 'borderRightWidth', + 'borderBottomWidth', + 'borderLeftWidth', + ] as const) { + style[property] = '1px'; + + for (const value of ['2px', '-1px', '0.5px', '1ch', 'thick', 1]) { + Reflect.set(style, property, value); + expect(style[property], `${property} after ${String(value)}`).toBe('1px'); + } + } + }); + + it('supports solid and none without erasing border width or color declarations', () => { + const style = new Document(() => {}).createElement('div').style; + style.borderTopWidth = '1px'; + style.borderColor = 'blue'; + const color = style.borderColor; + style.borderStyle = 'solid'; + expect(style.borderStyle).toBe('solid'); + + style.borderStyle = 'none'; + expect(style.borderStyle).toBe('none'); + expect(style.borderTopWidth).toBe('1px'); + expect(style.borderColor).toBe(color); + + Reflect.set(style, 'borderStyle', 'dashed'); + expect(style.borderStyle).toBe('none'); + }); + + it.each(['rgb(0 205 0)', 'rgba(0, 205, 0, 0.5)', '#00cd00', 'green', 'hsl(120 100% 40%)'])( + 'accepts %s for text and border colors', + (value) => { + const style = new Document(() => {}).createElement('span').style; + const color = value as ColorValue; + style.color = color; + style.borderColor = color; + + // Valid declarations may serialize into a normalized CSS color string. + expect(style.color).toEqual(expect.any(String)); + expect(style.color).not.toBe(''); + expect(style.borderColor).toEqual(expect.any(String)); + expect(style.borderColor).not.toBe(''); + }, + ); + + it('accepts currentColor as an explicit border color declaration', () => { + const style = new Document(() => {}).createElement('div').style; + style.borderColor = 'currentColor'; + + expect(style.borderColor.toLowerCase()).toBe('currentcolor'); + expect(style.color).toBe(''); + }); + + it('preserves previous color declarations after invalid assignments', () => { + const style = new Document(() => {}).createElement('span').style; + style.color = 'green'; + style.borderColor = 'blue'; + + for (const property of ['color', 'borderColor'] as const) { + const previous = style[property]; + + for (const value of ['not-a-color', '#xyz', 'rgb(0 205)', 42]) { + Reflect.set(style, property, value); + expect(style[property], `${property} after ${String(value)}`).toBe(previous); + } + } + }); + + it('removes inline declarations when assigned an empty string', () => { + const style = new Document(() => {}).createElement('div').style; + style.display = 'inline'; + style.flexDirection = 'column'; + style.gap = '1px'; + style.paddingLeft = '2px'; + style.borderStyle = 'solid'; + style.borderLeftWidth = '1px'; + style.borderColor = 'blue'; + style.color = 'green'; + + for (const property of [ + 'display', + 'flexDirection', + 'gap', + 'paddingLeft', + 'borderStyle', + 'borderLeftWidth', + 'borderColor', + 'color', + ] as const) { + style[property] = ''; + expect(style[property], property).toBe(''); + } + }); +}); diff --git a/packages/ui/src/style.ts b/packages/ui/src/style.ts new file mode 100644 index 0000000..f99a4da --- /dev/null +++ b/packages/ui/src/style.ts @@ -0,0 +1,451 @@ +/* oxlint-disable bombshell-dev/max-params -- Style setters take a property, value, and priority. */ +/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ +import { parse, type names, type ParseResult } from 'hueful'; +import type { StandardSchemaV1 } from '@standard-schema/spec'; +import { asciiLowercase } from './ascii.ts'; + +/** Approximate CSS color syntax; Hueful validates the contents at runtime. */ +export type ColorValue = + | keyof typeof names + | 'transparent' + | 'currentColor' + | `#${string}` + | `${'rgb' | 'rgba' | 'hsl' | 'hsla' | 'hwb' | 'lab' | 'lch' | 'oklab' | 'oklch' | 'device-cmyk'}(${string})`; + +export type DisplayValue = 'inline' | 'flex'; + +export type FlexDirectionValue = 'row' | 'column'; + +export type LengthValue = `${number}px`; +export type BorderWidthValue = '0px' | '1px'; +export type BorderStyleValue = 'solid' | 'none'; + +export interface StyleValues { + color: StyleValue; + display: StyleValue; + flexDirection: StyleValue; + gap: StyleValue; + paddingTop: StyleValue; + paddingRight: StyleValue; + paddingBottom: StyleValue; + paddingLeft: StyleValue; + borderStyle: StyleValue; + borderTopWidth: StyleValue; + borderRightWidth: StyleValue; + borderBottomWidth: StyleValue; + borderLeftWidth: StyleValue; + borderColor: StyleValue; +} + +export interface StyleValue { + value: T; + representation: R; +} + +export class StyleDeclaration { + #values: Partial; + #important = new Set(); + #changed: () => void; + constructor(changed: () => void = () => {}) { + this.#values = {}; + this.#changed = changed; + } + + get values(): Readonly> { + return { ...this.#values }; + } + + getPropertyValue(property: string): string { + if (arguments.length === 0) { + throw new TypeError('getPropertyValue requires a property name'); + } + const key = styleProperty(`${property}`); + return key === undefined ? '' : this.#getProperty(key); + } + + getPropertyPriority(property: string): string { + if (arguments.length === 0) { + throw new TypeError('getPropertyPriority requires a property name'); + } + const key = styleProperty(`${property}`); + return key !== undefined && this.#important.has(key) ? 'important' : ''; + } + + setProperty(property: string, value: string | null, priority: string | null = ''): void { + if (arguments.length < 2) { + throw new TypeError('setProperty requires a property name and value'); + } + const name = `${property}`; + const normalValue = value === null ? '' : `${value}`; + const normalPriority = priority === null ? '' : asciiLowercase(`${priority}`); + const key = styleProperty(name); + if (key === undefined) { + return; + } + if (normalValue !== '' && normalPriority !== '' && normalPriority !== 'important') { + return; + } + this.#setProperty(key, normalValue, normalPriority === 'important'); + } + + set color(value: ColorValue | '') { + this.#setProperty('color', value); + } + + get color(): ColorValue | '' { + return this.#getProperty('color'); + } + + set display(value: DisplayValue | '') { + this.#setProperty('display', value); + } + + get display(): DisplayValue | '' { + return this.#getProperty('display'); + } + + set flexDirection(value: FlexDirectionValue | '') { + this.#setProperty('flexDirection', value); + } + + get flexDirection(): FlexDirectionValue | '' { + return this.#getProperty('flexDirection'); + } + + set 'flex-direction'(value: FlexDirectionValue | '') { + this.flexDirection = value; + } + + get 'flex-direction'(): FlexDirectionValue | '' { + return this.flexDirection; + } + + set gap(value: LengthValue | '') { + this.#setProperty('gap', value); + } + + get gap(): LengthValue | '' { + return this.#getProperty('gap'); + } + + set paddingTop(value: LengthValue | '') { + this.#setProperty('paddingTop', value); + } + + get paddingTop(): LengthValue | '' { + return this.#getProperty('paddingTop'); + } + + set 'padding-top'(value: LengthValue | '') { + this.paddingTop = value; + } + + get 'padding-top'(): LengthValue | '' { + return this.paddingTop; + } + + set paddingRight(value: LengthValue | '') { + this.#setProperty('paddingRight', value); + } + + get paddingRight(): LengthValue | '' { + return this.#getProperty('paddingRight'); + } + + set 'padding-right'(value: LengthValue | '') { + this.paddingRight = value; + } + + get 'padding-right'(): LengthValue | '' { + return this.paddingRight; + } + + set paddingBottom(value: LengthValue | '') { + this.#setProperty('paddingBottom', value); + } + + get paddingBottom(): LengthValue | '' { + return this.#getProperty('paddingBottom'); + } + + set 'padding-bottom'(value: LengthValue | '') { + this.paddingBottom = value; + } + + get 'padding-bottom'(): LengthValue | '' { + return this.paddingBottom; + } + + set paddingLeft(value: LengthValue | '') { + this.#setProperty('paddingLeft', value); + } + + get paddingLeft(): LengthValue | '' { + return this.#getProperty('paddingLeft'); + } + + set 'padding-left'(value: LengthValue | '') { + this.paddingLeft = value; + } + + get 'padding-left'(): LengthValue | '' { + return this.paddingLeft; + } + + set borderTopWidth(value: BorderWidthValue | '') { + this.#setProperty('borderTopWidth', value); + } + + get borderTopWidth(): BorderWidthValue | '' { + return this.#getProperty('borderTopWidth'); + } + + set 'border-top-width'(value: BorderWidthValue | '') { + this.borderTopWidth = value; + } + + get 'border-top-width'(): BorderWidthValue | '' { + return this.borderTopWidth; + } + + set borderRightWidth(value: BorderWidthValue | '') { + this.#setProperty('borderRightWidth', value); + } + + get borderRightWidth(): BorderWidthValue | '' { + return this.#getProperty('borderRightWidth'); + } + + set 'border-right-width'(value: BorderWidthValue | '') { + this.borderRightWidth = value; + } + + get 'border-right-width'(): BorderWidthValue | '' { + return this.borderRightWidth; + } + + set borderBottomWidth(value: BorderWidthValue | '') { + this.#setProperty('borderBottomWidth', value); + } + + get borderBottomWidth(): BorderWidthValue | '' { + return this.#getProperty('borderBottomWidth'); + } + + set 'border-bottom-width'(value: BorderWidthValue | '') { + this.borderBottomWidth = value; + } + + get 'border-bottom-width'(): BorderWidthValue | '' { + return this.borderBottomWidth; + } + + set borderLeftWidth(value: BorderWidthValue | '') { + this.#setProperty('borderLeftWidth', value); + } + + get borderLeftWidth(): BorderWidthValue | '' { + return this.#getProperty('borderLeftWidth'); + } + + set 'border-left-width'(value: BorderWidthValue | '') { + this.borderLeftWidth = value; + } + + get 'border-left-width'(): BorderWidthValue | '' { + return this.borderLeftWidth; + } + + set borderStyle(value: BorderStyleValue | '') { + this.#setProperty('borderStyle', value); + } + + get borderStyle(): BorderStyleValue | '' { + return this.#getProperty('borderStyle'); + } + + set 'border-style'(value: BorderStyleValue | '') { + this.borderStyle = value; + } + + get 'border-style'(): BorderStyleValue | '' { + return this.borderStyle; + } + + set borderColor(value: ColorValue | '') { + this.#setProperty('borderColor', value); + } + + get borderColor(): ColorValue | '' { + return this.#getProperty('borderColor'); + } + + set 'border-color'(value: ColorValue | '') { + this.borderColor = value; + } + + get 'border-color'(): ColorValue | '' { + return this.borderColor; + } + + #setProperty(key: K, input: unknown, important = false): void { + const value = input === null ? '' : `${input}`; + if (value === '') { + if (this.#values[key] !== undefined) { + delete this.#values[key]; + this.#important.delete(key); + this.#changed(); + } + return; + } + const representation = value.trim() as StyleValues[K]['representation']; + const result = propertySchemas[key]['~standard'].validate( + representation, + ) as StandardSchemaV1.Result; + + // ignore styles that can't be validated and converted; + if (result.issues) { + return; //todo: issue warning. + } + + this.#values[key] = { value: result.value, representation } as StyleValues[K]; + if (important) { + this.#important.add(key); + } else { + this.#important.delete(key); + } + this.#changed(); + } + + #getProperty(property: K): StyleValues[K]['representation'] | '' { + return this.#values[property]?.representation ?? ''; + } +} + +const propertyNames = { + color: 'color', + display: 'display', + 'flex-direction': 'flexDirection', + gap: 'gap', + 'padding-top': 'paddingTop', + 'padding-right': 'paddingRight', + 'padding-bottom': 'paddingBottom', + 'padding-left': 'paddingLeft', + 'border-style': 'borderStyle', + 'border-top-width': 'borderTopWidth', + 'border-right-width': 'borderRightWidth', + 'border-bottom-width': 'borderBottomWidth', + 'border-left-width': 'borderLeftWidth', + 'border-color': 'borderColor', +} as const satisfies Record; + +function styleProperty(property: string): keyof StyleValues | undefined { + const name = asciiLowercase(property); + return Object.hasOwn(propertyNames, name) + ? propertyNames[name as keyof typeof propertyNames] + : undefined; +} + +function parseLength(representation: LengthValue): number | null { + const value = Number(representation.slice(0, -2)); + return /^\d+px$/.test(representation) && Number.isSafeInteger(value) ? value : null; +} + +function parseBorderWidth(representation: BorderWidthValue): number | null { + const value = parseLength(representation); + return value !== null && value <= 1 ? value : null; +} + +const schema = { + enum(...values: T[]) { + return { + '~standard': { + version: 1, + vendor: '@clack/ui', + validate(input: unknown): StandardSchemaV1.Result { + const value = values.find((candidate) => candidate === input); + return value === undefined + ? { issues: [{ message: `Expected one of: ${values.join(', ')}` }] } + : { value }; + }, + }, + } satisfies StandardSchemaV1; + }, + length: { + '~standard': { + version: 1, + vendor: '@clack/ui', + validate(input: unknown): StandardSchemaV1.Result { + const value = typeof input === 'string' ? parseLength(input as LengthValue) : null; + return value === null + ? { issues: [{ message: 'Expected a nonnegative whole-cell px length' }] } + : { value }; + }, + }, + } satisfies StandardSchemaV1, + borderWidth: { + '~standard': { + version: 1, + vendor: '@clack/ui', + validate(input: unknown): StandardSchemaV1.Result { + const value = + typeof input === 'string' ? parseBorderWidth(input as BorderWidthValue) : null; + return value === null + ? { issues: [{ message: 'Expected a border width of 0px or 1px' }] } + : { value }; + }, + }, + } satisfies StandardSchemaV1, + borderColor: { + '~standard': { + version: 1, + vendor: '@clack/ui', + validate(input: unknown): StandardSchemaV1.Result { + if (input === 'currentColor') { + return { value: input }; + } + return schema.color['~standard'].validate(input); + }, + }, + } satisfies StandardSchemaV1, + + color: { + '~standard': { + version: 1, + vendor: '@clack/ui', + validate(input: unknown): StandardSchemaV1.Result { + if (typeof input !== 'string') { + return { issues: [{ message: 'Expected a CSS color string' }] }; + } + const representation = input.trim(); + if (representation === 'currentColor') { + return { value: representation }; + } + const value = parse(representation); + return value === null ? { issues: [{ message: 'Invalid CSS color' }] } : { value }; + }, + }, + } satisfies StandardSchemaV1, +}; + +const propertySchemas = { + color: schema.color, + display: schema.enum('inline', 'flex'), + flexDirection: schema.enum('row', 'column'), + gap: schema.length, + paddingTop: schema.length, + paddingRight: schema.length, + paddingBottom: schema.length, + paddingLeft: schema.length, + borderStyle: schema.enum('solid', 'none'), + borderTopWidth: schema.borderWidth, + borderRightWidth: schema.borderWidth, + borderBottomWidth: schema.borderWidth, + borderLeftWidth: schema.borderWidth, + borderColor: schema.borderColor, +} satisfies { + [K in keyof StyleValues]: StandardSchemaV1< + StyleValues[K]['representation'], + StyleValues[K]['value'] + >; +}; diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index edff091..3ba7e94 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -22,6 +22,7 @@ import { } from './src/dom.ts'; import { NamedNodeMap } from './src/named-node-map.ts'; import { HTMLCollection } from './src/html-collection.ts'; +import { StyleDeclaration } from './src/style.ts'; const config: WPTConfig = { createDocument: () => createHTMLDocument(() => {}), @@ -30,6 +31,7 @@ const config: WPTConfig = { Attr, CharacterData, Comment, + CSSStyleDeclaration: StyleDeclaration, CustomEvent: globalThis.CustomEvent, Document, DocumentFragment, @@ -53,6 +55,56 @@ const config: WPTConfig = { XMLDocument, }, include: { + 'css/css-align/parsing/gap-invalid.html': true, + 'css/css-backgrounds/parsing/border-color-invalid.html': true, + 'css/css-backgrounds/parsing/border-style-invalid.html': true, + 'css/css-backgrounds/parsing/border-style-valid.html': [ + 'e.style[\'border-style\'] = "none" should set the property value', + // Per-side styles and multi-value shorthands are not supported yet. + ], + 'css/css-backgrounds/parsing/border-width-valid.html': [ + 'e.style[\'border-top-width\'] = "0px" should set the property value', + // Other cases require border-width shorthand or keyword widths. + ], + 'css/css-box/parsing/padding-invalid.html': [ + 'e.style[\'padding-top\'] = "auto" should not set the property value', + 'e.style[\'padding-bottom\'] = "10px 20px calc(2em + 3ex) auto" should not set the property value', + 'e.style[\'padding-top\'] = "-10px" should not set the property value', + 'e.style[\'padding-right\'] = "-20%" should not set the property value', + // Remaining cases target padding shorthand or an unknown property. + ], + 'css/css-box/parsing/padding-valid.html': [ + 'e.style[\'padding-top\'] = "10px" should set the property value', + 'e.style[\'padding-right\'] = "20px" should set the property value', + 'e.style[\'padding-bottom\'] = "30px" should set the property value', + 'e.style[\'padding-left\'] = "40px" should set the property value', + // Shorthands, percentages, and calc() remain unsupported. + ], + 'css/css-color/parsing/color-invalid-hex-color.html': true, + 'css/css-color/parsing/color-invalid-hwb.html': true, + 'css/css-color/parsing/color-invalid-lab.html': true, + 'css/css-color/parsing/color-valid.html': [ + 'e.style[\'color\'] = "transparent" should set the property value', + 'e.style[\'color\'] = "red" should set the property value', + 'e.style[\'color\'] = "magenta" should set the property value', + 'e.style[\'color\'] = "rgb(2, 3, 4)" should set the property value', + 'e.style[\'color\'] = "rgba(2, 3, 4, 0.5)" should set the property value', + // Other cases need canonical serialization, currentcolor, or light-dark(). + ], + 'css/css-display/parsing/display-invalid.html': true, + 'css/css-display/parsing/display-valid.html': [ + 'e.style[\'display\'] = "inline" should set the property value', + 'e.style[\'display\'] = "flex" should set the property value', + // Other cases need additional display modes or multi-keyword parsing. + ], + 'css/css-flexbox/parsing/flex-direction-valid.html': [ + 'e.style[\'flex-direction\'] = "row" should set the property value', + 'e.style[\'flex-direction\'] = "column" should set the property value', + // Reverse directions require terminal layout support. + ], + 'css/css-flexbox/parsing/flex-direction-invalid.html': true, + 'css/cssom/cssstyledeclaration-properties.html': true, + 'css/cssom/cssstyledeclaration-setter-attr.html': true, 'dom/events/Event-constructors.any.js': true, 'dom/events/EventTarget-addEventListener.any.js': true, 'dom/events/EventTarget-add-remove-listener.any.js': true, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59a7d1e..c513c7f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,9 +44,15 @@ importers: '@bomb.sh/tty': specifier: 'catalog:' version: 0.10.0 + '@standard-schema/spec': + specifier: ^1.1.0 + version: 1.1.0 css-select: specifier: ^7.0.0 version: 7.0.0 + hueful: + specifier: ^0.8.1 + version: 0.8.1 devDependencies: '@bomb.sh/web-platform-tests': specifier: workspace:* @@ -1477,6 +1483,9 @@ packages: resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} engines: {node: '>= 6'} + hueful@0.8.1: + resolution: {integrity: sha512-5JmU/74TAKM9BCRcwY046VImUb6dhvrsB2kvj5eEJ1eaCKu6EPPxtONF/kueY9PdzYgUz3g5zrrj+YENz2xy3A==} + human-id@4.2.2: resolution: {integrity: sha512-Z+8unD6em/MJwyrkWQ2M3wygRGI1+MztbutiNwk1DCuEPXOZRWGjtcMPZYP1exY9iNZMhd7ZOSMQSo9WYtiQRw==} hasBin: true @@ -3050,6 +3059,8 @@ snapshots: transitivePeerDependencies: - supports-color + hueful@0.8.1: {} + human-id@4.2.2: {} import-meta-resolve@4.2.0: {}