@astl/editor-tiptap 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 (69) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/LICENSE +202 -0
  3. package/README.md +49 -0
  4. package/dist/adapter.d.ts +13 -0
  5. package/dist/adapter.d.ts.map +1 -0
  6. package/dist/adapter.js +421 -0
  7. package/dist/adapter.js.map +1 -0
  8. package/dist/blocks.d.ts +96 -0
  9. package/dist/blocks.d.ts.map +1 -0
  10. package/dist/blocks.js +460 -0
  11. package/dist/blocks.js.map +1 -0
  12. package/dist/define.d.ts +64 -0
  13. package/dist/define.d.ts.map +1 -0
  14. package/dist/define.js +20 -0
  15. package/dist/define.js.map +1 -0
  16. package/dist/element.d.ts +91 -0
  17. package/dist/element.d.ts.map +1 -0
  18. package/dist/element.js +779 -0
  19. package/dist/element.js.map +1 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/layouts.d.ts +52 -0
  25. package/dist/layouts.d.ts.map +1 -0
  26. package/dist/layouts.js +198 -0
  27. package/dist/layouts.js.map +1 -0
  28. package/dist/nodes.d.ts +150 -0
  29. package/dist/nodes.d.ts.map +1 -0
  30. package/dist/nodes.js +2426 -0
  31. package/dist/nodes.js.map +1 -0
  32. package/dist/source-view.d.ts +26 -0
  33. package/dist/source-view.d.ts.map +1 -0
  34. package/dist/source-view.js +114 -0
  35. package/dist/source-view.js.map +1 -0
  36. package/dist/source.d.ts +8 -0
  37. package/dist/source.d.ts.map +1 -0
  38. package/dist/source.js +24 -0
  39. package/dist/source.js.map +1 -0
  40. package/dist/style.d.ts +16 -0
  41. package/dist/style.d.ts.map +1 -0
  42. package/dist/style.js +568 -0
  43. package/dist/style.js.map +1 -0
  44. package/dist/styles.d.ts +5 -0
  45. package/dist/styles.d.ts.map +1 -0
  46. package/dist/styles.js +921 -0
  47. package/dist/styles.js.map +1 -0
  48. package/dist/surface.d.ts +24 -0
  49. package/dist/surface.d.ts.map +1 -0
  50. package/dist/surface.js +90 -0
  51. package/dist/surface.js.map +1 -0
  52. package/dist/tiptap.d.ts +10 -0
  53. package/dist/tiptap.d.ts.map +1 -0
  54. package/dist/tiptap.js +9 -0
  55. package/dist/tiptap.js.map +1 -0
  56. package/package.json +51 -4
  57. package/src/adapter.ts +421 -0
  58. package/src/blocks.ts +577 -0
  59. package/src/define.ts +84 -0
  60. package/src/element.ts +988 -0
  61. package/src/index.ts +10 -0
  62. package/src/layouts.ts +220 -0
  63. package/src/nodes.ts +2690 -0
  64. package/src/source-view.ts +138 -0
  65. package/src/source.ts +27 -0
  66. package/src/style.ts +638 -0
  67. package/src/styles.ts +931 -0
  68. package/src/surface.ts +110 -0
  69. package/src/tiptap.ts +9 -0
package/src/element.ts ADDED
@@ -0,0 +1,988 @@
1
+ /**
2
+ * `<astl-editor>`: the authoring kit (toolbar, inspector, issues, preview) around an editing surface. The surface is
3
+ * TipTap by default, imported on demand; any other editor plugs in through `adapter` and a `slot="surface"` child, and
4
+ * then TipTap is never loaded.
5
+ */
6
+ import {
7
+ type AttemptPolicy,
8
+ type ComponentDefinition,
9
+ type ComponentManifest,
10
+ directionOf,
11
+ type EditorAdapter,
12
+ type EditorDescriptor,
13
+ type Engine,
14
+ type GroundColors,
15
+ type Issue,
16
+ type MessageCatalog,
17
+ type MessageParams,
18
+ type NormalisationProfile,
19
+ negotiateLocale,
20
+ PRACTICE_POLICY,
21
+ type SlotKind,
22
+ type StyleTemplate,
23
+ type UrlPolicy,
24
+ } from '@astl/core';
25
+ import {
26
+ type AstlPictureDialog,
27
+ type AstlPreview,
28
+ type AstlToolbar,
29
+ type Authoring,
30
+ createAuthoring,
31
+ DEFAULT_FONTS,
32
+ DEFAULT_STYLES,
33
+ EDITOR_NAMESPACE,
34
+ type EditorFont,
35
+ type EditorStylePreset,
36
+ editorMessages,
37
+ type Outline,
38
+ type PickPicture,
39
+ type ToolbarView,
40
+ type UploadAsset,
41
+ } from '@astl/editor';
42
+ import { createEngine } from '@astl/engine';
43
+ import type { ElementEntry } from '@astl/player';
44
+ import { type ThemeSetting, tokens, tokensCss } from '@astl/tokens';
45
+ import {
46
+ type CSSResult,
47
+ type CSSResultGroup,
48
+ css,
49
+ html,
50
+ LitElement,
51
+ nothing,
52
+ type PropertyDeclarations,
53
+ type PropertyValues,
54
+ type TemplateResult,
55
+ unsafeCSS,
56
+ } from 'lit';
57
+ import { keyed } from 'lit/directives/keyed.js';
58
+ import type { SurfaceChange } from './blocks.js';
59
+ import type { DefineEditorOptions, EditorHostView } from './define.js';
60
+ import type { Surface } from './surface.js';
61
+
62
+ /**
63
+ * Every token as `inherit` on `selector`, for elements that redeclare the tokens on their own `:host` (the kit
64
+ * elements): a rule from the outer tree wins over `:host`, so tokens set on `<astl-editor>` reach them. The kit's
65
+ * preview forwards them to its player the same way.
66
+ */
67
+ function inheritTokens(selector: string): CSSResult {
68
+ const names = [tokens.scale, tokens.themes.light, tokens.themeScale.light].flatMap(Object.keys);
69
+ const lines = ['color-scheme: inherit;', ...names.map((name) => `--astl-${name}: inherit;`)];
70
+ return unsafeCSS(`${selector} {\n${lines.join('\n')}\n}`);
71
+ }
72
+
73
+ /**
74
+ * The shadow root of `<astl-editor>`: tokens, the toolbar over the surface beside the kit, everything in one column
75
+ * when narrow. The surface's own stylesheet comes with the surface (`styles.ts`).
76
+ */
77
+ const editorStyles: CSSResultGroup = [
78
+ // Tokens sit on :host so host pages can override any --astl-* property on <astl-editor> itself.
79
+ unsafeCSS(tokensCss(':host')),
80
+ inheritTokens('astl-toolbar, astl-inspector, astl-issues, astl-preview, astl-picture-dialog'),
81
+ css`
82
+ :host {
83
+ display: block;
84
+ container-type: inline-size;
85
+ color: var(--astl-ink);
86
+ font-family: var(--astl-font-body);
87
+ font-size: var(--astl-size-ui);
88
+ line-height: 1.4;
89
+ }
90
+ :host([hidden]) {
91
+ display: none;
92
+ }
93
+ `,
94
+ // The bands are a column of flex items, not a grid: the spec makes a grid item's containing block its grid area,
95
+ // which may hold a host's sticky toolbar (`::part(toolbar)`) to its own row; a flex item's is the whole column.
96
+ css`
97
+ .layout {
98
+ display: flex;
99
+ flex-direction: column;
100
+ gap: var(--astl-editor-layout-gap, var(--astl-space-4));
101
+ }
102
+ .work {
103
+ display: grid;
104
+ grid-template-columns: minmax(0, 1fr);
105
+ align-items: start;
106
+ gap: var(--astl-space-4);
107
+ }
108
+ .surface,
109
+ .side,
110
+ .start,
111
+ .end {
112
+ display: flex;
113
+ flex-direction: column;
114
+ gap: var(--astl-space-4);
115
+ min-inline-size: 0;
116
+ }
117
+ .surface {
118
+ position: relative;
119
+ }
120
+ ::slotted(*) {
121
+ box-sizing: border-box;
122
+ inline-size: 100%;
123
+ max-inline-size: 100%;
124
+ }
125
+ .status {
126
+ margin: 0;
127
+ padding: var(--astl-space-4);
128
+ border: var(--astl-outline-width) solid var(--astl-line);
129
+ border-radius: var(--astl-radius-l);
130
+ background: var(--astl-surface);
131
+ color: var(--astl-ink-muted);
132
+ }
133
+ `,
134
+ // The side column and the host's columns in another view, and a host column with nothing slotted: out of the way (the
135
+ // grid keeps no track and no gap for them). The notice line with nothing to say: out of sight, but still in the
136
+ // accessibility tree, so its next message is announced.
137
+ css`
138
+ .side[hidden],
139
+ .start[hidden],
140
+ .end[hidden] {
141
+ display: none;
142
+ }
143
+ .status.idle {
144
+ position: absolute;
145
+ inline-size: 1px;
146
+ block-size: 1px;
147
+ padding: 0;
148
+ border: 0;
149
+ overflow: hidden;
150
+ clip-path: inset(50%);
151
+ white-space: nowrap;
152
+ }
153
+ `,
154
+ // The status line under the toolbar: the counts in mono, then whether it is ready to share (in words, never the
155
+ // colour alone).
156
+ css`
157
+ .status-line {
158
+ display: flex;
159
+ flex-wrap: wrap;
160
+ justify-content: space-between;
161
+ gap: 0 var(--astl-space-3);
162
+ margin: 0;
163
+ color: var(--astl-ink-muted);
164
+ font-size: var(--astl-size-small);
165
+ }
166
+ .counts {
167
+ font-family: var(--astl-font-mono);
168
+ }
169
+ .counts span + span::before {
170
+ content: '\\00b7' / '';
171
+ margin-inline: var(--astl-space-1);
172
+ }
173
+ .ready {
174
+ color: var(--astl-success);
175
+ font-weight: 600;
176
+ }
177
+ .error {
178
+ color: var(--astl-danger);
179
+ }
180
+ `,
181
+ // Wide: one row, between the toolbar and the preview: the host's `start` column, the surface, the side column (3:2 with
182
+ // the surface, at least 18rem), the host's `end` column. A row, not a grid, so a column that is not there takes no
183
+ // track and no gap. The side column and the host's columns stay in view while the content scrolls, within the work
184
+ // row only (never over the preview), each scrolling on its own when taller than the window.
185
+ css`
186
+ @container (min-inline-size: 48rem) {
187
+ .work {
188
+ display: flex;
189
+ }
190
+ .surface {
191
+ flex: 3 1 0;
192
+ }
193
+ .side {
194
+ flex: 2 1 0;
195
+ min-inline-size: 18rem;
196
+ }
197
+ .start,
198
+ .end {
199
+ flex: none;
200
+ }
201
+ .side,
202
+ .start,
203
+ .end {
204
+ position: sticky;
205
+ inset-block-start: var(--astl-editor-sticky-top, var(--astl-space-4));
206
+ max-block-size: calc(100dvh - var(--astl-editor-sticky-top, var(--astl-space-4)) - var(--astl-space-4));
207
+ overflow-y: auto;
208
+ padding: var(--astl-focus-width);
209
+ margin: calc(-1 * var(--astl-focus-width));
210
+ }
211
+ }
212
+ `,
213
+ ];
214
+
215
+ /** What `defineEditor` registered: shared by every `<astl-editor>` of this module instance. */
216
+ interface Registered {
217
+ readonly components: ReadonlyMap<string, ComponentDefinition>;
218
+ readonly editors: ReadonlyMap<string, EditorDescriptor>;
219
+ readonly elements: ReadonlyMap<string, ElementEntry>;
220
+ readonly styleTemplates: ReadonlyMap<string, StyleTemplate>;
221
+ readonly slotKinds: ReadonlyMap<string, SlotKind>;
222
+ readonly catalogs: readonly MessageCatalog[];
223
+ readonly profile: Partial<NormalisationProfile>;
224
+ readonly urlPolicy: UrlPolicy | null;
225
+ readonly groundColors: GroundColors | null;
226
+ readonly uploadAsset: UploadAsset | null;
227
+ readonly pickPicture: PickPicture | null;
228
+ /** The style controls' fonts (`DefineEditorOptions.fonts`). */
229
+ readonly fonts: readonly EditorFont[];
230
+ /** The ready styles (`DefineEditorOptions.styles`). */
231
+ readonly styles: readonly EditorStylePreset[];
232
+ /** The toolbar's featured inserts (`DefineEditorOptions.featured`). */
233
+ readonly featured: readonly string[];
234
+ /** The host's views (`DefineEditorOptions.views`). */
235
+ readonly views: readonly EditorHostView[];
236
+ /** The insert menus' catalogs (`DefineEditorOptions.menuMessages`). */
237
+ readonly menuMessages: (() => Promise<readonly MessageCatalog[]>) | null;
238
+ /** The engine of every registered component, for editors without a `components` list. */
239
+ readonly engine: Engine;
240
+ /** Bumped on every registration. */
241
+ readonly version: number;
242
+ }
243
+
244
+ /** The tag of a preview element: the one place that reads the shape of `elements`. */
245
+ const elementTag = (element: ElementEntry): string =>
246
+ 'load' in element ? element.tag : element.manifest.tag;
247
+
248
+ let secret: string | null = null;
249
+
250
+ /**
251
+ * The preview compiles in the browser, so its secret only keeps preview ids apart from published ones: a random one
252
+ * per page, never a known value.
253
+ */
254
+ function previewSecret(): string {
255
+ secret ??= Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) =>
256
+ b.toString(16).padStart(2, '0'),
257
+ ).join('');
258
+ return secret;
259
+ }
260
+
261
+ type Lists = Omit<Registered, 'engine' | 'version'>;
262
+
263
+ function engineOf(lists: Lists, components: readonly ComponentDefinition[]): Engine {
264
+ return createEngine({
265
+ components,
266
+ secret: previewSecret(),
267
+ slotKinds: [...lists.slotKinds.values()],
268
+ profile: lists.profile,
269
+ catalogs: lists.catalogs,
270
+ styleTemplates: [...lists.styleTemplates.values()],
271
+ ...(lists.urlPolicy === null ? {} : { urlPolicy: lists.urlPolicy }),
272
+ ...(lists.groundColors === null ? {} : { groundColors: lists.groundColors }),
273
+ });
274
+ }
275
+
276
+ const EMPTY: Lists = {
277
+ components: new Map(),
278
+ editors: new Map(),
279
+ elements: new Map(),
280
+ styleTemplates: new Map(),
281
+ slotKinds: new Map(),
282
+ catalogs: [],
283
+ profile: {},
284
+ urlPolicy: null,
285
+ groundColors: null,
286
+ uploadAsset: null,
287
+ pickPicture: null,
288
+ fonts: DEFAULT_FONTS,
289
+ styles: DEFAULT_STYLES,
290
+ featured: [],
291
+ views: [],
292
+ menuMessages: null,
293
+ };
294
+
295
+ let registered: Registered | null = null;
296
+
297
+ /** Without `defineEditor` (the class defined by hand): nothing registered. */
298
+ function current(): Registered {
299
+ registered ??= { ...EMPTY, engine: engineOf(EMPTY, []), version: 0 };
300
+ return registered;
301
+ }
302
+
303
+ /** Connected editors: a registration re-renders them. */
304
+ const connected = new Set<AstlEditor>();
305
+
306
+ /** `items` added by key: the same object again is skipped, another object under a taken key throws. */
307
+ function added<T>(
308
+ into: ReadonlyMap<string, T>,
309
+ items: readonly T[] | undefined,
310
+ key: (item: T) => string,
311
+ what: string,
312
+ ): ReadonlyMap<string, T> {
313
+ const out = new Map(into);
314
+ for (const item of items ?? []) {
315
+ const name = key(item);
316
+ const taken = out.get(name);
317
+ if (taken !== undefined && taken !== item) throw new Error(`${what} ${name} is already registered`);
318
+ out.set(name, item);
319
+ }
320
+ return out;
321
+ }
322
+
323
+ /** Adds to what every `<astl-editor>` offers (`defineEditor`). Checks everything before anything changes. */
324
+ export function register(options: DefineEditorOptions): void {
325
+ const before = registered ?? { ...EMPTY, version: 0 };
326
+ const tag = (item: { readonly manifest: ComponentManifest }) => item.manifest.tag;
327
+ const lists: Lists = {
328
+ components: added(before.components, options.components, tag, 'Component'),
329
+ editors: added(before.editors, options.editors, tag, 'Editor descriptor'),
330
+ elements: added(before.elements, options.elements, elementTag, 'Preview element'),
331
+ styleTemplates: added(before.styleTemplates, options.styleTemplates, (t) => t.name, 'Style template'),
332
+ slotKinds: added(before.slotKinds, options.slotKinds, (k) => k.kind, 'Slot kind'),
333
+ catalogs: [...new Set([...before.catalogs, ...(options.catalogs ?? [])])],
334
+ profile: { ...before.profile, ...options.profile },
335
+ urlPolicy: options.urlPolicy ?? before.urlPolicy,
336
+ groundColors: options.groundColors ?? before.groundColors,
337
+ uploadAsset: options.uploadAsset ?? before.uploadAsset,
338
+ pickPicture: options.pickPicture ?? before.pickPicture,
339
+ fonts: options.fonts ?? before.fonts,
340
+ styles: options.styles ?? before.styles,
341
+ featured: options.featured ?? before.featured,
342
+ views: options.views ?? before.views,
343
+ menuMessages: options.menuMessages ?? before.menuMessages,
344
+ };
345
+ // Nothing new (the same objects again): connected editors keep their surface, cursor and undo history.
346
+ const maps = ['components', 'editors', 'elements', 'styleTemplates', 'slotKinds'] as const;
347
+ const profile = (p: Lists['profile']) => JSON.stringify(Object.entries(p).sort());
348
+ if (
349
+ registered !== null &&
350
+ maps.every((list) => lists[list].size === before[list].size) &&
351
+ lists.catalogs.length === before.catalogs.length &&
352
+ lists.urlPolicy === before.urlPolicy &&
353
+ JSON.stringify(lists.groundColors) === JSON.stringify(before.groundColors) &&
354
+ lists.uploadAsset === before.uploadAsset &&
355
+ lists.pickPicture === before.pickPicture &&
356
+ lists.menuMessages === before.menuMessages &&
357
+ JSON.stringify(lists.fonts) === JSON.stringify(before.fonts) &&
358
+ JSON.stringify(lists.styles) === JSON.stringify(before.styles) &&
359
+ lists.featured.join(' ') === before.featured.join(' ') &&
360
+ JSON.stringify(lists.views) === JSON.stringify(before.views) &&
361
+ profile(lists.profile) === profile(before.profile)
362
+ ) {
363
+ return;
364
+ }
365
+ // The engine and the kit check definitions and descriptors now, not when an editor first renders.
366
+ const engine = engineOf(lists, [...lists.components.values()]);
367
+ createAuthoring({
368
+ engine,
369
+ descriptors: [...lists.editors.values()],
370
+ locale: 'en',
371
+ fonts: lists.fonts,
372
+ styles: lists.styles,
373
+ });
374
+ registered = { ...lists, engine, version: before.version + 1 };
375
+ for (const editor of connected) editor.requestUpdate();
376
+ }
377
+
378
+ /** The authoring of one editor: every registered type, or those `allowed` names. */
379
+ function authoringFor(r: Registered, locale: string, allowed: readonly string[] | null): Authoring {
380
+ const keep = <T>(items: ReadonlyMap<string, T>) =>
381
+ [...items.entries()].filter(([tag]) => allowed === null || allowed.includes(tag)).map(([, item]) => item);
382
+ return createAuthoring({
383
+ engine: allowed === null ? r.engine : engineOf(r, keep(r.components)),
384
+ descriptors: keep(r.editors),
385
+ elements: keep(r.elements),
386
+ locale,
387
+ catalogs: r.catalogs,
388
+ styleTemplates: [...r.styleTemplates.values()],
389
+ fonts: r.fonts,
390
+ styles: r.styles,
391
+ ...(r.urlPolicy === null ? {} : { urlPolicy: r.urlPolicy }),
392
+ ...(r.uploadAsset === null ? {} : { uploadAsset: r.uploadAsset }),
393
+ ...(r.pickPicture === null ? {} : { pickPicture: r.pickPicture }),
394
+ ...(r.menuMessages === null ? {} : { menuMessages: r.menuMessages }),
395
+ });
396
+ }
397
+
398
+ const THEMES: readonly ThemeSetting[] = ['light', 'dark', 'hc', 'auto'];
399
+
400
+ /** A message of the status line: a key of the kit's namespace and its parameters. */
401
+ interface Notice {
402
+ readonly key: string;
403
+ readonly params?: MessageParams;
404
+ }
405
+ const CHANGE = 'astl-editor-change';
406
+ const READY = 'astl-editor-ready';
407
+ const VIEW = 'astl-editor-view';
408
+
409
+ /** The views of every editor: the surface, and the source as HTML. */
410
+ const OWN_VIEWS: readonly string[] = ['visual', 'source'];
411
+
412
+ /** The status line counts this long after the last change, as the issues list does. */
413
+ const COUNT_DELAY_MS = 300;
414
+
415
+ /** The side panels, in the order `<astl-editor>` shows them by default. */
416
+ const PANELS: readonly string[] = ['issues', 'inspector'];
417
+
418
+ /** A space-separated list attribute as a list (null when absent). */
419
+ const listAttribute = {
420
+ fromAttribute: (value: string | null) =>
421
+ value === null ? null : value.split(/\s+/).filter((tag) => tag !== ''),
422
+ };
423
+
424
+ /** The `views` attribute: a JSON list of `{ name, label }` (null when absent or not JSON). */
425
+ const viewsAttribute = {
426
+ fromAttribute: (value: string | null): unknown => {
427
+ try {
428
+ return value === null ? null : JSON.parse(value);
429
+ } catch {
430
+ return null;
431
+ }
432
+ },
433
+ };
434
+
435
+ /** The icon parts of the toolbar, forwarded so hosts can draw their own icons (`::part(icon-text-t)`). */
436
+ const KIT_ICONS: readonly string[] = [
437
+ 'chevron',
438
+ 'bold',
439
+ 'italic',
440
+ 'underline',
441
+ 'link',
442
+ 'bulleted',
443
+ 'numbered',
444
+ 'undo',
445
+ 'redo',
446
+ 'wrap',
447
+ 'text',
448
+ 'image',
449
+ 'files',
450
+ 'add',
451
+ 'templates',
452
+ ];
453
+
454
+ /** The inspector's parts, forwarded so hosts can restyle its header, banners and fields (`::part(inspector-issue)`). */
455
+ const INSPECTOR_PARTS =
456
+ 'header: inspector-header, id: inspector-id, actions: inspector-actions, issue: inspector-issue, field: inspector-field, label: inspector-label, style: inspector-style';
457
+
458
+ /** The built-in surface module, once imported. */
459
+ let surfaces: typeof import('./surface.js') | null = null;
460
+ /** The source view's module, once imported (when the view first opens). */
461
+ let sourceViews: typeof import('./source-view.js') | null = null;
462
+
463
+ export class AstlEditor extends LitElement {
464
+ static override properties: PropertyDeclarations = {
465
+ locale: {},
466
+ components: { converter: listAttribute },
467
+ featured: { converter: listAttribute },
468
+ panels: { converter: listAttribute },
469
+ view: {},
470
+ views: { converter: viewsAttribute },
471
+ theme: {},
472
+ previewPolicy: { attribute: false },
473
+ adapter: { attribute: false },
474
+ };
475
+
476
+ static override styles: CSSResultGroup = editorStyles;
477
+
478
+ /** UI locale (`en`, `pl`); default: the `lang` attribute, else the browser languages, else `en`. */
479
+ declare locale: string | null;
480
+ /**
481
+ * The component types authors can use (space-separated tags in the attribute); null: every registered type. Others
482
+ * stay in the document, reported as unknown elements.
483
+ */
484
+ declare components: readonly string[] | null;
485
+ /**
486
+ * The toolbar's featured inserts, as buttons before "More" (space-separated in the attribute): component tags,
487
+ * `tag:template` for a named starter, and `text`, `picture`, `page-break`. Null: the list `defineEditor` got.
488
+ */
489
+ declare featured: readonly string[] | null;
490
+ /**
491
+ * The side column's panels, in order (space-separated in the attribute): `issues` and `inspector`. Null: both,
492
+ * issues first. Empty: no side column, the surface takes the width; a host then shows its own `<astl-inspector>`
493
+ * or `<astl-issues>`, wired with `authoring` and `adapter` once the editor is ready.
494
+ */
495
+ declare panels: readonly string[] | null;
496
+ /**
497
+ * What the editor shows: `visual` (default) the surface; `source` the document's HTML in a text area, which leaving
498
+ * applies (with errors the editor stays there and lists them, so no text is lost); or the `name` of one of `views`.
499
+ * The toolbar's view switch sets it; each change fires `astl-editor-view` (bubbles, composed; `detail.view`).
500
+ */
501
+ declare view: string;
502
+ /**
503
+ * The host's views, after "Visual" and "HTML" in the view switch: `{ name, label }` each (the attribute: a JSON
504
+ * list). One shows the host's `slot="view-<name>"` children in place of the editor. Null: the list `defineEditor` got.
505
+ */
506
+ declare views: readonly EditorHostView[] | null;
507
+ /** `light`, `dark`, `hc` or `auto` (the system's light or dark), passed on as `data-theme`. */
508
+ declare theme: ThemeSetting | null;
509
+ /**
510
+ * The policy the preview plays under: the one the host's students get, when it offers less than practice (no hints,
511
+ * no check of one interaction). Null: `PRACTICE_POLICY`. A change plays a shown preview again.
512
+ */
513
+ declare previewPolicy: AttemptPolicy | null;
514
+ /**
515
+ * The editor the kit drives. Default: TipTap, on a surface this element creates when it first renders without an
516
+ * adapter and without a `slot="surface"` child. Setting another adapter swaps the editor; null brings the TipTap
517
+ * surface back (with its document), unless a `slot="surface"` child is there.
518
+ */
519
+ declare adapter: EditorAdapter | null;
520
+
521
+ /** A value set while there is no adapter to take it. */
522
+ #pending: string | null = null;
523
+ /** Whether this element uses the built-in surface: decided when it first connects. */
524
+ #builtIn: boolean | null = null;
525
+ #surface: Surface | null = null;
526
+ #opening = false;
527
+ #failed = false;
528
+ /**
529
+ * The status line's message until the next edit: why a pasted or dropped picture was not inserted (no upload), or
530
+ * the page an edit added or joined.
531
+ */
532
+ #notice: Notice | null = null;
533
+ /** The page or block the surface's edit changed, waiting for that edit's change event, which shows it. */
534
+ #pageNotice: Notice | null = null;
535
+ /** Counts notices: the same message again is a new one for screen readers. */
536
+ #notices = 0;
537
+ /** The adapter the last ready event was for. */
538
+ #readyFor: EditorAdapter | null = null;
539
+ #resolveReady: () => void = () => {};
540
+ readonly #ready: Promise<void> = new Promise((resolve) => {
541
+ this.#resolveReady = resolve;
542
+ });
543
+
544
+ /** What the surface asks about pictures: the picture dialog of this element. */
545
+ #pictures = {
546
+ ask: (request: Parameters<AstlPictureDialog['ask']>[0]) =>
547
+ this.renderRoot.querySelector<AstlPictureDialog>('astl-picture-dialog')?.ask(request) ??
548
+ Promise.resolve(null),
549
+ refuse: () => {
550
+ this.#notice = { key: 'picture.pasteRefused' };
551
+ this.requestUpdate();
552
+ },
553
+ style: (kind: 'picture' | 'figure' | 'component') => {
554
+ void this.renderRoot.querySelector<AstlToolbar>('astl-toolbar')?.openStyle(kind);
555
+ },
556
+ };
557
+
558
+ /** What the surface tells of pages and blocks: a page added, joined or deleted, a block moved or deleted. */
559
+ #pages = (change: SurfaceChange) => {
560
+ this.#pageNotice = change;
561
+ };
562
+
563
+ /** Whether the host's `start` and `end` slots have elements: a column exists only while its slot does. */
564
+ #slotted = { start: false, end: false };
565
+ #slotChange = (event: Event): void => {
566
+ const slot = event.target as HTMLSlotElement;
567
+ const name = slot.name === 'end' ? 'end' : 'start';
568
+ const has = slot.assignedElements().length > 0;
569
+ if (this.#slotted[name] === has) return;
570
+ this.#slotted[name] = has;
571
+ this.requestUpdate();
572
+ };
573
+
574
+ /**
575
+ * The source view: the value laid out for reading when it opened (null until it shows), the author's text once they
576
+ * type (null before), and the errors that kept it there.
577
+ */
578
+ #shown: string | null = null;
579
+ #draft: string | null = null;
580
+ #errors: readonly Issue[] = [];
581
+ /** What the status line counts, a moment after each change. */
582
+ #outline: Outline | null = null;
583
+ #counting: ReturnType<typeof setTimeout> | undefined;
584
+ #authoring: { readonly key: string; readonly authoring: Authoring } | null = null;
585
+ #subscription: { readonly adapter: EditorAdapter; readonly off: () => void } | null = null;
586
+
587
+ constructor() {
588
+ super();
589
+ this.locale = null;
590
+ this.components = null;
591
+ this.featured = null;
592
+ this.panels = null;
593
+ this.view = 'visual';
594
+ this.views = null;
595
+ this.theme = 'auto';
596
+ this.previewPolicy = null;
597
+ this.adapter = null;
598
+ // A value set before the element was defined is an own property that hides the accessor.
599
+ if (Object.hasOwn(this, 'value')) {
600
+ const value: unknown = (this as { value?: unknown }).value;
601
+ delete (this as { value?: unknown }).value;
602
+ if (typeof value === 'string') this.value = value;
603
+ }
604
+ }
605
+
606
+ /** The source HTML (`<astl-doc>`): the adapter's, or a value waiting for it, or an empty document. */
607
+ get value(): string {
608
+ return (
609
+ this.adapter?.getSource() ?? this.#pending ?? `<astl-doc lang="${this.authoring.locale}"></astl-doc>`
610
+ );
611
+ }
612
+
613
+ set value(source: string) {
614
+ if (this.adapter === null) this.#pending = source;
615
+ else this.adapter.setSource(source);
616
+ }
617
+
618
+ /**
619
+ * Resolves when the editor is first ready: its surface loaded (or the host's `adapter` set) and the value in place,
620
+ * so `adapter`, `authoring` and `value` are usable. Each time an editor becomes ready (again after a swap or a
621
+ * reconnect, with a new `adapter`), `astl-editor-ready` fires (bubbles, composed).
622
+ */
623
+ get ready(): Promise<void> {
624
+ return this.#ready;
625
+ }
626
+
627
+ /**
628
+ * Compiles the current value and plays it in the preview, as the preview's own button does. Resolves when it plays,
629
+ * or shows why it cannot.
630
+ */
631
+ async preview(): Promise<void> {
632
+ await this.updateComplete;
633
+ await this.renderRoot.querySelector<AstlPreview>('astl-preview')?.refresh();
634
+ }
635
+
636
+ /** The kit's logic, built from the registrations, the UI locale and `components`. */
637
+ get authoring(): Authoring {
638
+ const r = current();
639
+ const locale = this.#uiLocale(r);
640
+ // The property also takes the attribute's form, a space-separated string.
641
+ const given = this.components as readonly string[] | string | null;
642
+ const allowed = typeof given === 'string' ? given.split(/\s+/).filter((tag) => tag !== '') : given;
643
+ const key = `${r.version}\n${locale}\n${allowed === null ? '*' : allowed.join(' ')}`;
644
+ if (this.#authoring?.key !== key) this.#authoring = { key, authoring: authoringFor(r, locale, allowed) };
645
+ return this.#authoring.authoring;
646
+ }
647
+
648
+ override connectedCallback(): void {
649
+ super.connectedCallback();
650
+ connected.add(this);
651
+ // Back in the document: the built-in surface again. The first decision waits for the first update, when Lit has
652
+ // applied the properties set before the element was defined (an `adapter`).
653
+ if (this.#builtIn === true) void this.#open();
654
+ this.#subscribe();
655
+ }
656
+
657
+ override disconnectedCallback(): void {
658
+ super.disconnectedCallback();
659
+ connected.delete(this);
660
+ clearTimeout(this.#counting);
661
+ this.#readyFor = null;
662
+ this.#subscribe();
663
+ // ProseMirror listens on the document: a removed editor is destroyed, its source kept for a reconnect.
664
+ const surface = this.#surface;
665
+ if (surface === null) return;
666
+ this.#pending = surface.adapter.getSource();
667
+ surface.destroy();
668
+ this.#surface = null;
669
+ this.adapter = null;
670
+ }
671
+
672
+ /** The host's views: the element's, else the registered ones. */
673
+ #hostViews(): readonly EditorHostView[] {
674
+ const views = this.views ?? current().views;
675
+ return Array.isArray(views) ? views : [];
676
+ }
677
+
678
+ /** The view on show: `view` when it names one, else `visual`. */
679
+ #view(): string {
680
+ const names = [...OWN_VIEWS, ...this.#hostViews().map((v) => v.name)];
681
+ return names.includes(this.view) ? this.view : 'visual';
682
+ }
683
+
684
+ /**
685
+ * Applies the source view's text, unless it has errors: then they show and the editor stays there. Only text that
686
+ * says something else than what was shown is applied (laid out the same, it is the same document): looking changes
687
+ * nothing.
688
+ */
689
+ #leaveSource(): boolean {
690
+ const text = this.#draft ?? this.#shown ?? this.value;
691
+ const errors = this.authoring.validate(text).issues.filter((issue) => issue.severity === 'error');
692
+ this.#errors = errors;
693
+ if (errors.length > 0) {
694
+ this.#notice = { key: 'view.sourceErrors', params: { n: errors.length } };
695
+ this.#notices++;
696
+ return false;
697
+ }
698
+ if (this.#draft !== null && sourceViews?.formatHtml(this.#draft) !== this.#shown)
699
+ this.value = this.#draft;
700
+ this.#draft = null;
701
+ return true;
702
+ }
703
+
704
+ /** Counts the document for the status line, after `delay` ms. */
705
+ #count(delay: number): void {
706
+ clearTimeout(this.#counting);
707
+ this.#counting = setTimeout(() => {
708
+ const adapter = this.adapter;
709
+ this.#outline = adapter === null ? null : this.authoring.outline(adapter.getSource());
710
+ this.requestUpdate();
711
+ }, delay);
712
+ }
713
+
714
+ protected override willUpdate(changed: PropertyValues<this>): void {
715
+ if (changed.has('theme')) this.dataset.theme = this.#theme();
716
+ if (changed.has('view')) {
717
+ const before = changed.get('view');
718
+ if (before === 'source' && this.view !== 'source' && !this.#leaveSource()) this.view = 'source';
719
+ else if (this.view === 'source' && before !== 'source') {
720
+ this.#shown = this.#draft = null;
721
+ this.#errors = [];
722
+ if (sourceViews === null) {
723
+ import('./source-view.js').then(
724
+ (module) => {
725
+ sourceViews = module;
726
+ this.requestUpdate();
727
+ },
728
+ (error: unknown) => console.error(error),
729
+ );
730
+ }
731
+ }
732
+ }
733
+ const surface = this.#surface;
734
+ if (surface !== null && this.adapter !== surface.adapter) {
735
+ // Another editor plugged in, or none (null): the built-in one goes, keeping its document for a comeback.
736
+ if (this.adapter === null) this.#pending = surface.adapter.getSource();
737
+ surface.destroy();
738
+ this.#surface = null;
739
+ }
740
+ if (this.adapter !== null && this.#surface === null) {
741
+ this.#builtIn = false;
742
+ if (this.#pending !== null) this.adapter.setSource(this.#pending);
743
+ this.#pending = null;
744
+ } else if (this.adapter === null && this.#surface === null) {
745
+ // The first update, or the host took its editor away: the built-in surface, unless one is in the slot.
746
+ if (this.isConnected && (this.#builtIn === null || changed.has('adapter'))) this.#decide();
747
+ } else if (this.#surface !== null && surfaces !== null && this.#surface.authoring !== this.authoring) {
748
+ // Other labels or other types: the same document in a new editor.
749
+ const source = this.#surface.adapter.getSource();
750
+ this.#surface.destroy();
751
+ this.#surface = surfaces.createSurface(
752
+ this,
753
+ this.authoring,
754
+ current().engine.manifests,
755
+ source,
756
+ this.#pictures,
757
+ this.#pages,
758
+ );
759
+ this.adapter = this.#surface.adapter;
760
+ }
761
+ this.#subscribe();
762
+ }
763
+
764
+ protected override updated(changed: PropertyValues<this>): void {
765
+ // The preview reads its theme when it renders.
766
+ if (changed.has('theme')) this.renderRoot.querySelector<LitElement>('astl-preview')?.requestUpdate();
767
+ const adapter = this.adapter;
768
+ if (adapter !== null && adapter !== this.#readyFor && this.isConnected) {
769
+ this.#readyFor = adapter;
770
+ this.#count(0);
771
+ this.#resolveReady();
772
+ this.dispatchEvent(new Event(READY, { bubbles: true, composed: true }));
773
+ }
774
+ const before = changed.get('view');
775
+ if (changed.has('view') && before !== undefined && before !== this.view) {
776
+ this.dispatchEvent(
777
+ new CustomEvent(VIEW, { detail: { view: this.view }, bubbles: true, composed: true }),
778
+ );
779
+ }
780
+ }
781
+
782
+ #decide(): void {
783
+ // An element the HTML parser is still filling may not have its slot="surface" child yet.
784
+ if (document.readyState === 'loading') {
785
+ document.addEventListener('DOMContentLoaded', () => this.requestUpdate('adapter'), { once: true });
786
+ return;
787
+ }
788
+ this.#builtIn = this.querySelector(':scope > [slot="surface"]') === null;
789
+ if (this.#builtIn) void this.#open();
790
+ }
791
+
792
+ async #open(): Promise<void> {
793
+ if (this.#opening || this.#surface !== null) return;
794
+ this.#opening = true;
795
+ this.#failed = false;
796
+ try {
797
+ surfaces ??= await import('./surface.js');
798
+ if (!this.isConnected || !this.#builtIn || this.adapter !== null || this.#surface !== null) return;
799
+ this.#surface = surfaces.createSurface(
800
+ this,
801
+ this.authoring,
802
+ current().engine.manifests,
803
+ this.value,
804
+ this.#pictures,
805
+ this.#pages,
806
+ );
807
+ this.#pending = null;
808
+ this.adapter = this.#surface.adapter;
809
+ } catch (error) {
810
+ // A failed chunk load is not cached by every browser: the next connect tries again.
811
+ this.#failed = true;
812
+ console.error(error);
813
+ } finally {
814
+ this.#opening = false;
815
+ this.requestUpdate();
816
+ }
817
+ }
818
+
819
+ #subscribe(): void {
820
+ const adapter = this.isConnected ? this.adapter : null;
821
+ if ((this.#subscription?.adapter ?? null) === adapter) return;
822
+ this.#subscription?.off();
823
+ this.#subscription =
824
+ adapter === null
825
+ ? null
826
+ : {
827
+ adapter,
828
+ off: adapter.onChange(() => {
829
+ const notice = this.#pageNotice;
830
+ this.#pageNotice = null;
831
+ if (this.#notice !== null || notice !== null) {
832
+ this.#notice = notice;
833
+ if (notice !== null) this.#notices++;
834
+ this.requestUpdate();
835
+ }
836
+ this.#count(COUNT_DELAY_MS);
837
+ this.dispatchEvent(new Event(CHANGE, { bubbles: true, composed: true }));
838
+ }),
839
+ };
840
+ }
841
+
842
+ #uiLocale(r: Registered): string {
843
+ const requested = this.locale
844
+ ? [this.locale]
845
+ : this.lang
846
+ ? [this.lang]
847
+ : [...(navigator.languages ?? []), navigator.language].filter((l) => !!l);
848
+ const available = [...editorMessages, ...r.catalogs]
849
+ .filter((c) => c.namespace === EDITOR_NAMESPACE)
850
+ .map((c) => c.locale);
851
+ return negotiateLocale(requested, [...new Set(available)], 'en');
852
+ }
853
+
854
+ #theme(): ThemeSetting {
855
+ const theme = this.theme;
856
+ return theme !== null && THEMES.includes(theme) ? theme : 'auto';
857
+ }
858
+
859
+ protected override render(): TemplateResult {
860
+ const { authoring, adapter } = this;
861
+ const theme = this.#theme();
862
+ const waiting: Notice | null = this.#failed
863
+ ? { key: 'surface.failed' }
864
+ : this.#builtIn && adapter === null
865
+ ? { key: 'surface.loading' }
866
+ : this.#notice;
867
+ const lang = authoring.locale;
868
+ // Given as a string (the attribute's form) or a list.
869
+ const list = (value: readonly string[] | string | null) =>
870
+ typeof value === 'string' ? value.split(/\s+/).filter((name) => name !== '') : value;
871
+ const featured = list(this.featured) ?? current().featured;
872
+ const panels = (list(this.panels) ?? PANELS).filter((name) => PANELS.includes(name));
873
+ const icons = new Set([
874
+ ...KIT_ICONS,
875
+ ...authoring.descriptors.flatMap((d) => [d.icon, ...(d.templates ?? []).map((t) => t.icon ?? d.icon)]),
876
+ ]);
877
+ const exported = [
878
+ 'toolbar: toolbar-bar',
879
+ 'button: toolbar-button',
880
+ 'icon-button: toolbar-icon-button',
881
+ 'views: toolbar-views',
882
+ 'view: toolbar-view',
883
+ 'separator: toolbar-separator',
884
+ 'icon: toolbar-icon',
885
+ 'insert',
886
+ 'menu: insert-menu',
887
+ 'style-menu',
888
+ 'style-colors',
889
+ 'style-panel',
890
+ ]
891
+ .concat([...icons].map((name) => `icon-${name}`))
892
+ .join(', ');
893
+ const panel = (name: string) =>
894
+ name === 'issues'
895
+ ? html`<astl-issues part="issues" data-theme=${theme} .authoring=${authoring} .adapter=${adapter}></astl-issues>`
896
+ : html`<astl-inspector part="inspector" exportparts=${INSPECTOR_PARTS} data-theme=${theme} .authoring=${authoring} .adapter=${adapter}></astl-inspector>`;
897
+ const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
898
+ const view = this.#view();
899
+ const views: ToolbarView[] = [
900
+ ...OWN_VIEWS.map((name) => ({ name, label: t(`view.${name}`) })),
901
+ ...this.#hostViews(),
902
+ ];
903
+ // The toolbar spans the editor, as a word processor's: above the text and the side column.
904
+ // Another view takes the surface's place, without the side column; the notice line stays, the one live region.
905
+ const away = view !== 'visual';
906
+ return html`<div class=${panels.length === 0 || away ? 'layout solo' : 'layout'}>
907
+ <astl-toolbar part="toolbar" exportparts=${exported} data-theme=${theme} .authoring=${authoring}
908
+ .adapter=${adapter} .featured=${featured} .views=${views} .view=${view}
909
+ @astl-toolbar-view=${(event: CustomEvent<{ view: string }>) => {
910
+ this.view = event.detail.view;
911
+ }}></astl-toolbar>
912
+ ${this.#statusLine()}
913
+ <div class="work" part="work">
914
+ <div class="start" part="start" ?hidden=${away || !this.#slotted.start}>
915
+ <slot name="start" @slotchange=${this.#slotChange}></slot>
916
+ </div>
917
+ <div class="surface" part="surface">
918
+ ${away ? nothing : html`<slot name="surface"></slot>`}
919
+ ${view === 'source' ? this.#source() : away ? html`<slot name="view-${view}"></slot>` : nothing}
920
+ <p class=${waiting === null ? 'status idle' : 'status'} role="status" lang=${lang} dir=${directionOf(lang)}
921
+ >${keyed(this.#notices, waiting === null ? '' : authoring.t(EDITOR_NAMESPACE, waiting.key, waiting.params))}</p>
922
+ <astl-picture-dialog data-theme=${theme} .authoring=${authoring}></astl-picture-dialog>
923
+ </div>
924
+ ${panels.length === 0 ? nothing : html`<div class="side" part="side" ?hidden=${away}>${panels.map(panel)}</div>`}
925
+ <div class="end" part="end" ?hidden=${away || !this.#slotted.end}>
926
+ <slot name="end" @slotchange=${this.#slotChange}></slot>
927
+ </div>
928
+ </div>
929
+ <astl-preview part="preview" data-theme=${theme} .authoring=${authoring} .adapter=${adapter}
930
+ .policy=${this.previewPolicy ?? PRACTICE_POLICY}></astl-preview>
931
+ </div>`;
932
+ }
933
+
934
+ /**
935
+ * The status line (`part="status-line"`): how many elements and points the document has, then "Ready to share" or
936
+ * its errors and warnings. Text to read, not a live region: the notice line stays the editor's one.
937
+ */
938
+ #statusLine(): TemplateResult | typeof nothing {
939
+ const outline = this.#outline;
940
+ if (outline === null) return nothing;
941
+ const { authoring } = this;
942
+ const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
943
+ const elements = outline.pages.reduce((n, page) => n + page.components.length, 0);
944
+ const ready = outline.errors === 0;
945
+ const lang = authoring.locale;
946
+ return html`<p class="status-line" part="status-line" lang=${lang} dir=${directionOf(lang)}>
947
+ <span class="counts"><span>${t('status.elements', { n: elements })}</span>${
948
+ outline.points === null
949
+ ? nothing
950
+ : html`<span>${t('surface.points', { points: outline.points })}</span>`
951
+ }</span>
952
+ <span class=${ready ? 'ready' : 'counts error'}>${
953
+ ready
954
+ ? t('status.ready')
955
+ : html`<span>${t('status.errors', { n: outline.errors })}</span><span>${t('status.warnings', { n: outline.warnings })}</span>`
956
+ }</span>
957
+ </p>`;
958
+ }
959
+
960
+ /**
961
+ * The source view (`source-view.ts`, nothing until its module has loaded), with the value laid out for reading once
962
+ * per opening.
963
+ */
964
+ #source(): TemplateResult | typeof nothing {
965
+ const views = sourceViews;
966
+ if (views === null) return nothing;
967
+ this.#shown ??= views.formatHtml(this.value);
968
+ return views.renderSource(
969
+ this.renderRoot,
970
+ this.authoring,
971
+ this.#draft ?? this.#shown,
972
+ this.#errors,
973
+ (text) => {
974
+ this.#draft = text;
975
+ },
976
+ );
977
+ }
978
+ }
979
+
980
+ declare global {
981
+ interface HTMLElementTagNameMap {
982
+ 'astl-editor': AstlEditor;
983
+ }
984
+ interface HTMLElementEventMap {
985
+ 'astl-editor-change': Event;
986
+ 'astl-editor-ready': Event;
987
+ }
988
+ }