@astl/player 0.0.0 → 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/CHANGELOG.md +48 -0
- package/LICENSE +202 -0
- package/README.md +37 -0
- package/dist/a11y.d.ts +41 -0
- package/dist/a11y.d.ts.map +1 -0
- package/dist/a11y.js +101 -0
- package/dist/a11y.js.map +1 -0
- package/dist/attempt/controller.d.ts +104 -0
- package/dist/attempt/controller.d.ts.map +1 -0
- package/dist/attempt/controller.js +325 -0
- package/dist/attempt/controller.js.map +1 -0
- package/dist/checker/http.d.ts +17 -0
- package/dist/checker/http.d.ts.map +1 -0
- package/dist/checker/http.js +115 -0
- package/dist/checker/http.js.map +1 -0
- package/dist/define.d.ts +35 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +84 -0
- package/dist/define.js.map +1 -0
- package/dist/element/base.d.ts +83 -0
- package/dist/element/base.d.ts.map +1 -0
- package/dist/element/base.js +239 -0
- package/dist/element/base.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/interaction/index.d.ts +12 -0
- package/dist/interaction/index.d.ts.map +1 -0
- package/dist/interaction/index.js +4 -0
- package/dist/interaction/index.js.map +1 -0
- package/dist/interaction/keys.d.ts +11 -0
- package/dist/interaction/keys.d.ts.map +1 -0
- package/dist/interaction/keys.js +13 -0
- package/dist/interaction/keys.js.map +1 -0
- package/dist/interaction/pick-and-place.d.ts +120 -0
- package/dist/interaction/pick-and-place.d.ts.map +1 -0
- package/dist/interaction/pick-and-place.js +395 -0
- package/dist/interaction/pick-and-place.js.map +1 -0
- package/dist/interaction/roving-focus.d.ts +44 -0
- package/dist/interaction/roving-focus.d.ts.map +1 -0
- package/dist/interaction/roving-focus.js +115 -0
- package/dist/interaction/roving-focus.js.map +1 -0
- package/dist/messages/en.json +53 -0
- package/dist/messages/help/en.json +14 -0
- package/dist/messages/help/pl.json +14 -0
- package/dist/messages/pl.json +53 -0
- package/dist/messages.d.ts +7 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +18 -0
- package/dist/messages.js.map +1 -0
- package/dist/player/book.d.ts +13 -0
- package/dist/player/book.d.ts.map +1 -0
- package/dist/player/book.js +65 -0
- package/dist/player/book.js.map +1 -0
- package/dist/player/help.d.ts +55 -0
- package/dist/player/help.d.ts.map +1 -0
- package/dist/player/help.js +484 -0
- package/dist/player/help.js.map +1 -0
- package/dist/player/player.d.ts +87 -0
- package/dist/player/player.d.ts.map +1 -0
- package/dist/player/player.js +1229 -0
- package/dist/player/player.js.map +1 -0
- package/dist/player/styled.d.ts +10 -0
- package/dist/player/styled.d.ts.map +1 -0
- package/dist/player/styled.js +213 -0
- package/dist/player/styled.js.map +1 -0
- package/dist/player/styles.d.ts +3 -0
- package/dist/player/styles.d.ts.map +1 -0
- package/dist/player/styles.js +355 -0
- package/dist/player/styles.js.map +1 -0
- package/dist/player/templates.d.ts +25 -0
- package/dist/player/templates.d.ts.map +1 -0
- package/dist/player/templates.js +101 -0
- package/dist/player/templates.js.map +1 -0
- package/dist/player/view.d.ts +44 -0
- package/dist/player/view.d.ts.map +1 -0
- package/dist/player/view.js +231 -0
- package/dist/player/view.js.map +1 -0
- package/dist/runtime.d.ts +45 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +48 -0
- package/dist/runtime.js.map +1 -0
- package/package.json +45 -4
- package/src/a11y.ts +134 -0
- package/src/attempt/controller.ts +381 -0
- package/src/checker/http.ts +149 -0
- package/src/define.ts +114 -0
- package/src/element/base.ts +310 -0
- package/src/index.ts +18 -0
- package/src/interaction/index.ts +11 -0
- package/src/interaction/keys.ts +16 -0
- package/src/interaction/pick-and-place.ts +464 -0
- package/src/interaction/roving-focus.ts +133 -0
- package/src/messages/en.json +53 -0
- package/src/messages/help/en.json +14 -0
- package/src/messages/help/pl.json +14 -0
- package/src/messages/pl.json +53 -0
- package/src/messages.ts +21 -0
- package/src/player/book.ts +70 -0
- package/src/player/help.ts +585 -0
- package/src/player/player.ts +1368 -0
- package/src/player/styled.ts +247 -0
- package/src/player/styles.ts +355 -0
- package/src/player/templates.ts +142 -0
- package/src/player/view.ts +294 -0
- package/src/runtime.ts +95 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The style template stylesheet: one CSSStyleSheet, generated from every registered template and adopted by every
|
|
3
|
+
* `<astl-player>`, rebuilt in place when registrations change (so mounted players restyle without a reload).
|
|
4
|
+
*
|
|
5
|
+
* - Document scope: on `.root` (canvas and chrome), from `<astl-doc style-template>` (mirrored to
|
|
6
|
+
* `.root[data-style-template]`), else from `<astl-player style-template>` (the host's default).
|
|
7
|
+
* - Component scope: on `.canvas <tag>[style-template]` and its subtree, for the tags the template allows.
|
|
8
|
+
* - Precedence by cascade layers: component, then document, then the player default; tokens reach the component's
|
|
9
|
+
* subtree by inheritance, `::part()` rules of a closer scope win.
|
|
10
|
+
* - Light values for `light`, no theme and `auto` on a light system; dark values for `dark` and for `auto` under
|
|
11
|
+
* `prefers-color-scheme: dark`. Nothing applies in `hc` or under `forced-colors: active`, and under
|
|
12
|
+
* `prefers-reduced-motion: reduce` durations stay zero whatever a template says.
|
|
13
|
+
* - Values are checked again here (`isSafeStyleValue`, `PART_PROPERTIES`): templates are trusted, but one bad value
|
|
14
|
+
* must not break the sheet every player shares.
|
|
15
|
+
*/
|
|
16
|
+
import type { Declarations, StyleTemplate, TokenOverrides } from '@astl/core';
|
|
17
|
+
import { isSafeStyleValue, PART_PROPERTIES } from '@astl/tokens';
|
|
18
|
+
import { runtime } from '../runtime.js';
|
|
19
|
+
|
|
20
|
+
/** The attribute on `.root` that mirrors the mounted view's `<astl-doc style-template>`. */
|
|
21
|
+
export const DOCUMENT_TEMPLATE_ATTRIBUTE = 'data-style-template';
|
|
22
|
+
|
|
23
|
+
const NAME = /^[a-z][a-z0-9-]*$/;
|
|
24
|
+
const TAG = /^[a-z][a-z0-9]*-[a-z0-9-]*$/;
|
|
25
|
+
const NOT_HC = ':not([data-theme="hc"])';
|
|
26
|
+
|
|
27
|
+
/** Token declarations that are safe to write (a bad value is dropped, never allowed to break the sheet). */
|
|
28
|
+
function tokenLines(values: TokenOverrides | undefined): string {
|
|
29
|
+
return Object.entries(values ?? {})
|
|
30
|
+
.filter(([name, value]) => NAME.test(name) && isSafeStyleValue(value))
|
|
31
|
+
.map(([name, value]) => ` --astl-${name}: ${value};\n`)
|
|
32
|
+
.join('');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Part declarations: allowed properties (no borders, colours or display: verdicts and focus stay) and safe values. */
|
|
36
|
+
function partLines(declarations: Declarations): string {
|
|
37
|
+
return Object.entries(declarations)
|
|
38
|
+
.filter(([property, value]) => PART_PROPERTIES.has(property) && isSafeStyleValue(value))
|
|
39
|
+
.map(([property, value]) => ` ${property}: ${value};\n`)
|
|
40
|
+
.join('');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const rule = (selectors: readonly string[], body: string): string =>
|
|
44
|
+
body === '' ? '' : `${selectors.join(',\n')} {\n${body}}\n`;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Rules of one template at one place: `host` adds conditions on the player itself, `target` selects inside its shadow
|
|
48
|
+
* root, `parts` maps a component tag to the selector of its elements there.
|
|
49
|
+
*/
|
|
50
|
+
function templateRules(
|
|
51
|
+
template: StyleTemplate,
|
|
52
|
+
host: string,
|
|
53
|
+
target: string,
|
|
54
|
+
parts: (tag: string) => string | null,
|
|
55
|
+
): string {
|
|
56
|
+
const at = (condition: string) => `:host(${host}${condition}) ${target}`;
|
|
57
|
+
const scheme = (query: string, body: string) =>
|
|
58
|
+
body === '' ? '' : `@media ${query} {\n${rule([at('[data-theme="auto"]')], body)}}\n`;
|
|
59
|
+
const light = tokenLines(template.light);
|
|
60
|
+
const dark = tokenLines(template.dark);
|
|
61
|
+
// `auto` takes the light values only when the system is not dark: a value set for light alone must never reach a
|
|
62
|
+
// dark scheme.
|
|
63
|
+
const out = [
|
|
64
|
+
rule([at(NOT_HC)], tokenLines(template.tokens)),
|
|
65
|
+
rule([at(':not([data-theme])'), at('[data-theme="light"]')], light),
|
|
66
|
+
scheme('not all and (prefers-color-scheme: dark)', light),
|
|
67
|
+
rule([at('[data-theme="dark"]')], dark),
|
|
68
|
+
scheme('(prefers-color-scheme: dark)', dark),
|
|
69
|
+
];
|
|
70
|
+
for (const [tag, byPart] of Object.entries(template.parts ?? {})) {
|
|
71
|
+
const scope = TAG.test(tag) ? parts(tag) : null;
|
|
72
|
+
if (scope === null) continue;
|
|
73
|
+
for (const [part, declarations] of Object.entries(byPart)) {
|
|
74
|
+
if (NAME.test(part))
|
|
75
|
+
out.push(rule([`:host(${host}${NOT_HC}) ${scope}::part(${part})`], partLines(declarations)));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out.join('');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The stylesheet text for these templates; `tags` are the registered component tags. */
|
|
82
|
+
export function styleTemplatesCss(templates: readonly StyleTemplate[], tags: readonly string[]): string {
|
|
83
|
+
const valid = templates.filter((t) => NAME.test(t.name));
|
|
84
|
+
const document = valid.filter((t) => t.scopes.includes('document'));
|
|
85
|
+
const component = valid.filter((t) => t.scopes.includes('component'));
|
|
86
|
+
const docAttribute = (name: string) => `[${DOCUMENT_TEMPLATE_ATTRIBUTE}="${name}"]`;
|
|
87
|
+
// The host's default applies only when the view names no document template this player knows.
|
|
88
|
+
const noDocumentTemplate =
|
|
89
|
+
document.length === 0 ? '.root' : `.root:not(${document.map((t) => docAttribute(t.name)).join(', ')})`;
|
|
90
|
+
|
|
91
|
+
const defaults = document.map((t) =>
|
|
92
|
+
templateRules(
|
|
93
|
+
t,
|
|
94
|
+
`[style-template="${t.name}"]`,
|
|
95
|
+
noDocumentTemplate,
|
|
96
|
+
(tag) => `${noDocumentTemplate} ${tag}`,
|
|
97
|
+
),
|
|
98
|
+
);
|
|
99
|
+
const documents = document.map((t) => {
|
|
100
|
+
const root = `.root${docAttribute(t.name)}`;
|
|
101
|
+
return templateRules(t, '', root, (tag) => `${root} ${tag}`);
|
|
102
|
+
});
|
|
103
|
+
const components = component.flatMap((t) => {
|
|
104
|
+
const allowed = (t.components ?? tags).filter((tag) => TAG.test(tag));
|
|
105
|
+
const element = (tag: string) => `.canvas ${tag}[style-template="${t.name}"]`;
|
|
106
|
+
// One rule list per tag keeps every selector simple: `.canvas astl-gap[style-template="notebook"]`.
|
|
107
|
+
return allowed.map((tag) =>
|
|
108
|
+
templateRules(t, '', element(tag), (owner) => (owner === tag ? element(tag) : null)),
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
const layer = (name: string, rules: readonly string[]) => `@layer ${name} {\n${rules.join('')}}\n`;
|
|
112
|
+
return [
|
|
113
|
+
'@layer astl-default, astl-document, astl-component;\n',
|
|
114
|
+
'@media (forced-colors: none) {\n',
|
|
115
|
+
layer('astl-default', defaults),
|
|
116
|
+
layer('astl-document', documents),
|
|
117
|
+
layer('astl-component', components),
|
|
118
|
+
'}\n',
|
|
119
|
+
// Outside the layers, so it beats every template: reduced motion keeps zero durations.
|
|
120
|
+
'@media (prefers-reduced-motion: reduce) {\n',
|
|
121
|
+
'.root,\n.canvas [style-template] {\n --astl-duration-fast: 0ms;\n --astl-duration-normal: 0ms;\n}\n',
|
|
122
|
+
'}\n',
|
|
123
|
+
].join('');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let sheet: CSSStyleSheet | null = null;
|
|
127
|
+
let built = -1;
|
|
128
|
+
|
|
129
|
+
/** The one template stylesheet of this module instance, up to date with the registrations. */
|
|
130
|
+
export function styleTemplateSheet(): CSSStyleSheet {
|
|
131
|
+
sheet ??= new CSSStyleSheet();
|
|
132
|
+
if (built !== runtime.version) {
|
|
133
|
+
sheet.replaceSync(styleTemplatesCss([...runtime.styleTemplates.values()], [...runtime.elements.keys()]));
|
|
134
|
+
built = runtime.version;
|
|
135
|
+
}
|
|
136
|
+
return sheet;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** After a registration: rebuilds the sheet in place if players already adopted it. */
|
|
140
|
+
export function refreshStyleTemplateSheet(): void {
|
|
141
|
+
if (sheet !== null) styleTemplateSheet();
|
|
142
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AttributeSpec,
|
|
3
|
+
allAttributes,
|
|
4
|
+
BLOCK_TAGS,
|
|
5
|
+
CAPTION_TAG,
|
|
6
|
+
type ChildSpec,
|
|
7
|
+
COLUMN_TAG,
|
|
8
|
+
COLUMNS_TAG,
|
|
9
|
+
CONTENT_ATTRIBUTES,
|
|
10
|
+
type ComponentManifest,
|
|
11
|
+
DOC_ATTRIBUTES,
|
|
12
|
+
DOC_TAG,
|
|
13
|
+
FIGURE_TAG,
|
|
14
|
+
HELP_ATTRIBUTES,
|
|
15
|
+
INERT_STYLE,
|
|
16
|
+
INLINE_TAGS,
|
|
17
|
+
inertStyles,
|
|
18
|
+
isOpaqueId,
|
|
19
|
+
isSafeUrl,
|
|
20
|
+
PAGE_ATTRIBUTES,
|
|
21
|
+
PAGE_TAG,
|
|
22
|
+
REMOVED_WITH_CONTENT,
|
|
23
|
+
TAG_ATTRIBUTES,
|
|
24
|
+
URL_ATTRIBUTES,
|
|
25
|
+
type UrlPolicy,
|
|
26
|
+
} from '@astl/core';
|
|
27
|
+
|
|
28
|
+
/** A load failure with a message code (`error.<code>` in the player catalog). */
|
|
29
|
+
export class LoadError extends Error {
|
|
30
|
+
readonly code: string;
|
|
31
|
+
|
|
32
|
+
constructor(code: string) {
|
|
33
|
+
super(code);
|
|
34
|
+
this.name = 'LoadError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Lowercase hex SHA-256 of the UTF-8 text; null where WebCrypto is unavailable (insecure contexts). */
|
|
40
|
+
export async function sha256Hex(text: string): Promise<string | null> {
|
|
41
|
+
const subtle = globalThis.crypto?.subtle;
|
|
42
|
+
if (subtle === undefined) return null;
|
|
43
|
+
const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
44
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A light-DOM `<astl-doc>` is a compiled view when every id on a custom element in it is opaque. */
|
|
48
|
+
export function isView(doc: Element): boolean {
|
|
49
|
+
return Array.from(doc.querySelectorAll('[id]'))
|
|
50
|
+
.filter((el) => el.localName.includes('-'))
|
|
51
|
+
.every((el) => isOpaqueId(el.id));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Attributes an unknown custom element keeps: enough for the "unsupported" notice. */
|
|
55
|
+
const UNKNOWN_ATTRIBUTES: readonly string[] = ['id', 'v', 'lang', 'dir'];
|
|
56
|
+
|
|
57
|
+
const NONE: ReadonlySet<string> = new Set();
|
|
58
|
+
const POSITIVE_INTEGER = /^[1-9]\d*$/;
|
|
59
|
+
|
|
60
|
+
/** What a cleaning pass needs: the manifests of the registered elements and the URL policy. */
|
|
61
|
+
export interface Cleaning {
|
|
62
|
+
readonly manifests: ReadonlyMap<string, ComponentManifest>;
|
|
63
|
+
readonly urlPolicy: UrlPolicy;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Removes every attribute not in `allowed`, and URL attributes whose URL the policy blocks. `style` always goes: a
|
|
68
|
+
* strict CSP would block it. What can be kept of it was taken before the cleaning, under its parsing name (`styled.ts`).
|
|
69
|
+
*/
|
|
70
|
+
function keepAttributes(
|
|
71
|
+
el: Element,
|
|
72
|
+
allowed: Iterable<string>,
|
|
73
|
+
policy: UrlPolicy = isSafeUrl,
|
|
74
|
+
urls: ReadonlySet<string> = NONE,
|
|
75
|
+
): void {
|
|
76
|
+
const names = new Set(allowed);
|
|
77
|
+
const tag = el.localName;
|
|
78
|
+
for (const { name, value } of Array.from(el.attributes)) {
|
|
79
|
+
const blocked = urls.has(name) && !policy(value, { tag, attribute: name });
|
|
80
|
+
if (name === 'style' || !names.has(name) || blocked) {
|
|
81
|
+
el.removeAttribute(name);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A picture keeps `src` (when the policy allows it), `alt`, and `width` and `height` when they are positive integers;
|
|
88
|
+
* one without `src` or `alt` is removed. The player adds lazy loading, asynchronous decoding and no referrer (the
|
|
89
|
+
* picture's host learns nothing of the page, an attempt id in its address say): they are never authored. Returns
|
|
90
|
+
* false when the picture is gone.
|
|
91
|
+
*/
|
|
92
|
+
function cleanPicture(el: Element, policy: UrlPolicy): boolean {
|
|
93
|
+
keepAttributes(el, [...CONTENT_ATTRIBUTES, ...(TAG_ATTRIBUTES.img ?? [])], policy, new Set(['src']));
|
|
94
|
+
for (const name of ['width', 'height']) {
|
|
95
|
+
if (!POSITIVE_INTEGER.test(el.getAttribute(name) ?? '1')) el.removeAttribute(name);
|
|
96
|
+
}
|
|
97
|
+
if (!el.getAttribute('src') || !el.hasAttribute('alt')) {
|
|
98
|
+
el.remove();
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
el.replaceChildren();
|
|
102
|
+
el.setAttribute('loading', 'lazy');
|
|
103
|
+
el.setAttribute('decoding', 'async');
|
|
104
|
+
el.setAttribute('referrerpolicy', 'no-referrer');
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A figure keeps its picture and its caption (rich inline text, and inline components unless it is inside one),
|
|
110
|
+
* nothing else.
|
|
111
|
+
*/
|
|
112
|
+
function cleanFigure(el: Element, cleaning: Cleaning, components: boolean): void {
|
|
113
|
+
keepAttributes(el, CONTENT_ATTRIBUTES);
|
|
114
|
+
for (const node of Array.from(el.childNodes)) {
|
|
115
|
+
if (node.nodeType === Node.TEXT_NODE) continue;
|
|
116
|
+
const child = node as Element;
|
|
117
|
+
if (node.nodeType !== Node.ELEMENT_NODE) node.remove();
|
|
118
|
+
else if (child.localName === 'img') cleanPicture(child, cleaning.urlPolicy);
|
|
119
|
+
else if (child.localName === CAPTION_TAG) {
|
|
120
|
+
keepAttributes(child, CONTENT_ATTRIBUTES);
|
|
121
|
+
cleanContent(child, cleaning, true, components);
|
|
122
|
+
} else child.remove();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Rich text and components, recursively. `inline` content (an option, a prompt) keeps inline tags only, and with
|
|
128
|
+
* `components` (a caption) inline components too. The content of a rich block (`host`) keeps blocks and the host's
|
|
129
|
+
* public children. Dangerous elements go with their content; other unknown HTML is unwrapped; unknown custom elements
|
|
130
|
+
* stay (with no content) so the player can show its "unsupported" notice in their place.
|
|
131
|
+
*/
|
|
132
|
+
export function cleanContent(
|
|
133
|
+
parent: Element,
|
|
134
|
+
cleaning: Cleaning,
|
|
135
|
+
inline: boolean,
|
|
136
|
+
components: boolean = !inline,
|
|
137
|
+
host?: ComponentManifest,
|
|
138
|
+
): void {
|
|
139
|
+
const { manifests, urlPolicy } = cleaning;
|
|
140
|
+
for (const node of Array.from(parent.childNodes)) {
|
|
141
|
+
if (node.nodeType === Node.TEXT_NODE) continue;
|
|
142
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
143
|
+
node.remove();
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const el = node as Element;
|
|
147
|
+
const tag = el.localName;
|
|
148
|
+
const spec = host && publicChild(host, tag);
|
|
149
|
+
if (REMOVED_WITH_CONTENT.has(tag)) {
|
|
150
|
+
el.remove();
|
|
151
|
+
} else if (tag === PAGE_TAG && components && !inline) {
|
|
152
|
+
keepAttributes(el, [...PAGE_ATTRIBUTES, ...HELP_ATTRIBUTES]);
|
|
153
|
+
cleanContent(el, cleaning, false);
|
|
154
|
+
} else if ((tag === COLUMNS_TAG || tag === COLUMN_TAG) && components && !inline) {
|
|
155
|
+
keepAttributes(el, CONTENT_ATTRIBUTES);
|
|
156
|
+
cleanContent(el, cleaning, false);
|
|
157
|
+
} else if (tag === 'img') {
|
|
158
|
+
cleanPicture(el, urlPolicy);
|
|
159
|
+
} else if (tag === FIGURE_TAG && !inline) {
|
|
160
|
+
cleanFigure(el, cleaning, components);
|
|
161
|
+
} else if (INLINE_TAGS.has(tag) || (BLOCK_TAGS.has(tag) && !inline)) {
|
|
162
|
+
const url = URL_ATTRIBUTES[tag];
|
|
163
|
+
const allowed = [...CONTENT_ATTRIBUTES, ...(TAG_ATTRIBUTES[tag] ?? [])];
|
|
164
|
+
keepAttributes(el, allowed, urlPolicy, url === undefined ? NONE : new Set([url]));
|
|
165
|
+
cleanContent(el, cleaning, inline, components, host);
|
|
166
|
+
} else if (spec) {
|
|
167
|
+
cleanChild(el, spec, cleaning);
|
|
168
|
+
} else if (
|
|
169
|
+
components &&
|
|
170
|
+
manifests.has(tag) &&
|
|
171
|
+
(!inline || (manifests.get(tag) as ComponentManifest).display === 'inline')
|
|
172
|
+
) {
|
|
173
|
+
cleanComponent(el, manifests.get(tag) as ComponentManifest, cleaning);
|
|
174
|
+
} else if (tag.includes('-') && tag !== DOC_TAG && tag !== PAGE_TAG) {
|
|
175
|
+
keepAttributes(el, UNKNOWN_ATTRIBUTES);
|
|
176
|
+
el.replaceChildren();
|
|
177
|
+
} else {
|
|
178
|
+
cleanContent(el, cleaning, inline, components, host);
|
|
179
|
+
el.replaceWith(...Array.from(el.childNodes));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const publicChild = (manifest: ComponentManifest, tag: string): ChildSpec | undefined =>
|
|
185
|
+
manifest.children.find((c) => c.tag === tag && c.visibility === 'public');
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Keeps `lang`, `dir`, the public and derived attributes of `specs` and the `extra` ones, URLs only where the policy
|
|
189
|
+
* allows them.
|
|
190
|
+
*/
|
|
191
|
+
function keepPublic(
|
|
192
|
+
el: Element,
|
|
193
|
+
specs: readonly AttributeSpec[],
|
|
194
|
+
cleaning: Cleaning,
|
|
195
|
+
extra: readonly string[] = [],
|
|
196
|
+
): void {
|
|
197
|
+
const kept = specs.filter((a) => a.visibility !== 'private');
|
|
198
|
+
keepAttributes(
|
|
199
|
+
el,
|
|
200
|
+
[...CONTENT_ATTRIBUTES, ...kept.map((a) => a.name), ...extra],
|
|
201
|
+
cleaning.urlPolicy,
|
|
202
|
+
new Set(kept.filter((a) => a.type === 'url').map((a) => a.name)),
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A declared public child: its public attributes, and its text or rich inline content. */
|
|
207
|
+
function cleanChild(child: Element, spec: ChildSpec, cleaning: Cleaning): void {
|
|
208
|
+
keepPublic(child, spec.attributes, cleaning);
|
|
209
|
+
if (spec.content === 'text') child.textContent = child.textContent ?? '';
|
|
210
|
+
else cleanContent(child, cleaning, true);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* A component keeps `id`, `v`, `lang`, `dir`, its public and derived attributes (the engine's view keeps a
|
|
215
|
+
* component's language) and what it offers of help (`HELP_ATTRIBUTES`), and its declared public children; a rich
|
|
216
|
+
* block also keeps its rich content around them.
|
|
217
|
+
*/
|
|
218
|
+
function cleanComponent(el: Element, manifest: ComponentManifest, cleaning: Cleaning): void {
|
|
219
|
+
keepPublic(el, allAttributes(manifest), cleaning, manifest.graded ? HELP_ATTRIBUTES : []);
|
|
220
|
+
if (manifest.content === 'flow') {
|
|
221
|
+
cleanContent(el, cleaning, false, false, manifest);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
for (const node of Array.from(el.childNodes)) {
|
|
225
|
+
if (node.nodeType === Node.TEXT_NODE) continue;
|
|
226
|
+
const spec = publicChild(manifest, (node as Element).localName);
|
|
227
|
+
if (node.nodeType !== Node.ELEMENT_NODE || spec === undefined) node.remove();
|
|
228
|
+
else cleanChild(node as Element, spec, cleaning);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Parses a view into an inert fragment (template content: no scripts run, nothing loads, no elements upgrade) that
|
|
234
|
+
* holds one `<astl-doc>`. Not cleaned yet: the manifests of its lazy elements may still have to load.
|
|
235
|
+
*/
|
|
236
|
+
export function readView(view: string): DocumentFragment {
|
|
237
|
+
const template = document.createElement('template');
|
|
238
|
+
template.innerHTML = inertStyles(view);
|
|
239
|
+
const roots = Array.from(template.content.children);
|
|
240
|
+
const doc = roots[0];
|
|
241
|
+
if (roots.length !== 1 || doc === undefined || doc.localName !== DOC_TAG)
|
|
242
|
+
throw new LoadError('view_invalid');
|
|
243
|
+
for (const node of Array.from(template.content.childNodes)) if (node !== doc) node.remove();
|
|
244
|
+
return template.content;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The custom element tags in a read view: the lazy elements to load before it is cleaned. */
|
|
248
|
+
export function viewTags(fragment: DocumentFragment): Set<string> {
|
|
249
|
+
return new Set(
|
|
250
|
+
Array.from(fragment.querySelectorAll('*'), (el) => el.localName).filter(
|
|
251
|
+
(tag) => tag.includes('-') && tag !== COLUMNS_TAG && tag !== COLUMN_TAG,
|
|
252
|
+
),
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Whether a read view offers help (hints, explanations, feedback): then the help module loads with it. */
|
|
257
|
+
export function hasHelp(fragment: DocumentFragment): boolean {
|
|
258
|
+
return fragment.querySelector(HELP_ATTRIBUTES.map((name) => `[${name}]`).join()) !== null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Whether a read view is a book (`kind="book"` on its `astl-doc`): then the book's module loads with it. */
|
|
262
|
+
export function isBook(fragment: DocumentFragment): boolean {
|
|
263
|
+
return fragment.firstElementChild?.getAttribute('kind') === 'book';
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Whether a read view needs the module of styles and layouts. */
|
|
267
|
+
export function isStyled(fragment: DocumentFragment): boolean {
|
|
268
|
+
return fragment.querySelector(`[${INERT_STYLE}],${COLUMNS_TAG}`) !== null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Cleans a read view in place. Views are engine output; the cleaning is defence in depth against a tampered or
|
|
273
|
+
* hand-edited view: the content format's allow-list (`@astl/core` content.ts), each registered component's
|
|
274
|
+
* manifest and the URL policy (the engine's, so the URLs it kept stay).
|
|
275
|
+
*/
|
|
276
|
+
export function cleanView(
|
|
277
|
+
fragment: DocumentFragment,
|
|
278
|
+
manifests: ReadonlyMap<string, ComponentManifest>,
|
|
279
|
+
urlPolicy: UrlPolicy = isSafeUrl,
|
|
280
|
+
): DocumentFragment {
|
|
281
|
+
const doc = fragment.firstElementChild as Element;
|
|
282
|
+
keepAttributes(doc, DOC_ATTRIBUTES);
|
|
283
|
+
cleanContent(doc, { manifests, urlPolicy }, false);
|
|
284
|
+
return fragment;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** `readView` and `cleanView` in one step, for views whose elements are all loaded. */
|
|
288
|
+
export function parseView(
|
|
289
|
+
view: string,
|
|
290
|
+
manifests: ReadonlyMap<string, ComponentManifest>,
|
|
291
|
+
urlPolicy: UrlPolicy = isSafeUrl,
|
|
292
|
+
): DocumentFragment {
|
|
293
|
+
return cleanView(readView(view), manifests, urlPolicy);
|
|
294
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ComponentManifest,
|
|
3
|
+
isSafeUrl,
|
|
4
|
+
type MessageCatalog,
|
|
5
|
+
type SourceCompiler,
|
|
6
|
+
type StyleTemplate,
|
|
7
|
+
type UrlPolicy,
|
|
8
|
+
} from '@astl/core';
|
|
9
|
+
|
|
10
|
+
/** One component element type for the player: its manifest, element class and message catalogs. */
|
|
11
|
+
export interface ElementRegistration {
|
|
12
|
+
readonly manifest: ComponentManifest;
|
|
13
|
+
readonly element: CustomElementConstructor;
|
|
14
|
+
readonly messages: readonly MessageCatalog[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Imported the first time a view mounted by <astl-player> contains `tag`; resolves to that tag's registration. */
|
|
18
|
+
export interface LazyElement {
|
|
19
|
+
readonly tag: string;
|
|
20
|
+
readonly load: () => Promise<ElementRegistration>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A component element for the player: registered right away, or lazily on first use. */
|
|
24
|
+
export type ElementEntry = ElementRegistration | LazyElement;
|
|
25
|
+
|
|
26
|
+
export function isLazyElement(entry: ElementEntry): entry is LazyElement {
|
|
27
|
+
return typeof (entry as Partial<LazyElement>).load === 'function';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What `definePlayer` registered. Shared by every `<astl-player>` of this module instance. */
|
|
31
|
+
export interface PlayerRuntime {
|
|
32
|
+
/** Registrations by tag: eager ones, and lazy ones once loaded. */
|
|
33
|
+
readonly elements: Map<string, ElementRegistration>;
|
|
34
|
+
/** Lazy elements by tag, with the registry `definePlayer` defines them in. */
|
|
35
|
+
readonly lazy: Map<
|
|
36
|
+
string,
|
|
37
|
+
{ readonly load: LazyElement['load']; readonly registry: CustomElementRegistry }
|
|
38
|
+
>;
|
|
39
|
+
/** Loads in flight by tag, shared by every player. */
|
|
40
|
+
readonly loading: Map<string, Promise<void>>;
|
|
41
|
+
readonly catalogs: MessageCatalog[];
|
|
42
|
+
/** Style templates by name. */
|
|
43
|
+
readonly styleTemplates: Map<string, StyleTemplate>;
|
|
44
|
+
compileSource: SourceCompiler | null;
|
|
45
|
+
/** The URL policy views are cleaned with: the engine's, so the URLs it kept stay. */
|
|
46
|
+
urlPolicy: UrlPolicy;
|
|
47
|
+
/**
|
|
48
|
+
* Bumped on every registration and every lazy element loaded, so players rebuild cached message tables and the
|
|
49
|
+
* template stylesheet.
|
|
50
|
+
*/
|
|
51
|
+
version: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const runtime: PlayerRuntime = {
|
|
55
|
+
elements: new Map(),
|
|
56
|
+
lazy: new Map(),
|
|
57
|
+
loading: new Map(),
|
|
58
|
+
catalogs: [],
|
|
59
|
+
styleTemplates: new Map(),
|
|
60
|
+
compileSource: null,
|
|
61
|
+
urlPolicy: isSafeUrl,
|
|
62
|
+
version: 0,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Loads and defines one lazy element; a failed load is dropped from `loading`, so the next view tries again. */
|
|
66
|
+
function loadElement(tag: string): Promise<void> {
|
|
67
|
+
const entry = runtime.lazy.get(tag);
|
|
68
|
+
if (entry === undefined || runtime.elements.has(tag)) return Promise.resolve();
|
|
69
|
+
let pending = runtime.loading.get(tag);
|
|
70
|
+
if (pending === undefined) {
|
|
71
|
+
pending = Promise.resolve()
|
|
72
|
+
.then(() => entry.load())
|
|
73
|
+
.then((registration) => {
|
|
74
|
+
const loaded = registration?.manifest?.tag;
|
|
75
|
+
if (loaded !== tag) throw new Error(`The lazy element for <${tag}> loaded <${String(loaded)}>`);
|
|
76
|
+
const existing = entry.registry.get(tag);
|
|
77
|
+
if (existing === undefined) entry.registry.define(tag, registration.element);
|
|
78
|
+
else if (existing !== registration.element)
|
|
79
|
+
throw new Error(`<${tag}> is already defined by another class`);
|
|
80
|
+
runtime.elements.set(tag, registration);
|
|
81
|
+
runtime.version++;
|
|
82
|
+
})
|
|
83
|
+
.finally(() => runtime.loading.delete(tag));
|
|
84
|
+
runtime.loading.set(tag, pending);
|
|
85
|
+
}
|
|
86
|
+
return pending;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Loads the lazy elements of these tags that are not loaded yet, in parallel, each at most once at a time for every
|
|
91
|
+
* player. Tags without a lazy element are skipped. Rejects when one fails.
|
|
92
|
+
*/
|
|
93
|
+
export async function loadElements(tags: Iterable<string>): Promise<void> {
|
|
94
|
+
await Promise.all(Array.from(new Set(tags), loadElement));
|
|
95
|
+
}
|