Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,19 @@ export interface EventListener {
(this: EventTarget, event: Event): void;
}

/** Mirrors the DOM spec's attribute change steps: https://dom.spec.whatwg.org/#concept-element-attributes-change-ext */
function attributeChanged(attr: Attr, value: string | null): void {
const element = attr.ownerElement;
if (element === null || attr.namespaceURI !== null) {
return;
}
switch (attr.localName) {
case 'style':
element.style.cssText = value ?? '';
break;
}
}

Comment on lines +478 to +489

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have them yet, but would this be a good case to use MutationObserver when we support them?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't think so, MutationObserver delivers records async, so right after setAttribute('style', ...) reading el.style.color would still give you the old value until the observer runs. the spec keeps them in sync inside the attribute change steps, and MO records get queued from that same algorithm. so once we add MO, this is where we'd queue the record, alongside the switch rather than replacing it

export class Element extends Node {
declare readonly ownerDocument: Document;

Expand Down Expand Up @@ -502,6 +515,7 @@ export class Element extends Node {
ownerElement: this,
createAttribute: (name, namespace) => new Attr(owner, name, notify, namespace),
notify,
attributeChanged,
});
}

Expand Down Expand Up @@ -657,6 +671,7 @@ export class Attr extends Node {
const normal = `${value}`;
if (this.#value !== normal) {
this.#value = normal;
attributeChanged(this, normal);
this.notify();
}
}
Expand Down
8 changes: 8 additions & 0 deletions packages/ui/src/named-node-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const HTML_NS = 'http://www.w3.org/1999/xhtml';

type AttributeNamespace = Pick<Attr, 'namespaceURI' | 'prefix'>;
type AttributeFactory = (localName: string, namespace: AttributeNamespace) => Attr;
/** Called with `null` when the attribute is removed. */
export type AttributeChanged = (attr: Attr, value: string | null) => void;

/**
* Holds Element attributes: https://dom.spec.whatwg.org/#interface-namednodemap
Expand All @@ -18,21 +20,25 @@ export class NamedNodeMap {
readonly #ownerElement: Element;
readonly #createAttribute: AttributeFactory;
readonly #notify: () => void;
readonly #attributeChanged: AttributeChanged;
readonly #attributes: Attr[] = [];
#properties: string[] = [];

constructor({
ownerElement,
createAttribute,
notify,
attributeChanged,
}: {
ownerElement: Element;
createAttribute: AttributeFactory;
notify: () => void;
attributeChanged: AttributeChanged;
}) {
this.#ownerElement = ownerElement;
this.#createAttribute = createAttribute;
this.#notify = notify;
this.#attributeChanged = attributeChanged;
}

get length(): number {
Expand Down Expand Up @@ -76,6 +82,7 @@ export class NamedNodeMap {
this.#attributes.push(attr);
}
attr.ownerElement = this.#ownerElement;
this.#attributeChanged(attr, attr.value);
this.#changed();
return previous;
}
Expand All @@ -98,6 +105,7 @@ export class NamedNodeMap {
throw new DOMException('Attribute is not attached to this element', 'NotFoundError');
}
this.#attributes.splice(index, 1);
this.#attributeChanged(attr, null);
attr.ownerElement = null;
this.#changed();
return attr;
Expand Down
118 changes: 117 additions & 1 deletion packages/ui/src/style.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// 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 { createHTMLDocument, Document, type Element } from './dom.ts';
import { StyleDeclaration, type ColorValue } from './style.ts';

describe('inline style declarations', () => {
Expand Down Expand Up @@ -364,3 +364,119 @@ describe('inline style declarations', () => {
}
});
});

describe('string styles', () => {
const createDiv = (): Element => new Document(() => {}).createElement('div');

it('reads back the declarations assigned to cssText', () => {
const style = createDiv().style;
style.cssText = 'color: red; padding-top: 2px; display: flex';

expect(style.color).toBe('red');
expect(style.paddingTop).toBe('2px');
expect(style.display).toBe('flex');
expect(style.cssText).toBe('color: red; padding-top: 2px; display: flex;');

style.cssText = 'gap:1px';
expect(style.color).toBe('');
expect(style.cssText).toBe('gap: 1px;');

style.cssText = '';
expect(style.cssText).toBe('');
expect(style.gap).toBe('');
});

it('round-trips !important declarations', () => {
const style = createDiv().style;
style.cssText = 'color: red ! IMPORTANT; gap: 1px';

expect(style.getPropertyPriority('color')).toBe('important');
expect(style.getPropertyPriority('gap')).toBe('');
expect(style.cssText).toBe('color: red !important; gap: 1px;');
});

it('serializes declarations set through properties in insertion order', () => {
const style = createDiv().style;
style.paddingLeft = '1px';
style.setProperty('border-color', 'blue', 'important');
style.flexDirection = 'column';

expect(style.cssText).toBe(
'padding-left: 1px; border-color: blue !important; flex-direction: column;',
);
});

it('ignores unknown properties, invalid values, and malformed declarations', () => {
const style = createDiv().style;
style.cssText =
'unknown: 1; color: not-a-color; padding-top: -1px; nonsense; : red; gap: 3px; ;';

expect(style.cssText).toBe('gap: 3px;');
});

it('notifies once per cssText assignment', () => {
let changes = 0;
const style = new StyleDeclaration(() => changes++);
style.cssText = 'color: red; gap: 1px; display: flex';
expect(changes).toBe(1);
});

it('applies the style attribute to the element style', () => {
const div = createDiv();
div.setAttribute('style', 'color: red; gap: 2px');
expect(div.style.color).toBe('red');
expect(div.style.gap).toBe('2px');

div.setAttribute('style', 'padding-top: 1px');
expect(div.style.color).toBe('');
expect(div.style.paddingTop).toBe('1px');
});

it('applies the style attribute when it is set on an attached Attr', () => {
const div = createDiv();
div.setAttribute('style', 'color: red');
div.getAttributeNode('style')!.value = 'color: blue';
expect(div.style.color).toBe('blue');

const attr = div.ownerDocument.createAttribute('style');
attr.value = 'gap: 4px';
div.setAttributeNode(attr);
expect(div.style.color).toBe('');
expect(div.style.gap).toBe('4px');
});

it('does not change the style of an element when a detached style Attr changes', () => {
const div = createDiv();
div.setAttribute('style', 'color: red');
const attr = div.removeAttributeNode(div.getAttributeNode('style')!);
attr.value = 'color: blue';
expect(div.style.color).toBe('');
});

it('clears the style when the style attribute is removed', () => {
const div = createDiv();
div.setAttribute('style', 'color: red');
div.removeAttribute('style');
expect(div.style.color).toBe('');

div.setAttribute('style', 'color: red');
expect(div.toggleAttribute('style')).toBe(false);
expect(div.style.color).toBe('');
});

it('clears the style when toggleAttribute adds an empty style attribute', () => {
const div = createDiv();
div.style.color = 'red';
expect(div.toggleAttribute('style')).toBe(true);
expect(div.style.color).toBe('');
});

it('ignores namespaced style attributes', () => {
const div = createDiv();
div.style.color = 'red';
div.setAttributeNS('http://example.com', 'style', 'color: blue');
expect(div.style.color).toBe('red');
div.removeAttributeNS('http://example.com', 'style');
expect(div.style.color).toBe('red');
});
});
62 changes: 55 additions & 7 deletions packages/ui/src/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ export class StyleDeclaration {
return key !== undefined && this.#important.has(key) ? 'important' : '';
}

get cssText(): string {
return Object.entries(this.#values)
.map(([key, { representation }]) => {
const important = this.#important.has(key as keyof StyleValues) ? ' !important' : '';
return `${dashedNames[key as keyof StyleValues]}: ${representation}${important};`;
})
.join(' ');
}

set cssText(text: string) {
const source = `${text}`;
this.#values = {};
this.#important.clear();
for (let start = 0; start < source.length;) {
const semicolon = source.indexOf(';', start);
const end = semicolon === -1 ? source.length : semicolon;
this.#declare(source.slice(start, end));
start = end + 1;
}
this.#changed();
}

setProperty(property: string, value: string | null, priority: string | null = ''): void {
if (arguments.length < 2) {
throw new TypeError('setProperty requires a property name and value');
Expand Down Expand Up @@ -288,15 +310,37 @@ export class StyleDeclaration {
return this.borderColor;
}

#declare(declaration: string): void {
const colon = declaration.indexOf(':');
const key = colon === -1 ? undefined : styleProperty(declaration.slice(0, colon).trim());
if (key === undefined) {
return;
}
let value = declaration.slice(colon + 1).trim();
const bang = value.lastIndexOf('!');
const important = bang !== -1 && asciiLowercase(value.slice(bang + 1).trim()) === 'important';
if (important) {
value = value.slice(0, bang);
}
this.#store(key, value, important);
}

#setProperty<K extends keyof StyleValues>(key: K, input: unknown, important = false): void {
if (this.#store(key, input, important)) {
this.#changed();
}
}

/** Applies one declaration and reports whether it changed anything, leaving notification to the caller. */
#store<K extends keyof StyleValues>(key: K, input: unknown, important: boolean): boolean {
const value = input === null ? '' : `${input}`;
if (value === '') {
if (this.#values[key] !== undefined) {
delete this.#values[key];
this.#important.delete(key);
this.#changed();
if (this.#values[key] === undefined) {
return false;
}
return;
delete this.#values[key];
this.#important.delete(key);
return true;
}
const representation = value.trim() as StyleValues[K]['representation'];
const result = propertySchemas[key]['~standard'].validate(
Expand All @@ -305,7 +349,7 @@ export class StyleDeclaration {

// ignore styles that can't be validated and converted;
if (result.issues) {
return; //todo: issue warning.
return false; //todo: issue warning.
}

this.#values[key] = { value: result.value, representation } as StyleValues[K];
Expand All @@ -314,7 +358,7 @@ export class StyleDeclaration {
} else {
this.#important.delete(key);
}
this.#changed();
return true;
}

#getProperty<K extends keyof StyleValues>(property: K): StyleValues[K]['representation'] | '' {
Expand All @@ -339,6 +383,10 @@ const propertyNames = {
'border-color': 'borderColor',
} as const satisfies Record<string, keyof StyleValues>;

const dashedNames = Object.fromEntries(
Object.entries(propertyNames).map(([dashed, key]) => [key, dashed]),
) as Record<keyof StyleValues, keyof typeof propertyNames>;

function styleProperty(property: string): keyof StyleValues | undefined {
const name = asciiLowercase(property);
return Object.hasOwn(propertyNames, name)
Expand Down
17 changes: 17 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,23 @@ const config: WPTConfig = {
],
'css/css-flexbox/parsing/flex-direction-invalid.html': true,
'css/cssom/cssstyledeclaration-properties.html': true,
'css/cssom/cssstyledeclaration-csstext.html': [
'uppercase property',
'uppercase value',
'overwriting with invalid value',
'use rgb',
// Other cases use unsupported properties, shorthands, or computed styles.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would it take to unlock these other test cases such as shorthands? Would it help to use a more formal CSS parser?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like we'd need a proper inline style parser ;)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't think the parser is the blocker here, those cases skip because we don't support the properties yet (font-size, font-weight, margin) or getComputedStyle. a real parser only matters once a value can contain ; or :, like strings or url(), and none of ours can today. for shorthands, padding is probably the one worth doing first

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As long as you see the path forward, sounds good!

],
'css/cssom/cssstyledeclaration-csstext-final-delimiter.html': [
'inline style - text - delimiters - zero declarations',
// The other cases use the unsupported left and right properties.
],
'css/cssom/serialization-CSSDeclaration-with-important.html': [
"Inline style declaration without whitespace between '!' and 'important'.",
"Style set dynamically via cssText without whitespace between '!' and 'important'.",
"Style set dynamically via cssText with whitespace between '!' and 'important'.",
// The remaining case unlocks once we support background-color.
],
'css/cssom/cssstyledeclaration-setter-attr.html': true,
'dom/events/Event-constructors.any.js': true,
'dom/events/EventTarget-addEventListener.any.js': true,
Expand Down
Loading