@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/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
This is free and unencumbered software released into the public domain.
|
|
2
|
+
|
|
3
|
+
Anyone is free to copy, modify, publish, use, compile, sell, or
|
|
4
|
+
distribute this software, either in source code form or as a compiled
|
|
5
|
+
binary, for any purpose, commercial or non-commercial, and by any
|
|
6
|
+
means.
|
|
7
|
+
|
|
8
|
+
In jurisdictions that recognize copyright laws, the author or authors
|
|
9
|
+
of this software dedicate any and all copyright interest in the
|
|
10
|
+
software to the public domain. We make this dedication for the benefit
|
|
11
|
+
of the public at large and to the detriment of our heirs and
|
|
12
|
+
successors. We intend this dedication to be an overt act of
|
|
13
|
+
relinquishment in perpetuity of all present and future rights to this
|
|
14
|
+
software under copyright law.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
20
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
21
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
|
23
|
+
|
|
24
|
+
For more information, please refer to <https://unlicense.org>
|
package/README.md
CHANGED
|
@@ -1,3 +1,296 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @link-foundation/ui-dom
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The reference DOM renderer of the associative UI framework. A
|
|
4
|
+
[`@link-foundation/ui-store`](../ui-store/README.md) document renders as
|
|
5
|
+
plain custom elements in the light DOM (`ui-document`, `ui-stack`,
|
|
6
|
+
`ui-text`, `ui-button`, `ui-image`), each carrying the stable store ID of
|
|
7
|
+
its element in `data-link-id`. The renderer then follows the store: every
|
|
8
|
+
committed transaction becomes an incremental patch of the affected nodes
|
|
9
|
+
only, applied in one microtask.
|
|
10
|
+
|
|
11
|
+
Styles come from [`ui-style`](../ui-style/README.md) rules and
|
|
12
|
+
[`ui-tokens`](../ui-tokens/README.md) CSS custom properties, adopted once
|
|
13
|
+
per root. `(on press (navigate home))` handlers are data: they dispatch a
|
|
14
|
+
`ui-action` event and never run code. `renderToHTML` writes the same
|
|
15
|
+
markup as a static HTML string.
|
|
16
|
+
|
|
17
|
+
There is no runtime dependency but the workspace packages (`ui-core`,
|
|
18
|
+
`ui-store`, `ui-style`, `ui-tokens`) and, through ui-core,
|
|
19
|
+
`links-notation`.
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import { mountDocument } from '@link-foundation/ui-dom';
|
|
23
|
+
|
|
24
|
+
const { store, handle } = mountDocument(
|
|
25
|
+
document.getElementById('app'),
|
|
26
|
+
`(app: document
|
|
27
|
+
(theme material3)
|
|
28
|
+
(body: stack
|
|
29
|
+
(direction vertical)
|
|
30
|
+
(gap (token space.medium))
|
|
31
|
+
(greeting: text 'Hello, links')
|
|
32
|
+
(ok: button (label 'OK') (variant filled) (on press (navigate home)))))`,
|
|
33
|
+
{
|
|
34
|
+
tokens: tokensLino, // ui-tokens LiNo text
|
|
35
|
+
styles: stylesLino, // ui-style LiNo text
|
|
36
|
+
onAction: (detail) => console.log(detail),
|
|
37
|
+
// { source: 'ok', event: 'press', action: ['navigate', 'home'] }
|
|
38
|
+
}
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
store.setProp('greeting', 'value', ['Hello again']); // one patch, one node
|
|
42
|
+
handle.nodeFor('ok'); // <ui-button data-link-id="ok" variant="filled">
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
renders
|
|
46
|
+
|
|
47
|
+
```html
|
|
48
|
+
<ui-document data-link-id="app" theme="material3">
|
|
49
|
+
<ui-stack
|
|
50
|
+
data-link-id="body"
|
|
51
|
+
style="flex-direction: column; gap: var(--space-medium);"
|
|
52
|
+
direction="vertical"
|
|
53
|
+
>
|
|
54
|
+
<ui-text data-link-id="greeting">Hello, links</ui-text>
|
|
55
|
+
<ui-button data-link-id="ok" variant="filled">
|
|
56
|
+
<button type="button">OK</button>
|
|
57
|
+
</ui-button>
|
|
58
|
+
</ui-stack>
|
|
59
|
+
</ui-document>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The example page [`examples/ui-dom/`](../../examples/ui-dom/) mounts the
|
|
63
|
+
issue-1 samples in a browser:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
node scripts/serve-static.mjs # then open http://127.0.0.1:4173/examples/ui-dom/
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+

|
|
70
|
+
|
|
71
|
+
## Decision: plain custom elements, light DOM
|
|
72
|
+
|
|
73
|
+
- **Plain custom elements, no Lit or other runtime.** Each kind is a
|
|
74
|
+
`customElements.define(tag, class extends HTMLElement {})`; the renderer
|
|
75
|
+
creates and patches the nodes itself from store events, so a component
|
|
76
|
+
library or a template compiler adds nothing but weight. Lit (BSD-3-Clause)
|
|
77
|
+
was studied and not used, to keep zero runtime dependencies besides the
|
|
78
|
+
workspace packages (research "Recommendations" A.2 and C of
|
|
79
|
+
[existing-solutions.md](../../docs/case-studies/issue-1/research/existing-solutions.md)).
|
|
80
|
+
A tag is defined only when `customElements.get(tag)` is undefined, so a
|
|
81
|
+
second copy of the package, or a page that defined the tag first, is safe.
|
|
82
|
+
- **Light DOM, no shadow root per kind.** Page CSS, the adopted stylesheet,
|
|
83
|
+
dev mode (which reads `data-link-id` from any node) and native form
|
|
84
|
+
participation of the inner `<button>` all work with ordinary DOM queries
|
|
85
|
+
and selectors. Shadow DOM per kind may be added later, kind by kind; a
|
|
86
|
+
render into a shadow root container already works (the sheet is adopted
|
|
87
|
+
on that root).
|
|
88
|
+
- **State as attributes and CSS variables.** Style-relevant properties are
|
|
89
|
+
mirrored as attributes (`variant="filled"`) and token values are CSS
|
|
90
|
+
custom properties, so a theme switch only swaps variables, as the
|
|
91
|
+
konard.github.io and immortality projects do for plain JS, React and Vue.
|
|
92
|
+
|
|
93
|
+
## API
|
|
94
|
+
|
|
95
|
+
### `render(container, store, options?)`
|
|
96
|
+
|
|
97
|
+
Renders every element of the store into `container` (roots in document
|
|
98
|
+
order) and subscribes to the store. Returns a handle:
|
|
99
|
+
|
|
100
|
+
| Member | Description |
|
|
101
|
+
| ------------- | ------------------------------------------------------------------------------ |
|
|
102
|
+
| `nodeFor(id)` | the node of a store ID, or `null` |
|
|
103
|
+
| `idFor(node)` | the store ID of a node or of its closest rendered ancestor, or `null` |
|
|
104
|
+
| `flush()` | apply the queued store events now (synchronously); returns how many there were |
|
|
105
|
+
| `destroy()` | remove every node, the store listener and the stylesheet (idempotent) |
|
|
106
|
+
| `store` | the store |
|
|
107
|
+
| `diagnostics` | the diagnostics of the first render (later ones go to `onDiagnostic`) |
|
|
108
|
+
| `styles` | `{ sheet?, element?, release() }` of the stylesheet, or `null` |
|
|
109
|
+
|
|
110
|
+
For every store ID, `handle.idFor(handle.nodeFor(id)) === id`. The IDs are
|
|
111
|
+
kept in a `Map` (ID → node) and a `WeakMap` (node → ID). Anonymous elements
|
|
112
|
+
carry their generated store ID (`_1`, …). The inner native `<button>` of a
|
|
113
|
+
`ui-button` and the `<img>` of a `ui-image` are parts of their element and
|
|
114
|
+
carry no `data-link-id` of their own, so `[data-link-id="ok"]` matches
|
|
115
|
+
exactly one node.
|
|
116
|
+
|
|
117
|
+
| Option | Description |
|
|
118
|
+
| ---------------------- | ----------------------------------------------------------------------------------- |
|
|
119
|
+
| `kinds` | kind renderers of this render (a `Map` or an object), looked up before the registry |
|
|
120
|
+
| `onAction(detail, ev)` | called for every action after the `ui-action` event is dispatched |
|
|
121
|
+
| `onDiagnostic(d)` | called with every diagnostic |
|
|
122
|
+
| `onPatch(events)` | called once per applied patch with its store events |
|
|
123
|
+
| `setTitle` | `true` sets `document.title` from the document's `title` |
|
|
124
|
+
| `tokens` | ui-tokens LiNo text, `{ sets }` of `readTokens`, or resolved tokens |
|
|
125
|
+
| `theme` | the token set (default: the document's `theme`, then the first set) |
|
|
126
|
+
| `styles` | ui-style LiNo text, or the rules of `readStyles` |
|
|
127
|
+
| `css` | extra CSS appended to the sheet |
|
|
128
|
+
| `prefix` | the CSS custom property prefix (`md` gives `--md-color-primary`) |
|
|
129
|
+
| `baseCss` | `false` leaves out the base rules |
|
|
130
|
+
| `adoptStyles` | `false` applies no stylesheet |
|
|
131
|
+
|
|
132
|
+
### `mountDocument(container, text, options?)`
|
|
133
|
+
|
|
134
|
+
Parses Links Notation with ui-core (`options.parseOptions`), creates a
|
|
135
|
+
store with ui-store (`options.storeOptions`) and renders it. Returns
|
|
136
|
+
`{ store, handle, diagnostics }`, the diagnostics of the parser and the
|
|
137
|
+
first render.
|
|
138
|
+
|
|
139
|
+
### Incremental updates
|
|
140
|
+
|
|
141
|
+
The store calls its listener once per committed transaction. The events
|
|
142
|
+
are queued and applied in one microtask, so 1,000 updates in one
|
|
143
|
+
transaction, or several transactions in one task, are one patch.
|
|
144
|
+
|
|
145
|
+
| Store event | DOM change |
|
|
146
|
+
| ----------- | ------------------------------------------------------------------------------ |
|
|
147
|
+
| `insert` | create the node, set `data-link-id`, insert it at its index among its siblings |
|
|
148
|
+
| `update` | the same node; the kind `update` receives only the changed property names |
|
|
149
|
+
| `remove` | the kind `destroy`, remove the node, drop both map entries (children first) |
|
|
150
|
+
| `move` | `insertBefore` at the new index; the node keeps its identity |
|
|
151
|
+
| `rename` | rewrite `data-link-id` and both maps |
|
|
152
|
+
|
|
153
|
+
An event that does not match the rendered tree is reported as a `bad-event`
|
|
154
|
+
diagnostic; it never throws.
|
|
155
|
+
|
|
156
|
+
### Events
|
|
157
|
+
|
|
158
|
+
`(on EVENT ACTION ARG...)` listens to the DOM event of `EVENT` on the
|
|
159
|
+
kind's event target (the native `<button>` of a `ui-button`, so Enter and
|
|
160
|
+
Space work as clicks) and dispatches
|
|
161
|
+
|
|
162
|
+
```js
|
|
163
|
+
new CustomEvent('ui-action', {
|
|
164
|
+
bubbles: true,
|
|
165
|
+
composed: true,
|
|
166
|
+
detail: { source: 'ok', event: 'press', action: ['navigate', 'home'] },
|
|
167
|
+
});
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
on the element node, then calls `options.onAction(detail, event)`.
|
|
171
|
+
`source` is the current store ID (it follows renames).
|
|
172
|
+
|
|
173
|
+
| `EVENT` | DOM event |
|
|
174
|
+
| ------- | -------------- |
|
|
175
|
+
| `press` | `click` |
|
|
176
|
+
| `focus` | `focusin` |
|
|
177
|
+
| `blur` | `focusout` |
|
|
178
|
+
| `hover` | `pointerenter` |
|
|
179
|
+
|
|
180
|
+
Handlers are data: the source contains no `eval` or `new Function`, no
|
|
181
|
+
`on*` attribute is ever set (a kind cannot list one in `attributes`), and
|
|
182
|
+
the action is passed on as names and values for the application to
|
|
183
|
+
interpret. A `navigate` target such as `javascript:…` is reported as
|
|
184
|
+
`unsafe-url`; an image source with a `javascript:`, `data:` or `vbscript:`
|
|
185
|
+
scheme is not set.
|
|
186
|
+
|
|
187
|
+
### `renderToHTML(source, options?)`
|
|
188
|
+
|
|
189
|
+
Static HTML of a document with the same tags and `data-link-id` attributes
|
|
190
|
+
(no hydration). `source` is LiNo text, a store, a ui-core document, a node
|
|
191
|
+
or a list of nodes; `options` takes `kinds`, `onDiagnostic` and `prefix`.
|
|
192
|
+
Text and attribute values are escaped (`& < > " '`), and no `on*`
|
|
193
|
+
attribute or `<script>` element is ever written, even by a custom kind.
|
|
194
|
+
Also available as `@link-foundation/ui-dom/html`.
|
|
195
|
+
|
|
196
|
+
### Styles
|
|
197
|
+
|
|
198
|
+
One stylesheet per render, in this order:
|
|
199
|
+
|
|
200
|
+
1. `BASE_CSS`: zero-specificity (`:where`) layout rules of the basic kinds,
|
|
201
|
+
a visible focus ring and the disabled state;
|
|
202
|
+
2. the token CSS custom properties (`:root, :host { --color-primary: … }`)
|
|
203
|
+
of the theme set;
|
|
204
|
+
3. the compiled style rules (`ui-button[variant='filled'] { background-color:
|
|
205
|
+
var(--color-primary); }`);
|
|
206
|
+
4. `options.css`.
|
|
207
|
+
|
|
208
|
+
The sheet is adopted (`adoptedStyleSheets`) on the root node of the
|
|
209
|
+
container, a document or a shadow root, once per root: renders that share
|
|
210
|
+
a root and the same CSS share one sheet, removed when the last of them is
|
|
211
|
+
destroyed. Without `adoptedStyleSheets` one `<style data-ui-dom>` element
|
|
212
|
+
is used instead. `buildCss(options, theme?)` returns the CSS text.
|
|
213
|
+
|
|
214
|
+
## Kind registry
|
|
215
|
+
|
|
216
|
+
```js
|
|
217
|
+
import { defineKind } from '@link-foundation/ui-dom';
|
|
218
|
+
|
|
219
|
+
defineKind('asset', {
|
|
220
|
+
tag: 'ui-asset',
|
|
221
|
+
attributes: { license: 'string' }, // mirrored for CSS selectors
|
|
222
|
+
create: (el, ctx) => ctx.document.createElement('ui-asset'),
|
|
223
|
+
update(node, el, changed, ctx) {
|
|
224
|
+
if (changed.includes('source')) {
|
|
225
|
+
node.textContent = el.props.get('source')?.[0] ?? '';
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
| Spec field | Description |
|
|
232
|
+
| -------------- | -------------------------------------------------------------------------------------------- |
|
|
233
|
+
| `tag` | a valid custom element name; defined on first use per window |
|
|
234
|
+
| `create` | build the node; `update` then runs with every property |
|
|
235
|
+
| `update` | apply the changed properties (`changed` lists their names) |
|
|
236
|
+
| `childrenSlot` | where the children go: a function of the node (default: the node itself), or `null` for none |
|
|
237
|
+
| `eventTarget` | the element the `(on ...)` listeners go on (default: the node) |
|
|
238
|
+
| `attributes` | `{ name: 'string' \| 'boolean' }` properties mirrored as attributes; `on*` names are refused |
|
|
239
|
+
| `destroy` | called before the node is removed |
|
|
240
|
+
|
|
241
|
+
The element model `el` has `id`, `name`, `kind`, `positional`,
|
|
242
|
+
`properties`, `unknown` and `props`: a `Map` of every property by name,
|
|
243
|
+
where the positional values take their ui-core vocabulary names (`value` of
|
|
244
|
+
a `text`, `label` of a `button`, `source` of an `image`) and named
|
|
245
|
+
properties override them. `ctx` has `document`, `options` and
|
|
246
|
+
`diagnostic(code, severity, at?)`.
|
|
247
|
+
|
|
248
|
+
The `kinds` render option overrides the registry for one render. A kind
|
|
249
|
+
without a renderer renders as `<ui-unknown data-kind="…">` (its children
|
|
250
|
+
still render inside it) with an `unknown-kind` warning; a renderer that
|
|
251
|
+
throws is reported as `kind-error` and the element falls back to
|
|
252
|
+
`ui-unknown`. Rendering never throws for document content.
|
|
253
|
+
|
|
254
|
+
### Basic kinds
|
|
255
|
+
|
|
256
|
+
| Kind | Element | Properties |
|
|
257
|
+
| ---------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
258
|
+
| `document` | `ui-document` | `theme`, `lang` (attributes); `title` sets `document.title` only with `setTitle: true` |
|
|
259
|
+
| `stack` | `ui-stack` | `direction` (`flex-direction`), `gap`, `padding` (typed by ui-style, tokens as CSS variables), `align` |
|
|
260
|
+
| `text` | `ui-text` | `value` (the positional text) as a text node |
|
|
261
|
+
| `button` | `ui-button > button[type=button]` | `label`, `variant` (attribute), `disabled` (attribute and native `disabled`) |
|
|
262
|
+
| `image` | `ui-image > img` | `source` (`src`; unsafe schemes are refused), `alt` (`alt=""` and `missing-alt` when absent), `width`, `height` |
|
|
263
|
+
|
|
264
|
+
## Diagnostics
|
|
265
|
+
|
|
266
|
+
`{ code, severity, message, at }`, as in ui-core; `at` names the `element`
|
|
267
|
+
(store ID) and `kind`.
|
|
268
|
+
|
|
269
|
+
| Code | Severity | When |
|
|
270
|
+
| ----------------- | -------- | --------------------------------------------------------------------- |
|
|
271
|
+
| `unknown-kind` | warning | no renderer for the kind; rendered as `ui-unknown` |
|
|
272
|
+
| `kind-error` | error | a kind renderer threw |
|
|
273
|
+
| `missing-alt` | warning | an `image` without `alt` (rendered with `alt=""`) |
|
|
274
|
+
| `unsafe-url` | error | a `javascript:`, `data:` or `vbscript:` URL in a source or `navigate` |
|
|
275
|
+
| `invalid-handler` | error | an `(on ...)` without an event and an action name |
|
|
276
|
+
| `unknown-event` | warning | an `(on EVENT ...)` event without a DOM mapping |
|
|
277
|
+
| `unknown-action` | warning | an action that is not a name |
|
|
278
|
+
| `invalid-value` | error | a `stack` `direction`, `gap` or `padding` value of the wrong type |
|
|
279
|
+
| `bad-event` | error | a store event that does not match the rendered tree |
|
|
280
|
+
|
|
281
|
+
## Tests
|
|
282
|
+
|
|
283
|
+
```bash
|
|
284
|
+
node --test packages/ui-dom/tests/*.test.js
|
|
285
|
+
npx playwright test packages/ui-dom/e2e
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
The unit tests run in [jsdom](https://github.com/jsdom/jsdom) (MIT, a dev
|
|
289
|
+
dependency), a fresh window per test. `UPDATE_SNAPSHOTS=1` rewrites
|
|
290
|
+
`tests/__snapshots__/document.html`. The Playwright check opens the example
|
|
291
|
+
page, asserts that `[data-link-id="ok"]` is visible with the token colour,
|
|
292
|
+
clicks it, changes the greeting, runs axe-core and attaches a screenshot.
|
|
293
|
+
|
|
294
|
+
## License
|
|
295
|
+
|
|
296
|
+
[Unlicense](LICENSE) (public domain).
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@link-foundation/ui-dom",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Reference DOM renderer of the associative UI framework written in Links Notation: a ui-store document as plain custom elements in the light DOM, patched incrementally from store events, with adopted token and style CSS and static HTML output",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./src/index.d.ts",
|
|
9
|
+
"default": "./src/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./html": {
|
|
12
|
+
"types": "./src/html.d.ts",
|
|
13
|
+
"default": "./src/html.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"types": "./src/index.d.ts",
|
|
17
|
+
"files": [
|
|
18
|
+
"src/",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"ui",
|
|
24
|
+
"links-notation",
|
|
25
|
+
"dom",
|
|
26
|
+
"renderer",
|
|
27
|
+
"custom-elements",
|
|
28
|
+
"web-components"
|
|
29
|
+
],
|
|
30
|
+
"license": "Unlicense",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/link-foundation/ui.git",
|
|
34
|
+
"directory": "packages/ui-dom"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/link-foundation/ui/tree/main/packages/ui-dom#readme",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/link-foundation/ui/issues"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=20"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@link-foundation/ui-core": "^0.1.0",
|
|
45
|
+
"@link-foundation/ui-store": "^0.1.0",
|
|
46
|
+
"@link-foundation/ui-style": "^0.1.0",
|
|
47
|
+
"@link-foundation/ui-tokens": "^0.1.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"jsdom": "^30.1.3",
|
|
51
|
+
"test-anywhere": "^0.8.48"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnostics of the DOM renderer, in the ui-core shape
|
|
3
|
+
* `{ code, severity, message, at }`. Rendering never throws on document
|
|
4
|
+
* content: every problem becomes a diagnostic.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const where = (at) =>
|
|
8
|
+
at.element === undefined ? 'The document' : `Element "${at.element}"`;
|
|
9
|
+
|
|
10
|
+
const MESSAGES = {
|
|
11
|
+
'unknown-kind': (at) =>
|
|
12
|
+
`${where(at)} has the kind "${at.kind}", which has no DOM renderer; it is rendered as ui-unknown`,
|
|
13
|
+
'kind-error': (at) =>
|
|
14
|
+
`${where(at)}: the renderer of kind "${at.kind}" failed (${at.error})`,
|
|
15
|
+
'missing-alt': (at) =>
|
|
16
|
+
`${where(at)} is an image without alt text; alt="" marks it decorative`,
|
|
17
|
+
'unsafe-url': (at) =>
|
|
18
|
+
`${where(at)} uses an unsafe URL${at.property ? ` in "${at.property}"` : ''}; it is ignored`,
|
|
19
|
+
'invalid-handler': (at) =>
|
|
20
|
+
`${where(at)} has a handler without a valid event and actions`,
|
|
21
|
+
'unknown-action': (at) =>
|
|
22
|
+
`${where(at)} has a handler with the unknown action "${at.action}"; it is ignored`,
|
|
23
|
+
'unknown-event': (at) =>
|
|
24
|
+
`${where(at)} handles the event "${at.event}", which the DOM renderer does not map; it is ignored`,
|
|
25
|
+
'invalid-value': (at) =>
|
|
26
|
+
`${where(at)} has an invalid value of "${at.property}"; it is ignored`,
|
|
27
|
+
'bad-event': (at) =>
|
|
28
|
+
`The store event ${at.type} of "${at.element}" does not match the rendered tree; it is ignored`,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} code
|
|
33
|
+
* @param {'error'|'warning'|'info'} severity
|
|
34
|
+
* @param {Record<string, unknown>} at
|
|
35
|
+
*/
|
|
36
|
+
export function diagnostic(code, severity, at) {
|
|
37
|
+
const message = MESSAGES[code]?.(at) ?? code;
|
|
38
|
+
return Object.freeze({ code, severity, message, at: Object.freeze(at) });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const UNSAFE_SCHEMES = ['javascript:', 'data:', 'vbscript:'];
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Whether a URL uses a scheme that runs code (`javascript:`, `vbscript:`)
|
|
45
|
+
* or embeds content (`data:`). Control characters and spaces are dropped
|
|
46
|
+
* first, as browsers do when they read a URL.
|
|
47
|
+
* @param {unknown} url
|
|
48
|
+
*/
|
|
49
|
+
export function isUnsafeUrl(url) {
|
|
50
|
+
let text = '';
|
|
51
|
+
for (const c of String(url ?? '')) {
|
|
52
|
+
if (c.codePointAt(0) > 0x20) {
|
|
53
|
+
text += c;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
text = text.toLowerCase();
|
|
57
|
+
return UNSAFE_SCHEMES.some((scheme) => text.startsWith(scheme));
|
|
58
|
+
}
|
package/src/events.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Behaviour (docs/spec/behaviour.md): `(on EVENT ACTION...)` handlers. An
|
|
3
|
+
* action is data: the renderer never evaluates it and never writes an
|
|
4
|
+
* `on*` attribute. When the event happens on the element, the renderer
|
|
5
|
+
* dispatches one `ui-action` CustomEvent per action from the element
|
|
6
|
+
* (bubbling, composed) and calls the `onAction` render option; the host
|
|
7
|
+
* decides what `(navigate home)` does.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { isUnsafeUrl } from './diagnostics.js';
|
|
11
|
+
import { vocabulary } from './model.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* UI events → the DOM events that trigger them. `change` is `ui-change`, a
|
|
15
|
+
* CustomEvent a control dispatches once per committed value change (its
|
|
16
|
+
* `detail.value` is the new value), not the native `change` of an input,
|
|
17
|
+
* so a control that is not a native input fires it too.
|
|
18
|
+
*/
|
|
19
|
+
export const DOM_EVENTS = Object.freeze({
|
|
20
|
+
press: 'click',
|
|
21
|
+
close: 'ui-close',
|
|
22
|
+
focus: 'focusin',
|
|
23
|
+
blur: 'focusout',
|
|
24
|
+
hover: 'pointerenter',
|
|
25
|
+
change: 'ui-change',
|
|
26
|
+
select: 'ui-select',
|
|
27
|
+
activate: 'ui-activate',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** Whether a name is a vocabulary action (`navigate`, `emit`...). */
|
|
31
|
+
const isVocabularyAction = (name) => vocabulary().actions.has(name);
|
|
32
|
+
|
|
33
|
+
/** A frozen deep copy of an action link (the event detail is data). */
|
|
34
|
+
function freeze(value) {
|
|
35
|
+
return Array.isArray(value) ? Object.freeze(value.map(freeze)) : value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The valid handlers of an element; problems are reported and the
|
|
40
|
+
* offending action (or handler) is left out.
|
|
41
|
+
* @param {import('./model.js').Element} element
|
|
42
|
+
* @param {(code: string, severity: string, at?: object) => void} report
|
|
43
|
+
* @param {(name: string) => boolean} [isAction] which action names are
|
|
44
|
+
* known; defaults to the vocabulary actions (a host with an actions
|
|
45
|
+
* registry passes its own check)
|
|
46
|
+
* @returns {{event: string, domEvent: string, actions: readonly any[]}[]}
|
|
47
|
+
*/
|
|
48
|
+
export function handlersOf(element, report, isAction = isVocabularyAction) {
|
|
49
|
+
const handlers = [];
|
|
50
|
+
for (const property of element.properties) {
|
|
51
|
+
if (property.name !== 'on') {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const [event, ...links] = property.values;
|
|
55
|
+
if (typeof event !== 'string' || links.length === 0) {
|
|
56
|
+
report('invalid-handler', 'error', { property: 'on' });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const domEvent = Object.hasOwn(DOM_EVENTS, event)
|
|
60
|
+
? DOM_EVENTS[event]
|
|
61
|
+
: undefined;
|
|
62
|
+
if (domEvent === undefined) {
|
|
63
|
+
report('unknown-event', 'warning', { property: 'on', event });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const actions = [];
|
|
67
|
+
for (const link of links) {
|
|
68
|
+
if (!Array.isArray(link) || typeof link[0] !== 'string') {
|
|
69
|
+
report('invalid-handler', 'error', { property: 'on' });
|
|
70
|
+
} else if (!isAction(link[0])) {
|
|
71
|
+
report('unknown-action', 'warning', {
|
|
72
|
+
property: 'on',
|
|
73
|
+
action: link[0],
|
|
74
|
+
});
|
|
75
|
+
} else if (link[0] === 'navigate' && isUnsafeUrl(link[1])) {
|
|
76
|
+
report('unsafe-url', 'error', { property: 'on' });
|
|
77
|
+
} else {
|
|
78
|
+
actions.push(freeze(link));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (actions.length > 0) {
|
|
82
|
+
handlers.push({ event, domEvent, actions: Object.freeze(actions) });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return handlers;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Listen for the handlers of an element.
|
|
90
|
+
* @param {HTMLElement} node the element `ui-action` is dispatched from
|
|
91
|
+
* @param {EventTarget} target the element the DOM events come from
|
|
92
|
+
* @param {ReturnType<typeof handlersOf>} handlers
|
|
93
|
+
* @param {{idFor: (node: Node) => string|null,
|
|
94
|
+
* onAction?: (detail: object, event: Event) => void,
|
|
95
|
+
* diagnostic?: Function}} host
|
|
96
|
+
* @returns {() => void} remove the listeners
|
|
97
|
+
*/
|
|
98
|
+
export function bindHandlers(node, target, handlers, host) {
|
|
99
|
+
const win = node.ownerDocument.defaultView;
|
|
100
|
+
const listeners = handlers.map(({ event, domEvent, actions }) => {
|
|
101
|
+
const listener = (domEventObject) => {
|
|
102
|
+
for (const action of actions) {
|
|
103
|
+
const resolved = resolveItemAction(action, domEventObject.detail?.item);
|
|
104
|
+
if (resolved[0] === 'navigate' && isUnsafeUrl(resolved[1])) {
|
|
105
|
+
host.diagnostic?.('unsafe-url', 'error', { property: 'on' });
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
// The ID at dispatch time: a rename after binding is honoured.
|
|
109
|
+
const detail = Object.freeze({
|
|
110
|
+
source: host.idFor(node),
|
|
111
|
+
event,
|
|
112
|
+
action: resolved,
|
|
113
|
+
...(domEventObject.detail?.target === undefined
|
|
114
|
+
? {}
|
|
115
|
+
: {
|
|
116
|
+
target: domEventObject.detail.target,
|
|
117
|
+
selection: domEventObject.detail.selection,
|
|
118
|
+
}),
|
|
119
|
+
});
|
|
120
|
+
node.dispatchEvent(
|
|
121
|
+
new win.CustomEvent('ui-action', {
|
|
122
|
+
bubbles: true,
|
|
123
|
+
composed: true,
|
|
124
|
+
detail,
|
|
125
|
+
})
|
|
126
|
+
);
|
|
127
|
+
host.onAction?.(detail, domEventObject);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
target.addEventListener(domEvent, listener);
|
|
131
|
+
return [domEvent, listener];
|
|
132
|
+
});
|
|
133
|
+
return () => {
|
|
134
|
+
for (const [domEvent, listener] of listeners) {
|
|
135
|
+
target.removeEventListener(domEvent, listener);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Resolve item references from data-kind events by own-property traversal only. */
|
|
141
|
+
function resolveItemAction(action, item) {
|
|
142
|
+
if (item === undefined) {
|
|
143
|
+
return action;
|
|
144
|
+
}
|
|
145
|
+
const resolve = (value) => {
|
|
146
|
+
const reference =
|
|
147
|
+
Array.isArray(value) &&
|
|
148
|
+
value[0] === 'param' &&
|
|
149
|
+
typeof value[1] === 'string' &&
|
|
150
|
+
value[1].startsWith('item.')
|
|
151
|
+
? value[1].slice(5)
|
|
152
|
+
: null;
|
|
153
|
+
if (Array.isArray(value) && reference === null) {
|
|
154
|
+
return Object.freeze(value.map(resolve));
|
|
155
|
+
}
|
|
156
|
+
if (reference === null) {
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
159
|
+
let current = item;
|
|
160
|
+
for (const name of reference.split('.')) {
|
|
161
|
+
if (
|
|
162
|
+
['__proto__', 'prototype', 'constructor'].includes(name) ||
|
|
163
|
+
current === null ||
|
|
164
|
+
typeof current !== 'object' ||
|
|
165
|
+
!Object.hasOwn(current, name)
|
|
166
|
+
) {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
current = current[name];
|
|
170
|
+
}
|
|
171
|
+
return current;
|
|
172
|
+
};
|
|
173
|
+
return resolve(action);
|
|
174
|
+
}
|