@link-foundation/ui-dom 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +295 -2
- package/package.json +54 -4
- package/src/diagnostics.js +58 -0
- package/src/events.js +174 -0
- package/src/frame-fit.js +205 -0
- package/src/html.d.ts +4 -0
- package/src/html.js +245 -0
- package/src/index.d.ts +267 -0
- package/src/index.js +47 -0
- package/src/kinds/basic.js +189 -0
- package/src/kinds.js +151 -0
- package/src/model.js +84 -0
- package/src/patch.js +62 -0
- package/src/render.js +121 -0
- package/src/scheduler.js +50 -0
- package/src/styles.js +190 -0
- package/src/themes.js +147 -0
- package/src/tree.js +335 -0
package/src/model.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The element model the kinds see: a store element view plus `props`, every
|
|
3
|
+
* property by name. Positional values take the property names the
|
|
4
|
+
* vocabulary gives them (`(greeting: text 'Hello')` has `value`), and an
|
|
5
|
+
* explicit property of the same name wins, as does the last of repeated
|
|
6
|
+
* properties.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { defaultVocabulary } from '@link-foundation/ui-core';
|
|
10
|
+
|
|
11
|
+
const VOCABULARY = defaultVocabulary();
|
|
12
|
+
|
|
13
|
+
/** The ui-core vocabulary the renderer checks actions against. */
|
|
14
|
+
export const vocabulary = () => VOCABULARY;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {import('@link-foundation/ui-core').RawValue} RawValue
|
|
18
|
+
* @typedef {import('@link-foundation/ui-core').UiProperty} UiProperty
|
|
19
|
+
*
|
|
20
|
+
* @typedef {object} Element
|
|
21
|
+
* @property {string} id the store ID (`data-link-id`)
|
|
22
|
+
* @property {string|null} name the id in the document
|
|
23
|
+
* @property {string|null} kind
|
|
24
|
+
* @property {readonly RawValue[]} positional
|
|
25
|
+
* @property {readonly UiProperty[]} properties
|
|
26
|
+
* @property {readonly RawValue[]} unknown
|
|
27
|
+
* @property {ReadonlyMap<string, readonly RawValue[]>} props
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The element model of a store element view (or a ui-core node with `id`).
|
|
32
|
+
* @param {{id: string, name?: string|null, kind: string|null,
|
|
33
|
+
* positional?: readonly RawValue[], properties?: readonly UiProperty[],
|
|
34
|
+
* unknown?: readonly RawValue[]}} view
|
|
35
|
+
* @returns {Element}
|
|
36
|
+
*/
|
|
37
|
+
export function elementOf(view) {
|
|
38
|
+
const positional = view.positional ?? [];
|
|
39
|
+
const properties = view.properties ?? [];
|
|
40
|
+
const names = VOCABULARY.kinds.get(view.kind)?.positional ?? [];
|
|
41
|
+
const props = new Map();
|
|
42
|
+
positional.forEach((value, i) => {
|
|
43
|
+
if (i < names.length) {
|
|
44
|
+
props.set(names[i], [value]);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
for (const property of properties) {
|
|
48
|
+
props.set(property.name, property.values);
|
|
49
|
+
}
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
id: view.id,
|
|
52
|
+
name: view.name ?? null,
|
|
53
|
+
kind: view.kind ?? null,
|
|
54
|
+
positional,
|
|
55
|
+
properties,
|
|
56
|
+
unknown: view.unknown ?? [],
|
|
57
|
+
props,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The same element with other properties (a store `update` event).
|
|
63
|
+
* @param {Element} element
|
|
64
|
+
* @param {readonly UiProperty[]} properties
|
|
65
|
+
*/
|
|
66
|
+
export const withProperties = (element, properties) =>
|
|
67
|
+
elementOf({ ...element, properties });
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The single text value of a property; `undefined` when it is missing or
|
|
71
|
+
* is not one plain value.
|
|
72
|
+
* @param {Element} element
|
|
73
|
+
* @param {string} name
|
|
74
|
+
* @returns {string|undefined}
|
|
75
|
+
*/
|
|
76
|
+
export function atom(element, name) {
|
|
77
|
+
const values = element.props.get(name);
|
|
78
|
+
return values?.length === 1 && typeof values[0] === 'string'
|
|
79
|
+
? values[0]
|
|
80
|
+
: undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Every property name of the element (the first `update` of a node). */
|
|
84
|
+
export const propNames = (element) => [...element.props.keys()];
|
package/src/patch.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apply store events to the rendered tree, in order, from the data of each
|
|
3
|
+
* event (not from the current store state, which may already be ahead):
|
|
4
|
+
*
|
|
5
|
+
* - insert: render the element (`after`) at `index` of `parentId`;
|
|
6
|
+
* - update: the kind's `update` with the one changed property name;
|
|
7
|
+
* - move: `insertBefore` at the new place;
|
|
8
|
+
* - remove: `destroy`, then drop the node and its map entries;
|
|
9
|
+
* - rename: rewrite `data-link-id` and both maps.
|
|
10
|
+
*
|
|
11
|
+
* An event that does not match the tree is reported, never thrown.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { diagnostic } from './diagnostics.js';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {ReturnType<typeof import('./tree.js').createTree>} tree
|
|
18
|
+
* @param {readonly import('@link-foundation/ui-store').StoreEvent[]} events
|
|
19
|
+
* @param {(d: object) => void} report
|
|
20
|
+
*/
|
|
21
|
+
export function applyEvents(tree, events, report) {
|
|
22
|
+
for (const event of events) {
|
|
23
|
+
let ok;
|
|
24
|
+
switch (event.type) {
|
|
25
|
+
case 'insert':
|
|
26
|
+
ok = event.after !== null && typeof event.after === 'object';
|
|
27
|
+
if (ok) {
|
|
28
|
+
tree.insert(event.after, event.parentId, event.index);
|
|
29
|
+
}
|
|
30
|
+
break;
|
|
31
|
+
case 'update':
|
|
32
|
+
ok =
|
|
33
|
+
event.prop === undefined
|
|
34
|
+
? tree.updatePositional(event.id, event.after)
|
|
35
|
+
: tree.update(event.id, event.props ?? [], [event.prop]);
|
|
36
|
+
break;
|
|
37
|
+
case 'move':
|
|
38
|
+
ok = tree.move(
|
|
39
|
+
event.id,
|
|
40
|
+
event.after?.parentId ?? null,
|
|
41
|
+
event.after?.index
|
|
42
|
+
);
|
|
43
|
+
break;
|
|
44
|
+
case 'remove':
|
|
45
|
+
ok = tree.remove(event.id);
|
|
46
|
+
break;
|
|
47
|
+
case 'rename':
|
|
48
|
+
ok = tree.rename(event.before, event.after);
|
|
49
|
+
break;
|
|
50
|
+
default:
|
|
51
|
+
ok = false;
|
|
52
|
+
}
|
|
53
|
+
if (!ok) {
|
|
54
|
+
report(
|
|
55
|
+
diagnostic('bad-event', 'warning', {
|
|
56
|
+
element: event.id,
|
|
57
|
+
type: event.type,
|
|
58
|
+
})
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/render.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `render(container, store, options)`: render a ui-store document as
|
|
3
|
+
* custom elements in `container` and keep it in sync. Store events are
|
|
4
|
+
* patched in one microtask per task (`flush()` patches synchronously), and the
|
|
5
|
+
* stylesheet is adopted a single time per root node.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { applyEvents } from './patch.js';
|
|
9
|
+
import { createScheduler } from './scheduler.js';
|
|
10
|
+
import { adoptStyles, buildCss } from './styles.js';
|
|
11
|
+
import { createTree } from './tree.js';
|
|
12
|
+
import { atom, elementOf } from './model.js';
|
|
13
|
+
import { applyThemes, themeRegistry } from './themes.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {import('@link-foundation/ui-store').Store} Store
|
|
17
|
+
*
|
|
18
|
+
* @typedef {object} RenderOptions
|
|
19
|
+
* @property {Map<string, import('./kinds.js').KindSpec>|
|
|
20
|
+
* Record<string, import('./kinds.js').KindSpec>} [kinds] kind
|
|
21
|
+
* renderers of this render, before the registry
|
|
22
|
+
* @property {(detail: {source: string|null, event: string,
|
|
23
|
+
* action: readonly any[]}, event: Event) => void} [onAction]
|
|
24
|
+
* @property {(name: string) => boolean} [isAction] which action names
|
|
25
|
+
* handlers may use (default: the vocabulary actions); others are
|
|
26
|
+
* reported as `unknown-action` and never dispatched
|
|
27
|
+
* @property {(diagnostic: object) => void} [onDiagnostic]
|
|
28
|
+
* @property {(events: readonly object[]) => void} [onPatch] called once
|
|
29
|
+
* per applied patch with its store events
|
|
30
|
+
* @property {boolean} [setTitle] set `document.title` from the document
|
|
31
|
+
* @property {string|object|Map<string, any>} [tokens] ui-tokens LiNo text,
|
|
32
|
+
* `{ sets }` of `readTokens`, or resolved tokens
|
|
33
|
+
* @property {string|object[]|Map<string, object>} [themes] theme packages
|
|
34
|
+
* @property {object} [config] layered configuration and comfort choices
|
|
35
|
+
* @property {string} [theme] the token set (default: the document's
|
|
36
|
+
* `theme`, else the first set)
|
|
37
|
+
* @property {string|object[]} [styles] ui-style LiNo text or read rules
|
|
38
|
+
* @property {string} [css] extra CSS appended to the sheet
|
|
39
|
+
* @property {string} [prefix] the CSS custom property prefix
|
|
40
|
+
* @property {boolean} [baseCss] `false` leaves out the base rules
|
|
41
|
+
* @property {boolean} [adoptStyles] `false` applies no stylesheet
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/** The `theme` of the first document element of the store. */
|
|
45
|
+
function documentTheme(store) {
|
|
46
|
+
for (const id of store.roots()) {
|
|
47
|
+
const view = store.get(id);
|
|
48
|
+
if (view?.kind === 'document') {
|
|
49
|
+
return atom(elementOf(view), 'theme');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {Element} container
|
|
57
|
+
* @param {Store} store
|
|
58
|
+
* @param {RenderOptions} [options]
|
|
59
|
+
*/
|
|
60
|
+
export function render(container, store, options = {}) {
|
|
61
|
+
const document = container.ownerDocument;
|
|
62
|
+
const diagnostics = [];
|
|
63
|
+
const report = (d) => {
|
|
64
|
+
diagnostics.push(d);
|
|
65
|
+
options.onDiagnostic?.(d);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
options = {
|
|
69
|
+
...options,
|
|
70
|
+
themeRegistry: themeRegistry(options.themes, report),
|
|
71
|
+
themeHost: container,
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const styles =
|
|
75
|
+
options.adoptStyles === false
|
|
76
|
+
? null
|
|
77
|
+
: adoptStyles(container, buildCss(options, documentTheme(store), report));
|
|
78
|
+
|
|
79
|
+
const tree = createTree({
|
|
80
|
+
document,
|
|
81
|
+
container,
|
|
82
|
+
options,
|
|
83
|
+
interactive: true,
|
|
84
|
+
report,
|
|
85
|
+
});
|
|
86
|
+
tree.mount(store);
|
|
87
|
+
const syncThemes = () => applyThemes(tree, store, options);
|
|
88
|
+
syncThemes();
|
|
89
|
+
const stopConfig = options.config?.subscribe(syncThemes);
|
|
90
|
+
|
|
91
|
+
const scheduler = createScheduler((events) => {
|
|
92
|
+
applyEvents(tree, events, report);
|
|
93
|
+
syncThemes();
|
|
94
|
+
options.onPatch?.(events);
|
|
95
|
+
});
|
|
96
|
+
let unsubscribe = store.subscribe((events) => scheduler.schedule(events));
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
store,
|
|
100
|
+
diagnostics,
|
|
101
|
+
styles,
|
|
102
|
+
/** The node of a store ID; `null` when it has none. */
|
|
103
|
+
nodeFor: tree.nodeFor,
|
|
104
|
+
/** The store ID of a node or of its closest rendered ancestor. */
|
|
105
|
+
idFor: tree.idFor,
|
|
106
|
+
/** Apply the pending store events now; returns how many there were. */
|
|
107
|
+
flush: () => scheduler.flush(),
|
|
108
|
+
/** Remove every node, the store listener and the stylesheet. */
|
|
109
|
+
destroy() {
|
|
110
|
+
if (unsubscribe === null) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
scheduler.cancel();
|
|
114
|
+
stopConfig?.();
|
|
115
|
+
unsubscribe();
|
|
116
|
+
unsubscribe = null;
|
|
117
|
+
tree.clear();
|
|
118
|
+
styles?.release();
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
package/src/scheduler.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batches store events into one patch per microtask: every transaction
|
|
3
|
+
* committed in the same task is applied by a single `run(events)` call.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @template T
|
|
8
|
+
* @param {(items: T[]) => void} run
|
|
9
|
+
* @returns {{schedule(items: readonly T[]): void, flush(): number,
|
|
10
|
+
* cancel(): void}}
|
|
11
|
+
*/
|
|
12
|
+
export function createScheduler(run) {
|
|
13
|
+
let queue = [];
|
|
14
|
+
let pending = false;
|
|
15
|
+
let cancelled = false;
|
|
16
|
+
|
|
17
|
+
const flush = () => {
|
|
18
|
+
if (queue.length === 0) {
|
|
19
|
+
return 0;
|
|
20
|
+
}
|
|
21
|
+
const batch = queue;
|
|
22
|
+
queue = [];
|
|
23
|
+
run(batch);
|
|
24
|
+
return batch.length;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
schedule(items) {
|
|
29
|
+
if (cancelled) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const item of items) {
|
|
33
|
+
queue.push(item);
|
|
34
|
+
}
|
|
35
|
+
if (!pending) {
|
|
36
|
+
pending = true;
|
|
37
|
+
globalThis.queueMicrotask(() => {
|
|
38
|
+
pending = false;
|
|
39
|
+
flush();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
/** Apply the queued items now; returns how many there were. */
|
|
44
|
+
flush,
|
|
45
|
+
cancel() {
|
|
46
|
+
cancelled = true;
|
|
47
|
+
queue = [];
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
package/src/styles.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One stylesheet per render: the base rules of the basic kinds, the token
|
|
3
|
+
* CSS custom properties (ui-tokens `toCss`), the compiled style rules
|
|
4
|
+
* (ui-style `compileCss`) and the `css` option, in that order.
|
|
5
|
+
*
|
|
6
|
+
* The sheet is adopted (`adoptedStyleSheets`) on the root node of the
|
|
7
|
+
* container, a Document or a ShadowRoot; where adoption is not supported
|
|
8
|
+
* one `<style data-ui-dom>` element is used instead. Renders that share a
|
|
9
|
+
* root and the same CSS share one sheet, which is removed when the last of
|
|
10
|
+
* them is destroyed.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { compileThemeCss } from '@link-foundation/ui-tokens/themes';
|
|
14
|
+
import { compileCss, readStyles } from '@link-foundation/ui-style';
|
|
15
|
+
import {
|
|
16
|
+
readTokens,
|
|
17
|
+
resolveTokens,
|
|
18
|
+
toCss as tokensCss,
|
|
19
|
+
} from '@link-foundation/ui-tokens';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Zero-specificity (`:where`) defaults, so every style rule wins over them.
|
|
23
|
+
* The custom elements are light DOM: these are ordinary document rules.
|
|
24
|
+
*/
|
|
25
|
+
export const BASE_CSS = `:where(ui-document, ui-text, ui-unknown) { display: block; }
|
|
26
|
+
:where(ui-stack) { display: flex; flex-direction: column; align-items: flex-start; }
|
|
27
|
+
:where(ui-stack[align='start']) { align-items: flex-start; }
|
|
28
|
+
:where(ui-stack[align='center']) { align-items: center; }
|
|
29
|
+
:where(ui-stack[align='end']) { align-items: flex-end; }
|
|
30
|
+
:where(ui-stack[align='stretch']) { align-items: stretch; }
|
|
31
|
+
:where(ui-button) { display: inline-flex; border-radius: 20px; }
|
|
32
|
+
:where(ui-button) > button { all: unset; box-sizing: border-box; padding: 10px 24px; border-radius: inherit; cursor: pointer; font: inherit; color: inherit; }
|
|
33
|
+
:where(ui-button) > button:focus-visible { outline: 3px solid CanvasText; outline-offset: 2px; }
|
|
34
|
+
:where(ui-button) > button:disabled { cursor: default; }
|
|
35
|
+
:where(ui-button[disabled]) { opacity: 0.38; }
|
|
36
|
+
:where(ui-image) { display: inline-block; }
|
|
37
|
+
:where(ui-image) > img { display: block; max-width: 100%; height: auto; }
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
const isMap = (value) => value instanceof Map;
|
|
41
|
+
|
|
42
|
+
/** The token sets of the `tokens` option: LiNo text or `{ sets }`. */
|
|
43
|
+
function tokenSets(tokens, report) {
|
|
44
|
+
if (typeof tokens === 'string') {
|
|
45
|
+
const read = readTokens(tokens);
|
|
46
|
+
read.diagnostics.forEach(report);
|
|
47
|
+
return read.sets;
|
|
48
|
+
}
|
|
49
|
+
return tokens?.sets;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The CSS custom properties of the theme (empty without tokens). */
|
|
53
|
+
function themeCss(options, theme, report) {
|
|
54
|
+
const { tokens, prefix = '' } = options;
|
|
55
|
+
if (tokens === undefined || tokens === null) {
|
|
56
|
+
return '';
|
|
57
|
+
}
|
|
58
|
+
// Already resolved tokens (ui-tokens `resolveTokens`).
|
|
59
|
+
if (isMap(tokens)) {
|
|
60
|
+
return tokensCss(tokens, { selector: ':root, :host', prefix });
|
|
61
|
+
}
|
|
62
|
+
const sets = tokenSets(tokens, report);
|
|
63
|
+
if (!isMap(sets) || sets.size === 0) {
|
|
64
|
+
return '';
|
|
65
|
+
}
|
|
66
|
+
const setId =
|
|
67
|
+
[options.theme, theme].find((id) => sets.has(id)) ?? [...sets.keys()][0];
|
|
68
|
+
const resolved = resolveTokens(sets, setId);
|
|
69
|
+
(resolved.diagnostics ?? []).forEach(report);
|
|
70
|
+
return tokensCss(resolved, { selector: ':root, :host', prefix });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The CSS of the `styles` option: LiNo text or ui-style rules. */
|
|
74
|
+
function rulesCss(options, report) {
|
|
75
|
+
const { styles, prefix = '' } = options;
|
|
76
|
+
if (styles === undefined || styles === null) {
|
|
77
|
+
return '';
|
|
78
|
+
}
|
|
79
|
+
let rules = styles;
|
|
80
|
+
if (typeof styles === 'string') {
|
|
81
|
+
const read = readStyles(styles);
|
|
82
|
+
read.diagnostics.forEach(report);
|
|
83
|
+
rules = read.rules;
|
|
84
|
+
}
|
|
85
|
+
return compileCss(rules, { prefix });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The CSS text of a render.
|
|
90
|
+
* @param {{tokens?: string|{sets: Map<string, any>}|Map<string, any>,
|
|
91
|
+
* styles?: string|any[], css?: string, theme?: string, prefix?: string,
|
|
92
|
+
* baseCss?: boolean}} options
|
|
93
|
+
* @param {string|undefined} theme the `theme` of the document element
|
|
94
|
+
* @param {(diagnostic: object) => void} report
|
|
95
|
+
*/
|
|
96
|
+
export function buildCss(options = {}, theme = undefined, report = () => {}) {
|
|
97
|
+
return [
|
|
98
|
+
options.baseCss === false ? '' : BASE_CSS,
|
|
99
|
+
themeCss(options, theme, report),
|
|
100
|
+
...[...(options.themeRegistry?.values() ?? [])].map((theme) =>
|
|
101
|
+
compileThemeCss(theme, { prefix: options.prefix, onDiagnostic: report })
|
|
102
|
+
),
|
|
103
|
+
rulesCss(options, report),
|
|
104
|
+
typeof options.css === 'string' ? options.css : '',
|
|
105
|
+
]
|
|
106
|
+
.filter((part) => part !== '')
|
|
107
|
+
.join('\n');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** root → CSS text → { count, release } */
|
|
111
|
+
const shared = new WeakMap();
|
|
112
|
+
|
|
113
|
+
/** Whether the root can adopt a constructed stylesheet. */
|
|
114
|
+
function canAdopt(root, win) {
|
|
115
|
+
return (
|
|
116
|
+
Array.isArray(root.adoptedStyleSheets) &&
|
|
117
|
+
typeof win?.CSSStyleSheet === 'function' &&
|
|
118
|
+
typeof win.CSSStyleSheet.prototype.replaceSync === 'function'
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function adoptSheet(root, win, css) {
|
|
123
|
+
const sheet = new win.CSSStyleSheet();
|
|
124
|
+
sheet.replaceSync(css);
|
|
125
|
+
root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
|
|
126
|
+
return {
|
|
127
|
+
sheet,
|
|
128
|
+
remove() {
|
|
129
|
+
root.adoptedStyleSheets = root.adoptedStyleSheets.filter(
|
|
130
|
+
(s) => s !== sheet
|
|
131
|
+
);
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function styleElement(root, container, css) {
|
|
137
|
+
const document = container.ownerDocument;
|
|
138
|
+
const style = document.createElement('style');
|
|
139
|
+
style.setAttribute('data-ui-dom', '');
|
|
140
|
+
style.textContent = css;
|
|
141
|
+
if (root.nodeType === 9) {
|
|
142
|
+
(root.head ?? root.documentElement).appendChild(style);
|
|
143
|
+
} else {
|
|
144
|
+
// A ShadowRoot, or the top of a detached tree.
|
|
145
|
+
root.insertBefore(style, root.firstChild);
|
|
146
|
+
}
|
|
147
|
+
return { element: style, remove: () => style.remove() };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Apply the CSS to the root node of the container, once per root and CSS.
|
|
152
|
+
* @param {Element} container
|
|
153
|
+
* @param {string} css
|
|
154
|
+
* @returns {{sheet?: CSSStyleSheet, element?: HTMLStyleElement,
|
|
155
|
+
* release(): void}}
|
|
156
|
+
*/
|
|
157
|
+
export function adoptStyles(container, css) {
|
|
158
|
+
const root = container.getRootNode();
|
|
159
|
+
const win = container.ownerDocument.defaultView;
|
|
160
|
+
let entries = shared.get(root);
|
|
161
|
+
if (entries === undefined) {
|
|
162
|
+
entries = new Map();
|
|
163
|
+
shared.set(root, entries);
|
|
164
|
+
}
|
|
165
|
+
let entry = entries.get(css);
|
|
166
|
+
if (entry === undefined) {
|
|
167
|
+
const applied = canAdopt(root, win)
|
|
168
|
+
? adoptSheet(root, win, css)
|
|
169
|
+
: styleElement(root, container, css);
|
|
170
|
+
entry = { ...applied, count: 0 };
|
|
171
|
+
entries.set(css, entry);
|
|
172
|
+
}
|
|
173
|
+
entry.count += 1;
|
|
174
|
+
let released = false;
|
|
175
|
+
return {
|
|
176
|
+
sheet: entry.sheet,
|
|
177
|
+
element: entry.element,
|
|
178
|
+
release() {
|
|
179
|
+
if (released) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
released = true;
|
|
183
|
+
entry.count -= 1;
|
|
184
|
+
if (entry.count === 0) {
|
|
185
|
+
entry.remove();
|
|
186
|
+
entries.delete(css);
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
package/src/themes.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Theme boundaries inherit choices, while only their attributes change on a switch. */
|
|
2
|
+
import { loadThemes, resolveTheme } from '@link-foundation/ui-tokens/themes';
|
|
3
|
+
import { atom, elementOf } from './model.js';
|
|
4
|
+
|
|
5
|
+
const BOUNDARY = ['theme', 'scheme', 'contrast', 'motion'];
|
|
6
|
+
const COMFORT = ['motion', 'sound', 'volume', 'transparency'];
|
|
7
|
+
const CHOICES = {
|
|
8
|
+
scheme: ['light', 'dark', 'system'],
|
|
9
|
+
contrast: ['normal', 'more', 'system'],
|
|
10
|
+
motion: ['full', 'reduced', 'system'],
|
|
11
|
+
};
|
|
12
|
+
const scalar = (entry) =>
|
|
13
|
+
entry?.value?.length === 1 ? entry.value[0] : undefined;
|
|
14
|
+
|
|
15
|
+
export function themeRegistry(input, report = () => {}) {
|
|
16
|
+
if (!input) {
|
|
17
|
+
return new Map();
|
|
18
|
+
}
|
|
19
|
+
const result =
|
|
20
|
+
typeof input === 'string'
|
|
21
|
+
? loadThemes(input)
|
|
22
|
+
: {
|
|
23
|
+
themes: input instanceof Map ? [...input.values()] : input,
|
|
24
|
+
diagnostics: [],
|
|
25
|
+
};
|
|
26
|
+
result.diagnostics.forEach(report);
|
|
27
|
+
const registry = new Map(result.themes.map((theme) => [theme.id, theme]));
|
|
28
|
+
return new Map(
|
|
29
|
+
[...registry].map(([id, theme]) => {
|
|
30
|
+
const resolved = theme.sets ? theme : resolveTheme(registry, id);
|
|
31
|
+
resolved.diagnostics.forEach(report);
|
|
32
|
+
return [id, resolved];
|
|
33
|
+
})
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Effective theme at creation time, including an element's own theme boundary. */
|
|
38
|
+
export function themeFor(store, id, options) {
|
|
39
|
+
for (let current = id; current !== null; current = store.parentOf(current)) {
|
|
40
|
+
const theme =
|
|
41
|
+
scalar(options.config?.resolve(current, 'theme')) ??
|
|
42
|
+
atom(elementOf(store.get(current)), 'theme');
|
|
43
|
+
if (theme !== undefined) {
|
|
44
|
+
return options.themeRegistry?.get(theme) ?? null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const inherited = inheritedChoices(options);
|
|
48
|
+
return options.themeRegistry?.get(inherited.theme) ?? null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Configuration values from user/session outrank all nested theme defaults. */
|
|
52
|
+
function comfort(config, lineage, name) {
|
|
53
|
+
for (const layer of ['session', 'user', 'site', 'theme', 'defaults']) {
|
|
54
|
+
for (const id of [...lineage].reverse()) {
|
|
55
|
+
const value = config?.valueIn(layer, id, name);
|
|
56
|
+
if (value?.length === 1) {
|
|
57
|
+
return value[0];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function inheritedChoices(options) {
|
|
65
|
+
const initial = {
|
|
66
|
+
theme: options.theme ?? options.themeRegistry?.keys().next().value ?? '',
|
|
67
|
+
scheme: 'system',
|
|
68
|
+
contrast: 'system',
|
|
69
|
+
motion: 'system',
|
|
70
|
+
};
|
|
71
|
+
// Copy each choice from its nearest DOM ancestor, including the boot script's html.
|
|
72
|
+
for (const name of [...BOUNDARY, ...COMFORT]) {
|
|
73
|
+
for (let host = options.themeHost; host; host = host.parentElement) {
|
|
74
|
+
if (host.hasAttribute(`data-${name}`)) {
|
|
75
|
+
initial[name] = host.getAttribute(`data-${name}`);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return initial;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function boundaryChoices(own, el, inherited, options, path) {
|
|
84
|
+
const next = { ...inherited };
|
|
85
|
+
for (const name of BOUNDARY) {
|
|
86
|
+
if (
|
|
87
|
+
own[name] !== undefined &&
|
|
88
|
+
(!CHOICES[name] || CHOICES[name].includes(own[name]))
|
|
89
|
+
) {
|
|
90
|
+
next[name] = own[name];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const defaults = options.themeRegistry?.get(next.theme)?.defaults ?? {};
|
|
94
|
+
for (const name of COMFORT) {
|
|
95
|
+
next[name] =
|
|
96
|
+
comfort(options.config, path, name) ??
|
|
97
|
+
atom(el, name) ??
|
|
98
|
+
(own.theme !== undefined ? defaults[name] : undefined) ??
|
|
99
|
+
inherited[name];
|
|
100
|
+
}
|
|
101
|
+
return next;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function writeBoundary(node, choices) {
|
|
105
|
+
for (const name of new Set([...BOUNDARY, ...COMFORT])) {
|
|
106
|
+
const value = choices?.[name];
|
|
107
|
+
if (value === undefined) {
|
|
108
|
+
node.removeAttribute(`data-${name}`);
|
|
109
|
+
} else if (node.getAttribute(`data-${name}`) !== String(value)) {
|
|
110
|
+
node.setAttribute(`data-${name}`, value);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function applyThemes(tree, store, options) {
|
|
116
|
+
const registry = options.themeRegistry;
|
|
117
|
+
const initial = inheritedChoices(options);
|
|
118
|
+
const visit = (id, inherited, lineage) => {
|
|
119
|
+
const el = tree.elementFor(id),
|
|
120
|
+
node = tree.nodeFor(id);
|
|
121
|
+
if (!el || !node) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const own = Object.fromEntries(
|
|
125
|
+
BOUNDARY.map((name) => [
|
|
126
|
+
name,
|
|
127
|
+
scalar(options.config?.resolve(id, name)) ?? atom(el, name),
|
|
128
|
+
])
|
|
129
|
+
);
|
|
130
|
+
const boundary =
|
|
131
|
+
BOUNDARY.some((name) => own[name] !== undefined) ||
|
|
132
|
+
(lineage.length === 0 && (registry?.size > 0 || options.config));
|
|
133
|
+
const path = [...lineage, id];
|
|
134
|
+
let next = inherited;
|
|
135
|
+
if (boundary) {
|
|
136
|
+
next = boundaryChoices(own, el, inherited, options, path);
|
|
137
|
+
}
|
|
138
|
+
writeBoundary(node, boundary ? next : null);
|
|
139
|
+
|
|
140
|
+
for (const child of store.children(id)) {
|
|
141
|
+
visit(child, next, path);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
for (const id of store.roots()) {
|
|
145
|
+
visit(id, initial, []);
|
|
146
|
+
}
|
|
147
|
+
}
|