@astl/editor 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.
Files changed (161) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/LICENSE +202 -0
  3. package/README.md +43 -0
  4. package/dist/authoring.d.ts +284 -0
  5. package/dist/authoring.d.ts.map +1 -0
  6. package/dist/authoring.js +566 -0
  7. package/dist/authoring.js.map +1 -0
  8. package/dist/define.d.ts +8 -0
  9. package/dist/define.d.ts.map +1 -0
  10. package/dist/define.js +35 -0
  11. package/dist/define.js.map +1 -0
  12. package/dist/edit.d.ts +45 -0
  13. package/dist/edit.d.ts.map +1 -0
  14. package/dist/edit.js +150 -0
  15. package/dist/edit.js.map +1 -0
  16. package/dist/elements/base.d.ts +31 -0
  17. package/dist/elements/base.d.ts.map +1 -0
  18. package/dist/elements/base.js +75 -0
  19. package/dist/elements/base.js.map +1 -0
  20. package/dist/elements/color-control.d.ts +25 -0
  21. package/dist/elements/color-control.d.ts.map +1 -0
  22. package/dist/elements/color-control.js +139 -0
  23. package/dist/elements/color-control.js.map +1 -0
  24. package/dist/elements/help-form.d.ts +31 -0
  25. package/dist/elements/help-form.d.ts.map +1 -0
  26. package/dist/elements/help-form.js +371 -0
  27. package/dist/elements/help-form.js.map +1 -0
  28. package/dist/elements/insert-menu.d.ts +79 -0
  29. package/dist/elements/insert-menu.d.ts.map +1 -0
  30. package/dist/elements/insert-menu.js +362 -0
  31. package/dist/elements/insert-menu.js.map +1 -0
  32. package/dist/elements/inspector.d.ts +24 -0
  33. package/dist/elements/inspector.d.ts.map +1 -0
  34. package/dist/elements/inspector.js +846 -0
  35. package/dist/elements/inspector.js.map +1 -0
  36. package/dist/elements/issue-list.d.ts +18 -0
  37. package/dist/elements/issue-list.d.ts.map +1 -0
  38. package/dist/elements/issue-list.js +85 -0
  39. package/dist/elements/issue-list.js.map +1 -0
  40. package/dist/elements/issues.d.ts +24 -0
  41. package/dist/elements/issues.d.ts.map +1 -0
  42. package/dist/elements/issues.js +81 -0
  43. package/dist/elements/issues.js.map +1 -0
  44. package/dist/elements/picture-dialog.d.ts +40 -0
  45. package/dist/elements/picture-dialog.d.ts.map +1 -0
  46. package/dist/elements/picture-dialog.js +433 -0
  47. package/dist/elements/picture-dialog.js.map +1 -0
  48. package/dist/elements/picture-field.d.ts +33 -0
  49. package/dist/elements/picture-field.d.ts.map +1 -0
  50. package/dist/elements/picture-field.js +692 -0
  51. package/dist/elements/picture-field.js.map +1 -0
  52. package/dist/elements/preview.d.ts +34 -0
  53. package/dist/elements/preview.d.ts.map +1 -0
  54. package/dist/elements/preview.js +165 -0
  55. package/dist/elements/preview.js.map +1 -0
  56. package/dist/elements/style-form.d.ts +30 -0
  57. package/dist/elements/style-form.d.ts.map +1 -0
  58. package/dist/elements/style-form.js +640 -0
  59. package/dist/elements/style-form.js.map +1 -0
  60. package/dist/elements/style-load.d.ts +26 -0
  61. package/dist/elements/style-load.d.ts.map +1 -0
  62. package/dist/elements/style-load.js +50 -0
  63. package/dist/elements/style-load.js.map +1 -0
  64. package/dist/elements/style-popups.d.ts +39 -0
  65. package/dist/elements/style-popups.d.ts.map +1 -0
  66. package/dist/elements/style-popups.js +173 -0
  67. package/dist/elements/style-popups.js.map +1 -0
  68. package/dist/elements/style-rules.d.ts +21 -0
  69. package/dist/elements/style-rules.d.ts.map +1 -0
  70. package/dist/elements/style-rules.js +274 -0
  71. package/dist/elements/style-rules.js.map +1 -0
  72. package/dist/elements/styles.d.ts +9 -0
  73. package/dist/elements/styles.d.ts.map +1 -0
  74. package/dist/elements/styles.js +161 -0
  75. package/dist/elements/styles.js.map +1 -0
  76. package/dist/elements/toolbar.d.ts +65 -0
  77. package/dist/elements/toolbar.d.ts.map +1 -0
  78. package/dist/elements/toolbar.js +1270 -0
  79. package/dist/elements/toolbar.js.map +1 -0
  80. package/dist/help.d.ts +33 -0
  81. package/dist/help.d.ts.map +1 -0
  82. package/dist/help.js +111 -0
  83. package/dist/help.js.map +1 -0
  84. package/dist/index.d.ts +32 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +17 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/inspect.d.ts +251 -0
  89. package/dist/inspect.d.ts.map +1 -0
  90. package/dist/inspect.js +428 -0
  91. package/dist/inspect.js.map +1 -0
  92. package/dist/messages/en.json +252 -0
  93. package/dist/messages/help/en.json +18 -0
  94. package/dist/messages/help/pl.json +18 -0
  95. package/dist/messages/pl.json +252 -0
  96. package/dist/messages/style/en.json +67 -0
  97. package/dist/messages/style/pl.json +67 -0
  98. package/dist/messages.d.ts +5 -0
  99. package/dist/messages.d.ts.map +1 -0
  100. package/dist/messages.js +9 -0
  101. package/dist/messages.js.map +1 -0
  102. package/dist/pages.d.ts +28 -0
  103. package/dist/pages.d.ts.map +1 -0
  104. package/dist/pages.js +147 -0
  105. package/dist/pages.js.map +1 -0
  106. package/dist/scan.d.ts +82 -0
  107. package/dist/scan.d.ts.map +1 -0
  108. package/dist/scan.js +329 -0
  109. package/dist/scan.js.map +1 -0
  110. package/dist/style-messages.d.ts +7 -0
  111. package/dist/style-messages.d.ts.map +1 -0
  112. package/dist/style-messages.js +12 -0
  113. package/dist/style-messages.js.map +1 -0
  114. package/dist/style-model.d.ts +50 -0
  115. package/dist/style-model.d.ts.map +1 -0
  116. package/dist/style-model.js +76 -0
  117. package/dist/style-model.js.map +1 -0
  118. package/dist/style-placing.d.ts +38 -0
  119. package/dist/style-placing.d.ts.map +1 -0
  120. package/dist/style-placing.js +98 -0
  121. package/dist/style-placing.js.map +1 -0
  122. package/dist/textarea.d.ts +17 -0
  123. package/dist/textarea.d.ts.map +1 -0
  124. package/dist/textarea.js +175 -0
  125. package/dist/textarea.js.map +1 -0
  126. package/package.json +42 -4
  127. package/src/authoring.ts +896 -0
  128. package/src/define.ts +34 -0
  129. package/src/edit.ts +195 -0
  130. package/src/elements/base.ts +93 -0
  131. package/src/elements/color-control.ts +159 -0
  132. package/src/elements/help-form.ts +404 -0
  133. package/src/elements/insert-menu.ts +481 -0
  134. package/src/elements/inspector.ts +941 -0
  135. package/src/elements/issue-list.ts +103 -0
  136. package/src/elements/issues.ts +89 -0
  137. package/src/elements/picture-dialog.ts +461 -0
  138. package/src/elements/picture-field.ts +770 -0
  139. package/src/elements/preview.ts +186 -0
  140. package/src/elements/style-form.ts +751 -0
  141. package/src/elements/style-load.ts +64 -0
  142. package/src/elements/style-popups.ts +257 -0
  143. package/src/elements/style-rules.ts +294 -0
  144. package/src/elements/styles.ts +162 -0
  145. package/src/elements/toolbar.ts +1386 -0
  146. package/src/help.ts +156 -0
  147. package/src/index.ts +81 -0
  148. package/src/inspect.ts +774 -0
  149. package/src/messages/en.json +252 -0
  150. package/src/messages/help/en.json +18 -0
  151. package/src/messages/help/pl.json +18 -0
  152. package/src/messages/pl.json +252 -0
  153. package/src/messages/style/en.json +67 -0
  154. package/src/messages/style/pl.json +67 -0
  155. package/src/messages.ts +11 -0
  156. package/src/pages.ts +158 -0
  157. package/src/scan.ts +382 -0
  158. package/src/style-messages.ts +13 -0
  159. package/src/style-model.ts +125 -0
  160. package/src/style-placing.ts +117 -0
  161. package/src/textarea.ts +182 -0
@@ -0,0 +1,896 @@
1
+ /**
2
+ * createAuthoring: the editor-independent logic of the authoring kit. Pure (no DOM), so hosts, agents and tests can
3
+ * use it in any runtime; the web components and adapters are thin layers on top.
4
+ */
5
+ import {
6
+ type AttemptPolicy,
7
+ COLUMN_TAG,
8
+ COLUMNS_TAG,
9
+ type ComponentManifest,
10
+ createI18n,
11
+ DOC_TAG,
12
+ type EditorDescriptor,
13
+ type EditorTemplate,
14
+ type ElementNode,
15
+ ENGINE_NAMESPACE,
16
+ type Engine,
17
+ element,
18
+ type Issue,
19
+ isElement,
20
+ isSafeUrl,
21
+ isSourceId,
22
+ type MessageCatalog,
23
+ type MessageParams,
24
+ type Node,
25
+ PAGE_TAG,
26
+ SCORING_ATTRIBUTES,
27
+ STYLE_TAG,
28
+ STYLE_TEMPLATE_ATTRIBUTE,
29
+ type StyleScope,
30
+ type StyleTemplate,
31
+ strictUrlPolicy,
32
+ type UrlPolicy,
33
+ type ValidationReport,
34
+ } from '@astl/core';
35
+ import { cleanStyle, isStyleName } from '@astl/core/declarations';
36
+ import { engineMessages, type LocalChecker, localChecker, parseHtml } from '@astl/engine';
37
+ import type { ElementEntry } from '@astl/player';
38
+ import { type InspectorChange, updateElement } from './edit.js';
39
+ import { type InspectorModel, type InspectorOption, inspectorModel, styleTemplateField } from './inspect.js';
40
+ import { EDITOR_NAMESPACE, editorMessages } from './messages.js';
41
+ import {
42
+ applyEdits,
43
+ attributeValue,
44
+ type Edit,
45
+ type ElementRange,
46
+ elementTree,
47
+ escapeHtml,
48
+ scanElements,
49
+ scanRanges,
50
+ tokenize,
51
+ usedIds,
52
+ } from './scan.js';
53
+ import { DEFAULT_FONTS, DEFAULT_STYLES, type EditorFont, type EditorStylePreset } from './style-model.js';
54
+
55
+ export interface AuthoringOptions {
56
+ readonly engine: Engine;
57
+ /** One per component type authors can insert and inspect. Each tag must be registered in the engine. */
58
+ readonly descriptors: readonly EditorDescriptor[];
59
+ /** Player elements for `<astl-preview>`, eager or lazy. */
60
+ readonly elements?: readonly ElementEntry[];
61
+ /** The author's UI locale: labels, issues, template texts. */
62
+ readonly locale: string;
63
+ /** More or overriding catalogs (any namespace), e.g. another UI locale. */
64
+ readonly catalogs?: readonly MessageCatalog[];
65
+ /**
66
+ * Catalogs only insert menus show (the one-line descriptions), loaded when a menu first opens rather than with the
67
+ * editor (`loadMenuMessages`): the built-ins' are the components package's `builtInMenuMessages`. The host's
68
+ * `catalogs` override them.
69
+ */
70
+ readonly menuMessages?: () => Promise<readonly MessageCatalog[]>;
71
+ /**
72
+ * Style templates authors can pick (register the same ones with the engine and the player): the inspector offers
73
+ * them per component and for the whole document, labelled from their catalogs; `<astl-preview>` renders them.
74
+ */
75
+ readonly styleTemplates?: readonly StyleTemplate[];
76
+ /**
77
+ * The engine's URL policy (`createEngine({ urlPolicy })`): the preview's player cleans with it and editors check
78
+ * picture addresses with it before they show them. Default `isSafeUrl`.
79
+ */
80
+ readonly urlPolicy?: UrlPolicy;
81
+ /**
82
+ * The fonts the style controls offer, in order. Default `DEFAULT_FONTS`, stacks every system has. A stack the style
83
+ * allow-list refuses throws.
84
+ */
85
+ readonly fonts?: readonly EditorFont[];
86
+ /**
87
+ * The ready styles the style menu and the style form offer, in order; `[]`: none. Default `DEFAULT_STYLES`. A name
88
+ * `isStyleName` refuses, a declaration the style allow-list refuses, or a name given twice throws.
89
+ */
90
+ readonly styles?: readonly EditorStylePreset[];
91
+ /**
92
+ * Stores a picture file and returns its address (and size): the host's upload, used by the picture dialog, by
93
+ * pictures pasted or dropped into the editor and by picture fields; also by `url` fields with `accept` (a video,
94
+ * its captions). The address must pass `urlPolicy`. Without it, files are added by address only (pictures also
95
+ * from `pickPicture`). `signal` aborts when the author cancels or picks another file. The file's type is the
96
+ * browser's guess: check type and size on the server, and serve SVG with `nosniff`. Reject with `UploadRefused` to
97
+ * tell the author why.
98
+ */
99
+ readonly uploadAsset?: UploadAsset;
100
+ /**
101
+ * Opens the host's own picture library: the picture dialog and picture fields offer it beside the upload. The
102
+ * address it gives must pass `urlPolicy`. The picture dialog closes while the library is open, keeping what the
103
+ * author typed, so a modal of the host's own takes the pointer and the keys; it opens again when the library
104
+ * settles. Reject with `UploadRefused` to tell the author why.
105
+ */
106
+ readonly pickPicture?: PickPicture;
107
+ }
108
+
109
+ /** A host's font with its stack in the allow-list's normal form, what a style then holds. */
110
+ function normalFont(font: EditorFont): EditorFont {
111
+ const stack = cleanStyle(`font-family: ${font.stack}`).declarations[0]?.[1];
112
+ if (stack === undefined) throw new TypeError(`Font "${font.name}": the style allow-list refuses its stack`);
113
+ return { name: font.name, stack };
114
+ }
115
+
116
+ /**
117
+ * A host's ready styles with each style in the allow-list's normal form, what its rule then holds, and each label in
118
+ * the authoring locale. A name `isStyleName` refuses, a declaration the allow-list refuses or a name given twice
119
+ * throws: a style that could not be written as it was offered.
120
+ */
121
+ function readyStyles(
122
+ presets: readonly EditorStylePreset[],
123
+ label: (name: string) => string,
124
+ ): (EditorStylePreset & { readonly label: string })[] {
125
+ const names = new Set<string>();
126
+ return presets.map((preset) => {
127
+ const { name } = preset;
128
+ if (!isStyleName(name)) throw new TypeError(`Style "${name}": not a style name`);
129
+ if (names.has(name)) throw new TypeError(`Style "${name}" is given twice`);
130
+ names.add(name);
131
+ const { style, removed } = cleanStyle(preset.style);
132
+ if (removed.length > 0)
133
+ throw new TypeError(`Style "${name}": the style allow-list refuses ${removed.join(', ')}`);
134
+ return { ...preset, style, label: preset.label ?? label(name) };
135
+ });
136
+ }
137
+
138
+ /** A stored picture, as `uploadAsset` and `pickPicture` give it: its address, and its size in pixels when known. */
139
+ export interface UploadedAsset {
140
+ readonly src: string;
141
+ readonly width?: number;
142
+ readonly height?: number;
143
+ }
144
+
145
+ export type UploadAsset = (file: File, options: { readonly signal: AbortSignal }) => Promise<UploadedAsset>;
146
+
147
+ /**
148
+ * Opens the host's own picture library and resolves with the chosen picture (its address, and its size when known),
149
+ * or null when the author closes it without one. The address must pass `urlPolicy`. Settle once the library has
150
+ * closed: the picture dialog and the picture fields then give the focus back themselves. `signal` aborts when the
151
+ * editor no longer waits for it (the picture dialog was asked for another picture or left the page, the picture field
152
+ * started another upload or pick): the host should then close its library.
153
+ */
154
+ export type PickPicture = (options: { readonly signal: AbortSignal }) => Promise<UploadedAsset | null>;
155
+
156
+ /**
157
+ * What a host's `uploadAsset` or `pickPicture` rejects with to tell the author why: its message, already in the
158
+ * editor's locale, is shown as it is, instead of the generic failure text.
159
+ */
160
+ export class UploadRefused extends Error {
161
+ constructor(message: string, options?: ErrorOptions) {
162
+ super(message, options);
163
+ this.name = 'UploadRefused';
164
+ }
165
+ }
166
+
167
+ /**
168
+ * The words of a host's refusal: the message of an `UploadRefused`, known by its name so that another copy of this
169
+ * package counts too; undefined for any other error and for a refusal without words.
170
+ */
171
+ export function refusalOf(error: unknown): string | undefined {
172
+ return error instanceof Error && error.name === 'UploadRefused' && error.message.trim() !== ''
173
+ ? error.message
174
+ : undefined;
175
+ }
176
+
177
+ /** A picture as the picture dialog asks for it: `alt` is `''` for a decorative picture. */
178
+ export interface PictureFields {
179
+ readonly src: string;
180
+ readonly alt: string;
181
+ readonly width?: number;
182
+ readonly height?: number;
183
+ /** A caption makes the picture a figure. */
184
+ readonly caption?: string;
185
+ }
186
+
187
+ /**
188
+ * A picture's width or height as the content format takes it: a positive whole number of pixels (a safe integer),
189
+ * from a number or its written form; anything else is no size.
190
+ */
191
+ export function pictureSize(value: unknown): number | undefined {
192
+ const n =
193
+ typeof value === 'number'
194
+ ? value
195
+ : typeof value === 'string' && /^[1-9]\d*$/.test(value)
196
+ ? Number(value)
197
+ : NaN;
198
+ return Number.isSafeInteger(n) && n > 0 ? n : undefined;
199
+ }
200
+
201
+ /**
202
+ * The source HTML of a picture: an `<img>` that sits in text, or with a caption a `<figure>` that stands on its own.
203
+ * Every value is read once and escaped, and only the attributes of the content format are written.
204
+ */
205
+ export function pictureHtml(picture: PictureFields): string {
206
+ const size = (name: string, value: unknown) => {
207
+ const n = pictureSize(value);
208
+ return n === undefined ? '' : ` ${name}="${n}"`;
209
+ };
210
+ const img =
211
+ `<img src="${escapeHtml(String(picture.src))}" alt="${escapeHtml(String(picture.alt))}"` +
212
+ `${size('width', picture.width)}${size('height', picture.height)}>`;
213
+ const caption = String(picture.caption ?? '').trim();
214
+ return caption === '' ? img : `<figure>${img}<figcaption>${escapeHtml(caption)}</figcaption></figure>`;
215
+ }
216
+
217
+ export interface OutlineComponent {
218
+ readonly id: string | null;
219
+ readonly tag: string;
220
+ /** Translated type label (the tag when there is no descriptor). */
221
+ readonly label: string;
222
+ /** Its `points` (default 1) when the type is graded, else null. */
223
+ readonly points: number | null;
224
+ /** Issues located on this component or its children. */
225
+ readonly errors: number;
226
+ readonly warnings: number;
227
+ }
228
+
229
+ /**
230
+ * One block of a page (`EditorBlockPlace`): a block component directly on the page, or the content between two of
231
+ * them (paragraphs, headings, lists, quotes, pictures, with the inline components in their text).
232
+ */
233
+ export interface OutlineBlock {
234
+ readonly kind: 'component' | 'text';
235
+ /** The component's source id (null when it has none), or null for a text block. */
236
+ readonly id: string | null;
237
+ /** The component's tag, or null for a text block. */
238
+ readonly tag: string | null;
239
+ /**
240
+ * The block's type: the component's label, else `block.gap` ("Gap") for text that holds a graded component and
241
+ * `block.text` ("Text") for the rest.
242
+ */
243
+ readonly label: string;
244
+ /** The sum of its components' points, or null when none of them is graded. */
245
+ readonly points: number | null;
246
+ /** Its component, or the components in its text, in document order. */
247
+ readonly components: readonly OutlineComponent[];
248
+ /** Issues located on its components. */
249
+ readonly errors: number;
250
+ readonly warnings: number;
251
+ }
252
+
253
+ export interface OutlinePage {
254
+ /** null for the implicit page of a document without pages. */
255
+ readonly id: string | null;
256
+ readonly label: string | null;
257
+ /** Issues located on the page, its content and its components. */
258
+ readonly errors: number;
259
+ readonly warnings: number;
260
+ readonly components: readonly OutlineComponent[];
261
+ /** Its content as blocks, in order. */
262
+ readonly blocks: readonly OutlineBlock[];
263
+ /** The sum of its blocks' points, or null when nothing on it is graded. */
264
+ readonly points: number | null;
265
+ }
266
+
267
+ export interface Outline {
268
+ readonly pages: readonly OutlinePage[];
269
+ /** Every issue of the document. */
270
+ readonly errors: number;
271
+ readonly warnings: number;
272
+ /** The sum of its pages' points, or null when nothing is graded. */
273
+ readonly points: number | null;
274
+ }
275
+
276
+ /** A playable preview, or the issues that block compiling. */
277
+ /** How `Authoring.preview` grades. */
278
+ export interface PreviewOptions {
279
+ /**
280
+ * The policy of the local grading, the one the host plays the result under: a host whose students get less help than
281
+ * practice offers (no hints, no check of one interaction) previews with that. Default `PRACTICE_POLICY`.
282
+ */
283
+ readonly policy?: AttemptPolicy;
284
+ }
285
+
286
+ export type PreviewResult =
287
+ | {
288
+ readonly ok: true;
289
+ readonly view: string;
290
+ /** Local grading for this preview, under its policy (`PreviewOptions.policy`, practice by default). */
291
+ readonly checker: LocalChecker;
292
+ /** Warnings. */
293
+ readonly issues: readonly Issue[];
294
+ }
295
+ | { readonly ok: false; readonly issues: readonly Issue[] };
296
+
297
+ /** How `Authoring.describe` names a component. */
298
+ export interface DescribeOptions {
299
+ /**
300
+ * Whether the name says the component's page when the document has pages: "Question 2 on page 1" (default true), or
301
+ * "Question 2" (false) for a host that shows the page apart.
302
+ */
303
+ readonly page?: boolean;
304
+ }
305
+
306
+ export interface Authoring {
307
+ readonly engine: Engine;
308
+ readonly locale: string;
309
+ readonly descriptors: readonly EditorDescriptor[];
310
+ readonly elements: readonly ElementEntry[];
311
+ readonly styleTemplates: readonly StyleTemplate[];
312
+ readonly urlPolicy: UrlPolicy;
313
+ /** The fonts the style controls offer, each stack in the allow-list's normal form. */
314
+ readonly fonts: readonly EditorFont[];
315
+ /**
316
+ * The ready styles the style menu and the style form offer, each style in the allow-list's normal form and each with
317
+ * its label: the host's, else the kit's message `style.preset.<name>` in the authoring locale, else the name.
318
+ */
319
+ readonly styles: readonly (EditorStylePreset & { readonly label: string })[];
320
+ /** The host's upload, or null: files are added by address only. */
321
+ readonly uploadAsset: UploadAsset | null;
322
+ /** The host's picture library, or null. */
323
+ readonly pickPicture: PickPicture | null;
324
+ /** The descriptor of a component tag, or null. */
325
+ descriptor(tag: string): EditorDescriptor | null;
326
+ /** The named starters of a component tag (`EditorDescriptor.templates`); none without a descriptor. */
327
+ templates(tag: string): readonly EditorTemplate[];
328
+ /** A message in the authoring locale: kit (`astl.editor`), descriptor, engine and extra catalogs. */
329
+ t(namespace: string, key: string, params?: MessageParams): string;
330
+ /**
331
+ * Loads the `menuMessages` option's catalogs (what only insert menus show) once; `t` has them when it resolves. A
332
+ * failed load resolves too, and the next call tries again.
333
+ */
334
+ loadMenuMessages(): Promise<void>;
335
+ /**
336
+ * Adds the catalogs of a part of the kit that loads later, under the host's `catalogs`, which may override them; `t`
337
+ * has them at once. Adding the same ones again does nothing.
338
+ */
339
+ addMessages(catalogs: readonly MessageCatalog[]): void;
340
+ /**
341
+ * The descriptor's template, or its named starter `templateId`, ready to insert into `source`: `{{id}}` becomes
342
+ * `<idPrefix>-<n>` with the smallest n whose id `source` does not use, `{{selection}}` the escaped `selection` (the
343
+ * text the author selected, `EditorAdapter.selectedText`; default `''`), `{{t:key}}` an escaped message of the
344
+ * manifest namespace, and other components written without an id get fresh ones too. An element of a type with a
345
+ * `companion` and an empty attribute names the first such element of the template, else of `source`, else the one
346
+ * `withCompanion` adds. Throws for a tag without a descriptor or an unknown starter.
347
+ */
348
+ instantiate(tag: string, source: string, templateId?: string, selection?: string): string;
349
+ /**
350
+ * `source` (with an inserted `tag` element) where that element, the one with the id `id` (default: the first whose
351
+ * companion attribute names none on its page), names a companion element of its own page, as pages play one at a
352
+ * time: the first one there, else the descriptor's `companion` template, added at the end of that page (of the
353
+ * document, without pages). Null when nothing changes: the type has no companion, or the element names one of its
354
+ * page already.
355
+ */
356
+ withCompanion(tag: string, source: string, id?: string): string | null;
357
+ /**
358
+ * The inspector model of one component element (source HTML), or null for elements it does not know. With the
359
+ * whole document (`source`), fields offer what other elements hold (the words of the bank a drop takes its words
360
+ * from); without it they show the attribute's own control.
361
+ */
362
+ inspect(elementHtml: string, source?: string): InspectorModel | null;
363
+ /**
364
+ * The document's own settings (its style template) as an inspector model for `<astl-doc>`, or null when the source
365
+ * has no `<astl-doc>` root or there is nothing to set. Apply its changes with `update(source, change)`: the first
366
+ * element of the source is the document, so only its start tag changes.
367
+ */
368
+ inspectDocument(source: string): InspectorModel | null;
369
+ /** The element HTML with one inspector change applied; everything else stays byte-identical. */
370
+ update(elementHtml: string, change: InspectorChange): string;
371
+ validate(source: string): ValidationReport;
372
+ /**
373
+ * An issue as a sentence in the authoring locale. With the document it is about (`source`), a component's issue
374
+ * names the component as the author sees it, never by its id (the id stays in `issue.at` for "Show"): a block
375
+ * component by the number of its block on its page, as its card's head shows it ("Question 2 on page 1" for block 2),
376
+ * a component in text by its number among the components of its type on its page ("Gap 3 on page 1"); with
377
+ * `page: false`, without its page ("Question 2").
378
+ */
379
+ describe(issue: Issue, source?: string, options?: DescribeOptions): string;
380
+ /** `source` with fresh ids on pages and components that lack one (or have an empty one). */
381
+ assignIds(source: string): string;
382
+ /** Pages, their blocks and components, points and issue counts. */
383
+ outline(source: string): Outline;
384
+ /**
385
+ * Compiles with a random per-session salt and grades locally, under `options.policy` (default `PRACTICE_POLICY`). The
386
+ * source is not stored anywhere.
387
+ */
388
+ preview(source: string, options?: PreviewOptions): Promise<PreviewResult>;
389
+ }
390
+
391
+ /** 128 random bits as hex: mixed into every preview, so preview ids never match published views. */
392
+ function sessionSalt(): string {
393
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
394
+ return `preview-${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
395
+ }
396
+
397
+ const TEMPLATE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
398
+
399
+ function freshId(prefix: string, used: ReadonlySet<string>): string {
400
+ for (let n = 1; ; n++) {
401
+ const id = `${prefix}-${n}`;
402
+ if (!used.has(id)) return id;
403
+ }
404
+ }
405
+
406
+ /**
407
+ * The content of a document without its named styles: they are not on any page. What one holds stays: all that follows
408
+ * a self-closed one, as HTML reads it.
409
+ */
410
+ const withoutRules = (nodes: readonly Node[]): readonly Node[] =>
411
+ nodes.flatMap((node): readonly Node[] =>
412
+ isElement(node, STYLE_TAG) ? withoutRules(node.children) : [node],
413
+ );
414
+
415
+ function firstElement(nodes: readonly Node[]): ElementNode | null {
416
+ return nodes.find((n): n is ElementNode => n.type === 'element') ?? null;
417
+ }
418
+
419
+ interface Counts {
420
+ errors: number;
421
+ warnings: number;
422
+ }
423
+
424
+ /** A graded component's points when its `points` is absent or not a number (`SCORING_ATTRIBUTES`). */
425
+ const DEFAULT_POINTS = Number(SCORING_ATTRIBUTES.find((a) => a.name === 'points')?.default ?? 1);
426
+
427
+ /** The sum of the numbers (to the hundredth, as points are written), or null when there are none. */
428
+ function sum(values: readonly (number | null)[]): number | null {
429
+ const numbers = values.filter((v): v is number => v !== null);
430
+ if (numbers.length === 0) return null;
431
+ return Math.round(numbers.reduce((a, b) => a + b, 0) * 100) / 100;
432
+ }
433
+
434
+ function count(issues: readonly Issue[], where: (issue: Issue) => boolean): Counts {
435
+ const out = { errors: 0, warnings: 0 };
436
+ for (const issue of issues) {
437
+ if (!where(issue)) continue;
438
+ if (issue.severity === 'error') out.errors++;
439
+ else out.warnings++;
440
+ }
441
+ return out;
442
+ }
443
+
444
+ export function createAuthoring(options: AuthoringOptions): Authoring {
445
+ const { engine, locale } = options;
446
+ const registered = new Map(engine.manifests.map((m) => [m.tag, m]));
447
+ const byTag = new Map<string, EditorDescriptor>();
448
+ for (const descriptor of options.descriptors) {
449
+ const tag = descriptor.manifest.tag;
450
+ if (byTag.has(tag)) throw new TypeError(`Editor descriptor for <${tag}> is given twice`);
451
+ if (!registered.has(tag))
452
+ throw new TypeError(`Editor descriptor <${tag}> has no component in the engine`);
453
+ if (!isSourceId(`${descriptor.idPrefix}-1`)) {
454
+ throw new TypeError(
455
+ `Editor descriptor <${tag}>: idPrefix "${descriptor.idPrefix}" does not make valid ids`,
456
+ );
457
+ }
458
+ const ids = (descriptor.templates ?? []).map((template) => template.id);
459
+ if (ids.some((id, i) => !TEMPLATE_ID.test(id) || ids.indexOf(id) !== i)) {
460
+ throw new TypeError(`Editor descriptor <${tag}>: template ids must be distinct kebab-case names`);
461
+ }
462
+ byTag.set(tag, descriptor);
463
+ }
464
+ const styleTemplates = options.styleTemplates ?? [];
465
+ // Catalogs that load later go before the host's, which may override them.
466
+ const i18nWith = (later: readonly MessageCatalog[]) =>
467
+ createI18n({
468
+ catalogs: [
469
+ ...editorMessages,
470
+ ...engineMessages,
471
+ ...options.descriptors.flatMap((d) => d.messages ?? []),
472
+ ...later,
473
+ ...styleTemplates.flatMap((template) => template.catalogs ?? []),
474
+ ...(options.catalogs ?? []),
475
+ ],
476
+ });
477
+ let i18n = i18nWith([]);
478
+ let later: readonly MessageCatalog[] = [];
479
+ const addMessages = (catalogs: readonly MessageCatalog[]): void => {
480
+ const added = catalogs.filter((catalog) => !later.includes(catalog));
481
+ if (added.length === 0) return;
482
+ later = [...later, ...added];
483
+ i18n = i18nWith(later);
484
+ };
485
+ let menus: Promise<void> | null = null;
486
+ const t = (namespace: string, key: string, params?: MessageParams): string =>
487
+ i18n.t(locale, namespace, key, params);
488
+ const manifestOf = (tag: string): ComponentManifest | null =>
489
+ byTag.get(tag)?.manifest ?? registered.get(tag) ?? null;
490
+ const salt = sessionSalt();
491
+
492
+ const textsFor = (manifest: ComponentManifest) => ({
493
+ message: (key: string, fallback: string, params?: MessageParams) => {
494
+ const message = t(manifest.messages, key, params);
495
+ return message === key ? fallback : message;
496
+ },
497
+ unset: t(EDITOR_NAMESPACE, 'inspector.unset'),
498
+ untitled: (n: number) => t(EDITOR_NAMESPACE, 'inspector.untitled', { n }),
499
+ region: (n: number) => t(EDITOR_NAMESPACE, 'field.region', { n }),
500
+ point: (n: number) => t(EDITOR_NAMESPACE, 'field.point', { n }),
501
+ variant: t(EDITOR_NAMESPACE, 'inspector.variant'),
502
+ styleTemplate: t(EDITOR_NAMESPACE, 'inspector.styleTemplate'),
503
+ sameAsDocument: t(EDITOR_NAMESPACE, 'inspector.styleTemplate.inherit'),
504
+ });
505
+
506
+ /** Templates usable at `scope` (and for `tag` at the component scope), labelled in the authoring locale. */
507
+ const templateOptions = (scope: StyleScope, tag?: string): InspectorOption[] =>
508
+ styleTemplates
509
+ .filter(
510
+ (template) =>
511
+ template.scopes.includes(scope) &&
512
+ (tag === undefined || template.components === undefined || template.components.includes(tag)),
513
+ )
514
+ .map((template) => {
515
+ const label = t(template.messages, 'label');
516
+ return { value: template.name, label: label === 'label' ? template.name : label };
517
+ });
518
+
519
+ const labelOf = (tag: string): string => {
520
+ const descriptor = byTag.get(tag);
521
+ if (descriptor === undefined) return tag;
522
+ const label = t(descriptor.manifest.messages, descriptor.label);
523
+ return label === descriptor.label ? tag : label;
524
+ };
525
+
526
+ const pointsOf = (node: ElementNode): number | null => {
527
+ if (registered.get(node.tag)?.graded !== true) return null;
528
+ const n = Object.hasOwn(node.attrs, 'points') ? Number(node.attrs.points) : Number.NaN;
529
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_POINTS;
530
+ };
531
+
532
+ const outline = (source: string): Outline => {
533
+ const { issues } = engine.validate(source);
534
+ const idOf = (node: ElementNode) => (Object.hasOwn(node.attrs, 'id') ? (node.attrs.id ?? null) : null);
535
+ const entry = (node: ElementNode): OutlineComponent => {
536
+ const id = idOf(node);
537
+ const counts = count(issues, (i) => id !== null && i.at.element === id);
538
+ return { id, tag: node.tag, label: labelOf(node.tag), points: pointsOf(node), ...counts };
539
+ };
540
+ const components = (nodes: readonly Node[], out: OutlineComponent[] = []): OutlineComponent[] => {
541
+ for (const node of nodes) {
542
+ if (node.type !== 'element') continue;
543
+ if (registered.has(node.tag)) out.push(entry(node));
544
+ else components(node.children, out);
545
+ }
546
+ return out;
547
+ };
548
+ const block = (
549
+ kind: OutlineBlock['kind'],
550
+ node: ElementNode | null,
551
+ parts: readonly OutlineComponent[],
552
+ ): OutlineBlock => {
553
+ const ids = new Set(parts.flatMap((part) => (part.id === null ? [] : [part.id])));
554
+ const points = sum(parts.map((part) => part.points));
555
+ const label =
556
+ node !== null ? labelOf(node.tag) : t(EDITOR_NAMESPACE, points === null ? 'block.text' : 'block.gap');
557
+ return {
558
+ kind,
559
+ id: node === null ? null : idOf(node),
560
+ tag: node?.tag ?? null,
561
+ label,
562
+ points,
563
+ components: parts,
564
+ ...count(issues, (i) => i.at.element !== null && ids.has(i.at.element)),
565
+ };
566
+ };
567
+ const blocks = (content: readonly Node[]): OutlineBlock[] => {
568
+ const out: OutlineBlock[] = [];
569
+ let run: Node[] = [];
570
+ const flush = () => {
571
+ if (run.some((n) => n.type === 'element' || n.value.trim() !== ''))
572
+ out.push(block('text', null, components(run)));
573
+ run = [];
574
+ };
575
+ for (const node of content) {
576
+ if (node.type === 'element' && node.tag === COLUMNS_TAG) {
577
+ // In reading order, as the surface numbers them: a layout is no block, what is in its columns is.
578
+ flush();
579
+ for (const column of node.children) {
580
+ if (isElement(column, COLUMN_TAG)) out.push(...blocks(column.children));
581
+ }
582
+ } else if (node.type === 'element' && registered.get(node.tag)?.display === 'block') {
583
+ flush();
584
+ out.push(block('component', node, [entry(node)]));
585
+ } else {
586
+ run.push(node);
587
+ }
588
+ }
589
+ flush();
590
+ return out;
591
+ };
592
+ const page = (id: string | null, label: string | null, content: readonly Node[]): OutlinePage => {
593
+ const list = blocks(content);
594
+ return {
595
+ id,
596
+ label,
597
+ ...count(issues, (i) =>
598
+ id === null ? i.at.page === null && i.at.tag !== null && i.at.tag !== DOC_TAG : i.at.page === id,
599
+ ),
600
+ components: components(content),
601
+ blocks: list,
602
+ points: sum(list.map((b) => b.points)),
603
+ };
604
+ };
605
+ const nodes = parseHtml(source);
606
+ const doc = nodes.find((n): n is ElementNode => isElement(n, DOC_TAG));
607
+ const content = withoutRules(doc?.children ?? nodes);
608
+ const pages: OutlinePage[] = [];
609
+ if (content.some((n) => isElement(n, PAGE_TAG))) {
610
+ // Loose content between pages (an error) is listed as an implicit page where it has components.
611
+ let loose: Node[] = [];
612
+ const flush = () => {
613
+ const entry = page(null, null, loose);
614
+ if (entry.components.length > 0) pages.push(entry);
615
+ loose = [];
616
+ };
617
+ for (const node of content) {
618
+ if (!isElement(node, PAGE_TAG)) {
619
+ loose.push(node);
620
+ continue;
621
+ }
622
+ flush();
623
+ const attr = (name: string) => (Object.hasOwn(node.attrs, name) ? (node.attrs[name] ?? null) : null);
624
+ pages.push(page(attr('id'), attr('label'), node.children));
625
+ }
626
+ flush();
627
+ } else {
628
+ pages.push(page(null, null, content));
629
+ }
630
+ return { pages, ...count(issues, () => true), points: sum(pages.map((p) => p.points)) };
631
+ };
632
+
633
+ /**
634
+ * How authors know each component with an id, with its page's number when the document has pages: a block
635
+ * component directly on its page by the number of its block there (the blocks of `outline`, which its card's head
636
+ * shows), any other by its number among the components of its type on its page (document order); `page` is null
637
+ * without pages. The last source's names are kept.
638
+ */
639
+ type Name = { readonly n: number; readonly page: number | null };
640
+ let named: { readonly source: string; readonly names: Map<string, Name> } | null = null;
641
+ const namesIn = (source: string): Map<string, Name> => {
642
+ if (named?.source === source) return named.names;
643
+ const names = new Map<string, Name>();
644
+ const nodes = parseHtml(source);
645
+ const content = withoutRules(
646
+ nodes.find((n): n is ElementNode => isElement(n, DOC_TAG))?.children ?? nodes,
647
+ );
648
+ const paged = content.some((n) => isElement(n, PAGE_TAG));
649
+ const set = (node: ElementNode, n: number, page: number | null) => {
650
+ const id = Object.hasOwn(node.attrs, 'id') ? node.attrs.id : undefined;
651
+ if (id === undefined || id === '' || names.has(id)) return;
652
+ names.set(id, { n, page });
653
+ };
654
+ const inText = (nodes: readonly Node[], page: number | null, seen: Map<string, number>) => {
655
+ for (const node of nodes) {
656
+ if (node.type !== 'element') continue;
657
+ if (!registered.has(node.tag)) {
658
+ inText(node.children, page, seen);
659
+ continue;
660
+ }
661
+ const n = (seen.get(node.tag) ?? 0) + 1;
662
+ seen.set(node.tag, n);
663
+ set(node, n, page);
664
+ }
665
+ };
666
+ const blocks = (nodes: readonly Node[], page: number | null) => {
667
+ const seen = new Map<string, number>();
668
+ let block = 0;
669
+ let text = false;
670
+ const walk = (nodes: readonly Node[]) => {
671
+ for (const node of nodes) {
672
+ if (node.type === 'element' && node.tag === COLUMNS_TAG) {
673
+ for (const column of node.children) {
674
+ text = false;
675
+ if (isElement(column, COLUMN_TAG)) walk(column.children);
676
+ }
677
+ text = false;
678
+ continue;
679
+ }
680
+ if (node.type === 'element' && registered.get(node.tag)?.display === 'block') {
681
+ block++;
682
+ text = false;
683
+ set(node, block, page);
684
+ continue;
685
+ }
686
+ // A text block starts with its first element or words, as in `outline`.
687
+ if (!text && (node.type === 'element' || node.value.trim() !== '')) {
688
+ block++;
689
+ text = true;
690
+ }
691
+ inText([node], page, seen);
692
+ }
693
+ };
694
+ walk(nodes);
695
+ };
696
+ if (paged) {
697
+ const pages = content.filter((n): n is ElementNode => isElement(n, PAGE_TAG));
698
+ pages.forEach((page, i) => {
699
+ blocks(page.children, i + 1);
700
+ });
701
+ } else {
702
+ blocks(content, null);
703
+ }
704
+ named = { source, names };
705
+ return names;
706
+ };
707
+
708
+ /** `source` with fresh ids, none of them in `used` (which takes them), on pages and components without one. */
709
+ function withIds(source: string, used: Set<string>): string {
710
+ const edits: Edit[] = [];
711
+ for (const { tag, id, range } of scanRanges(source)) {
712
+ if (id !== null && id.trim() !== '') continue;
713
+ if (tag !== PAGE_TAG && !registered.has(tag)) continue;
714
+ const prefix = tag === PAGE_TAG ? 'page' : (byTag.get(tag)?.idPrefix ?? tag.replace(/^astl-/, ''));
715
+ const fresh = freshId(isSourceId(`${prefix}-1`) ? prefix : 'item', used);
716
+ used.add(fresh);
717
+ const written = range.startTag.attributes.find((a) => a.name === 'id');
718
+ const at = range.startTag.start + 1 + tag.length;
719
+ edits.push(
720
+ written === undefined
721
+ ? { start: at, end: at, text: ` id="${fresh}"` }
722
+ : { start: written.start, end: written.end, text: `id="${fresh}"` },
723
+ );
724
+ }
725
+ return applyEdits(source, edits);
726
+ }
727
+
728
+ /**
729
+ * `html` (to insert into `source`) where each element of a type with a `companion` whose attribute is empty names
730
+ * one: the first of `html` (a starter brings its own), else of `source`, else the one `withCompanion` adds.
731
+ */
732
+ function linkCompanions(html: string, source: string, used: ReadonlySet<string>): string {
733
+ const edits: Edit[] = [];
734
+ for (const { tag, range } of scanRanges(html)) {
735
+ const companion = byTag.get(tag)?.companion;
736
+ const other = companion === undefined ? undefined : byTag.get(companion.tag);
737
+ if (companion === undefined || other === undefined) continue;
738
+ if (attributeValue(range.startTag, companion.attribute)) continue;
739
+ const first = (within: string) => scanElements(within).find((e) => e.tag === companion.tag && e.id)?.id;
740
+ const value = first(html) ?? first(source) ?? freshId(other.idPrefix, used);
741
+ const own = html.slice(range.start, range.end);
742
+ const text = updateElement(own, { kind: 'attribute', name: companion.attribute, value });
743
+ edits.push({ start: range.start, end: range.end, text });
744
+ }
745
+ return applyEdits(html, edits);
746
+ }
747
+
748
+ function instantiate(tag: string, source: string, templateId?: string, selection = ''): string {
749
+ const descriptor = byTag.get(tag);
750
+ if (descriptor === undefined) throw new TypeError(`No editor descriptor for <${tag}>`);
751
+ const named = templateId === undefined ? null : descriptor.templates?.find((x) => x.id === templateId);
752
+ if (named === undefined)
753
+ throw new TypeError(`Editor descriptor <${tag}> has no template "${templateId}"`);
754
+ const used = usedIds(source);
755
+ const id = freshId(descriptor.idPrefix, used);
756
+ const namespace = descriptor.manifest.messages;
757
+ const html = (named?.template ?? descriptor.template)
758
+ .replace(/\{\{t:([^}]+)\}\}/g, (_, key: string) => escapeHtml(t(namespace, key.trim())))
759
+ .replace(/\{\{id\}\}/g, id)
760
+ // Last: the author's text is never read for placeholders.
761
+ .replace(/\{\{selection\}\}/g, () => escapeHtml(selection));
762
+ for (const written of usedIds(html)) used.add(written);
763
+ // A starter can hold more components (gaps and their word bank): those it writes without an id get fresh ones.
764
+ return linkCompanions(withIds(html, used), source, used);
765
+ }
766
+
767
+ return {
768
+ engine,
769
+ locale,
770
+ descriptors: [...byTag.values()],
771
+ elements: options.elements ?? [],
772
+ styleTemplates,
773
+ urlPolicy: strictUrlPolicy(options.urlPolicy ?? isSafeUrl),
774
+ fonts: (options.fonts ?? DEFAULT_FONTS).map(normalFont),
775
+ styles: readyStyles(options.styles ?? DEFAULT_STYLES, (name) => {
776
+ const key = `style.preset.${name}`;
777
+ const label = t(EDITOR_NAMESPACE, key);
778
+ return label === key ? name : label;
779
+ }),
780
+ uploadAsset: options.uploadAsset ?? null,
781
+ pickPicture: options.pickPicture ?? null,
782
+ descriptor: (tag) => byTag.get(tag) ?? null,
783
+ templates: (tag) => byTag.get(tag)?.templates ?? [],
784
+ t,
785
+ loadMenuMessages: () =>
786
+ (menus ??= Promise.resolve(options.menuMessages?.() ?? []).then(addMessages, (error: unknown) => {
787
+ menus = null;
788
+ console.error(error);
789
+ })),
790
+ addMessages,
791
+ instantiate,
792
+ withCompanion(tag, source, id) {
793
+ const companion = byTag.get(tag)?.companion;
794
+ if (companion === undefined || !byTag.has(companion.tag)) return null;
795
+ const doc = elementTree(source).find((range) => range.name === DOC_TAG);
796
+ if (doc === undefined) return null;
797
+ const pages = doc.children.filter((range) => range.name === PAGE_TAG);
798
+ const elements = scanRanges(source);
799
+ // The page an element plays on: the document without pages (or for an element on none).
800
+ const pageOf = (range: ElementRange) =>
801
+ pages.find((page) => page.start <= range.start && range.end <= page.end) ?? doc;
802
+ const companionsOf = (page: ElementRange) =>
803
+ elements.flatMap((e) =>
804
+ e.tag === companion.tag && e.id && page.start <= e.start && e.end <= page.end ? [e.id] : [],
805
+ );
806
+ const named = (range: ElementRange) => attributeValue(range.startTag, companion.attribute) ?? '';
807
+ const target = elements.find(
808
+ (e) =>
809
+ e.tag === tag &&
810
+ (id === undefined ? !companionsOf(pageOf(e.range)).includes(named(e.range)) : e.id === id),
811
+ );
812
+ if (target === undefined) return null;
813
+ const page = pageOf(target.range);
814
+ const own = companionsOf(page);
815
+ if (own.includes(named(target.range))) return null;
816
+ const [first] = own;
817
+ const added = first === undefined ? instantiate(companion.tag, source) : '';
818
+ const value = first ?? scanElements(added).find((e) => e.tag === companion.tag)?.id ?? '';
819
+ const html = source.slice(target.start, target.end);
820
+ const at = page.endTag?.start ?? page.end;
821
+ return applyEdits(source, [
822
+ {
823
+ start: target.start,
824
+ end: target.end,
825
+ text: updateElement(html, { kind: 'attribute', name: companion.attribute, value }),
826
+ },
827
+ { start: at, end: at, text: added },
828
+ ]);
829
+ },
830
+ inspect(elementHtml, source) {
831
+ const el = firstElement(parseHtml(elementHtml));
832
+ if (el === null) return null;
833
+ const manifest = manifestOf(el.tag);
834
+ if (manifest === null) return null;
835
+ const templates = templateOptions('component', el.tag);
836
+ // Another component of the document, scanned and parsed only when a field asks for it.
837
+ const find = (id: string): ElementNode | null => {
838
+ if (source === undefined || id === '') return null;
839
+ const at = scanElements(source).find((e) => e.id === id);
840
+ return at === undefined ? null : firstElement(parseHtml(source.slice(at.start, at.end)));
841
+ };
842
+ return inspectorModel(el, manifest, byTag.get(el.tag) ?? null, textsFor(manifest), templates, find);
843
+ },
844
+ inspectDocument(source) {
845
+ // The scanner, as `update` uses it: the document is the first start tag (and no full parse per keystroke).
846
+ const start = tokenize(source).find((tag) => tag.type === 'start');
847
+ if (start?.name !== DOC_TAG) return null;
848
+ const written = attributeValue(start, STYLE_TEMPLATE_ATTRIBUTE);
849
+ const templates = templateOptions('document');
850
+ if (templates.length === 0 && written === null) return null;
851
+ const root = element(DOC_TAG, written === null ? {} : { [STYLE_TEMPLATE_ATTRIBUTE]: written });
852
+ const label = t(EDITOR_NAMESPACE, 'inspector.documentStyle');
853
+ const unset = t(EDITOR_NAMESPACE, 'inspector.styleTemplate.default');
854
+ return {
855
+ tag: DOC_TAG,
856
+ id: null,
857
+ label: t(EDITOR_NAMESPACE, 'inspector.document'),
858
+ icon: null,
859
+ fields: [styleTemplateField(root, label, unset, templates)],
860
+ };
861
+ },
862
+ update: updateElement,
863
+ validate: (source) => engine.validate(source),
864
+ describe(issue, source, options) {
865
+ const { id } = issue.params;
866
+ const at =
867
+ source !== undefined &&
868
+ issue.namespace !== ENGINE_NAMESPACE &&
869
+ id === issue.at.element &&
870
+ typeof id === 'string'
871
+ ? namesIn(source).get(id)
872
+ : undefined;
873
+ const name =
874
+ at === undefined
875
+ ? undefined
876
+ : at.page === null || options?.page === false
877
+ ? String(at.n)
878
+ : t(EDITOR_NAMESPACE, 'issue.onPage', { n: at.n, page: at.page });
879
+ const named = name === undefined ? issue : { ...issue, params: { ...issue.params, id: name } };
880
+ const own = t(named.namespace, named.code, named.params);
881
+ return own === named.code ? engine.describe(named, locale) : own;
882
+ },
883
+ assignIds: (source) => withIds(source, usedIds(source)),
884
+ outline,
885
+ async preview(source, options) {
886
+ const result = await engine.compile(source, { salt });
887
+ if (!result.ok) return { ok: false, issues: result.issues };
888
+ return {
889
+ ok: true,
890
+ view: result.view,
891
+ checker: localChecker(engine, result.key, options?.policy),
892
+ issues: result.issues,
893
+ };
894
+ },
895
+ };
896
+ }