@link-foundation/ui-dom 0.0.0-stage → 0.1.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/index.d.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
Diagnostic as CoreDiagnostic,
|
|
5
|
+
ParseOptions,
|
|
6
|
+
RawValue,
|
|
7
|
+
UiDocument,
|
|
8
|
+
UiNode,
|
|
9
|
+
UiProperty,
|
|
10
|
+
} from '@link-foundation/ui-core';
|
|
11
|
+
import type { Store, StoreOptions } from '@link-foundation/ui-store';
|
|
12
|
+
import type { ResolvedTokens } from '@link-foundation/ui-tokens';
|
|
13
|
+
|
|
14
|
+
/** A diagnostic of the renderer (`unknown-kind`, `missing-alt`, …). */
|
|
15
|
+
export interface DomDiagnostic {
|
|
16
|
+
code:
|
|
17
|
+
| 'unknown-kind'
|
|
18
|
+
| 'kind-error'
|
|
19
|
+
| 'missing-alt'
|
|
20
|
+
| 'unsafe-url'
|
|
21
|
+
| 'invalid-handler'
|
|
22
|
+
| 'unknown-action'
|
|
23
|
+
| 'unknown-event'
|
|
24
|
+
| 'invalid-value'
|
|
25
|
+
| 'bad-event'
|
|
26
|
+
| (string & {});
|
|
27
|
+
severity: 'error' | 'warning' | 'info';
|
|
28
|
+
message: string;
|
|
29
|
+
at: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A diagnostic of the renderer, the parser, the tokens or the styles. */
|
|
33
|
+
export type Diagnostic = DomDiagnostic | CoreDiagnostic;
|
|
34
|
+
|
|
35
|
+
/** The element model a kind renderer sees. */
|
|
36
|
+
export interface UiElement {
|
|
37
|
+
/** The store ID (`data-link-id`). */
|
|
38
|
+
readonly id: string;
|
|
39
|
+
/** The id in the document; `null` for an anonymous element. */
|
|
40
|
+
readonly name: string | null;
|
|
41
|
+
readonly kind: string | null;
|
|
42
|
+
readonly positional: readonly RawValue[];
|
|
43
|
+
readonly properties: readonly UiProperty[];
|
|
44
|
+
readonly unknown: readonly RawValue[];
|
|
45
|
+
/**
|
|
46
|
+
* Every property by name: the positional values under their vocabulary
|
|
47
|
+
* names (`text` → `value`, `button` → `label`, `image` → `source`),
|
|
48
|
+
* overridden by the named properties.
|
|
49
|
+
*/
|
|
50
|
+
readonly props: ReadonlyMap<string, readonly RawValue[]>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface KindContext {
|
|
54
|
+
/** Effective theme at mount time. Theme switching preserves this part tree. */
|
|
55
|
+
theme(): import('@link-foundation/ui-tokens/themes').Theme | null;
|
|
56
|
+
/** The document nodes are created in. */
|
|
57
|
+
document: Document;
|
|
58
|
+
/** The render options. */
|
|
59
|
+
options: RenderOptions;
|
|
60
|
+
/**
|
|
61
|
+
* The element models of the current element's children in the store (a
|
|
62
|
+
* kind without a children slot reads sublinks that the projection made
|
|
63
|
+
* child elements, such as `(label ...)`).
|
|
64
|
+
*/
|
|
65
|
+
children(): UiElement[];
|
|
66
|
+
/** Report a problem of the current element. */
|
|
67
|
+
diagnostic(
|
|
68
|
+
code: string,
|
|
69
|
+
severity: 'error' | 'warning' | 'info',
|
|
70
|
+
at?: Record<string, unknown>
|
|
71
|
+
): void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The DOM renderer of one element kind. */
|
|
75
|
+
export interface KindSpec {
|
|
76
|
+
/** A valid custom element name (`ui-button`). */
|
|
77
|
+
tag: string;
|
|
78
|
+
/** Build the node; the renderer then calls `update` with every property. */
|
|
79
|
+
create(el: UiElement, ctx: KindContext): HTMLElement;
|
|
80
|
+
/** Apply the changed properties. */
|
|
81
|
+
update?(
|
|
82
|
+
node: HTMLElement,
|
|
83
|
+
el: UiElement,
|
|
84
|
+
changed: string[],
|
|
85
|
+
ctx: KindContext
|
|
86
|
+
): void;
|
|
87
|
+
/** Where the children go (default: the node itself; `null`: none). */
|
|
88
|
+
childrenSlot?: null | ((node: HTMLElement) => HTMLElement);
|
|
89
|
+
/** The element the `(on EVENT ...)` listeners go on (default: the node). */
|
|
90
|
+
eventTarget?(node: HTMLElement): HTMLElement;
|
|
91
|
+
/**
|
|
92
|
+
* Properties mirrored as attributes for CSS; `on*` names are refused.
|
|
93
|
+
* A boolean attribute is present for `true` and absent otherwise.
|
|
94
|
+
*/
|
|
95
|
+
attributes?: Record<string, 'string' | 'boolean'>;
|
|
96
|
+
destroy?(node: HTMLElement, ctx: KindContext): void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The detail of a `ui-action` event. */
|
|
100
|
+
export interface ActionDetail {
|
|
101
|
+
/** The store ID of the element whose handler fired. */
|
|
102
|
+
readonly source: string | null;
|
|
103
|
+
/** The document event (`press`, `focus`, `blur`, `hover`). */
|
|
104
|
+
readonly event: string;
|
|
105
|
+
/** The action and its arguments: `['navigate', 'home']`. */
|
|
106
|
+
readonly action: readonly RawValue[];
|
|
107
|
+
/** Context-menu target and current selection are independent. */
|
|
108
|
+
readonly target?: string;
|
|
109
|
+
readonly selection?: readonly string[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type Kinds = Map<string, KindSpec> | Record<string, KindSpec>;
|
|
113
|
+
|
|
114
|
+
export interface StyleOptions {
|
|
115
|
+
/** ui-tokens LiNo text, `{ sets }` of `readTokens`, or resolved tokens. */
|
|
116
|
+
tokens?: string | { sets: Map<string, unknown> } | ResolvedTokens;
|
|
117
|
+
/** The token set (default: the document's `theme`, else the first set). */
|
|
118
|
+
theme?: string;
|
|
119
|
+
/** ui-style LiNo text, or the rules of `readStyles`. */
|
|
120
|
+
styles?: string | readonly object[];
|
|
121
|
+
/** Extra CSS appended to the sheet. */
|
|
122
|
+
css?: string;
|
|
123
|
+
/** The CSS custom property prefix (`md` → `--md-color-primary`). */
|
|
124
|
+
prefix?: string;
|
|
125
|
+
/** `false` leaves out the base rules. */
|
|
126
|
+
baseCss?: boolean;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface RenderOptions extends StyleOptions {
|
|
130
|
+
/** Theme packages as LiNo, loaded themes, or a registry. */
|
|
131
|
+
themes?:
|
|
132
|
+
| string
|
|
133
|
+
| import('@link-foundation/ui-tokens/themes').Theme[]
|
|
134
|
+
| Map<string, import('@link-foundation/ui-tokens/themes').Theme>;
|
|
135
|
+
/** Layered configuration; comfort choices from user/session always win. */
|
|
136
|
+
config?: {
|
|
137
|
+
resolve(
|
|
138
|
+
id: string,
|
|
139
|
+
name: string
|
|
140
|
+
): { value: readonly unknown[] } | undefined;
|
|
141
|
+
valueIn(
|
|
142
|
+
layer: string,
|
|
143
|
+
id: string,
|
|
144
|
+
name: string
|
|
145
|
+
): readonly unknown[] | undefined;
|
|
146
|
+
subscribe(listener: (...args: any[]) => void): () => void;
|
|
147
|
+
};
|
|
148
|
+
/** Kind renderers of this render, looked up before the registry. */
|
|
149
|
+
kinds?: Kinds;
|
|
150
|
+
/** Called for every `ui-action`, after the event is dispatched. */
|
|
151
|
+
onAction?(detail: ActionDetail, event: Event): void;
|
|
152
|
+
/**
|
|
153
|
+
* Which action names handlers may use (default: the vocabulary
|
|
154
|
+
* actions); others are reported as `unknown-action` and never dispatched.
|
|
155
|
+
*/
|
|
156
|
+
isAction?(name: string): boolean;
|
|
157
|
+
onDiagnostic?(diagnostic: Diagnostic): void;
|
|
158
|
+
/** Called once per applied patch with its store events. */
|
|
159
|
+
onPatch?(events: readonly object[]): void;
|
|
160
|
+
/** Set `document.title` from the document's `title`. */
|
|
161
|
+
setTitle?: boolean;
|
|
162
|
+
/** `false` applies no stylesheet. */
|
|
163
|
+
adoptStyles?: boolean;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface RenderHandle {
|
|
167
|
+
readonly store: Store;
|
|
168
|
+
/** The diagnostics of the first render. */
|
|
169
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
170
|
+
readonly styles: {
|
|
171
|
+
sheet?: CSSStyleSheet;
|
|
172
|
+
element?: HTMLStyleElement;
|
|
173
|
+
release(): void;
|
|
174
|
+
} | null;
|
|
175
|
+
/** The node of a store ID; `null` when it has none. */
|
|
176
|
+
nodeFor(id: string): HTMLElement | null;
|
|
177
|
+
/** The store ID of a node or of its closest rendered ancestor. */
|
|
178
|
+
idFor(node: Node): string | null;
|
|
179
|
+
/** Apply the pending store events now; returns how many there were. */
|
|
180
|
+
flush(): number;
|
|
181
|
+
/** Remove every node, the store listener and the stylesheet. */
|
|
182
|
+
destroy(): void;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Render a ui-store document as custom elements and keep it in sync. */
|
|
186
|
+
export function render(
|
|
187
|
+
container: globalThis.Element | ParentNode,
|
|
188
|
+
store: Store,
|
|
189
|
+
options?: RenderOptions
|
|
190
|
+
): RenderHandle;
|
|
191
|
+
|
|
192
|
+
/** Parse Links Notation, create a store and render it. */
|
|
193
|
+
export function mountDocument(
|
|
194
|
+
container: globalThis.Element | ParentNode,
|
|
195
|
+
text: string,
|
|
196
|
+
options?: RenderOptions & {
|
|
197
|
+
parseOptions?: ParseOptions;
|
|
198
|
+
storeOptions?: Omit<StoreOptions, 'document'>;
|
|
199
|
+
}
|
|
200
|
+
): {
|
|
201
|
+
store: Store;
|
|
202
|
+
handle: RenderHandle;
|
|
203
|
+
diagnostics: Diagnostic[];
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
export interface HtmlOptions {
|
|
207
|
+
kinds?: Kinds;
|
|
208
|
+
onDiagnostic?(diagnostic: Diagnostic): void;
|
|
209
|
+
prefix?: string;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Static HTML of a document: escaped, without `on*` attributes or scripts. */
|
|
213
|
+
export function renderToHTML(
|
|
214
|
+
source: string | Store | UiDocument | UiNode | UiNode[],
|
|
215
|
+
options?: HtmlOptions
|
|
216
|
+
): string;
|
|
217
|
+
|
|
218
|
+
/** Escape `& < > " '` for HTML text and attribute values. */
|
|
219
|
+
export function escapeHtml(text: string): string;
|
|
220
|
+
|
|
221
|
+
/** Register the DOM renderer of a kind (replacing an earlier one). */
|
|
222
|
+
export function defineKind(kind: string, spec: KindSpec): Readonly<KindSpec>;
|
|
223
|
+
/** The renderer of a kind: the overrides first, then the registry. */
|
|
224
|
+
export function getKind(
|
|
225
|
+
kind: string | null,
|
|
226
|
+
overrides?: Kinds
|
|
227
|
+
): Readonly<KindSpec> | undefined;
|
|
228
|
+
export function registeredKinds(): string[];
|
|
229
|
+
export function isCustomElementName(tag: string): boolean;
|
|
230
|
+
/** The `ui-unknown` fallback of a kind without a renderer. */
|
|
231
|
+
export const UNKNOWN_KIND: Readonly<KindSpec>;
|
|
232
|
+
|
|
233
|
+
/** The DOM event of each document event. */
|
|
234
|
+
export const DOM_EVENTS: Readonly<{
|
|
235
|
+
press: 'click';
|
|
236
|
+
close: 'ui-close';
|
|
237
|
+
select: 'ui-select';
|
|
238
|
+
focus: 'focusin';
|
|
239
|
+
blur: 'focusout';
|
|
240
|
+
hover: 'pointerenter';
|
|
241
|
+
change: 'ui-change';
|
|
242
|
+
}>;
|
|
243
|
+
|
|
244
|
+
/** The base rules: layout of the basic kinds, focus ring, disabled state. */
|
|
245
|
+
export const BASE_CSS: string;
|
|
246
|
+
/** The CSS text of a render: base rules, tokens, style rules, `css`. */
|
|
247
|
+
export function buildCss(
|
|
248
|
+
options?: StyleOptions,
|
|
249
|
+
theme?: string,
|
|
250
|
+
report?: (diagnostic: Diagnostic) => void
|
|
251
|
+
): string;
|
|
252
|
+
|
|
253
|
+
/** Whether a URL uses a `javascript:`, `data:` or `vbscript:` scheme. */
|
|
254
|
+
export function isUnsafeUrl(url: string): boolean;
|
|
255
|
+
|
|
256
|
+
/** Opt-in threshold markers; no ResizeObserver is allocated without limits. */
|
|
257
|
+
export function observeFrameFit(
|
|
258
|
+
root: Element | Document,
|
|
259
|
+
options: {
|
|
260
|
+
levels: Record<string, string[]>;
|
|
261
|
+
scope?: Element;
|
|
262
|
+
prefix?: string;
|
|
263
|
+
boundaryAttribute?: string;
|
|
264
|
+
ResizeObserver?: typeof ResizeObserver;
|
|
265
|
+
MutationObserver?: typeof MutationObserver;
|
|
266
|
+
}
|
|
267
|
+
): { refresh(): void; dispose(): void };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@link-foundation/ui-dom`: the reference DOM renderer. A ui-store
|
|
3
|
+
* document renders as plain custom elements in the light DOM
|
|
4
|
+
* (`ui-document`, `ui-stack`, `ui-text`, `ui-button`, …), each carrying its
|
|
5
|
+
* store ID in `data-link-id`, and is patched incrementally from store
|
|
6
|
+
* events. See README.md.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { parse } from '@link-foundation/ui-core';
|
|
10
|
+
import { createStore } from '@link-foundation/ui-store/memory';
|
|
11
|
+
import './kinds/basic.js';
|
|
12
|
+
import { render } from './render.js';
|
|
13
|
+
|
|
14
|
+
export { render };
|
|
15
|
+
export { renderToHTML, escapeHtml } from './html.js';
|
|
16
|
+
export {
|
|
17
|
+
defineKind,
|
|
18
|
+
getKind,
|
|
19
|
+
registeredKinds,
|
|
20
|
+
isCustomElementName,
|
|
21
|
+
} from './kinds.js';
|
|
22
|
+
export { UNKNOWN_KIND } from './kinds/basic.js';
|
|
23
|
+
export { DOM_EVENTS } from './events.js';
|
|
24
|
+
export { BASE_CSS, buildCss } from './styles.js';
|
|
25
|
+
export { isUnsafeUrl } from './diagnostics.js';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Parse Links Notation, create a store and render it.
|
|
29
|
+
* @param {Element} container
|
|
30
|
+
* @param {string} text
|
|
31
|
+
* @param {import('./render.js').RenderOptions & {parseOptions?: object,
|
|
32
|
+
* storeOptions?: object}} [options] `parseOptions` go to ui-core
|
|
33
|
+
* `parse`, `storeOptions` to ui-store `createStore`
|
|
34
|
+
*/
|
|
35
|
+
export function mountDocument(container, text, options = {}) {
|
|
36
|
+
const parsed = parse(text, options.parseOptions);
|
|
37
|
+
parsed.diagnostics.forEach((d) => options.onDiagnostic?.(d));
|
|
38
|
+
const store = createStore({ ...options.storeOptions, document: parsed });
|
|
39
|
+
const handle = render(container, store, options);
|
|
40
|
+
return {
|
|
41
|
+
store,
|
|
42
|
+
handle,
|
|
43
|
+
diagnostics: [...parsed.diagnostics, ...handle.diagnostics],
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { observeFrameFit } from './frame-fit.js';
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The basic kinds of the vocabulary: document, stack, text, button and
|
|
3
|
+
* image, plus `ui-unknown`, the fallback of a kind without a renderer.
|
|
4
|
+
*
|
|
5
|
+
* Every value reaches the DOM as text (`Text.data`, `setAttribute`) or as a
|
|
6
|
+
* CSS value typed by ui-style: never as markup, and never as an `on*`
|
|
7
|
+
* attribute.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
PROPERTIES,
|
|
12
|
+
declarationCss,
|
|
13
|
+
typeDeclaration,
|
|
14
|
+
} from '@link-foundation/ui-style';
|
|
15
|
+
import { cssVariable } from '@link-foundation/ui-tokens';
|
|
16
|
+
import { isUnsafeUrl } from '../diagnostics.js';
|
|
17
|
+
import { defineKind } from '../kinds.js';
|
|
18
|
+
import { atom } from '../model.js';
|
|
19
|
+
|
|
20
|
+
/** A custom element holding an empty Text node (its label or value). */
|
|
21
|
+
function withText(tag, ctx) {
|
|
22
|
+
const node = ctx.document.createElement(tag);
|
|
23
|
+
node.appendChild(ctx.document.createTextNode(''));
|
|
24
|
+
return node;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Write the text of a property into a Text node (not into markup). */
|
|
28
|
+
function setText(textNode, element, name) {
|
|
29
|
+
const value = atom(element, name) ?? '';
|
|
30
|
+
if (textNode.data !== value) {
|
|
31
|
+
textNode.data = value;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The CSS context of ui-style `declarationCss`: tokens → `var(--…)`. */
|
|
36
|
+
function cssContext(prefix = '') {
|
|
37
|
+
const refToVar = (ref, fallback) =>
|
|
38
|
+
`var(${cssVariable(ref.path, prefix)}${fallback === undefined ? '' : `, ${fallback}`})`;
|
|
39
|
+
return {
|
|
40
|
+
refToVar,
|
|
41
|
+
variable: (path) => refToVar({ type: 'token-ref', path }),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Set one style property of the node from a property of the element,
|
|
47
|
+
* typed by ui-style; an invalid value is reported and left out.
|
|
48
|
+
*/
|
|
49
|
+
function setStyle(node, element, name, ctx) {
|
|
50
|
+
const css = PROPERTIES[name].css;
|
|
51
|
+
const raws = element.props.get(name);
|
|
52
|
+
if (raws === undefined) {
|
|
53
|
+
node.style.removeProperty(css);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const problems = [];
|
|
57
|
+
const decl = typeDeclaration(name, [...raws], {}, problems);
|
|
58
|
+
if (decl === null) {
|
|
59
|
+
node.style.removeProperty(css);
|
|
60
|
+
ctx.diagnostic('invalid-value', 'error', { property: name });
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
node.style.setProperty(
|
|
64
|
+
css,
|
|
65
|
+
declarationCss(decl, cssContext(ctx.options.prefix))
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
defineKind('document', {
|
|
70
|
+
tag: 'ui-document',
|
|
71
|
+
attributes: { theme: 'string', lang: 'string' },
|
|
72
|
+
create: (el, ctx) => ctx.document.createElement('ui-document'),
|
|
73
|
+
update(node, el, changed, ctx) {
|
|
74
|
+
const title = atom(el, 'title');
|
|
75
|
+
if (
|
|
76
|
+
changed.includes('title') &&
|
|
77
|
+
ctx.options.setTitle === true &&
|
|
78
|
+
title !== undefined
|
|
79
|
+
) {
|
|
80
|
+
ctx.document.title = title;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const STACK_STYLES = ['direction', 'gap', 'padding'];
|
|
86
|
+
|
|
87
|
+
defineKind('stack', {
|
|
88
|
+
tag: 'ui-stack',
|
|
89
|
+
attributes: { direction: 'string', align: 'string' },
|
|
90
|
+
create: (el, ctx) => ctx.document.createElement('ui-stack'),
|
|
91
|
+
update(node, el, changed, ctx) {
|
|
92
|
+
for (const name of STACK_STYLES) {
|
|
93
|
+
if (changed.includes(name)) {
|
|
94
|
+
setStyle(node, el, name, ctx);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
defineKind('text', {
|
|
101
|
+
tag: 'ui-text',
|
|
102
|
+
childrenSlot: null,
|
|
103
|
+
create: (el, ctx) => withText('ui-text', ctx),
|
|
104
|
+
update(node, el, changed) {
|
|
105
|
+
if (changed.includes('value')) {
|
|
106
|
+
setText(node.firstChild, el, 'value');
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
defineKind('button', {
|
|
112
|
+
tag: 'ui-button',
|
|
113
|
+
childrenSlot: null,
|
|
114
|
+
attributes: { variant: 'string', disabled: 'boolean' },
|
|
115
|
+
// A native button: keyboard activation, focus and the button role for free.
|
|
116
|
+
create(el, ctx) {
|
|
117
|
+
const node = ctx.document.createElement('ui-button');
|
|
118
|
+
const button = withText('button', ctx);
|
|
119
|
+
button.setAttribute('type', 'button');
|
|
120
|
+
node.appendChild(button);
|
|
121
|
+
return node;
|
|
122
|
+
},
|
|
123
|
+
eventTarget: (node) => node.firstChild,
|
|
124
|
+
update(node, el, changed) {
|
|
125
|
+
const button = node.firstChild;
|
|
126
|
+
if (changed.includes('label')) {
|
|
127
|
+
setText(button.firstChild, el, 'label');
|
|
128
|
+
}
|
|
129
|
+
if (changed.includes('disabled')) {
|
|
130
|
+
button.toggleAttribute('disabled', atom(el, 'disabled') === 'true');
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
defineKind('image', {
|
|
136
|
+
tag: 'ui-image',
|
|
137
|
+
childrenSlot: null,
|
|
138
|
+
create(el, ctx) {
|
|
139
|
+
const node = ctx.document.createElement('ui-image');
|
|
140
|
+
node.appendChild(ctx.document.createElement('img'));
|
|
141
|
+
return node;
|
|
142
|
+
},
|
|
143
|
+
update(node, el, changed, ctx) {
|
|
144
|
+
const img = node.firstChild;
|
|
145
|
+
if (changed.includes('source')) {
|
|
146
|
+
const source = atom(el, 'source');
|
|
147
|
+
if (source !== undefined && isUnsafeUrl(source)) {
|
|
148
|
+
ctx.diagnostic('unsafe-url', 'error', { property: 'source' });
|
|
149
|
+
img.removeAttribute('src');
|
|
150
|
+
} else if (source === undefined) {
|
|
151
|
+
img.removeAttribute('src');
|
|
152
|
+
} else {
|
|
153
|
+
img.setAttribute('src', source);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// An image without alt text is announced by its file name: alt=""
|
|
157
|
+
// marks it decorative instead, and the author gets a diagnostic.
|
|
158
|
+
if (changed.includes('alt') || img.getAttribute('alt') === null) {
|
|
159
|
+
const alt = atom(el, 'alt');
|
|
160
|
+
if (alt === undefined) {
|
|
161
|
+
ctx.diagnostic('missing-alt', 'warning', { property: 'alt' });
|
|
162
|
+
}
|
|
163
|
+
img.setAttribute('alt', alt ?? '');
|
|
164
|
+
}
|
|
165
|
+
for (const name of ['width', 'height']) {
|
|
166
|
+
if (changed.includes(name)) {
|
|
167
|
+
const value = atom(el, name);
|
|
168
|
+
if (value === undefined) {
|
|
169
|
+
img.removeAttribute(name);
|
|
170
|
+
} else {
|
|
171
|
+
img.setAttribute(name, value);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The fallback of a kind without a renderer (`ui-unknown data-kind="…"`).
|
|
180
|
+
* Not registered under a kind name: the renderer picks it.
|
|
181
|
+
*/
|
|
182
|
+
export const UNKNOWN_KIND = Object.freeze({
|
|
183
|
+
tag: 'ui-unknown',
|
|
184
|
+
create(el, ctx) {
|
|
185
|
+
const node = ctx.document.createElement('ui-unknown');
|
|
186
|
+
node.setAttribute('data-kind', el.kind ?? '');
|
|
187
|
+
return node;
|
|
188
|
+
},
|
|
189
|
+
});
|
package/src/kinds.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The kind registry: one DOM renderer per element kind. A kind renders as a
|
|
3
|
+
* custom element (`ui-KIND`) defined once per window as a plain subclass of
|
|
4
|
+
* `HTMLElement`: no shadow DOM, so page styles and the adopted stylesheet
|
|
5
|
+
* reach every element (light DOM).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {import('./model.js').Element} Element
|
|
10
|
+
*
|
|
11
|
+
* @typedef {object} KindContext
|
|
12
|
+
* @property {Document} document the document nodes are created in
|
|
13
|
+
* @property {Record<string, any>} options the render options
|
|
14
|
+
* @property {(code: string, severity: 'error'|'warning'|'info',
|
|
15
|
+
* at?: Record<string, unknown>) => void} diagnostic report a problem of
|
|
16
|
+
* the current element
|
|
17
|
+
* @property {() => Element[]} children the element models of the current
|
|
18
|
+
* element's children in the store (a kind without a children slot reads
|
|
19
|
+
* sublinks that the projection made child elements, such as `(label ...)`)
|
|
20
|
+
*
|
|
21
|
+
* @typedef {object} KindSpec
|
|
22
|
+
* @property {string} tag a valid custom element name (`ui-button`)
|
|
23
|
+
* @property {(el: Element, ctx: KindContext) => HTMLElement} create build
|
|
24
|
+
* the node; the renderer then calls `update` with every property
|
|
25
|
+
* @property {(node: HTMLElement, el: Element, changed: string[],
|
|
26
|
+
* ctx: KindContext) => void} [update] apply the changed properties
|
|
27
|
+
* @property {null|((node: HTMLElement) => HTMLElement)} [childrenSlot]
|
|
28
|
+
* where the children go (default: the node itself; `null`: no children)
|
|
29
|
+
* @property {(node: HTMLElement) => HTMLElement} [eventTarget] the element
|
|
30
|
+
* the `(on EVENT ...)` listeners go on (default: the node)
|
|
31
|
+
* @property {Record<string, 'string'|'boolean'>} [attributes] properties
|
|
32
|
+
* mirrored as attributes for CSS (`variant` → `variant="filled"`); a
|
|
33
|
+
* boolean attribute is present for `true` and absent otherwise
|
|
34
|
+
* @property {(node: HTMLElement, ctx: KindContext) => void} [destroy]
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
const registry = new Map();
|
|
38
|
+
|
|
39
|
+
const isLower = (c) => c >= 'a' && c <= 'z';
|
|
40
|
+
const isNameChar = (c) =>
|
|
41
|
+
isLower(c) || (c >= '0' && c <= '9') || c === '-' || c === '.' || c === '_';
|
|
42
|
+
|
|
43
|
+
/** Whether `tag` is a valid custom element name (ASCII subset). */
|
|
44
|
+
export function isCustomElementName(tag) {
|
|
45
|
+
if (typeof tag !== 'string' || !isLower(tag[0]) || !tag.includes('-')) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
return [...tag].every(isNameChar);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Check the optional hooks and attributes of a kind spec. */
|
|
52
|
+
function checkHooks(kind, spec) {
|
|
53
|
+
for (const name of ['update', 'destroy', 'eventTarget']) {
|
|
54
|
+
if (spec[name] !== undefined && typeof spec[name] !== 'function') {
|
|
55
|
+
throw new TypeError(`defineKind(${kind}): ${name} must be a function`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const slot = spec.childrenSlot;
|
|
59
|
+
if (slot !== undefined && slot !== null && typeof slot !== 'function') {
|
|
60
|
+
throw new TypeError(
|
|
61
|
+
`defineKind(${kind}): childrenSlot must be a function or null`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
for (const name of Object.keys(spec.attributes ?? {})) {
|
|
65
|
+
// Event handler attributes would run text as code.
|
|
66
|
+
if (name.toLowerCase().startsWith('on')) {
|
|
67
|
+
throw new TypeError(
|
|
68
|
+
`defineKind(${kind}): "${name}" cannot be an attribute (on* attributes run code)`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Check a kind spec; throws a `TypeError` naming the problem.
|
|
76
|
+
* @param {string} kind
|
|
77
|
+
* @param {KindSpec} spec
|
|
78
|
+
* @returns {Readonly<KindSpec>}
|
|
79
|
+
*/
|
|
80
|
+
export function checkKind(kind, spec) {
|
|
81
|
+
if (typeof kind !== 'string' || kind === '') {
|
|
82
|
+
throw new TypeError('defineKind: the kind must be a non-empty string');
|
|
83
|
+
}
|
|
84
|
+
if (spec === null || typeof spec !== 'object') {
|
|
85
|
+
throw new TypeError(`defineKind(${kind}): the spec must be an object`);
|
|
86
|
+
}
|
|
87
|
+
if (!isCustomElementName(spec.tag)) {
|
|
88
|
+
throw new TypeError(
|
|
89
|
+
`defineKind(${kind}): "${spec.tag}" is not a valid custom element name`
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
if (typeof spec.create !== 'function') {
|
|
93
|
+
throw new TypeError(`defineKind(${kind}): create must be a function`);
|
|
94
|
+
}
|
|
95
|
+
checkHooks(kind, spec);
|
|
96
|
+
return Object.freeze({ ...spec });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Register the DOM renderer of a kind (replacing an earlier one).
|
|
101
|
+
* @param {string} kind
|
|
102
|
+
* @param {KindSpec} spec
|
|
103
|
+
* @returns {Readonly<KindSpec>}
|
|
104
|
+
*/
|
|
105
|
+
export function defineKind(kind, spec) {
|
|
106
|
+
const checked = checkKind(kind, spec);
|
|
107
|
+
registry.set(kind, checked);
|
|
108
|
+
return checked;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The renderer of a kind: `overrides` (the `kinds` render option, a Map or
|
|
113
|
+
* an object) first, then the registry.
|
|
114
|
+
* @param {string|null} kind
|
|
115
|
+
* @param {Map<string, KindSpec>|Record<string, KindSpec>} [overrides]
|
|
116
|
+
* @returns {Readonly<KindSpec>|undefined}
|
|
117
|
+
*/
|
|
118
|
+
export function getKind(kind, overrides) {
|
|
119
|
+
if (kind === null || kind === undefined) {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
const own =
|
|
123
|
+
overrides instanceof Map
|
|
124
|
+
? overrides.get(kind)
|
|
125
|
+
: overrides !== undefined && Object.hasOwn(overrides, kind)
|
|
126
|
+
? overrides[kind]
|
|
127
|
+
: undefined;
|
|
128
|
+
return own === undefined ? registry.get(kind) : checkKind(kind, own);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The registered kinds (for documentation and tests). */
|
|
132
|
+
export const registeredKinds = () => [...registry.keys()];
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Define `tag` as a plain custom element in the window, unless it is
|
|
136
|
+
* already defined there (by this renderer or by the page).
|
|
137
|
+
* @param {Window|undefined|null} win
|
|
138
|
+
* @param {string} tag
|
|
139
|
+
*/
|
|
140
|
+
export function ensureTag(win, tag) {
|
|
141
|
+
const elements = win?.customElements;
|
|
142
|
+
if (
|
|
143
|
+
elements === null ||
|
|
144
|
+
elements === undefined ||
|
|
145
|
+
elements.get(tag) !== undefined
|
|
146
|
+
) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
// A fresh class per tag: one constructor cannot back two names.
|
|
150
|
+
elements.define(tag, class extends win.HTMLElement {});
|
|
151
|
+
}
|