@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.
- package/CHANGELOG.md +99 -0
- package/LICENSE +202 -0
- package/README.md +49 -0
- package/dist/adapter.d.ts +13 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +421 -0
- package/dist/adapter.js.map +1 -0
- package/dist/blocks.d.ts +96 -0
- package/dist/blocks.d.ts.map +1 -0
- package/dist/blocks.js +460 -0
- package/dist/blocks.js.map +1 -0
- package/dist/define.d.ts +64 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +20 -0
- package/dist/define.js.map +1 -0
- package/dist/element.d.ts +91 -0
- package/dist/element.d.ts.map +1 -0
- package/dist/element.js +779 -0
- package/dist/element.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/layouts.d.ts +52 -0
- package/dist/layouts.d.ts.map +1 -0
- package/dist/layouts.js +198 -0
- package/dist/layouts.js.map +1 -0
- package/dist/nodes.d.ts +150 -0
- package/dist/nodes.d.ts.map +1 -0
- package/dist/nodes.js +2426 -0
- package/dist/nodes.js.map +1 -0
- package/dist/source-view.d.ts +26 -0
- package/dist/source-view.d.ts.map +1 -0
- package/dist/source-view.js +114 -0
- package/dist/source-view.js.map +1 -0
- package/dist/source.d.ts +8 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +24 -0
- package/dist/source.js.map +1 -0
- package/dist/style.d.ts +16 -0
- package/dist/style.d.ts.map +1 -0
- package/dist/style.js +568 -0
- package/dist/style.js.map +1 -0
- package/dist/styles.d.ts +5 -0
- package/dist/styles.d.ts.map +1 -0
- package/dist/styles.js +921 -0
- package/dist/styles.js.map +1 -0
- package/dist/surface.d.ts +24 -0
- package/dist/surface.d.ts.map +1 -0
- package/dist/surface.js +90 -0
- package/dist/surface.js.map +1 -0
- package/dist/tiptap.d.ts +10 -0
- package/dist/tiptap.d.ts.map +1 -0
- package/dist/tiptap.js +9 -0
- package/dist/tiptap.js.map +1 -0
- package/package.json +51 -4
- package/src/adapter.ts +421 -0
- package/src/blocks.ts +577 -0
- package/src/define.ts +84 -0
- package/src/element.ts +988 -0
- package/src/index.ts +10 -0
- package/src/layouts.ts +220 -0
- package/src/nodes.ts +2690 -0
- package/src/source-view.ts +138 -0
- package/src/source.ts +27 -0
- package/src/style.ts +638 -0
- package/src/styles.ts +931 -0
- package/src/surface.ts +110 -0
- package/src/tiptap.ts +9 -0
package/src/nodes.ts
ADDED
|
@@ -0,0 +1,2690 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TipTap nodes derived from component manifests: the editor learns every registered component without any
|
|
3
|
+
* type-specific code. The manifest says how to map an element:
|
|
4
|
+
*
|
|
5
|
+
* - `display: 'inline'` (a gap, a select): an inline atom. Its attributes and its children (accepted alternatives,
|
|
6
|
+
* options, with their own attributes) are kept as data; the inspector edits them.
|
|
7
|
+
* - `display: 'block'` with rich (`content: 'inline'`) children (a closed question): a block whose rich children
|
|
8
|
+
* (prompt, options) are editable. Child attributes (an option's `correct`) are kept on the child nodes; text
|
|
9
|
+
* children are kept as data in small atoms, like the children of an inline atom.
|
|
10
|
+
* - `display: 'block'` without rich children: a block atom, kept as data like an inline atom.
|
|
11
|
+
* - `content: 'flow'` (a callout, a passage to select words in): a block whose rich content (paragraphs, lists,
|
|
12
|
+
* figures) is editable, and whose inline children (the words) are marks over its text; a child that leads it
|
|
13
|
+
* (`place: 'lead'`, a prompt) is an editable rich child before that content. Removing the block keeps its
|
|
14
|
+
* text; the `astlWrap` command marks words (`EditorDescriptor.wrap`).
|
|
15
|
+
* - `<astl-page>`: a top-level node with an editable label; `<astl-doc lang style-template>` are document attributes.
|
|
16
|
+
* Mod-Enter breaks the page at the cursor; Backspace at the very start of a page, Delete at the very end of the page
|
|
17
|
+
* before, or the page's join button join it to the page before (`splitPageIn`, `addPageIn`, `mergePageIn`).
|
|
18
|
+
*
|
|
19
|
+
* `renderHTML` writes the real `<astl-*>` tags (that is what `getSource()` serialises). The editing surface uses node
|
|
20
|
+
* views instead, so no `<astl-*>` custom element is ever created inside the editor (the preview defines them).
|
|
21
|
+
*/
|
|
22
|
+
import {
|
|
23
|
+
CAPTION_TAG,
|
|
24
|
+
type ChildSpec,
|
|
25
|
+
CLASS_ATTRIBUTE,
|
|
26
|
+
COLUMN_TAG,
|
|
27
|
+
COLUMNS_TAG,
|
|
28
|
+
CONTENT_ATTRIBUTES,
|
|
29
|
+
type ComponentManifest,
|
|
30
|
+
childTagConflict,
|
|
31
|
+
directionOf,
|
|
32
|
+
type EditorDescriptor,
|
|
33
|
+
type EditorWrap,
|
|
34
|
+
EXPLANATION_TAG,
|
|
35
|
+
FEEDBACK_TAG,
|
|
36
|
+
FEEDBACK_VARIANTS,
|
|
37
|
+
FIGURE_TAG,
|
|
38
|
+
HELP_TAGS,
|
|
39
|
+
HINT_TAG,
|
|
40
|
+
INERT_STYLE,
|
|
41
|
+
inertStyles,
|
|
42
|
+
isSourceId,
|
|
43
|
+
MAX_COLUMNS,
|
|
44
|
+
type MessageParams,
|
|
45
|
+
MIN_COLUMNS,
|
|
46
|
+
TAG_ATTRIBUTES,
|
|
47
|
+
} from '@astl/core';
|
|
48
|
+
import { cleanClass, cleanStyle, isStyleName } from '@astl/core/declarations';
|
|
49
|
+
import {
|
|
50
|
+
type Authoring,
|
|
51
|
+
EDITOR_NAMESPACE,
|
|
52
|
+
type PictureFields,
|
|
53
|
+
type PictureRequest,
|
|
54
|
+
type Placement,
|
|
55
|
+
pictureHtml,
|
|
56
|
+
pictureSize,
|
|
57
|
+
positionOf,
|
|
58
|
+
splitPlacement,
|
|
59
|
+
widthChanges,
|
|
60
|
+
widthPercent,
|
|
61
|
+
} from '@astl/editor';
|
|
62
|
+
import { type Editor, Extension, type Extensions, Mark, Node } from '@tiptap/core';
|
|
63
|
+
import { closeHistory } from '@tiptap/pm/history';
|
|
64
|
+
import {
|
|
65
|
+
type DOMOutputSpec,
|
|
66
|
+
Fragment,
|
|
67
|
+
type Mark as PMMark,
|
|
68
|
+
type Node as PMNode,
|
|
69
|
+
Slice,
|
|
70
|
+
} from '@tiptap/pm/model';
|
|
71
|
+
import {
|
|
72
|
+
type EditorState,
|
|
73
|
+
NodeSelection,
|
|
74
|
+
Plugin,
|
|
75
|
+
Selection,
|
|
76
|
+
TextSelection,
|
|
77
|
+
type Transaction,
|
|
78
|
+
} from '@tiptap/pm/state';
|
|
79
|
+
import { Decoration, DecorationSet } from '@tiptap/pm/view';
|
|
80
|
+
import { StarterKit } from '@tiptap/starter-kit';
|
|
81
|
+
import {
|
|
82
|
+
blocksExtension,
|
|
83
|
+
historyKey,
|
|
84
|
+
LAYOUT,
|
|
85
|
+
LAYOUT_COLUMN,
|
|
86
|
+
placeLabel,
|
|
87
|
+
type SurfaceChange,
|
|
88
|
+
} from './blocks.js';
|
|
89
|
+
import { currentLayoutExtension, deleteLayoutIn, isEmptyLayout, layoutAt } from './layouts.js';
|
|
90
|
+
import { setPlacedStyle } from './style.js';
|
|
91
|
+
|
|
92
|
+
type Attributes = Record<string, string>;
|
|
93
|
+
|
|
94
|
+
/** A child kept as data: its text, or an element with its attributes and children. */
|
|
95
|
+
type Kept =
|
|
96
|
+
| string
|
|
97
|
+
| { readonly tag: string; readonly attributes: Attributes; readonly children: readonly Kept[] };
|
|
98
|
+
|
|
99
|
+
/** `astl-choice` becomes `astlChoice`: ProseMirror content expressions only take word characters. */
|
|
100
|
+
export const nodeName = (tag: string): string =>
|
|
101
|
+
tag.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase());
|
|
102
|
+
|
|
103
|
+
/** Names `setAttribute` takes: the HTML parser accepts more (`@click`), and serialising those would throw. */
|
|
104
|
+
const ATTRIBUTE_NAME = /^[A-Za-z_:][\w.:-]*$/;
|
|
105
|
+
|
|
106
|
+
/** ProseMirror marks the first element it copies with this attribute: clipboard data, never content. */
|
|
107
|
+
const CLIPBOARD_MARK = 'data-pm-slice';
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* An element's attributes as written, in order, for every node and mark: only what the allow-list keeps of a `style`
|
|
111
|
+
* (read under its parsing name too: `inertStyles`), and only the classes that can name a style. Nothing else ever
|
|
112
|
+
* reaches the editing DOM or the source.
|
|
113
|
+
*/
|
|
114
|
+
export const attributesOf = (el: Element): Attributes =>
|
|
115
|
+
Object.fromEntries(
|
|
116
|
+
[...el.attributes].flatMap(({ name, value }): [string, string][] => {
|
|
117
|
+
if (!ATTRIBUTE_NAME.test(name) || name === CLIPBOARD_MARK) return [];
|
|
118
|
+
if (name !== 'style' && name !== INERT_STYLE && name !== CLASS_ATTRIBUTE) return [[name, value]];
|
|
119
|
+
const kept = name === CLASS_ATTRIBUTE ? cleanClass(value) : cleanStyle(value).style;
|
|
120
|
+
return kept === '' ? [] : [[name === INERT_STYLE ? 'style' : name, kept]];
|
|
121
|
+
}),
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Draws an element's own `style` and classes on what shows it, and names its tag there for the document's rules (a node
|
|
126
|
+
* view's dom is rarely that tag). Through the CSSOM, which a strict CSP allows. ProseMirror and decorations put classes
|
|
127
|
+
* on the same dom, so an author's come and go one by one.
|
|
128
|
+
*/
|
|
129
|
+
function painter(dom: HTMLElement, tag: string): (attributes: Attributes) => void {
|
|
130
|
+
dom.dataset.astlTag = tag;
|
|
131
|
+
let shown = '';
|
|
132
|
+
let classes: readonly string[] = [];
|
|
133
|
+
return (attributes) => {
|
|
134
|
+
const style = attributes.style ?? '';
|
|
135
|
+
if (style !== shown) dom.style.cssText = style;
|
|
136
|
+
shown = style;
|
|
137
|
+
const next = (attributes.class ?? '').split(' ').filter(Boolean);
|
|
138
|
+
dom.classList.remove(...classes);
|
|
139
|
+
dom.classList.add(...next);
|
|
140
|
+
classes = next;
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const keep = (node: ChildNode): Kept[] => {
|
|
145
|
+
if (node.nodeType === globalThis.Node.TEXT_NODE) return [node.textContent ?? ''];
|
|
146
|
+
if (node.nodeType !== globalThis.Node.ELEMENT_NODE) return [];
|
|
147
|
+
const el = node as Element;
|
|
148
|
+
return [{ tag: el.localName, attributes: attributesOf(el), children: [...el.childNodes].flatMap(keep) }];
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/** A text (a string) or an element, as new arrays: ProseMirror refuses to render arrays taken from node attributes. */
|
|
152
|
+
const spec = (kept: Kept): string | DOMOutputSpec =>
|
|
153
|
+
typeof kept === 'string' ? kept : [kept.tag, { ...kept.attributes }, ...kept.children.map(spec)];
|
|
154
|
+
|
|
155
|
+
const textOf = (kept: Kept): string => (typeof kept === 'string' ? kept : kept.children.map(textOf).join(''));
|
|
156
|
+
|
|
157
|
+
/** Every source attribute in one record, so attributes the editor does not know (lang, dir) survive too. */
|
|
158
|
+
const sourceAttributes = { attributes: { default: {}, rendered: false, parseHTML: attributesOf } };
|
|
159
|
+
|
|
160
|
+
/** An atom's attributes and all its children, as data. */
|
|
161
|
+
const keptAttributes = {
|
|
162
|
+
...sourceAttributes,
|
|
163
|
+
children: {
|
|
164
|
+
default: [],
|
|
165
|
+
rendered: false,
|
|
166
|
+
parseHTML: (el: HTMLElement): Kept[] => [...el.childNodes].flatMap(keep),
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
interface NodeLike {
|
|
171
|
+
readonly type: { readonly name: string };
|
|
172
|
+
readonly attrs: Record<string, unknown>;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* A picture field of a type (its descriptor's `picture-regions` or `picture-points`): the zones or pins (children of
|
|
177
|
+
* `tag`) on the picture of the element's `src` attribute, and the child flag (`flag`, a hotspot's right places) that
|
|
178
|
+
* draws a zone solid rather than dashed.
|
|
179
|
+
*/
|
|
180
|
+
export interface PictureLayer {
|
|
181
|
+
readonly kind: 'picture-regions' | 'picture-points';
|
|
182
|
+
readonly tag: string;
|
|
183
|
+
readonly src: string;
|
|
184
|
+
readonly flag: string | null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A child of a block with its attributes, as the picture view reads it (a child node, or a child kept as data). */
|
|
188
|
+
interface Placed {
|
|
189
|
+
readonly tag: string;
|
|
190
|
+
readonly attributes: Attributes;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** How the surface shows the picture of a block with picture fields: the layers of a tag, and a view to draw them. */
|
|
194
|
+
export interface PictureView {
|
|
195
|
+
layers(tag: string): readonly PictureLayer[];
|
|
196
|
+
create(tag: string): {
|
|
197
|
+
readonly dom: HTMLElement;
|
|
198
|
+
render(attributes: Attributes, children: readonly Placed[]): void;
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
203
|
+
/** A coordinate in percent of the picture: 0 to 100, anything else 0. */
|
|
204
|
+
const percent = (value: string | undefined): number => {
|
|
205
|
+
const n = Number.parseFloat(value ?? '');
|
|
206
|
+
return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : 0;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The picture of a block with its zones and pins numbered on it, in the palette colour of their number (a flag's
|
|
211
|
+
* zones solid, the others dashed), and its alt text below, as the inspector's picture field draws them: the surface
|
|
212
|
+
* shows a picture type as the picture it is, not as empty lines. The picture shows only when the URL policy allows
|
|
213
|
+
* its address; its box keeps the picture's shape (as loaded, else its `width` and `height`, else 4:3).
|
|
214
|
+
*/
|
|
215
|
+
export function zonesView(authoring: Authoring): PictureView {
|
|
216
|
+
const layers = (tag: string): PictureLayer[] => {
|
|
217
|
+
const fields = authoring.descriptor(tag)?.fields ?? [];
|
|
218
|
+
return fields.flatMap((field): PictureLayer[] => {
|
|
219
|
+
if (field.kind !== 'picture-regions' && field.kind !== 'picture-points') return [];
|
|
220
|
+
const flag = fields.find((f) => f.kind === 'child-flag' && f.tag === field.tag);
|
|
221
|
+
return [
|
|
222
|
+
{
|
|
223
|
+
kind: field.kind,
|
|
224
|
+
tag: field.tag,
|
|
225
|
+
src: field.src,
|
|
226
|
+
flag: flag?.kind === 'child-flag' ? flag.attribute : null,
|
|
227
|
+
},
|
|
228
|
+
];
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
232
|
+
return {
|
|
233
|
+
layers,
|
|
234
|
+
create(tag) {
|
|
235
|
+
const own = layers(tag);
|
|
236
|
+
const dom = document.createElement('div');
|
|
237
|
+
dom.className = 'astl-zones';
|
|
238
|
+
dom.contentEditable = 'false';
|
|
239
|
+
const frame = dom.appendChild(document.createElement('div'));
|
|
240
|
+
frame.className = 'astl-zones-frame';
|
|
241
|
+
const img = document.createElement('img');
|
|
242
|
+
img.alt = '';
|
|
243
|
+
img.draggable = false;
|
|
244
|
+
img.referrerPolicy = 'no-referrer';
|
|
245
|
+
const caption = dom.appendChild(document.createElement('span'));
|
|
246
|
+
caption.className = 'astl-picture-alt';
|
|
247
|
+
let loaded: number | null = null;
|
|
248
|
+
let last: { attributes: Attributes; children: readonly Placed[] } = { attributes: {}, children: [] };
|
|
249
|
+
const draw = () => {
|
|
250
|
+
const { attributes, children } = last;
|
|
251
|
+
const name = own[0]?.src ?? 'src';
|
|
252
|
+
const src = attributes[name] ?? '';
|
|
253
|
+
const shown = src.trim() !== '' && authoring.urlPolicy(src, { tag, attribute: name });
|
|
254
|
+
const width = pictureSize(attributes.width);
|
|
255
|
+
const height = pictureSize(attributes.height);
|
|
256
|
+
const aspect = loaded ?? (width !== undefined && height !== undefined ? width / height : 4 / 3);
|
|
257
|
+
frame.style.setProperty('aspect-ratio', String(aspect));
|
|
258
|
+
if (shown && img.getAttribute('src') !== src) {
|
|
259
|
+
loaded = null;
|
|
260
|
+
img.src = src;
|
|
261
|
+
}
|
|
262
|
+
const svg = document.createElementNS(SVG_NS, 'svg');
|
|
263
|
+
svg.setAttribute('viewBox', '0 0 100 100');
|
|
264
|
+
svg.setAttribute('preserveAspectRatio', 'none');
|
|
265
|
+
svg.setAttribute('aria-hidden', 'true');
|
|
266
|
+
const badges: HTMLElement[] = [];
|
|
267
|
+
const badge = (n: number, x: number, y: number, pin: boolean) => {
|
|
268
|
+
const span = document.createElement('span');
|
|
269
|
+
span.className = `astl-zone-badge${pin ? ' astl-zone-pin' : ''} c${((n - 1) % 8) + 1}`;
|
|
270
|
+
span.setAttribute('aria-hidden', 'true');
|
|
271
|
+
span.style.setProperty('--x', `${x}%`);
|
|
272
|
+
span.style.setProperty('--y', `${y}%`);
|
|
273
|
+
span.textContent = String(n);
|
|
274
|
+
badges.push(span);
|
|
275
|
+
};
|
|
276
|
+
for (const layer of own) {
|
|
277
|
+
children
|
|
278
|
+
.filter((c) => c.tag === layer.tag)
|
|
279
|
+
.forEach((child, i) => {
|
|
280
|
+
const a = child.attributes;
|
|
281
|
+
if (layer.kind === 'picture-points') {
|
|
282
|
+
badge(i + 1, percent(a.x), percent(a.y), true);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const shape = a.shape === 'circle' || a.shape === 'polygon' ? a.shape : 'rect';
|
|
286
|
+
let el: SVGElement;
|
|
287
|
+
let centre: [number, number];
|
|
288
|
+
if (shape === 'circle') {
|
|
289
|
+
const [x, y, r] = [percent(a.x), percent(a.y), percent(a.r)];
|
|
290
|
+
el = document.createElementNS(SVG_NS, 'ellipse');
|
|
291
|
+
for (const [k, v] of [
|
|
292
|
+
['cx', x],
|
|
293
|
+
['cy', y],
|
|
294
|
+
['rx', r],
|
|
295
|
+
['ry', r * aspect],
|
|
296
|
+
] as const)
|
|
297
|
+
el.setAttribute(k, String(v));
|
|
298
|
+
centre = [x, y];
|
|
299
|
+
} else if (shape === 'polygon') {
|
|
300
|
+
const points = (a.points ?? '')
|
|
301
|
+
.trim()
|
|
302
|
+
.split(/\s+/)
|
|
303
|
+
.filter(Boolean)
|
|
304
|
+
.map((pair) => pair.split(',').map((n) => percent(n)) as [number, number]);
|
|
305
|
+
el = document.createElementNS(SVG_NS, 'polygon');
|
|
306
|
+
el.setAttribute('points', points.map((p) => p.join(',')).join(' '));
|
|
307
|
+
// A loop, not Math.min(...xs): a polygon of any size stays off the call stack.
|
|
308
|
+
const box = { left: 100, top: 100, right: 0, bottom: 0 };
|
|
309
|
+
for (const [x, y] of points) {
|
|
310
|
+
box.left = Math.min(box.left, x);
|
|
311
|
+
box.top = Math.min(box.top, y);
|
|
312
|
+
box.right = Math.max(box.right, x);
|
|
313
|
+
box.bottom = Math.max(box.bottom, y);
|
|
314
|
+
}
|
|
315
|
+
centre = [(box.left + box.right) / 2, (box.top + box.bottom) / 2];
|
|
316
|
+
} else {
|
|
317
|
+
const [x, y, w, h] = [percent(a.x), percent(a.y), percent(a.width), percent(a.height)];
|
|
318
|
+
el = document.createElementNS(SVG_NS, 'rect');
|
|
319
|
+
for (const [k, v] of [
|
|
320
|
+
['x', x],
|
|
321
|
+
['y', y],
|
|
322
|
+
['width', w],
|
|
323
|
+
['height', h],
|
|
324
|
+
] as const)
|
|
325
|
+
el.setAttribute(k, String(v));
|
|
326
|
+
centre = [x + w / 2, y + h / 2];
|
|
327
|
+
}
|
|
328
|
+
const dashed = layer.flag !== null && !Object.hasOwn(a, layer.flag);
|
|
329
|
+
el.setAttribute('class', `astl-zone c${(i % 8) + 1}${dashed ? ' astl-zone-dashed' : ''}`);
|
|
330
|
+
svg.append(el);
|
|
331
|
+
badge(i + 1, ...centre, false);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
frame.replaceChildren(...(shown ? [img] : []), svg, ...badges);
|
|
335
|
+
frame.classList.toggle('astl-zones-blank', !shown);
|
|
336
|
+
const alt = attributes.alt;
|
|
337
|
+
const text =
|
|
338
|
+
alt === undefined || alt.trim() === ''
|
|
339
|
+
? t('surface.picture.noAlt')
|
|
340
|
+
: t('surface.picture.alt', { alt });
|
|
341
|
+
caption.textContent = shown || src.trim() === '' ? text : `${text} ${t('surface.picture.blocked')}`;
|
|
342
|
+
};
|
|
343
|
+
img.addEventListener('load', () => {
|
|
344
|
+
if (img.naturalHeight === 0) return;
|
|
345
|
+
loaded = img.naturalWidth / img.naturalHeight;
|
|
346
|
+
draw();
|
|
347
|
+
});
|
|
348
|
+
return {
|
|
349
|
+
dom,
|
|
350
|
+
render(attributes, children) {
|
|
351
|
+
last = { attributes, children };
|
|
352
|
+
draw();
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Node views must say whether they took an update; this one re-renders for the same node type. */
|
|
360
|
+
const updater =
|
|
361
|
+
(type: string, render: (attrs: Record<string, unknown>) => void) =>
|
|
362
|
+
(next: NodeLike): boolean => {
|
|
363
|
+
if (next.type.name !== type) return false;
|
|
364
|
+
render(next.attrs);
|
|
365
|
+
return true;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The text an atom shows: its first string attribute (a gap's `answer`), else the text of each child element (a
|
|
370
|
+
* select's options), else its own text (an accepted alternative).
|
|
371
|
+
*/
|
|
372
|
+
function summary(manifest: ComponentManifest | null, attrs: Record<string, unknown>): string {
|
|
373
|
+
const main = manifest?.attributes.find((a) => a.type === 'string')?.name;
|
|
374
|
+
if (main !== undefined) return (attrs.attributes as Attributes)[main] ?? '';
|
|
375
|
+
// Its help for students is not what it holds: the frame shows it apart (`keptHelp`).
|
|
376
|
+
const children = (attrs.children as readonly Kept[]).filter(
|
|
377
|
+
(c) => typeof c === 'string' || !HELP_TAGS.has(c.tag),
|
|
378
|
+
);
|
|
379
|
+
const elements = children.filter((c) => typeof c !== 'string');
|
|
380
|
+
return elements.length > 0
|
|
381
|
+
? elements.map((c) => textOf(c).trim()).join(' | ')
|
|
382
|
+
: children.map(textOf).join('').trim();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The element children kept as data, as the picture view reads them. */
|
|
386
|
+
const placedOf = (children: readonly Kept[]): Placed[] =>
|
|
387
|
+
children.flatMap((c) => (typeof c === 'string' ? [] : [{ tag: c.tag, attributes: c.attributes }]));
|
|
388
|
+
|
|
389
|
+
/** What an inline component's chip says: its answer (`''`: none yet) and how many other answers count too. */
|
|
390
|
+
export interface ChipText {
|
|
391
|
+
readonly answer: string;
|
|
392
|
+
readonly more: number;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* A chip's text from its type's editor fields: the text its reference names (`reference`, a drop's word from its
|
|
397
|
+
* bank), else its flagged children (a select's correct options), else its first string attribute (a gap's answer) with
|
|
398
|
+
* its `text-list` children as the others (accepted alternatives).
|
|
399
|
+
*/
|
|
400
|
+
export function chipText(
|
|
401
|
+
manifest: ComponentManifest | null,
|
|
402
|
+
descriptor: EditorDescriptor | null,
|
|
403
|
+
attrs: Record<string, unknown>,
|
|
404
|
+
reference: string | null,
|
|
405
|
+
): ChipText {
|
|
406
|
+
const fields = descriptor?.fields ?? [];
|
|
407
|
+
const children = (attrs.children as readonly Kept[]).filter((c) => typeof c !== 'string');
|
|
408
|
+
if (reference !== null) return { answer: reference, more: 0 };
|
|
409
|
+
const flag = fields.find((f) => f.kind === 'child-flag');
|
|
410
|
+
if (flag?.kind === 'child-flag') {
|
|
411
|
+
const flagged = children.filter((c) => c.tag === flag.tag && Object.hasOwn(c.attributes, flag.attribute));
|
|
412
|
+
return {
|
|
413
|
+
answer: flagged[0] === undefined ? '' : textOf(flagged[0]).trim(),
|
|
414
|
+
more: Math.max(0, flagged.length - 1),
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
const lists = new Set(fields.flatMap((f) => (f.kind === 'text-list' ? [f.tag] : [])));
|
|
418
|
+
return {
|
|
419
|
+
answer: summary(manifest, attrs).trim(),
|
|
420
|
+
more: children.filter((c) => lists.has(c.tag) && textOf(c).trim() !== '').length,
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const SVG_ICONS = {
|
|
425
|
+
check: 'M4 10.5l4 4 8-9',
|
|
426
|
+
warning: 'M10 3l8 14H2zM10 8v4M10 14.5v.5',
|
|
427
|
+
add: 'M10 4v12M4 10h12',
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
/** A 20 by 20 line icon, hidden from assistive technology. */
|
|
431
|
+
function lineIcon(name: keyof typeof SVG_ICONS, className: string): SVGSVGElement {
|
|
432
|
+
const svg = document.createElementNS(SVG_NS, 'svg');
|
|
433
|
+
svg.setAttribute('viewBox', '0 0 20 20');
|
|
434
|
+
svg.setAttribute('aria-hidden', 'true');
|
|
435
|
+
svg.setAttribute('focusable', 'false');
|
|
436
|
+
svg.setAttribute('class', className);
|
|
437
|
+
const path = svg.appendChild(document.createElementNS(SVG_NS, 'path'));
|
|
438
|
+
path.setAttribute('d', SVG_ICONS[name]);
|
|
439
|
+
return svg;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** The decoration spec key a chip reads the text of its reference from (`referencesExtension`). */
|
|
443
|
+
const REFERENCE = 'astlReference';
|
|
444
|
+
|
|
445
|
+
/** A chip's reference text among a node view's decorations, or null. */
|
|
446
|
+
const referenceIn = (decorations: readonly { spec: Record<string, unknown> }[]): string | null => {
|
|
447
|
+
for (const decoration of decorations) {
|
|
448
|
+
const text = decoration.spec[REFERENCE];
|
|
449
|
+
if (typeof text === 'string') return text;
|
|
450
|
+
}
|
|
451
|
+
return null;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* An element kept whole as data: a component (inline, shown as a chip such as "[grey]"; or a block, framed and
|
|
456
|
+
* labelled, with its picture when it has picture fields) or a text child of a rich block (a chip on its own line,
|
|
457
|
+
* allowed only where its block allows it; a zone or a pin, which its block's picture shows, takes no line).
|
|
458
|
+
*/
|
|
459
|
+
function atomNode(
|
|
460
|
+
tag: string,
|
|
461
|
+
manifest: ComponentManifest | null,
|
|
462
|
+
label: string,
|
|
463
|
+
place: 'inline' | 'block' | 'child' | 'zone',
|
|
464
|
+
pictures?: PictureView,
|
|
465
|
+
authoring?: Authoring,
|
|
466
|
+
): Node {
|
|
467
|
+
const name = nodeName(tag);
|
|
468
|
+
const inline = place !== 'block';
|
|
469
|
+
const descriptor = authoring?.descriptor(tag) ?? null;
|
|
470
|
+
const t = (key: string, params?: MessageParams) => authoring?.t(EDITOR_NAMESPACE, key, params) ?? key;
|
|
471
|
+
return Node.create({
|
|
472
|
+
name,
|
|
473
|
+
...(place === 'inline' || place === 'block' ? { group: place } : {}),
|
|
474
|
+
inline: place === 'inline',
|
|
475
|
+
atom: true,
|
|
476
|
+
selectable: true,
|
|
477
|
+
addAttributes: () => keptAttributes,
|
|
478
|
+
parseHTML: () => [{ tag }],
|
|
479
|
+
renderHTML: ({ node }) => [
|
|
480
|
+
tag,
|
|
481
|
+
{ ...node.attrs.attributes },
|
|
482
|
+
...(node.attrs.children as readonly Kept[]).map(spec),
|
|
483
|
+
],
|
|
484
|
+
addNodeView:
|
|
485
|
+
() =>
|
|
486
|
+
({ node, decorations, getPos, editor }) => {
|
|
487
|
+
if (place === 'zone') {
|
|
488
|
+
const dom = document.createElement('div');
|
|
489
|
+
dom.hidden = true;
|
|
490
|
+
return { dom, update: (next: NodeLike) => next.type.name === name };
|
|
491
|
+
}
|
|
492
|
+
if (place === 'inline') {
|
|
493
|
+
// A component in text: a chip with an icon, its answer and how many others count, or "no answer" (dashed).
|
|
494
|
+
const dom = document.createElement('span');
|
|
495
|
+
dom.className = 'astl-chip';
|
|
496
|
+
const paint = painter(dom, tag);
|
|
497
|
+
const render = (attrs: Record<string, unknown>, reference: string | null) => {
|
|
498
|
+
paint(attrs.attributes as Attributes);
|
|
499
|
+
const { answer, more } = chipText(manifest, descriptor, attrs, reference);
|
|
500
|
+
dom.replaceChildren(lineIcon(answer === '' ? 'warning' : 'check', 'astl-chip-icon'));
|
|
501
|
+
const text = dom.appendChild(document.createElement('span'));
|
|
502
|
+
text.className = 'astl-chip-answer';
|
|
503
|
+
text.textContent = answer === '' ? t('surface.chip.empty') : answer;
|
|
504
|
+
if (more > 0) {
|
|
505
|
+
const badge = dom.appendChild(document.createElement('span'));
|
|
506
|
+
badge.className = 'astl-chip-more';
|
|
507
|
+
badge.textContent = t('surface.chip.more', { n: more });
|
|
508
|
+
}
|
|
509
|
+
dom.toggleAttribute('data-empty', answer === '');
|
|
510
|
+
dom.title = t('label.text', { label, text: text.textContent });
|
|
511
|
+
};
|
|
512
|
+
render(node.attrs, referenceIn(decorations));
|
|
513
|
+
return {
|
|
514
|
+
dom,
|
|
515
|
+
update: (next: NodeLike, nextDecorations: readonly { spec: Record<string, unknown> }[]) => {
|
|
516
|
+
if (next.type.name !== name) return false;
|
|
517
|
+
render(next.attrs, referenceIn(nextDecorations));
|
|
518
|
+
return true;
|
|
519
|
+
},
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
if (inline) {
|
|
523
|
+
// A text child of a block sits on its own line.
|
|
524
|
+
const dom = document.createElement('div');
|
|
525
|
+
dom.className = 'astl-chip';
|
|
526
|
+
const paint = painter(dom, tag);
|
|
527
|
+
const render = (attrs: Record<string, unknown>) => {
|
|
528
|
+
paint(attrs.attributes as Attributes);
|
|
529
|
+
dom.textContent = `[${summary(manifest, attrs) || '?'}]`;
|
|
530
|
+
};
|
|
531
|
+
render(node.attrs);
|
|
532
|
+
return { dom, update: updater(name, render) };
|
|
533
|
+
}
|
|
534
|
+
// A block component kept as data: its picture, or a summary of what it holds; the frame's tab names it.
|
|
535
|
+
const dom = document.createElement('div');
|
|
536
|
+
dom.className = 'astl-block astl-atom';
|
|
537
|
+
const picture = pictures?.layers(tag).length ? pictures.create(tag) : null;
|
|
538
|
+
if (picture !== null) dom.append(picture.dom);
|
|
539
|
+
const body = dom.appendChild(document.createElement('div'));
|
|
540
|
+
body.className = 'astl-atom-summary';
|
|
541
|
+
// Its help for students, read only (the inspector edits it), under what it holds.
|
|
542
|
+
const help = dom.appendChild(document.createElement('div'));
|
|
543
|
+
help.className = 'astl-help-kept';
|
|
544
|
+
// Inside the frame, not on it: an author's border must not hide what the frame says.
|
|
545
|
+
const paint = placedPainter(body, tag);
|
|
546
|
+
const showPlace = authoring === undefined ? null : componentPlacing(authoring, dom, editor, getPos);
|
|
547
|
+
const render = (attrs: Record<string, unknown>) => {
|
|
548
|
+
paint(attrs.attributes as Attributes);
|
|
549
|
+
showPlace?.((attrs.attributes as Attributes).style);
|
|
550
|
+
picture?.render(attrs.attributes as Attributes, placedOf(attrs.children as readonly Kept[]));
|
|
551
|
+
// The picture shows the zones and pins; a summary of them would only repeat them.
|
|
552
|
+
body.textContent = picture === null ? summary(manifest, attrs) : '';
|
|
553
|
+
body.hidden = picture !== null;
|
|
554
|
+
if (authoring !== undefined)
|
|
555
|
+
help.replaceChildren(...keptHelp(attrs.children as readonly Kept[], authoring));
|
|
556
|
+
};
|
|
557
|
+
render(node.attrs);
|
|
558
|
+
return {
|
|
559
|
+
dom,
|
|
560
|
+
update: updater(name, render),
|
|
561
|
+
stopEvent: (event) => (event.target as Element).closest?.('.astl-picture-handle') != null,
|
|
562
|
+
ignoreMutation: () => true,
|
|
563
|
+
};
|
|
564
|
+
},
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** What a rich block (`content: 'flow'`) holds: the blocks of the content format, never a component. */
|
|
569
|
+
const FLOW_NODES: readonly string[] = [
|
|
570
|
+
'paragraph',
|
|
571
|
+
'heading',
|
|
572
|
+
'bulletList',
|
|
573
|
+
'orderedList',
|
|
574
|
+
'blockquote',
|
|
575
|
+
'astlFigure',
|
|
576
|
+
];
|
|
577
|
+
const FLOW = `(${FLOW_NODES.join(' | ')})+`;
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* The group of the help for students (`<astl-hint>`, `<astl-explanation>`, `<astl-feedback>`): rich content in a page
|
|
581
|
+
* or in a block component, never in a column or in text (an inline component or an atom keeps its own as data). In
|
|
582
|
+
* the editor, a labelled box; its select sets a hint's cost or the verdict a feedback text is for.
|
|
583
|
+
*/
|
|
584
|
+
const HELP = 'help';
|
|
585
|
+
|
|
586
|
+
/** The label of a help element in the UI language: what it is, with its cost or its verdict. */
|
|
587
|
+
function helpLabel(
|
|
588
|
+
tag: string,
|
|
589
|
+
attributes: Attributes,
|
|
590
|
+
t: (key: string, params?: MessageParams) => string,
|
|
591
|
+
): string {
|
|
592
|
+
if (tag === HINT_TAG) {
|
|
593
|
+
const percent = Math.round(Number(attributes.cost ?? 0) * 100);
|
|
594
|
+
return percent > 0 ? `${t('insert.hint')}, ${t('help.cost', { percent })}` : t('insert.hint');
|
|
595
|
+
}
|
|
596
|
+
if (tag === EXPLANATION_TAG) return t('insert.explanation');
|
|
597
|
+
return `${t('insert.feedback')}: ${t(`help.when.${attributes.when ?? ''}`)}`;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** An atom's help kept as data, as read-only labelled boxes. */
|
|
601
|
+
function keptHelp(children: readonly Kept[], authoring: Authoring): HTMLElement[] {
|
|
602
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
603
|
+
return children.flatMap((c) => {
|
|
604
|
+
if (typeof c === 'string' || !HELP_TAGS.has(c.tag)) return [];
|
|
605
|
+
const box = document.createElement('div');
|
|
606
|
+
box.className = 'astl-help-box';
|
|
607
|
+
box.dataset.help = c.tag;
|
|
608
|
+
const head = box.appendChild(document.createElement('div'));
|
|
609
|
+
head.className = 'astl-help-head';
|
|
610
|
+
head.lang = authoring.locale;
|
|
611
|
+
head.textContent = helpLabel(c.tag, c.attributes, t);
|
|
612
|
+
box.appendChild(document.createElement('div')).textContent = textOf(c).trim();
|
|
613
|
+
return [box];
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Costs the select offers, as written in `cost` ('0': free, no attribute). */
|
|
618
|
+
const COSTS: readonly string[] = ['0', '0.1', '0.25', '0.5', '1'];
|
|
619
|
+
|
|
620
|
+
function helpNode(tag: string, authoring?: Authoring): Node {
|
|
621
|
+
const name = nodeName(tag);
|
|
622
|
+
const t = (key: string, params?: MessageParams) => authoring?.t(EDITOR_NAMESPACE, key, params) ?? key;
|
|
623
|
+
return Node.create({
|
|
624
|
+
name,
|
|
625
|
+
group: HELP,
|
|
626
|
+
content: FLOW,
|
|
627
|
+
defining: true,
|
|
628
|
+
isolating: true,
|
|
629
|
+
addAttributes: () => sourceAttributes,
|
|
630
|
+
parseHTML: () => [{ tag }],
|
|
631
|
+
renderHTML: ({ node }) => [tag, { ...node.attrs.attributes }, 0],
|
|
632
|
+
addNodeView:
|
|
633
|
+
() =>
|
|
634
|
+
({ node, editor, getPos }) => {
|
|
635
|
+
const dom = document.createElement('div');
|
|
636
|
+
dom.className = 'astl-help-box';
|
|
637
|
+
dom.dataset.help = tag;
|
|
638
|
+
const head = dom.appendChild(document.createElement('div'));
|
|
639
|
+
head.className = 'astl-help-head';
|
|
640
|
+
head.contentEditable = 'false';
|
|
641
|
+
if (authoring !== undefined) {
|
|
642
|
+
head.lang = authoring.locale;
|
|
643
|
+
head.dir = directionOf(authoring.locale);
|
|
644
|
+
}
|
|
645
|
+
// What the box is; its select says the cost or the verdict (a kept box, without one, says them in its label).
|
|
646
|
+
const label = head.appendChild(document.createElement('span'));
|
|
647
|
+
label.textContent = t(
|
|
648
|
+
tag === HINT_TAG
|
|
649
|
+
? 'insert.hint'
|
|
650
|
+
: tag === EXPLANATION_TAG
|
|
651
|
+
? 'insert.explanation'
|
|
652
|
+
: 'insert.feedback',
|
|
653
|
+
);
|
|
654
|
+
const select = tag === EXPLANATION_TAG ? null : head.appendChild(document.createElement('select'));
|
|
655
|
+
const values = tag === HINT_TAG ? COSTS : FEEDBACK_VARIANTS;
|
|
656
|
+
select?.setAttribute('aria-label', t(tag === HINT_TAG ? 'help.costLabel' : 'help.whenLabel'));
|
|
657
|
+
select?.addEventListener('change', () => {
|
|
658
|
+
const pos = getPos();
|
|
659
|
+
const current = typeof pos === 'number' ? editor.state.doc.nodeAt(pos) : null;
|
|
660
|
+
if (current === null || typeof pos !== 'number' || select === null) return;
|
|
661
|
+
const attributes: Attributes = { ...(current.attrs.attributes as Attributes) };
|
|
662
|
+
if (tag === HINT_TAG && select.value === '0') delete attributes.cost;
|
|
663
|
+
else attributes[tag === HINT_TAG ? 'cost' : 'when'] = select.value;
|
|
664
|
+
editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, 'attributes', attributes));
|
|
665
|
+
});
|
|
666
|
+
const content = dom.appendChild(document.createElement('div'));
|
|
667
|
+
content.className = 'astl-help-content';
|
|
668
|
+
const render = (attrs: Record<string, unknown>) => {
|
|
669
|
+
const attributes = attrs.attributes as Attributes;
|
|
670
|
+
if (select === null) return;
|
|
671
|
+
const value =
|
|
672
|
+
(tag === HINT_TAG ? attributes.cost : attributes.when) ?? (tag === HINT_TAG ? '0' : '');
|
|
673
|
+
const options = values.includes(value) ? values : [...values, value];
|
|
674
|
+
select.replaceChildren(
|
|
675
|
+
...options.map((v) => {
|
|
676
|
+
const option = document.createElement('option');
|
|
677
|
+
option.value = v;
|
|
678
|
+
option.textContent = tag === HINT_TAG ? `${Math.round(Number(v) * 100)}%` : t(`help.when.${v}`);
|
|
679
|
+
return option;
|
|
680
|
+
}),
|
|
681
|
+
);
|
|
682
|
+
select.value = value;
|
|
683
|
+
};
|
|
684
|
+
render(node.attrs);
|
|
685
|
+
return {
|
|
686
|
+
dom,
|
|
687
|
+
contentDOM: content,
|
|
688
|
+
update: (next: NodeLike) => {
|
|
689
|
+
if (next.type.name !== name) return false;
|
|
690
|
+
render(next.attrs);
|
|
691
|
+
return true;
|
|
692
|
+
},
|
|
693
|
+
stopEvent: (event) => head.contains(event.target as globalThis.Node),
|
|
694
|
+
ignoreMutation: (mutation) => head.contains(mutation.target),
|
|
695
|
+
};
|
|
696
|
+
},
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** The nodes of the help for students. */
|
|
701
|
+
export function helpNodes(authoring?: Authoring): Node[] {
|
|
702
|
+
return [HINT_TAG, EXPLANATION_TAG, FEEDBACK_TAG].map((tag) => helpNode(tag, authoring));
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* A block with rich children, or with rich content (`content: 'flow'`), framed and labelled in the editor, with its
|
|
707
|
+
* picture when it has picture fields.
|
|
708
|
+
*/
|
|
709
|
+
function blockNode(manifest: ComponentManifest, pictures?: PictureView, authoring?: Authoring): Node {
|
|
710
|
+
const name = nodeName(manifest.tag);
|
|
711
|
+
const tags = new Map(manifest.children.map((c) => [nodeName(c.tag), c.tag]));
|
|
712
|
+
const placed = (node: PMNode): Placed[] => {
|
|
713
|
+
const out: Placed[] = [];
|
|
714
|
+
node.forEach((child) => {
|
|
715
|
+
const tag = tags.get(child.type.name);
|
|
716
|
+
if (tag !== undefined) out.push({ tag, attributes: child.attrs.attributes as Attributes });
|
|
717
|
+
});
|
|
718
|
+
return out;
|
|
719
|
+
};
|
|
720
|
+
// The child an author adds more of with a button: a repeatable rich child that carries a flag (an option).
|
|
721
|
+
const flags = authoring
|
|
722
|
+
?.descriptor(manifest.tag)
|
|
723
|
+
?.fields?.flatMap((f) => (f.kind === 'child-flag' ? [f.tag] : []));
|
|
724
|
+
const repeated = manifest.children.find(
|
|
725
|
+
(c) => c.content === 'inline' && (c.max === null || c.max > 1) && flags?.includes(c.tag) === true,
|
|
726
|
+
);
|
|
727
|
+
return Node.create({
|
|
728
|
+
name,
|
|
729
|
+
group: 'block',
|
|
730
|
+
// A block holds help for students among its children (an ungraded one too: the engine says it has none).
|
|
731
|
+
content:
|
|
732
|
+
manifest.content === 'flow'
|
|
733
|
+
? `${manifest.children
|
|
734
|
+
.filter((c) => c.place === 'lead')
|
|
735
|
+
.map((c) => `${nodeName(c.tag)}?`)
|
|
736
|
+
.join(' ')} (${[...FLOW_NODES, HELP].join(' | ')})+`.trimStart()
|
|
737
|
+
: `(${[...manifest.children.map((c) => nodeName(c.tag)), HELP].join(' | ')})+`,
|
|
738
|
+
defining: true,
|
|
739
|
+
isolating: true,
|
|
740
|
+
addAttributes: () => sourceAttributes,
|
|
741
|
+
parseHTML: () => [{ tag: manifest.tag }],
|
|
742
|
+
renderHTML: ({ node }) => [manifest.tag, { ...node.attrs.attributes }, 0],
|
|
743
|
+
addNodeView:
|
|
744
|
+
() =>
|
|
745
|
+
({ node, getPos, editor }) => {
|
|
746
|
+
const dom = document.createElement('div');
|
|
747
|
+
dom.className = 'astl-block';
|
|
748
|
+
const picture = pictures?.layers(manifest.tag).length ? pictures.create(manifest.tag) : null;
|
|
749
|
+
const contentDOM = document.createElement('div');
|
|
750
|
+
// Inside the frame, not on it: an author's border must not hide what the frame says.
|
|
751
|
+
const paint = placedPainter(contentDOM, manifest.tag);
|
|
752
|
+
// The picture under the task (and an image drop's labels), as the student sees them.
|
|
753
|
+
dom.append(contentDOM, ...(picture === null ? [] : [picture.dom]));
|
|
754
|
+
let add: HTMLButtonElement | null = null;
|
|
755
|
+
if (repeated !== undefined && authoring !== undefined) {
|
|
756
|
+
const childType = nodeName(repeated.tag);
|
|
757
|
+
const row = dom.appendChild(document.createElement('div'));
|
|
758
|
+
row.className = 'astl-block-add';
|
|
759
|
+
row.contentEditable = 'false';
|
|
760
|
+
Object.assign(row, { lang: authoring.locale, dir: directionOf(authoring.locale) });
|
|
761
|
+
add = row.appendChild(Object.assign(document.createElement('button'), { type: 'button' }));
|
|
762
|
+
add.append(lineIcon('add', 'astl-icon'), authoring.t(EDITOR_NAMESPACE, 'surface.addOption'));
|
|
763
|
+
add.addEventListener('click', () => {
|
|
764
|
+
const pos = getPos();
|
|
765
|
+
const block = typeof pos === 'number' ? editor.state.doc.nodeAt(pos) : null;
|
|
766
|
+
const type = editor.schema.nodes[childType];
|
|
767
|
+
if (typeof pos !== 'number' || block === null || type === undefined) return;
|
|
768
|
+
// After the last child of that tag (an option goes after the options, before anything after them).
|
|
769
|
+
let at = pos + block.nodeSize - 1;
|
|
770
|
+
block.forEach((child, offset) => {
|
|
771
|
+
if (child.type === type) at = pos + 1 + offset + child.nodeSize;
|
|
772
|
+
});
|
|
773
|
+
const tr = closeHistory(editor.state.tr).insert(at, type.create());
|
|
774
|
+
tr.setSelection(TextSelection.create(tr.doc, at + 1)).scrollIntoView();
|
|
775
|
+
editor.view.dispatch(tr);
|
|
776
|
+
editor.view.focus();
|
|
777
|
+
});
|
|
778
|
+
add.addEventListener('keydown', (event) => historyKey(editor.view, event));
|
|
779
|
+
}
|
|
780
|
+
const showPlace = authoring === undefined ? null : componentPlacing(authoring, dom, editor, getPos);
|
|
781
|
+
// The picture draws the block's children too: every change of the block reaches it.
|
|
782
|
+
const render = (next: PMNode) => {
|
|
783
|
+
paint(next.attrs.attributes as Attributes);
|
|
784
|
+
showPlace?.((next.attrs.attributes as Attributes).style);
|
|
785
|
+
picture?.render(next.attrs.attributes as Attributes, placed(next));
|
|
786
|
+
if (add !== null && repeated !== undefined) {
|
|
787
|
+
let count = 0;
|
|
788
|
+
next.forEach((child) => {
|
|
789
|
+
if (child.type.name === nodeName(repeated.tag)) count++;
|
|
790
|
+
});
|
|
791
|
+
add.disabled = repeated.max !== null && count >= repeated.max;
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
render(node);
|
|
795
|
+
const tools = (target: globalThis.Node | null) =>
|
|
796
|
+
(target as Element | null)?.closest?.('.astl-picture-handle') != null;
|
|
797
|
+
const own = (target: globalThis.Node) =>
|
|
798
|
+
(picture?.dom.contains(target) ?? false) ||
|
|
799
|
+
(add?.parentElement?.contains(target) ?? false) ||
|
|
800
|
+
tools(target instanceof Element ? target : target.parentElement);
|
|
801
|
+
return {
|
|
802
|
+
dom,
|
|
803
|
+
contentDOM,
|
|
804
|
+
update: (next: PMNode) => {
|
|
805
|
+
if (next.type.name !== name) return false;
|
|
806
|
+
render(next);
|
|
807
|
+
return true;
|
|
808
|
+
},
|
|
809
|
+
stopEvent: (event) =>
|
|
810
|
+
(add?.parentElement?.contains(event.target as globalThis.Node) ?? false) ||
|
|
811
|
+
tools(event.target as globalThis.Node),
|
|
812
|
+
// A drag of the handle writes the frame's width as it goes.
|
|
813
|
+
ignoreMutation: (m) => own(m.target) || (m.target === dom && m.type === 'attributes'),
|
|
814
|
+
};
|
|
815
|
+
},
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* A rich child of a block (prompt, option): one line of rich text, in a plain element so no custom element claims
|
|
821
|
+
* it. A child the manifest allows once (a prompt) is marked `single`.
|
|
822
|
+
*/
|
|
823
|
+
function childNode(
|
|
824
|
+
child: ChildSpec,
|
|
825
|
+
flag?: { readonly attribute: string; readonly label: string },
|
|
826
|
+
authoring?: Authoring,
|
|
827
|
+
): Node {
|
|
828
|
+
const name = nodeName(child.tag);
|
|
829
|
+
return Node.create({
|
|
830
|
+
name,
|
|
831
|
+
content: 'inline*',
|
|
832
|
+
addAttributes: () => sourceAttributes,
|
|
833
|
+
parseHTML: () => [{ tag: child.tag }],
|
|
834
|
+
renderHTML: ({ node }) => [child.tag, { ...node.attrs.attributes }, 0],
|
|
835
|
+
addNodeView:
|
|
836
|
+
() =>
|
|
837
|
+
({ node, getPos, editor }) => {
|
|
838
|
+
const dom = document.createElement('div');
|
|
839
|
+
dom.className = child.max === 1 ? 'astl-child astl-single' : 'astl-child';
|
|
840
|
+
const paint = painter(dom, child.tag);
|
|
841
|
+
paint(node.attrs.attributes as Attributes);
|
|
842
|
+
if (flag === undefined || authoring === undefined)
|
|
843
|
+
return {
|
|
844
|
+
dom,
|
|
845
|
+
contentDOM: dom,
|
|
846
|
+
update: updater(name, (attrs) => paint(attrs.attributes as Attributes)),
|
|
847
|
+
};
|
|
848
|
+
// A marker before the text sets the child's flag (an option's `correct`): a toggle button named by the flag's
|
|
849
|
+
// label and the child's text.
|
|
850
|
+
dom.classList.add('astl-flaggable');
|
|
851
|
+
const marker = Object.assign(document.createElement('button'), {
|
|
852
|
+
type: 'button',
|
|
853
|
+
className: 'astl-flag',
|
|
854
|
+
});
|
|
855
|
+
marker.contentEditable = 'false';
|
|
856
|
+
Object.assign(marker, { lang: authoring.locale, dir: directionOf(authoring.locale) });
|
|
857
|
+
marker.append(lineIcon('check', 'astl-icon'));
|
|
858
|
+
const contentDOM = document.createElement('div');
|
|
859
|
+
contentDOM.className = 'astl-child-text';
|
|
860
|
+
dom.append(marker, contentDOM);
|
|
861
|
+
let current = node;
|
|
862
|
+
const render = (next: PMNode) => {
|
|
863
|
+
current = next;
|
|
864
|
+
paint(next.attrs.attributes as Attributes);
|
|
865
|
+
const on = Object.hasOwn(next.attrs.attributes as Attributes, flag.attribute);
|
|
866
|
+
marker.setAttribute('aria-pressed', String(on));
|
|
867
|
+
dom.toggleAttribute('data-flagged', on);
|
|
868
|
+
const pos = getPos();
|
|
869
|
+
const index = typeof pos === 'number' ? editor.state.doc.resolve(pos).index() + 1 : 1;
|
|
870
|
+
const item =
|
|
871
|
+
next.textContent.trim() || authoring.t(EDITOR_NAMESPACE, 'inspector.untitled', { n: index });
|
|
872
|
+
marker.setAttribute(
|
|
873
|
+
'aria-label',
|
|
874
|
+
authoring.t(EDITOR_NAMESPACE, 'label.text', { label: flag.label, text: item }),
|
|
875
|
+
);
|
|
876
|
+
};
|
|
877
|
+
render(node);
|
|
878
|
+
marker.addEventListener('click', () => {
|
|
879
|
+
const pos = getPos();
|
|
880
|
+
if (typeof pos !== 'number') return;
|
|
881
|
+
const attributes = current.attrs.attributes as Attributes;
|
|
882
|
+
const { [flag.attribute]: _, ...rest } = attributes;
|
|
883
|
+
const next = Object.hasOwn(attributes, flag.attribute)
|
|
884
|
+
? rest
|
|
885
|
+
: { ...attributes, [flag.attribute]: '' };
|
|
886
|
+
editor.view.dispatch(closeHistory(editor.state.tr.setNodeAttribute(pos, 'attributes', next)));
|
|
887
|
+
});
|
|
888
|
+
marker.addEventListener('keydown', (event) => historyKey(editor.view, event));
|
|
889
|
+
return {
|
|
890
|
+
dom,
|
|
891
|
+
contentDOM,
|
|
892
|
+
update: (next: PMNode) => {
|
|
893
|
+
if (next.type.name !== name) return false;
|
|
894
|
+
render(next);
|
|
895
|
+
return true;
|
|
896
|
+
},
|
|
897
|
+
stopEvent: (event) => marker.contains(event.target as globalThis.Node),
|
|
898
|
+
ignoreMutation: (m) => marker.contains(m.target),
|
|
899
|
+
};
|
|
900
|
+
},
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* An inline child of a rich block (a word to select): a mark over its text, written as its tag in the source and kept
|
|
906
|
+
* outside formatting (one element for a word in bold). The surface shows it as a plain span (no custom element, no
|
|
907
|
+
* source attributes), `data-flagged` while one of its boolean attributes is set (a correct word).
|
|
908
|
+
*/
|
|
909
|
+
function childMark(child: ChildSpec): Mark {
|
|
910
|
+
const flags = child.attributes.filter((a) => a.type === 'boolean').map((a) => a.name);
|
|
911
|
+
return Mark.create({
|
|
912
|
+
name: nodeName(child.tag),
|
|
913
|
+
priority: 200,
|
|
914
|
+
// Text typed right after a word is not part of it.
|
|
915
|
+
inclusive: false,
|
|
916
|
+
addAttributes: () => sourceAttributes,
|
|
917
|
+
parseHTML: () => [{ tag: child.tag }],
|
|
918
|
+
renderHTML: ({ mark }) => [child.tag, { ...mark.attrs.attributes }, 0],
|
|
919
|
+
addMarkView:
|
|
920
|
+
() =>
|
|
921
|
+
({ mark }) => {
|
|
922
|
+
const dom = document.createElement('span');
|
|
923
|
+
dom.className = 'astl-mark';
|
|
924
|
+
painter(dom, child.tag)(mark.attrs.attributes as Attributes);
|
|
925
|
+
if (flags.some((flag) => Object.hasOwn(mark.attrs.attributes, flag))) dom.dataset.flagged = '';
|
|
926
|
+
return { dom, contentDOM: dom };
|
|
927
|
+
},
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Nodes for every manifest, and marks for the inline children of rich blocks; `label` names a type in the UI,
|
|
933
|
+
* `pictures` shows the picture of a type with picture fields. A child tag several blocks share (`astl-prompt`) becomes
|
|
934
|
+
* one node (or mark): TipTap needs unique names. It is built from the first block's spec, so it throws for a tag two
|
|
935
|
+
* manifests declare differently (see `childTagConflict`) and for one two blocks give different content (or one keeps
|
|
936
|
+
* as a node, another as a mark).
|
|
937
|
+
*/
|
|
938
|
+
export function componentNodes(
|
|
939
|
+
manifests: readonly ComponentManifest[],
|
|
940
|
+
label: (tag: string) => string,
|
|
941
|
+
pictures?: PictureView,
|
|
942
|
+
authoring?: Authoring,
|
|
943
|
+
): (Node | Mark)[] {
|
|
944
|
+
const clash = (first: string, second: string, tag: string): never => {
|
|
945
|
+
throw new TypeError(
|
|
946
|
+
`Component manifests ${first} and ${second} declare the child ${tag} differently: one editor node cannot hold both`,
|
|
947
|
+
);
|
|
948
|
+
};
|
|
949
|
+
const conflict = childTagConflict(manifests);
|
|
950
|
+
if (conflict !== null) clash(...conflict.components, conflict.tag);
|
|
951
|
+
/** Child nodes and marks by tag: the block that made each one, and its content (`mark` for an inline child). */
|
|
952
|
+
const children = new Map<string, { readonly block: string; readonly content: string }>();
|
|
953
|
+
return manifests.flatMap((m) => {
|
|
954
|
+
const flow = m.content === 'flow';
|
|
955
|
+
const rich = flow || m.children.some((c) => c.content === 'inline');
|
|
956
|
+
if (m.display === 'inline') return [atomNode(m.tag, m, label(m.tag), 'inline', undefined, authoring)];
|
|
957
|
+
if (!rich) return [atomNode(m.tag, m, label(m.tag), 'block', pictures, authoring)];
|
|
958
|
+
// In a rich block a child that leads it (a prompt) is a node before the content; the others are marks in its text.
|
|
959
|
+
const asMark = (c: ChildSpec) => flow && c.place !== 'lead';
|
|
960
|
+
for (const c of m.children) {
|
|
961
|
+
const content = asMark(c) ? 'mark' : c.content;
|
|
962
|
+
const made = children.get(c.tag);
|
|
963
|
+
if (made === undefined) children.set(c.tag, { block: m.tag, content });
|
|
964
|
+
else if (made.content !== content) clash(made.block, m.tag, c.tag);
|
|
965
|
+
}
|
|
966
|
+
const fresh = m.children.filter((c) => children.get(c.tag)?.block === m.tag);
|
|
967
|
+
const zones = new Set(pictures?.layers(m.tag).map((layer) => layer.tag));
|
|
968
|
+
const descriptor = authoring?.descriptor(m.tag) ?? null;
|
|
969
|
+
/** The flag field of a child tag (an option's `correct`), with its label in the UI language. */
|
|
970
|
+
const flagOf = (tag: string) => {
|
|
971
|
+
const field = descriptor?.fields?.find((f) => f.kind === 'child-flag' && f.tag === tag);
|
|
972
|
+
if (field?.kind !== 'child-flag' || descriptor === null || authoring === undefined) return undefined;
|
|
973
|
+
return { attribute: field.attribute, label: authoring.t(descriptor.manifest.messages, field.label) };
|
|
974
|
+
};
|
|
975
|
+
return [
|
|
976
|
+
blockNode(m, pictures, authoring),
|
|
977
|
+
...fresh.map((c) =>
|
|
978
|
+
asMark(c)
|
|
979
|
+
? childMark(c)
|
|
980
|
+
: c.content === 'inline'
|
|
981
|
+
? childNode(c, flagOf(c.tag), authoring)
|
|
982
|
+
: atomNode(c.tag, null, '', zones.has(c.tag) ? 'zone' : 'child'),
|
|
983
|
+
),
|
|
984
|
+
];
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** What a picture keeps: the attributes the content format allows on `img`, as written; nothing else is data. */
|
|
989
|
+
const PICTURE_ATTRIBUTES: ReadonlySet<string> = new Set([
|
|
990
|
+
...(TAG_ATTRIBUTES.img ?? []),
|
|
991
|
+
...CONTENT_ATTRIBUTES,
|
|
992
|
+
CLASS_ATTRIBUTE,
|
|
993
|
+
]);
|
|
994
|
+
|
|
995
|
+
const only =
|
|
996
|
+
(names: ReadonlySet<string>) =>
|
|
997
|
+
(el: Element | null): Attributes =>
|
|
998
|
+
el === null
|
|
999
|
+
? {}
|
|
1000
|
+
: Object.fromEntries(Object.entries(attributesOf(el)).filter(([name]) => names.has(name)));
|
|
1001
|
+
|
|
1002
|
+
const pictureAttributesOf = only(PICTURE_ATTRIBUTES);
|
|
1003
|
+
const languageOf = only(new Set([...CONTENT_ATTRIBUTES, CLASS_ATTRIBUTE]));
|
|
1004
|
+
|
|
1005
|
+
/** What the surface offers on a picture or a component for where it sits and how wide it is. */
|
|
1006
|
+
interface Placing {
|
|
1007
|
+
/** The element that sits on the page: the picture's view, its figure, or the component's frame. */
|
|
1008
|
+
box(): HTMLElement;
|
|
1009
|
+
/** A new width chosen with the corner handle, in percent of what holds it. */
|
|
1010
|
+
commit(percent: number): void;
|
|
1011
|
+
/** Opens the form with the position and the width (for the keyboard: the same, through the toolbar's style menu). */
|
|
1012
|
+
open: (() => void) | null;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/** What a pointer can make of a box: never so small that its handle is out of reach, never wider than its column. */
|
|
1016
|
+
const MIN_DRAGGED_WIDTH = 5;
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* The handle on a placed box's corner: a drag sizes `box` in percent of what holds it, shown as it goes, and one commit
|
|
1020
|
+
* at the end, one undo step. On the corner away from the edge the box is anchored to; a centred box grows both ways.
|
|
1021
|
+
* Dragging has a single-pointer alternative, the width field of the style form (WCAG 2.5.7), so the handle is for the
|
|
1022
|
+
* pointer alone.
|
|
1023
|
+
*/
|
|
1024
|
+
function placeHandle(
|
|
1025
|
+
placing: Placing,
|
|
1026
|
+
position: () => Placement,
|
|
1027
|
+
preview: (percent: number | null) => void,
|
|
1028
|
+
): HTMLElement {
|
|
1029
|
+
const handle = document.createElement('span');
|
|
1030
|
+
handle.className = 'astl-picture-handle';
|
|
1031
|
+
handle.setAttribute('aria-hidden', 'true');
|
|
1032
|
+
// No drag of the picture itself, whose node is draggable, from its handle.
|
|
1033
|
+
handle.addEventListener('mousedown', (event) => event.preventDefault());
|
|
1034
|
+
handle.addEventListener('pointerdown', (event) => {
|
|
1035
|
+
if (event.button !== 0) return;
|
|
1036
|
+
event.preventDefault();
|
|
1037
|
+
event.stopPropagation();
|
|
1038
|
+
const box = placing.box();
|
|
1039
|
+
const holder = box.parentElement;
|
|
1040
|
+
if (holder === null) return;
|
|
1041
|
+
const style = getComputedStyle(holder);
|
|
1042
|
+
const room =
|
|
1043
|
+
holder.clientWidth -
|
|
1044
|
+
Number.parseFloat(style.paddingInlineStart) -
|
|
1045
|
+
Number.parseFloat(style.paddingInlineEnd);
|
|
1046
|
+
if (room <= 0) return;
|
|
1047
|
+
const start = box.getBoundingClientRect().width;
|
|
1048
|
+
const startX = event.clientX;
|
|
1049
|
+
const rtl = getComputedStyle(box).direction === 'rtl';
|
|
1050
|
+
const where = position();
|
|
1051
|
+
const pull = (where === 'end' ? -1 : 1) * (where === 'center' ? 2 : 1) * (rtl ? -1 : 1);
|
|
1052
|
+
const written = box.style.cssText;
|
|
1053
|
+
let percent: number | null = null;
|
|
1054
|
+
handle.setPointerCapture(event.pointerId);
|
|
1055
|
+
const move = (moved: PointerEvent) => {
|
|
1056
|
+
const width = start + pull * (moved.clientX - startX);
|
|
1057
|
+
percent = Math.round(Math.min(100, Math.max(MIN_DRAGGED_WIDTH, (width / room) * 100)));
|
|
1058
|
+
box.style.setProperty('width', `${percent}%`);
|
|
1059
|
+
preview(percent);
|
|
1060
|
+
};
|
|
1061
|
+
const end = (ended: PointerEvent) => {
|
|
1062
|
+
handle.removeEventListener('pointermove', move);
|
|
1063
|
+
handle.removeEventListener('pointerup', end);
|
|
1064
|
+
handle.removeEventListener('pointercancel', end);
|
|
1065
|
+
// What the document says draws it again; a press without a move changes nothing.
|
|
1066
|
+
box.style.cssText = written;
|
|
1067
|
+
preview(null);
|
|
1068
|
+
if (ended.type === 'pointerup' && percent !== null) placing.commit(percent);
|
|
1069
|
+
};
|
|
1070
|
+
handle.addEventListener('pointermove', move);
|
|
1071
|
+
handle.addEventListener('pointerup', end);
|
|
1072
|
+
handle.addEventListener('pointercancel', end);
|
|
1073
|
+
});
|
|
1074
|
+
return handle;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* Draws a component's own style inside its frame, all but what places it (its position and width): the frame takes
|
|
1079
|
+
* those (`blocksExtension`), so the frame, its tab and its notes sit where the author put the component.
|
|
1080
|
+
*/
|
|
1081
|
+
function placedPainter(dom: HTMLElement, tag: string): (attributes: Attributes) => void {
|
|
1082
|
+
const paint = painter(dom, tag);
|
|
1083
|
+
return (attributes) => paint({ ...attributes, style: splitPlacement(attributes.style ?? '').rest });
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
* A component's handle, on the edge of its frame away from the side it floats to, half in the frame's padding and half
|
|
1088
|
+
* out: never over its content or its tab. Its position line is in the row of its tab (`blocksExtension`), which a drag
|
|
1089
|
+
* keeps up to date. Shown while the cursor is in the frame or the frame is selected.
|
|
1090
|
+
*/
|
|
1091
|
+
function componentPlacing(
|
|
1092
|
+
authoring: Authoring,
|
|
1093
|
+
dom: HTMLElement,
|
|
1094
|
+
editor: Editor,
|
|
1095
|
+
getPos: () => number | undefined,
|
|
1096
|
+
): (style: string | undefined) => void {
|
|
1097
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
1098
|
+
let position: Placement = 'inline';
|
|
1099
|
+
let width: number | null = null;
|
|
1100
|
+
/** The line in the row over this frame: the widgets before it are its notes and that row. */
|
|
1101
|
+
const line = () => {
|
|
1102
|
+
let at = dom.previousElementSibling;
|
|
1103
|
+
for (let step = 0; at !== null && step < 2; step++, at = at.previousElementSibling) {
|
|
1104
|
+
const found = at.querySelector<HTMLElement>(':scope > .astl-frame-line');
|
|
1105
|
+
if (found !== null) return found;
|
|
1106
|
+
}
|
|
1107
|
+
return null;
|
|
1108
|
+
};
|
|
1109
|
+
const preview = (percent: number | null) => {
|
|
1110
|
+
const shown = line();
|
|
1111
|
+
if (shown === null) return;
|
|
1112
|
+
const said = placeLabel(t, position, percent ?? width);
|
|
1113
|
+
shown.textContent = said.text;
|
|
1114
|
+
shown.setAttribute('aria-label', said.label);
|
|
1115
|
+
};
|
|
1116
|
+
dom.append(
|
|
1117
|
+
placeHandle(
|
|
1118
|
+
{ box: () => dom, commit: (percent) => commitWidth(editor, getPos(), percent), open: null },
|
|
1119
|
+
() => position,
|
|
1120
|
+
preview,
|
|
1121
|
+
),
|
|
1122
|
+
);
|
|
1123
|
+
return (style) => {
|
|
1124
|
+
position = positionOf(style ?? '');
|
|
1125
|
+
width = widthPercent(style ?? '');
|
|
1126
|
+
dom.dataset.astlPosition = position;
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* A picture as the surface shows it: the image, only when the URL policy allows its address, above a line with its
|
|
1132
|
+
* alt text, so a sighted author sees what a screen reader reads. The image itself is presentational there: the line
|
|
1133
|
+
* says it for screen readers too, decorative pictures included. Once selected it also says where it sits and how wide
|
|
1134
|
+
* it is, and has a handle on its corner.
|
|
1135
|
+
*/
|
|
1136
|
+
function pictureView(
|
|
1137
|
+
authoring: Authoring,
|
|
1138
|
+
tag: 'span' | 'div',
|
|
1139
|
+
edit: (() => void) | null,
|
|
1140
|
+
placing: Placing | null = null,
|
|
1141
|
+
) {
|
|
1142
|
+
const dom = document.createElement(tag);
|
|
1143
|
+
dom.className = 'astl-picture';
|
|
1144
|
+
dom.contentEditable = 'false';
|
|
1145
|
+
const img = document.createElement('img');
|
|
1146
|
+
img.alt = '';
|
|
1147
|
+
img.draggable = false;
|
|
1148
|
+
// As in the player: the picture's host learns nothing of the page.
|
|
1149
|
+
img.referrerPolicy = 'no-referrer';
|
|
1150
|
+
const label = dom.appendChild(document.createElement('span'));
|
|
1151
|
+
label.className = 'astl-picture-alt';
|
|
1152
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
1153
|
+
const tools = dom.appendChild(document.createElement('span'));
|
|
1154
|
+
tools.className = 'astl-picture-tools';
|
|
1155
|
+
if (edit !== null) {
|
|
1156
|
+
// For the pointer (shown once a picture in text is selected: a click selects it; always in a figure); from the
|
|
1157
|
+
// keyboard, Enter on the picture (or in its caption) does the same.
|
|
1158
|
+
const button = tools.appendChild(document.createElement('button'));
|
|
1159
|
+
button.type = 'button';
|
|
1160
|
+
button.className = 'astl-picture-edit';
|
|
1161
|
+
button.tabIndex = -1;
|
|
1162
|
+
button.textContent = t('surface.picture.edit');
|
|
1163
|
+
button.addEventListener('click', (event) => {
|
|
1164
|
+
event.preventDefault();
|
|
1165
|
+
edit();
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
const showPlace = placing === null ? null : placeTools(authoring, placing, tools, dom);
|
|
1169
|
+
const paint = painter(dom, 'img');
|
|
1170
|
+
const render = (attributes: Attributes) => {
|
|
1171
|
+
paint(attributes);
|
|
1172
|
+
const src = attributes.src ?? '';
|
|
1173
|
+
const shown = src.trim() !== '' && authoring.urlPolicy(src, { tag: 'img', attribute: 'src' });
|
|
1174
|
+
if (shown) {
|
|
1175
|
+
img.src = src;
|
|
1176
|
+
for (const name of ['width', 'height']) {
|
|
1177
|
+
const value = pictureSize(attributes[name]);
|
|
1178
|
+
if (value === undefined) img.removeAttribute(name);
|
|
1179
|
+
else img.setAttribute(name, String(value));
|
|
1180
|
+
}
|
|
1181
|
+
dom.prepend(img);
|
|
1182
|
+
} else img.remove();
|
|
1183
|
+
const alt = attributes.alt;
|
|
1184
|
+
const text =
|
|
1185
|
+
alt === undefined
|
|
1186
|
+
? t('surface.picture.noAlt')
|
|
1187
|
+
: alt === ''
|
|
1188
|
+
? t('surface.picture.decorative')
|
|
1189
|
+
: t('surface.picture.alt', { alt });
|
|
1190
|
+
label.textContent = shown ? text : `${text} ${t('surface.picture.blocked')}`;
|
|
1191
|
+
};
|
|
1192
|
+
return { dom, render, showPlace: (style: string | undefined) => showPlace?.(style) };
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
/**
|
|
1196
|
+
* The position line and the corner handle of a placed box, for a picture, a figure and a component alike: the line says
|
|
1197
|
+
* where it sits and how wide it is (a drag's width while it lasts, then the document's), and opens the style form with
|
|
1198
|
+
* those two fields when there is one. Returns what draws them for a `style` value; the handle's corner follows.
|
|
1199
|
+
*/
|
|
1200
|
+
function placeTools(
|
|
1201
|
+
authoring: Authoring,
|
|
1202
|
+
placing: Placing,
|
|
1203
|
+
tools: HTMLElement,
|
|
1204
|
+
dom: HTMLElement,
|
|
1205
|
+
): (style: string | undefined) => void {
|
|
1206
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
1207
|
+
let position: Placement = 'inline';
|
|
1208
|
+
let width: number | null = null;
|
|
1209
|
+
const open = placing.open;
|
|
1210
|
+
const place = tools.appendChild(document.createElement(open === null ? 'span' : 'button'));
|
|
1211
|
+
place.className = 'astl-picture-place';
|
|
1212
|
+
if (open !== null) {
|
|
1213
|
+
place.tabIndex = -1;
|
|
1214
|
+
(place as HTMLButtonElement).type = 'button';
|
|
1215
|
+
place.addEventListener('click', (event) => {
|
|
1216
|
+
event.preventDefault();
|
|
1217
|
+
open();
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
const sayPlace = (percent: number | null) => {
|
|
1221
|
+
const said = placeLabel(t, position, percent ?? width);
|
|
1222
|
+
place.textContent = said.text;
|
|
1223
|
+
place.setAttribute('aria-label', said.label);
|
|
1224
|
+
};
|
|
1225
|
+
dom.append(placeHandle(placing, () => position, sayPlace));
|
|
1226
|
+
return (style) => {
|
|
1227
|
+
position = positionOf(style ?? '');
|
|
1228
|
+
width = widthPercent(style ?? '');
|
|
1229
|
+
dom.dataset.astlPosition = position;
|
|
1230
|
+
sayPlace(null);
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/**
|
|
1235
|
+
* How the surface asks the author about pictures (`<astl-editor>` answers with its picture dialog). Without it,
|
|
1236
|
+
* picture files that are pasted or dropped are left to the browser's default and Enter on a picture does nothing new.
|
|
1237
|
+
*/
|
|
1238
|
+
export interface PictureHooks {
|
|
1239
|
+
/** Asks for a picture: a new one from `file` (uploaded first), or `current` to edit. Null: the author cancelled. */
|
|
1240
|
+
ask(request: PictureRequest): Promise<PictureFields | null>;
|
|
1241
|
+
/** A picture file was pasted or dropped, but there is no upload: say why nothing was inserted. */
|
|
1242
|
+
refuse(): void;
|
|
1243
|
+
/**
|
|
1244
|
+
* Opens the style form of the selected picture, figure or component (`<astl-editor>`: as its toolbar's style menu
|
|
1245
|
+
* does).
|
|
1246
|
+
*/
|
|
1247
|
+
style?(kind: 'picture' | 'figure' | 'component'): void;
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/** A width from the corner handle on the node at `pos`, one undo step; a figure's picture follows. */
|
|
1251
|
+
function commitWidth(editor: Editor, pos: unknown, percent: number): void {
|
|
1252
|
+
if (typeof pos !== 'number') return;
|
|
1253
|
+
const node = editor.state.doc.nodeAt(pos);
|
|
1254
|
+
if (node === null) return;
|
|
1255
|
+
const tr = editor.state.tr;
|
|
1256
|
+
closeHistory(tr);
|
|
1257
|
+
setPlacedStyle(tr, pos, node, widthChanges((node.attrs.attributes as Attributes).style ?? '', percent));
|
|
1258
|
+
if (tr.docChanged) editor.view.dispatch(tr);
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/** Asks for a picture's address and alt text again and writes them on the node at `pos` (`attributes` or `picture`). */
|
|
1262
|
+
async function editPicture(editor: Editor, hooks: PictureHooks, pos: number, key: 'attributes' | 'picture') {
|
|
1263
|
+
const node = editor.state.doc.nodeAt(pos);
|
|
1264
|
+
if (node === null) return;
|
|
1265
|
+
const attrs = node.attrs[key] as Attributes;
|
|
1266
|
+
const size = (name: 'width' | 'height') => {
|
|
1267
|
+
const value = pictureSize(attrs[name]);
|
|
1268
|
+
return value === undefined ? {} : { [name]: value };
|
|
1269
|
+
};
|
|
1270
|
+
const current: PictureFields = {
|
|
1271
|
+
src: attrs.src ?? '',
|
|
1272
|
+
alt: attrs.alt ?? '',
|
|
1273
|
+
...size('width'),
|
|
1274
|
+
...size('height'),
|
|
1275
|
+
};
|
|
1276
|
+
const fields = await hooks.ask({ current, caption: false, decorative: attrs.alt === '' });
|
|
1277
|
+
// The same node still there (nodes are immutable: anything else changed it, or moved it).
|
|
1278
|
+
if (fields === null || editor.isDestroyed || editor.state.doc.nodeAt(pos) !== node) return;
|
|
1279
|
+
const changed: Attributes = { src: fields.src, alt: fields.alt };
|
|
1280
|
+
if (fields.width !== undefined) changed.width = String(fields.width);
|
|
1281
|
+
if (fields.height !== undefined) changed.height = String(fields.height);
|
|
1282
|
+
// In the order written: new values in place, the language and the look kept, a size the dialog dropped left out.
|
|
1283
|
+
const next: Attributes = {};
|
|
1284
|
+
for (const [name, value] of Object.entries(attrs)) {
|
|
1285
|
+
if (Object.hasOwn(changed, name)) next[name] = changed[name] as string;
|
|
1286
|
+
else if (CONTENT_ATTRIBUTES.has(name) || name === CLASS_ATTRIBUTE) next[name] = value;
|
|
1287
|
+
}
|
|
1288
|
+
editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, key, { ...next, ...changed }));
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
/** A picture in text, a prompt or an option: an inline atom keeping the picture's attributes as data. */
|
|
1292
|
+
function pictureNode(authoring: Authoring, hooks: PictureHooks | undefined): Node {
|
|
1293
|
+
return Node.create({
|
|
1294
|
+
name: 'astlPicture',
|
|
1295
|
+
group: 'inline',
|
|
1296
|
+
inline: true,
|
|
1297
|
+
atom: true,
|
|
1298
|
+
selectable: true,
|
|
1299
|
+
draggable: true,
|
|
1300
|
+
addAttributes: () => ({ attributes: { default: {}, rendered: false, parseHTML: pictureAttributesOf } }),
|
|
1301
|
+
parseHTML: () => [{ tag: 'img' }],
|
|
1302
|
+
renderHTML: ({ node }) => ['img', { ...node.attrs.attributes }],
|
|
1303
|
+
addNodeView:
|
|
1304
|
+
() =>
|
|
1305
|
+
({ node, getPos, editor }) => {
|
|
1306
|
+
const edit = () => {
|
|
1307
|
+
const pos = getPos();
|
|
1308
|
+
if (hooks !== undefined && typeof pos === 'number')
|
|
1309
|
+
void editPicture(editor, hooks, pos, 'attributes');
|
|
1310
|
+
};
|
|
1311
|
+
const view = pictureView(authoring, 'span', hooks === undefined ? null : edit, {
|
|
1312
|
+
box: () => view.dom,
|
|
1313
|
+
commit: (percent) => commitWidth(editor, getPos(), percent),
|
|
1314
|
+
open: hooks?.style === undefined ? null : () => hooks.style?.('picture'),
|
|
1315
|
+
});
|
|
1316
|
+
const render = (attributes: Attributes) => {
|
|
1317
|
+
view.render(attributes);
|
|
1318
|
+
view.showPlace(attributes.style);
|
|
1319
|
+
};
|
|
1320
|
+
render(node.attrs.attributes as Attributes);
|
|
1321
|
+
return {
|
|
1322
|
+
dom: view.dom,
|
|
1323
|
+
update: updater('astlPicture', (attrs) => render(attrs.attributes as Attributes)),
|
|
1324
|
+
stopEvent: (event) => (event.target as Element).closest?.('.astl-picture-handle') !== null,
|
|
1325
|
+
};
|
|
1326
|
+
},
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* A figure: a block whose editable content is its caption, with its picture's attributes as data (`picture`), the
|
|
1332
|
+
* attributes of the figure and of the caption as written, and whether the caption comes first. An empty caption is
|
|
1333
|
+
* left out of the source.
|
|
1334
|
+
*/
|
|
1335
|
+
function figureNode(authoring: Authoring, hooks: PictureHooks | undefined): Node {
|
|
1336
|
+
const caption = (el: HTMLElement) => el.querySelector<HTMLElement>(`:scope > ${CAPTION_TAG}`);
|
|
1337
|
+
return Node.create({
|
|
1338
|
+
name: 'astlFigure',
|
|
1339
|
+
group: 'block',
|
|
1340
|
+
content: 'inline*',
|
|
1341
|
+
defining: true,
|
|
1342
|
+
isolating: true,
|
|
1343
|
+
addAttributes: () => ({
|
|
1344
|
+
attributes: { default: {}, rendered: false, parseHTML: languageOf },
|
|
1345
|
+
picture: {
|
|
1346
|
+
default: {},
|
|
1347
|
+
rendered: false,
|
|
1348
|
+
parseHTML: (el: HTMLElement) => pictureAttributesOf(el.querySelector(':scope > img')),
|
|
1349
|
+
},
|
|
1350
|
+
caption: { default: {}, rendered: false, parseHTML: (el: HTMLElement) => languageOf(caption(el)) },
|
|
1351
|
+
captionFirst: {
|
|
1352
|
+
default: false,
|
|
1353
|
+
rendered: false,
|
|
1354
|
+
parseHTML: (el: HTMLElement) => el.firstElementChild?.localName === CAPTION_TAG,
|
|
1355
|
+
},
|
|
1356
|
+
}),
|
|
1357
|
+
parseHTML: () => [
|
|
1358
|
+
{
|
|
1359
|
+
tag: FIGURE_TAG,
|
|
1360
|
+
contentElement: (el) => caption(el) ?? el.ownerDocument.createElement(CAPTION_TAG),
|
|
1361
|
+
},
|
|
1362
|
+
],
|
|
1363
|
+
renderHTML: ({ node }) => {
|
|
1364
|
+
const img: DOMOutputSpec = ['img', { ...node.attrs.picture }];
|
|
1365
|
+
if (node.content.size === 0) return [FIGURE_TAG, { ...node.attrs.attributes }, img];
|
|
1366
|
+
const text: DOMOutputSpec = [CAPTION_TAG, { ...node.attrs.caption }, 0];
|
|
1367
|
+
return [
|
|
1368
|
+
FIGURE_TAG,
|
|
1369
|
+
{ ...node.attrs.attributes },
|
|
1370
|
+
...(node.attrs.captionFirst ? [text, img] : [img, text]),
|
|
1371
|
+
];
|
|
1372
|
+
},
|
|
1373
|
+
addNodeView:
|
|
1374
|
+
() =>
|
|
1375
|
+
({ node, getPos, editor }) => {
|
|
1376
|
+
const dom = document.createElement(FIGURE_TAG);
|
|
1377
|
+
dom.className = 'astl-figure';
|
|
1378
|
+
const edit = () => {
|
|
1379
|
+
const pos = getPos();
|
|
1380
|
+
if (hooks !== undefined && typeof pos === 'number') void editPicture(editor, hooks, pos, 'picture');
|
|
1381
|
+
};
|
|
1382
|
+
const picture = pictureView(authoring, 'div', hooks === undefined ? null : edit, {
|
|
1383
|
+
box: () => dom,
|
|
1384
|
+
commit: (percent) => commitWidth(editor, getPos(), percent),
|
|
1385
|
+
open: hooks?.style === undefined ? null : () => hooks.style?.('figure'),
|
|
1386
|
+
});
|
|
1387
|
+
const contentDOM = document.createElement(CAPTION_TAG);
|
|
1388
|
+
dom.append(...(node.attrs.captionFirst ? [contentDOM, picture.dom] : [picture.dom, contentDOM]));
|
|
1389
|
+
const [paintFigure, paintCaption] = [painter(dom, FIGURE_TAG), painter(contentDOM, CAPTION_TAG)];
|
|
1390
|
+
const render = (attrs: Record<string, unknown>) => {
|
|
1391
|
+
picture.render(attrs.picture as Attributes);
|
|
1392
|
+
picture.showPlace((attrs.attributes as Attributes).style);
|
|
1393
|
+
paintFigure(attrs.attributes as Attributes);
|
|
1394
|
+
paintCaption(attrs.caption as Attributes);
|
|
1395
|
+
};
|
|
1396
|
+
render(node.attrs);
|
|
1397
|
+
return {
|
|
1398
|
+
dom,
|
|
1399
|
+
contentDOM,
|
|
1400
|
+
update: updater('astlFigure', render),
|
|
1401
|
+
stopEvent: (event) => (event.target as Element).closest?.('.astl-picture-handle') !== null,
|
|
1402
|
+
// A drag of the handle writes the figure's width as it goes.
|
|
1403
|
+
ignoreMutation: (m) =>
|
|
1404
|
+
picture.dom.contains(m.target) || (m.target === dom && m.type === 'attributes'),
|
|
1405
|
+
};
|
|
1406
|
+
},
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
/** The node name of `<astl-page>`. */
|
|
1411
|
+
const PAGE = 'astlPage';
|
|
1412
|
+
|
|
1413
|
+
/** What a page or a document without pages holds: blocks and layouts. */
|
|
1414
|
+
const PAGE_CONTENT = `(block | ${LAYOUT} | ${HELP})+`;
|
|
1415
|
+
|
|
1416
|
+
/**
|
|
1417
|
+
* A layout: `<astl-columns>` with its `<astl-column>`s, under their real tags (nothing in them asks for a node view).
|
|
1418
|
+
* Outside the `block` group, so one holds no other, nor does a list or a rich block. Isolating: Backspace at the start
|
|
1419
|
+
* of a column or Delete at its end stays in it. `astl-match` has a child `astl-column` too, kept apart by the parse
|
|
1420
|
+
* rules' context: only a layout's direct child is a layout's column, and there these rules go first.
|
|
1421
|
+
*/
|
|
1422
|
+
const layoutNodes: readonly Node[] = [
|
|
1423
|
+
Node.create({
|
|
1424
|
+
name: LAYOUT,
|
|
1425
|
+
content: `${LAYOUT_COLUMN}{${MIN_COLUMNS},${MAX_COLUMNS}}`,
|
|
1426
|
+
isolating: true,
|
|
1427
|
+
addAttributes: () => sourceAttributes,
|
|
1428
|
+
addKeyboardShortcuts() {
|
|
1429
|
+
return {
|
|
1430
|
+
// Isolating keeps Backspace in a column; at the start of an empty layout, it takes the layout away.
|
|
1431
|
+
Backspace: ({ editor }) => {
|
|
1432
|
+
const { selection } = editor.state;
|
|
1433
|
+
const at = layoutAt(editor.state);
|
|
1434
|
+
const { $from } = selection;
|
|
1435
|
+
if (at === null || !selection.empty || $from.parentOffset > 0 || !isEmptyLayout(at.node))
|
|
1436
|
+
return false;
|
|
1437
|
+
if ($from.pos !== at.pos + 3) return false;
|
|
1438
|
+
const tr = closeHistory(editor.state.tr);
|
|
1439
|
+
deleteLayoutIn(tr, at, true);
|
|
1440
|
+
editor.view.dispatch(tr.scrollIntoView());
|
|
1441
|
+
return true;
|
|
1442
|
+
},
|
|
1443
|
+
};
|
|
1444
|
+
},
|
|
1445
|
+
parseHTML: () => [{ tag: COLUMNS_TAG }],
|
|
1446
|
+
renderHTML: ({ node }) => [COLUMNS_TAG, { ...node.attrs.attributes }, 0],
|
|
1447
|
+
}),
|
|
1448
|
+
Node.create({
|
|
1449
|
+
name: LAYOUT_COLUMN,
|
|
1450
|
+
content: 'block+',
|
|
1451
|
+
isolating: true,
|
|
1452
|
+
selectable: false,
|
|
1453
|
+
addAttributes: () => sourceAttributes,
|
|
1454
|
+
parseHTML: () => [
|
|
1455
|
+
{ tag: COLUMN_TAG, context: `${LAYOUT}/`, priority: 60 },
|
|
1456
|
+
// Out of place, its content stays where it is: no match made up to hold it.
|
|
1457
|
+
{ tag: COLUMN_TAG, context: `doc/|${PAGE}/|${LAYOUT_COLUMN}/`, skip: true, priority: 60 },
|
|
1458
|
+
],
|
|
1459
|
+
renderHTML: ({ node }) => [COLUMN_TAG, { ...node.attrs.attributes }, 0],
|
|
1460
|
+
}),
|
|
1461
|
+
];
|
|
1462
|
+
|
|
1463
|
+
/** Page heads made so far: each gets ids of its own for its title field's name. */
|
|
1464
|
+
let pageHeads = 0;
|
|
1465
|
+
|
|
1466
|
+
/**
|
|
1467
|
+
* `<astl-page>` with a head: the page's number of all (`surface.pageNumber`), "Add title" (`surface.pageAddTitle`: a
|
|
1468
|
+
* page has no title until it gets one), from the second page on a button that joins it to the page before
|
|
1469
|
+
* (`surface.pageJoin`) and, while there are other pages, one that deletes it (`surface.pageDelete`). A title shows under
|
|
1470
|
+
* the head in its field, named by the page's number (`surface.pageTitleOf`, placeholder `surface.pageTitle`), with
|
|
1471
|
+
* "Remove title". The field opens while the page has a label and while it has the focus, and closes when it loses the
|
|
1472
|
+
* focus empty, without touching the document. The buttons are named by their text and the number, the join button by
|
|
1473
|
+
* the page before, so each control has a name of its own. A node view never learns its index: a plugin numbers the
|
|
1474
|
+
* heads after every change of the document.
|
|
1475
|
+
*/
|
|
1476
|
+
export function pageNode(authoring: Authoring): Node {
|
|
1477
|
+
const t = (key: string, params?: MessageParams) => authoring.t(EDITOR_NAMESPACE, key, params);
|
|
1478
|
+
// UI texts in the content: in the UI language.
|
|
1479
|
+
const ui = { lang: authoring.locale, dir: directionOf(authoring.locale) };
|
|
1480
|
+
/** The head of each page, by the page's element: shows the page's number (from 1) of all. */
|
|
1481
|
+
const heads = new WeakMap<Element, (page: number, pages: number) => void>();
|
|
1482
|
+
const numbering = new Plugin({
|
|
1483
|
+
view(view) {
|
|
1484
|
+
const number = () => {
|
|
1485
|
+
const pages = view.state.doc.childCount;
|
|
1486
|
+
view.state.doc.forEach((node, offset, index) => {
|
|
1487
|
+
const dom = view.nodeDOM(offset);
|
|
1488
|
+
if (node.type.name === PAGE && dom instanceof Element) heads.get(dom)?.(index + 1, pages);
|
|
1489
|
+
});
|
|
1490
|
+
};
|
|
1491
|
+
number();
|
|
1492
|
+
return {
|
|
1493
|
+
update: (current, previous) => {
|
|
1494
|
+
if (current.state.doc !== previous.doc) number();
|
|
1495
|
+
},
|
|
1496
|
+
};
|
|
1497
|
+
},
|
|
1498
|
+
});
|
|
1499
|
+
return Node.create({
|
|
1500
|
+
name: PAGE,
|
|
1501
|
+
content: PAGE_CONTENT,
|
|
1502
|
+
defining: true,
|
|
1503
|
+
isolating: true,
|
|
1504
|
+
addAttributes: () => sourceAttributes,
|
|
1505
|
+
parseHTML: () => [{ tag: 'astl-page' }],
|
|
1506
|
+
renderHTML: ({ node }) => ['astl-page', { ...node.attrs.attributes }, 0],
|
|
1507
|
+
addProseMirrorPlugins: () => [numbering],
|
|
1508
|
+
addNodeView:
|
|
1509
|
+
() =>
|
|
1510
|
+
({ node, getPos, editor }) => {
|
|
1511
|
+
const dom = document.createElement('section');
|
|
1512
|
+
dom.className = 'astl-page';
|
|
1513
|
+
const head = document.createElement('div');
|
|
1514
|
+
head.className = 'astl-page-head';
|
|
1515
|
+
head.contentEditable = 'false';
|
|
1516
|
+
const id = `astl-page-head-${++pageHeads}`;
|
|
1517
|
+
const number = Object.assign(document.createElement('span'), {
|
|
1518
|
+
className: 'astl-page-number',
|
|
1519
|
+
id: `${id}-number`,
|
|
1520
|
+
...ui,
|
|
1521
|
+
});
|
|
1522
|
+
/** A button named by its text and the page's number, so each page's has a name of its own. */
|
|
1523
|
+
const named = (suffix: string, text: string): HTMLButtonElement => {
|
|
1524
|
+
const button = Object.assign(document.createElement('button'), {
|
|
1525
|
+
type: 'button',
|
|
1526
|
+
className: `astl-page-${suffix}`,
|
|
1527
|
+
id: `${id}-${suffix}`,
|
|
1528
|
+
textContent: text,
|
|
1529
|
+
...ui,
|
|
1530
|
+
});
|
|
1531
|
+
button.setAttribute('aria-labelledby', `${button.id} ${number.id}`);
|
|
1532
|
+
return button;
|
|
1533
|
+
};
|
|
1534
|
+
const addTitle = named('add-title', t('surface.pageAddTitle'));
|
|
1535
|
+
// Hidden until numbered: the first page has no join button, the only page no delete button.
|
|
1536
|
+
const join = Object.assign(document.createElement('button'), {
|
|
1537
|
+
type: 'button',
|
|
1538
|
+
className: 'astl-page-join',
|
|
1539
|
+
hidden: true,
|
|
1540
|
+
...ui,
|
|
1541
|
+
});
|
|
1542
|
+
const remove = named('delete', t('surface.pageDelete'));
|
|
1543
|
+
remove.hidden = true;
|
|
1544
|
+
const field = Object.assign(document.createElement('div'), {
|
|
1545
|
+
className: 'astl-page-field',
|
|
1546
|
+
hidden: true,
|
|
1547
|
+
});
|
|
1548
|
+
const input = Object.assign(document.createElement('input'), {
|
|
1549
|
+
className: 'astl-page-label',
|
|
1550
|
+
placeholder: t('surface.pageTitle'),
|
|
1551
|
+
});
|
|
1552
|
+
const removeTitle = named('remove-title', t('surface.pageRemoveTitle'));
|
|
1553
|
+
field.append(input, removeTitle);
|
|
1554
|
+
let attributes = node.attrs.attributes as Attributes;
|
|
1555
|
+
// The author is in the field, or just asked for it: it stays while empty, till the focus leaves.
|
|
1556
|
+
let editing = false;
|
|
1557
|
+
const sync = () => {
|
|
1558
|
+
const titled = (attributes.label ?? '') !== '';
|
|
1559
|
+
field.hidden = !(titled || editing);
|
|
1560
|
+
addTitle.hidden = titled || editing;
|
|
1561
|
+
removeTitle.hidden = !titled;
|
|
1562
|
+
};
|
|
1563
|
+
let shown = '';
|
|
1564
|
+
heads.set(dom, (page, pages) => {
|
|
1565
|
+
if (`${page}/${pages}` === shown) return;
|
|
1566
|
+
shown = `${page}/${pages}`;
|
|
1567
|
+
number.textContent = t('surface.pageNumber', { page, pages });
|
|
1568
|
+
input.setAttribute('aria-label', t('surface.pageTitleOf', { page }));
|
|
1569
|
+
join.textContent = t('surface.pageJoin', { previous: page - 1 });
|
|
1570
|
+
join.hidden = page === 1;
|
|
1571
|
+
remove.hidden = pages === 1;
|
|
1572
|
+
});
|
|
1573
|
+
addTitle.addEventListener('click', () => {
|
|
1574
|
+
editing = true;
|
|
1575
|
+
sync();
|
|
1576
|
+
input.focus();
|
|
1577
|
+
});
|
|
1578
|
+
input.addEventListener('focus', () => {
|
|
1579
|
+
editing = true;
|
|
1580
|
+
});
|
|
1581
|
+
input.addEventListener('blur', () => {
|
|
1582
|
+
editing = false;
|
|
1583
|
+
sync();
|
|
1584
|
+
});
|
|
1585
|
+
removeTitle.addEventListener('click', () => {
|
|
1586
|
+
const pos = getPos();
|
|
1587
|
+
if (typeof pos !== 'number') return;
|
|
1588
|
+
const { label: _, ...rest } = attributes;
|
|
1589
|
+
const page = editor.state.doc.resolve(pos).index(0) + 1;
|
|
1590
|
+
// One undo step of its own, said on the notice line; the cursor and the scroll stay where they are.
|
|
1591
|
+
const tr = closeHistory(editor.state.tr.setNodeAttribute(pos, 'attributes', rest)).setMeta(
|
|
1592
|
+
PAGE_CHANGE,
|
|
1593
|
+
{
|
|
1594
|
+
key: 'surface.pageTitleRemoved',
|
|
1595
|
+
params: { page },
|
|
1596
|
+
} satisfies SurfaceChange,
|
|
1597
|
+
);
|
|
1598
|
+
editor.view.dispatch(tr);
|
|
1599
|
+
// The button went with the field: the focus goes to "Add title".
|
|
1600
|
+
editing = false;
|
|
1601
|
+
sync();
|
|
1602
|
+
addTitle.focus();
|
|
1603
|
+
});
|
|
1604
|
+
join.addEventListener('click', () => {
|
|
1605
|
+
const pos = getPos();
|
|
1606
|
+
if (typeof pos !== 'number' || editor.state.doc.resolve(pos).index(0) === 0) return;
|
|
1607
|
+
const tr = editor.state.tr;
|
|
1608
|
+
joinPage(tr, pos, true);
|
|
1609
|
+
editor.view.dispatch(tr);
|
|
1610
|
+
// The button went with its page: the editor takes the focus, the cursor at the joined content.
|
|
1611
|
+
editor.view.focus();
|
|
1612
|
+
});
|
|
1613
|
+
remove.addEventListener('click', () => {
|
|
1614
|
+
const pos = getPos();
|
|
1615
|
+
const tr = editor.state.tr;
|
|
1616
|
+
if (typeof pos !== 'number' || !removePageAt(tr, pos)) return;
|
|
1617
|
+
editor.view.dispatch(tr);
|
|
1618
|
+
// As after a join: the editor takes the focus, the cursor at the start of the page it went to.
|
|
1619
|
+
editor.view.focus();
|
|
1620
|
+
});
|
|
1621
|
+
head.append(number, addTitle, join, remove, field);
|
|
1622
|
+
const contentDOM = document.createElement('div');
|
|
1623
|
+
// The page's look is for its content, not for the controls in its head.
|
|
1624
|
+
const paint = painter(contentDOM, 'astl-page');
|
|
1625
|
+
paint(attributes);
|
|
1626
|
+
dom.append(head, contentDOM);
|
|
1627
|
+
input.value = attributes.label ?? '';
|
|
1628
|
+
sync();
|
|
1629
|
+
input.addEventListener('input', () => {
|
|
1630
|
+
const pos = getPos();
|
|
1631
|
+
if (typeof pos !== 'number') return;
|
|
1632
|
+
const { label: _, ...rest } = attributes;
|
|
1633
|
+
const next = input.value === '' ? rest : { ...rest, label: input.value };
|
|
1634
|
+
editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, 'attributes', next));
|
|
1635
|
+
});
|
|
1636
|
+
const render = (attrs: Record<string, unknown>) => {
|
|
1637
|
+
attributes = attrs.attributes as Attributes;
|
|
1638
|
+
paint(attributes);
|
|
1639
|
+
if (input.value !== (attributes.label ?? '')) input.value = attributes.label ?? '';
|
|
1640
|
+
sync();
|
|
1641
|
+
};
|
|
1642
|
+
return {
|
|
1643
|
+
dom,
|
|
1644
|
+
contentDOM,
|
|
1645
|
+
update: updater(PAGE, render),
|
|
1646
|
+
// The head (the number, the buttons, the title field) is not document content: ProseMirror must leave its
|
|
1647
|
+
// events and mutations alone.
|
|
1648
|
+
stopEvent: (event) => head.contains(event.target as HTMLElement),
|
|
1649
|
+
ignoreMutation: (m) => head.contains(m.target),
|
|
1650
|
+
};
|
|
1651
|
+
},
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
/**
|
|
1656
|
+
* The document: loose blocks and layouts (one implicit page; an empty document gets a paragraph), or pages. `attributes`
|
|
1657
|
+
* are those of `<astl-doc>` as written: its content language, direction and look (set in the inspector). `rules` are its
|
|
1658
|
+
* `<astl-style>` elements, as the attributes of each: on the node, so undo covers them.
|
|
1659
|
+
*/
|
|
1660
|
+
export const docNode: Node = Node.create({
|
|
1661
|
+
name: 'doc',
|
|
1662
|
+
topNode: true,
|
|
1663
|
+
content: `(${PAGE_CONTENT} | astlPage+)`,
|
|
1664
|
+
addAttributes: () => ({
|
|
1665
|
+
attributes: { default: {}, rendered: false },
|
|
1666
|
+
rules: { default: [], rendered: false },
|
|
1667
|
+
}),
|
|
1668
|
+
});
|
|
1669
|
+
|
|
1670
|
+
/** The transaction meta of a page transaction: its `SurfaceChange`, for the surface to announce. */
|
|
1671
|
+
export const PAGE_CHANGE = 'astlPageChange';
|
|
1672
|
+
|
|
1673
|
+
/** Blocks directly on a page that break at the cursor; any other block breaks after itself. */
|
|
1674
|
+
const BREAKING: ReadonlySet<string> = new Set(['paragraph', 'heading']);
|
|
1675
|
+
|
|
1676
|
+
/** A page transaction: one undo step of its own, announced, scrolled to. */
|
|
1677
|
+
function pageStep(tr: Transaction, change: SurfaceChange): void {
|
|
1678
|
+
closeHistory(tr).setMeta(PAGE_CHANGE, change).scrollIntoView();
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/** The first page with the id `id`: its position, node and index, or null. */
|
|
1682
|
+
function findPage(doc: PMNode, id: string | undefined): { pos: number; node: PMNode; index: number } | null {
|
|
1683
|
+
let found: { pos: number; node: PMNode; index: number } | null = null;
|
|
1684
|
+
doc.forEach((node, pos, index) => {
|
|
1685
|
+
const own = (node.attrs.attributes as Attributes | undefined)?.id;
|
|
1686
|
+
if (found === null && id !== undefined && node.type.name === PAGE && own === id)
|
|
1687
|
+
found = { pos, node, index };
|
|
1688
|
+
});
|
|
1689
|
+
return found;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/** A document without pages becomes one page in `tr`, with a fresh id from `taken`: its content moves one in. */
|
|
1693
|
+
function intoPages(tr: Transaction, taken: Set<string>): void {
|
|
1694
|
+
const { doc } = tr;
|
|
1695
|
+
const type = doc.type.schema.nodes[PAGE];
|
|
1696
|
+
if (type === undefined || doc.firstChild?.type === type) return;
|
|
1697
|
+
const range = doc.resolve(0).blockRange(doc.resolve(doc.content.size));
|
|
1698
|
+
if (range !== null) tr.wrap(range, [{ type, attrs: { attributes: { id: freshId('page', taken) } } }]);
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
/**
|
|
1702
|
+
* A page break at the cursor in `tr` (`EditorAdapter.splitPage`): the new page's id, or null, changing nothing, when
|
|
1703
|
+
* the cursor is in no page's content.
|
|
1704
|
+
*/
|
|
1705
|
+
export function splitPageIn(tr: Transaction): string | null {
|
|
1706
|
+
const { doc, selection } = tr;
|
|
1707
|
+
const { $from } = selection;
|
|
1708
|
+
const { nodes } = doc.type.schema;
|
|
1709
|
+
const [page, paragraph] = [nodes[PAGE], nodes.paragraph];
|
|
1710
|
+
const paged = doc.firstChild?.type === page;
|
|
1711
|
+
// The depth of the node whose blocks the cursor is among: its page, or a document without pages.
|
|
1712
|
+
const top = paged ? 1 : 0;
|
|
1713
|
+
if (page === undefined || paragraph === undefined || $from.depth < top) return null;
|
|
1714
|
+
// In a paragraph or a heading directly on the page: at the cursor (at its start before it, at its end after it).
|
|
1715
|
+
// In any other block: after the block on the page. Between blocks (a selected one counts): there.
|
|
1716
|
+
let at = selection instanceof NodeSelection && $from.depth === top ? selection.to : $from.pos;
|
|
1717
|
+
let inside = false;
|
|
1718
|
+
if ($from.depth === top + 1 && BREAKING.has($from.parent.type.name)) {
|
|
1719
|
+
if ($from.parentOffset === 0) at = $from.before();
|
|
1720
|
+
else if ($from.parentOffset === $from.parent.content.size) at = $from.after();
|
|
1721
|
+
else inside = true;
|
|
1722
|
+
} else if ($from.depth > top) at = $from.after(top + 1);
|
|
1723
|
+
const taken = idsIn(doc);
|
|
1724
|
+
const language = Object.fromEntries(
|
|
1725
|
+
Object.entries(paged ? ($from.node(1).attrs.attributes as Attributes) : {}).filter(
|
|
1726
|
+
([name]) => CONTENT_ATTRIBUTES.has(name) || name === CLASS_ATTRIBUTE,
|
|
1727
|
+
),
|
|
1728
|
+
);
|
|
1729
|
+
intoPages(tr, taken);
|
|
1730
|
+
const id = freshId('page', taken);
|
|
1731
|
+
const after = { type: page, attrs: { attributes: { id, ...language } } };
|
|
1732
|
+
// Wrapped into a page, the content moved one position in.
|
|
1733
|
+
let pos = paged ? at : at + 1;
|
|
1734
|
+
let start: number;
|
|
1735
|
+
if (inside) {
|
|
1736
|
+
tr.split(pos, 2, [after]);
|
|
1737
|
+
start = pos + 2;
|
|
1738
|
+
} else {
|
|
1739
|
+
// A side left without blocks gets an empty paragraph: a page holds at least one block.
|
|
1740
|
+
const $pos = tr.doc.resolve(pos);
|
|
1741
|
+
if ($pos.index() === 0) {
|
|
1742
|
+
tr.insert(pos, paragraph.create());
|
|
1743
|
+
pos += 2;
|
|
1744
|
+
} else if ($pos.index() === $pos.parent.childCount) tr.insert(pos, paragraph.create());
|
|
1745
|
+
tr.split(pos, 1, [after]);
|
|
1746
|
+
start = pos + 1;
|
|
1747
|
+
}
|
|
1748
|
+
tr.setSelection(Selection.near(tr.doc.resolve(start + 1)));
|
|
1749
|
+
pageStep(tr, { key: 'surface.pageAdded', params: { page: tr.doc.resolve(start).index(0) + 1 } });
|
|
1750
|
+
return id;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
/** An empty page after the page `after`, else after the last page, in `tr` (`EditorAdapter.addPage`): its id. */
|
|
1754
|
+
export function addPageIn(tr: Transaction, after?: string): string {
|
|
1755
|
+
const { nodes } = tr.doc.type.schema;
|
|
1756
|
+
const [page, paragraph] = [nodes[PAGE], nodes.paragraph];
|
|
1757
|
+
if (page === undefined || paragraph === undefined) throw new Error('the schema has no pages');
|
|
1758
|
+
const taken = idsIn(tr.doc);
|
|
1759
|
+
intoPages(tr, taken);
|
|
1760
|
+
const target = findPage(tr.doc, after);
|
|
1761
|
+
const at = target === null ? tr.doc.content.size : target.pos + target.node.nodeSize;
|
|
1762
|
+
const id = freshId('page', taken);
|
|
1763
|
+
tr.insert(at, page.create({ attributes: { id } }, paragraph.create()));
|
|
1764
|
+
tr.setSelection(TextSelection.create(tr.doc, at + 2));
|
|
1765
|
+
pageStep(tr, { key: 'surface.pageAdded', params: { page: tr.doc.resolve(at).index(0) + 1 } });
|
|
1766
|
+
return id;
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
/**
|
|
1770
|
+
* Joins the page `id` to the page before it in `tr` (`EditorAdapter.mergePage`), the cursor at the start of the joined
|
|
1771
|
+
* content: false, changing nothing, for the first page or an id that is not a page's.
|
|
1772
|
+
*/
|
|
1773
|
+
export function mergePageIn(tr: Transaction, id: string): boolean {
|
|
1774
|
+
const target = findPage(tr.doc, id);
|
|
1775
|
+
if (target === null || target.index === 0) return false;
|
|
1776
|
+
joinPage(tr, target.pos, true);
|
|
1777
|
+
return true;
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* Deletes the page `id` with its content in `tr` (`EditorAdapter.removePage`): false, changing nothing, for the only
|
|
1782
|
+
* page or an id that is not a page's.
|
|
1783
|
+
*/
|
|
1784
|
+
export function removePageIn(tr: Transaction, id: string): boolean {
|
|
1785
|
+
const target = findPage(tr.doc, id);
|
|
1786
|
+
return target !== null && removePageAt(tr, target.pos);
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/**
|
|
1790
|
+
* Deletes the page at `pos` with its content, the cursor at the start of the page before it, or of the next one for
|
|
1791
|
+
* the first page: false, changing nothing, for the only page.
|
|
1792
|
+
*/
|
|
1793
|
+
function removePageAt(tr: Transaction, pos: number): boolean {
|
|
1794
|
+
const { doc } = tr;
|
|
1795
|
+
const index = doc.resolve(pos).index(0);
|
|
1796
|
+
const page = doc.child(index);
|
|
1797
|
+
if (doc.childCount === 1) return false;
|
|
1798
|
+
// Before the page, nothing moves: the page before starts where it did, the next one where this one did.
|
|
1799
|
+
const start = index === 0 ? pos : pos - doc.child(index - 1).nodeSize;
|
|
1800
|
+
tr.delete(pos, pos + page.nodeSize);
|
|
1801
|
+
tr.setSelection(Selection.near(tr.doc.resolve(start + 1)));
|
|
1802
|
+
pageStep(tr, { key: 'surface.pageDeleted', params: { n: index + 1 } });
|
|
1803
|
+
return true;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
/** Joins the page at `pos` to the one before it, the cursor kept, or at the start of the joined content (`place`). */
|
|
1807
|
+
function joinPage(tr: Transaction, pos: number, place: boolean): void {
|
|
1808
|
+
const joined = tr.doc.resolve(pos).index(0) + 1;
|
|
1809
|
+
tr.join(pos);
|
|
1810
|
+
if (place) tr.setSelection(Selection.near(tr.doc.resolve(pos - 1)));
|
|
1811
|
+
pageStep(tr, { key: 'surface.pageJoined', params: { page: joined, previous: joined - 1 } });
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/** Whether a position on a page is in a layout: a column's edge is not the page's, even at the very start of the page. */
|
|
1815
|
+
const inLayout = ($pos: Selection['$from']): boolean => $pos.depth > 1 && $pos.node(2).type.name === LAYOUT;
|
|
1816
|
+
|
|
1817
|
+
/** With the cursor at the very start of a page but the first, that page's position (where it joins the page before). */
|
|
1818
|
+
function pageStartAt(selection: Selection): number | null {
|
|
1819
|
+
const { $from, empty } = selection;
|
|
1820
|
+
if (!(selection instanceof TextSelection) || !empty || $from.parentOffset !== 0 || inLayout($from))
|
|
1821
|
+
return null;
|
|
1822
|
+
if ($from.depth < 2 || $from.node(1).type.name !== PAGE || $from.index(0) === 0) return null;
|
|
1823
|
+
for (let depth = 1; depth < $from.depth; depth++) if ($from.index(depth) !== 0) return null;
|
|
1824
|
+
return $from.before(1);
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/** With the cursor at the very end of a page but the last, the next page's position (where it joins this one). */
|
|
1828
|
+
function nextPageAt(selection: Selection): number | null {
|
|
1829
|
+
const { $to, empty } = selection;
|
|
1830
|
+
if (
|
|
1831
|
+
!(selection instanceof TextSelection) ||
|
|
1832
|
+
!empty ||
|
|
1833
|
+
$to.parentOffset !== $to.parent.content.size ||
|
|
1834
|
+
inLayout($to)
|
|
1835
|
+
)
|
|
1836
|
+
return null;
|
|
1837
|
+
if ($to.depth < 2 || $to.node(1).type.name !== PAGE || $to.index(0) === $to.node(0).childCount - 1)
|
|
1838
|
+
return null;
|
|
1839
|
+
for (let depth = 1; depth < $to.depth; depth++) {
|
|
1840
|
+
if ($to.index(depth) !== $to.node(depth).childCount - 1) return null;
|
|
1841
|
+
}
|
|
1842
|
+
return $to.after(1);
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/**
|
|
1846
|
+
* Pages from the keyboard: Mod-Enter breaks the page at the cursor (Shift-Enter stays a line break); Backspace at the
|
|
1847
|
+
* very start of a page joins it to the page before, Delete at the very end of a page joins the next page to it (pages
|
|
1848
|
+
* are isolating: ProseMirror's own joins stop at them).
|
|
1849
|
+
*/
|
|
1850
|
+
const pagesExtension: Extension = Extension.create({
|
|
1851
|
+
name: 'astlPages',
|
|
1852
|
+
priority: 1000,
|
|
1853
|
+
addKeyboardShortcuts: () => ({
|
|
1854
|
+
// The page break's key: where no page can break (between pages), nothing, never a line break.
|
|
1855
|
+
'Mod-Enter': ({ editor }) => {
|
|
1856
|
+
const tr = editor.state.tr;
|
|
1857
|
+
if (splitPageIn(tr) !== null) editor.view.dispatch(tr);
|
|
1858
|
+
return true;
|
|
1859
|
+
},
|
|
1860
|
+
Backspace: ({ editor }) => {
|
|
1861
|
+
const pos = pageStartAt(editor.state.selection);
|
|
1862
|
+
if (pos === null) return false;
|
|
1863
|
+
// Right after an input rule (a heading from "## "), Backspace undoes it first, as anywhere else.
|
|
1864
|
+
if (editor.commands.undoInputRule()) return true;
|
|
1865
|
+
const tr = editor.state.tr;
|
|
1866
|
+
joinPage(tr, pos, false);
|
|
1867
|
+
editor.view.dispatch(tr);
|
|
1868
|
+
return true;
|
|
1869
|
+
},
|
|
1870
|
+
Delete: ({ editor }) => {
|
|
1871
|
+
const pos = nextPageAt(editor.state.selection);
|
|
1872
|
+
if (pos === null) return false;
|
|
1873
|
+
const tr = editor.state.tr;
|
|
1874
|
+
joinPage(tr, pos, false);
|
|
1875
|
+
editor.view.dispatch(tr);
|
|
1876
|
+
return true;
|
|
1877
|
+
},
|
|
1878
|
+
}),
|
|
1879
|
+
});
|
|
1880
|
+
|
|
1881
|
+
const specOf = (manifest: ComponentManifest, child: PMNode): ChildSpec | undefined =>
|
|
1882
|
+
manifest.children.find((c) => nodeName(c.tag) === child.type.name);
|
|
1883
|
+
|
|
1884
|
+
/**
|
|
1885
|
+
* Children of a rich block keep local ids of their own: a child without one (just added) or with one an earlier child
|
|
1886
|
+
* has (a split or pasted copy) gets a fresh one, `<tag>-<n>`, and none of the answer attributes of the child it copies.
|
|
1887
|
+
*/
|
|
1888
|
+
function uniqueLocalIds(
|
|
1889
|
+
blocks: ReadonlyMap<string, ComponentManifest>,
|
|
1890
|
+
state: EditorState,
|
|
1891
|
+
): Transaction | null {
|
|
1892
|
+
const tr = state.tr;
|
|
1893
|
+
state.doc.descendants((node, pos) => {
|
|
1894
|
+
const manifest = blocks.get(node.type.name);
|
|
1895
|
+
if (manifest === undefined) return true;
|
|
1896
|
+
const idsOf = (child: PMNode) =>
|
|
1897
|
+
(specOf(manifest, child)?.attributes ?? []).filter((a) => a.type === 'id');
|
|
1898
|
+
const taken = new Set<string>();
|
|
1899
|
+
node.forEach((child) => {
|
|
1900
|
+
for (const { name } of idsOf(child)) taken.add((child.attrs.attributes as Attributes)[name] ?? '');
|
|
1901
|
+
});
|
|
1902
|
+
const seen = new Set<string>();
|
|
1903
|
+
node.forEach((child, offset) => {
|
|
1904
|
+
const spec = specOf(manifest, child);
|
|
1905
|
+
const attributes = child.attrs.attributes as Attributes;
|
|
1906
|
+
let next: Attributes | null = null;
|
|
1907
|
+
for (const { name, required } of idsOf(child)) {
|
|
1908
|
+
const value = attributes[name] ?? '';
|
|
1909
|
+
if (value !== '' && !seen.has(value)) {
|
|
1910
|
+
seen.add(value);
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
if (value === '' && !required) continue;
|
|
1914
|
+
next ??= Object.fromEntries(
|
|
1915
|
+
Object.entries(attributes).filter(
|
|
1916
|
+
([attr]) => spec?.attributes.find((a) => a.name === attr)?.visibility !== 'private',
|
|
1917
|
+
),
|
|
1918
|
+
);
|
|
1919
|
+
const prefix = spec?.tag.replace(/^astl-/, '') ?? 'item';
|
|
1920
|
+
let n = 1;
|
|
1921
|
+
while (taken.has(`${prefix}-${n}`)) n++;
|
|
1922
|
+
next[name] = `${prefix}-${n}`;
|
|
1923
|
+
taken.add(next[name]);
|
|
1924
|
+
seen.add(next[name]);
|
|
1925
|
+
}
|
|
1926
|
+
if (next !== null) tr.setNodeAttribute(pos + 1 + offset, 'attributes', next);
|
|
1927
|
+
});
|
|
1928
|
+
return false;
|
|
1929
|
+
});
|
|
1930
|
+
return tr.docChanged ? tr : null;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
/**
|
|
1934
|
+
* Enter in a rich child of a block adds a sibling after the cursor: the same type, or after a child the type allows
|
|
1935
|
+
* once (a prompt) its first repeated rich child (an option), with no attribute copied (the plugin gives it its local
|
|
1936
|
+
* id). TipTap's default would add the first child type of the block (a second prompt) with the attributes copied.
|
|
1937
|
+
*/
|
|
1938
|
+
function childrenExtension(manifests: readonly ComponentManifest[]): Extension {
|
|
1939
|
+
const blocks = new Map(
|
|
1940
|
+
manifests
|
|
1941
|
+
.filter(
|
|
1942
|
+
(m) =>
|
|
1943
|
+
m.display === 'block' && m.content !== 'flow' && m.children.some((c) => c.content === 'inline'),
|
|
1944
|
+
)
|
|
1945
|
+
.map((m) => [nodeName(m.tag), m]),
|
|
1946
|
+
);
|
|
1947
|
+
return Extension.create({
|
|
1948
|
+
name: 'astlChildren',
|
|
1949
|
+
priority: 1000,
|
|
1950
|
+
addKeyboardShortcuts() {
|
|
1951
|
+
return {
|
|
1952
|
+
Enter: ({ editor }) => {
|
|
1953
|
+
const { state } = editor;
|
|
1954
|
+
const { $from } = state.selection;
|
|
1955
|
+
if ($from.depth < 2 || !$from.parent.isTextblock) return false;
|
|
1956
|
+
const manifest = blocks.get($from.node(-1).type.name);
|
|
1957
|
+
const spec = manifest === undefined ? undefined : specOf(manifest, $from.parent);
|
|
1958
|
+
if (manifest === undefined || spec === undefined) return false;
|
|
1959
|
+
const next =
|
|
1960
|
+
spec.max === 1 ? manifest.children.find((c) => c.max !== 1 && c.content === 'inline') : spec;
|
|
1961
|
+
const type = next === undefined ? undefined : state.schema.nodes[nodeName(next.tag)];
|
|
1962
|
+
// Nothing repeats in this block: no new line.
|
|
1963
|
+
if (type === undefined) return true;
|
|
1964
|
+
const tr = state.tr.deleteSelection();
|
|
1965
|
+
tr.split(tr.selection.from, 1, [{ type, attrs: { attributes: {} } }]);
|
|
1966
|
+
editor.view.dispatch(tr.scrollIntoView());
|
|
1967
|
+
return true;
|
|
1968
|
+
},
|
|
1969
|
+
};
|
|
1970
|
+
},
|
|
1971
|
+
addProseMirrorPlugins: () => [
|
|
1972
|
+
new Plugin({
|
|
1973
|
+
appendTransaction: (transactions, _, state) =>
|
|
1974
|
+
transactions.some((tr) => tr.docChanged) ? uniqueLocalIds(blocks, state) : null,
|
|
1975
|
+
}),
|
|
1976
|
+
],
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
declare module '@tiptap/core' {
|
|
1981
|
+
interface Commands<ReturnType> {
|
|
1982
|
+
astlWrap: {
|
|
1983
|
+
/** Runs the `wrap` command of the type `tag` (`EditorDescriptor.wrap`) on the selection. */
|
|
1984
|
+
astlWrap: (tag: string) => ReturnType;
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
/** One inline child in the text: the stretch of text one mark covers. */
|
|
1990
|
+
interface Run {
|
|
1991
|
+
readonly from: number;
|
|
1992
|
+
to: number;
|
|
1993
|
+
readonly mark: PMMark;
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
/** The marks named `names` in the text of `node` (at `pos`), one run per child, in order; captions left out. */
|
|
1997
|
+
function runsIn(node: PMNode, pos: number, names: ReadonlySet<string>): Run[] {
|
|
1998
|
+
const runs: Run[] = [];
|
|
1999
|
+
const last = new Map<string, Run>();
|
|
2000
|
+
node.descendants((child, offset) => {
|
|
2001
|
+
if (child.type.name === 'astlFigure') return false;
|
|
2002
|
+
if (!child.isText) return true;
|
|
2003
|
+
const from = pos + 1 + offset;
|
|
2004
|
+
for (const mark of child.marks) {
|
|
2005
|
+
if (!names.has(mark.type.name)) continue;
|
|
2006
|
+
const run = last.get(mark.type.name);
|
|
2007
|
+
if (run !== undefined && run.to === from && run.mark.eq(mark)) run.to = from + child.nodeSize;
|
|
2008
|
+
else {
|
|
2009
|
+
const next = { from, to: from + child.nodeSize, mark };
|
|
2010
|
+
runs.push(next);
|
|
2011
|
+
last.set(mark.type.name, next);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
return false;
|
|
2015
|
+
});
|
|
2016
|
+
return runs;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
const markId = (mark: PMMark): string => (mark.attrs.attributes as Attributes).id ?? '';
|
|
2020
|
+
|
|
2021
|
+
/** `<prefix>-<n>` with the smallest n not in `taken`, which takes it. */
|
|
2022
|
+
function freshId(prefix: string, taken: Set<string>): string {
|
|
2023
|
+
let n = 1;
|
|
2024
|
+
while (taken.has(`${prefix}-${n}`)) n++;
|
|
2025
|
+
taken.add(`${prefix}-${n}`);
|
|
2026
|
+
return `${prefix}-${n}`;
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
/**
|
|
2030
|
+
* The inline children of rich blocks after any change: only in a block whose type declares them, never in a caption
|
|
2031
|
+
* (removed elsewhere, so removing a block keeps its text and nothing else), each with an id of its own: one without
|
|
2032
|
+
* an id gets one, and a copy of another (pasted, or split by Enter) gets a fresh one and none of its private
|
|
2033
|
+
* attributes.
|
|
2034
|
+
*/
|
|
2035
|
+
function tidyInlineChildren(
|
|
2036
|
+
state: EditorState,
|
|
2037
|
+
blocks: ReadonlyMap<string, ComponentManifest>,
|
|
2038
|
+
marks: ReadonlySet<string>,
|
|
2039
|
+
): Transaction | null {
|
|
2040
|
+
const tr = state.tr;
|
|
2041
|
+
/** Removes the inline-child marks of a text node at `pos` other than `own` ones (all of them in a caption). */
|
|
2042
|
+
const strays = (text: PMNode, pos: number, own: ReadonlySet<string>, parent: PMNode | null) => {
|
|
2043
|
+
for (const mark of text.marks) {
|
|
2044
|
+
const name = mark.type.name;
|
|
2045
|
+
if (marks.has(name) && (!own.has(name) || parent?.type.name === 'astlFigure')) {
|
|
2046
|
+
tr.removeMark(pos, pos + text.nodeSize, mark.type);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
const none = new Set<string>();
|
|
2051
|
+
state.doc.descendants((node, pos, parent) => {
|
|
2052
|
+
const manifest = blocks.get(node.type.name);
|
|
2053
|
+
if (manifest === undefined) {
|
|
2054
|
+
if (node.isText) strays(node, pos, none, parent);
|
|
2055
|
+
return true;
|
|
2056
|
+
}
|
|
2057
|
+
const own = new Map(manifest.children.map((c) => [nodeName(c.tag), c]));
|
|
2058
|
+
const names = new Set(own.keys());
|
|
2059
|
+
node.descendants((child, offset, inner) => {
|
|
2060
|
+
if (child.isText) strays(child, pos + 1 + offset, names, inner);
|
|
2061
|
+
return true;
|
|
2062
|
+
});
|
|
2063
|
+
const runs = runsIn(node, pos, names);
|
|
2064
|
+
const taken = new Set(runs.map((run) => markId(run.mark)));
|
|
2065
|
+
const seen = new Set<string>();
|
|
2066
|
+
for (const run of runs) {
|
|
2067
|
+
const spec = own.get(run.mark.type.name);
|
|
2068
|
+
const id = markId(run.mark);
|
|
2069
|
+
if (spec === undefined || !spec.attributes.some((a) => a.name === 'id')) continue;
|
|
2070
|
+
if (id !== '' && !seen.has(id)) {
|
|
2071
|
+
seen.add(id);
|
|
2072
|
+
continue;
|
|
2073
|
+
}
|
|
2074
|
+
const attributes = run.mark.attrs.attributes as Attributes;
|
|
2075
|
+
const kept = Object.entries(attributes).filter(
|
|
2076
|
+
([name]) =>
|
|
2077
|
+
name !== 'id' &&
|
|
2078
|
+
(id === '' || spec.attributes.find((a) => a.name === name)?.visibility !== 'private'),
|
|
2079
|
+
);
|
|
2080
|
+
const fresh = freshId(spec.tag.replace(/^astl-/, ''), taken);
|
|
2081
|
+
seen.add(fresh);
|
|
2082
|
+
const next = run.mark.type.create({ attributes: { id: fresh, ...Object.fromEntries(kept) } });
|
|
2083
|
+
tr.removeMark(run.from, run.to, run.mark).addMark(run.from, run.to, next);
|
|
2084
|
+
}
|
|
2085
|
+
return false;
|
|
2086
|
+
});
|
|
2087
|
+
return tr.docChanged ? tr : null;
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
/** A word: letters, digits and marks, with an apostrophe or a hyphen inside (`don't`, `biało-czerwony`). */
|
|
2091
|
+
const WORD = /[\p{L}\p{N}\p{M}]+(?:['’-][\p{L}\p{N}\p{M}]+)*/gu;
|
|
2092
|
+
|
|
2093
|
+
/**
|
|
2094
|
+
* The `wrap` command (`EditorDescriptor.wrap`) of a rich block `manifest` on the selection: the whole words it touches
|
|
2095
|
+
* (the word at the cursor when it is collapsed; an inline child counts as one word). When every one is already a
|
|
2096
|
+
* child, it removes them, keeping the text; otherwise it makes each other word a child (a fresh id and the command's
|
|
2097
|
+
* attributes), first putting the blocks around them in a block of the type (a fresh id, joined to one right before or
|
|
2098
|
+
* after) unless they are in one. Nothing happens in another component, or across a component or a page. Returns
|
|
2099
|
+
* whether `tr` changed.
|
|
2100
|
+
*/
|
|
2101
|
+
function wrapWords(
|
|
2102
|
+
state: EditorState,
|
|
2103
|
+
tr: Transaction,
|
|
2104
|
+
manifest: ComponentManifest,
|
|
2105
|
+
wrap: EditorWrap,
|
|
2106
|
+
idPrefix: string,
|
|
2107
|
+
components: ReadonlySet<string>,
|
|
2108
|
+
): boolean {
|
|
2109
|
+
const type = state.schema.nodes[nodeName(manifest.tag)];
|
|
2110
|
+
const markType = state.schema.marks[nodeName(wrap.child)];
|
|
2111
|
+
if (type === undefined || markType === undefined) return false;
|
|
2112
|
+
const { from, to, $from, $to } = state.selection;
|
|
2113
|
+
let inside = false;
|
|
2114
|
+
for (let depth = $from.depth; depth > 0; depth--) {
|
|
2115
|
+
const node = $from.node(depth);
|
|
2116
|
+
if (node.type === type) {
|
|
2117
|
+
inside = to <= $from.end(depth);
|
|
2118
|
+
break;
|
|
2119
|
+
}
|
|
2120
|
+
if (components.has(node.type.name)) return false;
|
|
2121
|
+
}
|
|
2122
|
+
const names = new Set([markType.name]);
|
|
2123
|
+
const words: { readonly from: number; readonly to: number; readonly marked: boolean }[] = [];
|
|
2124
|
+
state.doc.nodesBetween(from, to, (node, pos) => {
|
|
2125
|
+
if (!node.isTextblock || node.type.name === 'astlFigure') return !node.isTextblock;
|
|
2126
|
+
const runs = runsIn(node, pos, names);
|
|
2127
|
+
const text = node.textBetween(0, node.content.size, undefined, '');
|
|
2128
|
+
for (const match of text.matchAll(WORD)) {
|
|
2129
|
+
const start = pos + 1 + match.index;
|
|
2130
|
+
const end = start + match[0].length;
|
|
2131
|
+
if (from === to ? start > from || end < from : start >= to || end <= from) continue;
|
|
2132
|
+
const run = runs.find((r) => r.from < end && r.to > start);
|
|
2133
|
+
if (run === undefined) words.push({ from: start, to: end, marked: false });
|
|
2134
|
+
else if (!words.some((w) => w.from === run.from))
|
|
2135
|
+
words.push({ from: run.from, to: run.to, marked: true });
|
|
2136
|
+
}
|
|
2137
|
+
return false;
|
|
2138
|
+
});
|
|
2139
|
+
if (words.length === 0) return false;
|
|
2140
|
+
if (words.every((w) => w.marked)) {
|
|
2141
|
+
for (const word of words) tr.removeMark(word.from, word.to, markType);
|
|
2142
|
+
return true;
|
|
2143
|
+
}
|
|
2144
|
+
let block: number | null = null;
|
|
2145
|
+
if (!inside) {
|
|
2146
|
+
const range = $from.blockRange($to, (node) => ['doc', PAGE, LAYOUT_COLUMN].includes(node.type.name));
|
|
2147
|
+
if (range === null) return false;
|
|
2148
|
+
for (let i = range.startIndex; i < range.endIndex; i++) {
|
|
2149
|
+
if (!FLOW_NODES.includes(range.parent.child(i).type.name)) return false;
|
|
2150
|
+
}
|
|
2151
|
+
tr.wrap(range, [{ type, attrs: { attributes: { id: freshId(idPrefix, idsIn(state.doc)) } } }]);
|
|
2152
|
+
block = range.start;
|
|
2153
|
+
}
|
|
2154
|
+
const taken = new Set<string>();
|
|
2155
|
+
state.doc.descendants((node) => {
|
|
2156
|
+
for (const mark of node.marks) if (mark.type === markType) taken.add(markId(mark));
|
|
2157
|
+
return true;
|
|
2158
|
+
});
|
|
2159
|
+
const prefix = wrap.child.replace(/^astl-/, '');
|
|
2160
|
+
for (const word of words) {
|
|
2161
|
+
if (word.marked) continue;
|
|
2162
|
+
const attributes = { id: freshId(prefix, taken), ...wrap.attributes };
|
|
2163
|
+
tr.addMark(tr.mapping.map(word.from), tr.mapping.map(word.to), markType.create({ attributes }));
|
|
2164
|
+
}
|
|
2165
|
+
if (block !== null) {
|
|
2166
|
+
const end = block + (tr.doc.nodeAt(block)?.nodeSize ?? 0);
|
|
2167
|
+
if (tr.doc.resolve(end).nodeAfter?.type === type) tr.join(end);
|
|
2168
|
+
if (tr.doc.resolve(block).nodeBefore?.type === type) tr.join(block);
|
|
2169
|
+
}
|
|
2170
|
+
return true;
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
/**
|
|
2174
|
+
* Rich blocks (`content: 'flow'`): their inline children stay where they may (`tidyInlineChildren`); Delete or
|
|
2175
|
+
* Backspace on a selected block removes the block and keeps its content; `astlWrap` runs a descriptor's `wrap`.
|
|
2176
|
+
*/
|
|
2177
|
+
function richBlocksExtension(authoring: Authoring, manifests: readonly ComponentManifest[]): Extension {
|
|
2178
|
+
const blocks = new Map(manifests.filter((m) => m.content === 'flow').map((m) => [nodeName(m.tag), m]));
|
|
2179
|
+
const marks = new Set(
|
|
2180
|
+
[...blocks.values()].flatMap((m) =>
|
|
2181
|
+
m.children.filter((c) => c.place !== 'lead').map((c) => nodeName(c.tag)),
|
|
2182
|
+
),
|
|
2183
|
+
);
|
|
2184
|
+
const components = new Set(manifests.map((m) => nodeName(m.tag)));
|
|
2185
|
+
const unwrap = ({ editor }: { editor: Editor }): boolean => {
|
|
2186
|
+
const { selection } = editor.state;
|
|
2187
|
+
if (!(selection instanceof NodeSelection) || !blocks.has(selection.node.type.name)) return false;
|
|
2188
|
+
const tr = editor.state.tr.replaceWith(selection.from, selection.to, selection.node.content);
|
|
2189
|
+
editor.view.dispatch(tr.scrollIntoView());
|
|
2190
|
+
return true;
|
|
2191
|
+
};
|
|
2192
|
+
return Extension.create({
|
|
2193
|
+
name: 'astlRichBlocks',
|
|
2194
|
+
priority: 1000,
|
|
2195
|
+
addKeyboardShortcuts: () => ({ Backspace: unwrap, Delete: unwrap }),
|
|
2196
|
+
addCommands: () => ({
|
|
2197
|
+
astlWrap:
|
|
2198
|
+
(tag: string) =>
|
|
2199
|
+
({ state, tr }) => {
|
|
2200
|
+
const descriptor = authoring.descriptor(tag);
|
|
2201
|
+
const manifest = blocks.get(nodeName(tag));
|
|
2202
|
+
if (descriptor?.wrap === undefined || manifest === undefined) return false;
|
|
2203
|
+
return wrapWords(state, tr, manifest, descriptor.wrap, descriptor.idPrefix, components);
|
|
2204
|
+
},
|
|
2205
|
+
}),
|
|
2206
|
+
addProseMirrorPlugins: () => [
|
|
2207
|
+
new Plugin({
|
|
2208
|
+
appendTransaction: (transactions, _, state) =>
|
|
2209
|
+
marks.size > 0 && transactions.some((tr) => tr.docChanged)
|
|
2210
|
+
? tidyInlineChildren(state, blocks, marks)
|
|
2211
|
+
: null,
|
|
2212
|
+
}),
|
|
2213
|
+
],
|
|
2214
|
+
});
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
/** The ranges of the final document that paste and drop transactions inserted. */
|
|
2218
|
+
function pastedRanges(transactions: readonly Transaction[]): [number, number][] {
|
|
2219
|
+
let ranges: [number, number][] = [];
|
|
2220
|
+
for (const tr of transactions) {
|
|
2221
|
+
ranges = ranges.map(([from, to]) => [tr.mapping.map(from, 1), tr.mapping.map(to, -1)]);
|
|
2222
|
+
const event = tr.getMeta('uiEvent');
|
|
2223
|
+
if (event !== 'paste' && event !== 'drop') continue;
|
|
2224
|
+
tr.steps.forEach((step, index) => {
|
|
2225
|
+
const after = tr.mapping.slice(index + 1);
|
|
2226
|
+
step.getMap().forEach((_from, _to, start, end) => {
|
|
2227
|
+
ranges.push([after.map(start, 1), after.map(end, -1)]);
|
|
2228
|
+
});
|
|
2229
|
+
});
|
|
2230
|
+
}
|
|
2231
|
+
return ranges;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
/** Every id the source of `doc` has: pages, components, their rich children and the children kept as data. */
|
|
2235
|
+
function idsIn(doc: PMNode): Set<string> {
|
|
2236
|
+
const ids = new Set<string>();
|
|
2237
|
+
const kept = (children: readonly Kept[]) => {
|
|
2238
|
+
for (const child of children) {
|
|
2239
|
+
if (typeof child === 'string') continue;
|
|
2240
|
+
if (child.attributes.id !== undefined) ids.add(child.attributes.id);
|
|
2241
|
+
kept(child.children);
|
|
2242
|
+
}
|
|
2243
|
+
};
|
|
2244
|
+
doc.descendants((node) => {
|
|
2245
|
+
const id = (node.attrs.attributes as Attributes | undefined)?.id;
|
|
2246
|
+
if (id !== undefined) ids.add(id);
|
|
2247
|
+
if (Array.isArray(node.attrs.children)) kept(node.attrs.children as Kept[]);
|
|
2248
|
+
return true;
|
|
2249
|
+
});
|
|
2250
|
+
return ids;
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
/**
|
|
2254
|
+
* A pasted or dropped page or component whose id another page or component has gets a fresh one, made as the insert
|
|
2255
|
+
* menu makes them: `<idPrefix>-<n>` with the smallest n no id of the document uses. Pages and components share one id
|
|
2256
|
+
* namespace; the ids inside a component (option ids) are local to it, so a copy keeps them. A move (cut and paste, a
|
|
2257
|
+
* drag) keeps its id: the original is gone when it lands. A page that a pasted page splits keeps its id in its first
|
|
2258
|
+
* half.
|
|
2259
|
+
*
|
|
2260
|
+
* Picture files pasted or dropped go through the host's upload and the picture dialog (`hooks`), which asks for the
|
|
2261
|
+
* alt text; without an upload nothing is inserted and `hooks.refuse` says why. Pasted with text (a word processor's
|
|
2262
|
+
* copy), they paste as rich text. Enter on a picture, or in a figure's caption, edits the picture's address and alt
|
|
2263
|
+
* text.
|
|
2264
|
+
*/
|
|
2265
|
+
function pastedIdsExtension(
|
|
2266
|
+
authoring: Authoring,
|
|
2267
|
+
manifests: readonly ComponentManifest[],
|
|
2268
|
+
hooks: PictureHooks | undefined,
|
|
2269
|
+
): Extension {
|
|
2270
|
+
const tags = new Map(manifests.map((m) => [nodeName(m.tag), m.tag]));
|
|
2271
|
+
const prefixOf = (name: string): string => {
|
|
2272
|
+
const tag = tags.get(name);
|
|
2273
|
+
if (tag === undefined) return 'page';
|
|
2274
|
+
const prefix = authoring.descriptor(tag)?.idPrefix ?? tag.replace(/^astl-/, '');
|
|
2275
|
+
return isSourceId(`${prefix}-1`) ? prefix : 'item';
|
|
2276
|
+
};
|
|
2277
|
+
const fresh = (state: EditorState, ranges: readonly [number, number][]): Transaction | null => {
|
|
2278
|
+
const owners: { readonly node: PMNode; readonly pos: number; readonly pasted: boolean }[] = [];
|
|
2279
|
+
state.doc.descendants((node, pos) => {
|
|
2280
|
+
const page = node.type.name === 'astlPage';
|
|
2281
|
+
if (!page && !tags.has(node.type.name)) return true;
|
|
2282
|
+
// Starting in a pasted range: pasted, or the second half of a page the paste split (it has the page's id).
|
|
2283
|
+
const pasted = ranges.some(([from, to]) => pos >= from && pos < to);
|
|
2284
|
+
owners.push({ node, pos, pasted });
|
|
2285
|
+
// Components do not nest: only a page holds more of them.
|
|
2286
|
+
return page;
|
|
2287
|
+
});
|
|
2288
|
+
const idOf = (node: PMNode) => (node.attrs.attributes as Attributes).id ?? '';
|
|
2289
|
+
const taken = new Set(owners.filter((o) => !o.pasted).map((o) => idOf(o.node)));
|
|
2290
|
+
const used = idsIn(state.doc);
|
|
2291
|
+
const tr = state.tr;
|
|
2292
|
+
for (const { node, pos, pasted } of owners) {
|
|
2293
|
+
const id = idOf(node);
|
|
2294
|
+
if (!pasted || id === '') continue;
|
|
2295
|
+
if (!taken.has(id)) {
|
|
2296
|
+
taken.add(id);
|
|
2297
|
+
continue;
|
|
2298
|
+
}
|
|
2299
|
+
const prefix = prefixOf(node.type.name);
|
|
2300
|
+
let n = 1;
|
|
2301
|
+
while (used.has(`${prefix}-${n}`)) n++;
|
|
2302
|
+
const next = `${prefix}-${n}`;
|
|
2303
|
+
used.add(next);
|
|
2304
|
+
taken.add(next);
|
|
2305
|
+
tr.setNodeAttribute(pos, 'attributes', { ...(node.attrs.attributes as Attributes), id: next });
|
|
2306
|
+
}
|
|
2307
|
+
return tr.docChanged ? tr : null;
|
|
2308
|
+
};
|
|
2309
|
+
/** Handles picture files: true when there were some (inserted after the dialog, or refused). */
|
|
2310
|
+
const pictures = (editor: Editor, files: FileList | undefined, at: number | null): boolean => {
|
|
2311
|
+
const images = [...(files ?? [])].filter((file) => file.type.startsWith('image/'));
|
|
2312
|
+
if (images.length === 0 || hooks === undefined) return false;
|
|
2313
|
+
if (authoring.uploadAsset === null) {
|
|
2314
|
+
hooks.refuse();
|
|
2315
|
+
return true;
|
|
2316
|
+
}
|
|
2317
|
+
void (async () => {
|
|
2318
|
+
let next = at;
|
|
2319
|
+
for (const file of images) {
|
|
2320
|
+
const fields = await hooks.ask({ file });
|
|
2321
|
+
if (fields === null || editor.isDestroyed) return;
|
|
2322
|
+
const pos = Math.min(next ?? editor.state.selection.from, editor.state.doc.content.size);
|
|
2323
|
+
editor.chain().insertContentAt(pos, pictureHtml(fields)).run();
|
|
2324
|
+
// The next one after it: the insertion leaves the cursor there.
|
|
2325
|
+
next = editor.state.selection.to;
|
|
2326
|
+
}
|
|
2327
|
+
})();
|
|
2328
|
+
return true;
|
|
2329
|
+
};
|
|
2330
|
+
return Extension.create({
|
|
2331
|
+
name: 'astlPastedIds',
|
|
2332
|
+
addKeyboardShortcuts() {
|
|
2333
|
+
return {
|
|
2334
|
+
Enter: ({ editor }) => {
|
|
2335
|
+
if (hooks === undefined) return false;
|
|
2336
|
+
const { selection } = editor.state;
|
|
2337
|
+
if (selection instanceof NodeSelection && selection.node.type.name === 'astlPicture') {
|
|
2338
|
+
void editPicture(editor, hooks, selection.from, 'attributes');
|
|
2339
|
+
return true;
|
|
2340
|
+
}
|
|
2341
|
+
// A caption is one line: Enter in it edits its picture instead of splitting the figure.
|
|
2342
|
+
if (selection.$from.parent.type.name !== 'astlFigure') return false;
|
|
2343
|
+
void editPicture(editor, hooks, selection.$from.before(), 'picture');
|
|
2344
|
+
return true;
|
|
2345
|
+
},
|
|
2346
|
+
};
|
|
2347
|
+
},
|
|
2348
|
+
addProseMirrorPlugins() {
|
|
2349
|
+
const editor = this.editor;
|
|
2350
|
+
return [
|
|
2351
|
+
new Plugin({
|
|
2352
|
+
appendTransaction: (transactions, _, state) => {
|
|
2353
|
+
const ranges = pastedRanges(transactions);
|
|
2354
|
+
return ranges.length === 0 ? null : fresh(state, ranges);
|
|
2355
|
+
},
|
|
2356
|
+
props: {
|
|
2357
|
+
// Text with pictures (from a word processor) pastes as rich text; picture files alone are pictures.
|
|
2358
|
+
handlePaste: (_view, event) =>
|
|
2359
|
+
(event.clipboardData?.getData('text/plain') ?? '').trim() === '' &&
|
|
2360
|
+
pictures(editor, event.clipboardData?.files, null),
|
|
2361
|
+
handleDrop: (view, event) =>
|
|
2362
|
+
pictures(
|
|
2363
|
+
editor,
|
|
2364
|
+
event.dataTransfer?.files,
|
|
2365
|
+
view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos ?? null,
|
|
2366
|
+
),
|
|
2367
|
+
},
|
|
2368
|
+
}),
|
|
2369
|
+
];
|
|
2370
|
+
},
|
|
2371
|
+
});
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
/**
|
|
2375
|
+
* The attributes the content format allows on all of rich text: `lang`, `dir`, `style`, and `class` for the surface to
|
|
2376
|
+
* keep. Marks have no node views, so ProseMirror renders their attributes into the live editing DOM (`style` through
|
|
2377
|
+
* the CSSOM); nothing else (an `onclick` in pasted HTML) may get there.
|
|
2378
|
+
*/
|
|
2379
|
+
const richAttribute = (name: string) => [
|
|
2380
|
+
name,
|
|
2381
|
+
{
|
|
2382
|
+
default: null,
|
|
2383
|
+
parseHTML: (el: HTMLElement) => attributesOf(el)[name] ?? null,
|
|
2384
|
+
renderHTML: (attrs: Record<string, unknown>) => (attrs[name] ? { [name]: attrs[name] } : {}),
|
|
2385
|
+
},
|
|
2386
|
+
];
|
|
2387
|
+
const languageAttributes = Object.fromEntries([...CONTENT_ATTRIBUTES].map(richAttribute));
|
|
2388
|
+
const richAttributes = Object.fromEntries([...CONTENT_ATTRIBUTES, CLASS_ATTRIBUTE].map(richAttribute));
|
|
2389
|
+
|
|
2390
|
+
/**
|
|
2391
|
+
* Inline formatting of the content format that StarterKit has no mark for. Spans do not exclude each other: text in two
|
|
2392
|
+
* of them, or in one that holds part of another, keeps both.
|
|
2393
|
+
*/
|
|
2394
|
+
const formatMarks = ['sub', 'sup', 'mark', 'span'].map((tag) =>
|
|
2395
|
+
Mark.create({
|
|
2396
|
+
name: tag === 'span' ? 'textSpan' : tag,
|
|
2397
|
+
...(tag === 'span' ? { excludes: '' } : {}),
|
|
2398
|
+
addAttributes: () => richAttributes,
|
|
2399
|
+
parseHTML: () => [{ tag }],
|
|
2400
|
+
renderHTML: ({ HTMLAttributes }) => [tag, HTMLAttributes, 0],
|
|
2401
|
+
}),
|
|
2402
|
+
);
|
|
2403
|
+
|
|
2404
|
+
/** The same on the formatting StarterKit adds. A link has a `class` of its own in StarterKit, which goes first. */
|
|
2405
|
+
const contentAttributes = Extension.create({
|
|
2406
|
+
name: 'astlContentAttributes',
|
|
2407
|
+
addGlobalAttributes: () => [
|
|
2408
|
+
{
|
|
2409
|
+
types: [
|
|
2410
|
+
'paragraph',
|
|
2411
|
+
'heading',
|
|
2412
|
+
'blockquote',
|
|
2413
|
+
'bulletList',
|
|
2414
|
+
'orderedList',
|
|
2415
|
+
'listItem',
|
|
2416
|
+
'bold',
|
|
2417
|
+
'italic',
|
|
2418
|
+
'underline',
|
|
2419
|
+
'strike',
|
|
2420
|
+
'code',
|
|
2421
|
+
],
|
|
2422
|
+
attributes: richAttributes,
|
|
2423
|
+
},
|
|
2424
|
+
{ types: ['link'], attributes: languageAttributes },
|
|
2425
|
+
],
|
|
2426
|
+
});
|
|
2427
|
+
|
|
2428
|
+
/** A record of attributes (or a list of them, a child kept as data), with only the classes in `known`. */
|
|
2429
|
+
function withKnownClasses(value: unknown, known: ReadonlySet<string>): unknown {
|
|
2430
|
+
if (Array.isArray(value)) return value.map((inner) => withKnownClasses(inner, known));
|
|
2431
|
+
if (value === null || typeof value !== 'object') return value;
|
|
2432
|
+
return Object.fromEntries(
|
|
2433
|
+
Object.entries(value).flatMap(([name, inner]) => {
|
|
2434
|
+
if (name !== CLASS_ATTRIBUTE) return [[name, withKnownClasses(inner, known)]];
|
|
2435
|
+
const classes = String(inner ?? '').split(/\s+/);
|
|
2436
|
+
const kept = classes.filter((one) => known.has(one)).join(' ');
|
|
2437
|
+
return kept === '' ? [] : [[name, kept]];
|
|
2438
|
+
}),
|
|
2439
|
+
);
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2442
|
+
/** Nodes and marks of what was pasted, with only the classes in `known`. */
|
|
2443
|
+
function pastedWith(content: Fragment, known: ReadonlySet<string>): Fragment {
|
|
2444
|
+
const nodes: PMNode[] = [];
|
|
2445
|
+
content.forEach((node) => {
|
|
2446
|
+
const marks = node.marks.map((mark) =>
|
|
2447
|
+
mark.type.create(withKnownClasses(mark.attrs, known) as Record<string, unknown>),
|
|
2448
|
+
);
|
|
2449
|
+
nodes.push(
|
|
2450
|
+
node.isText
|
|
2451
|
+
? node.mark(marks)
|
|
2452
|
+
: node.type.create(
|
|
2453
|
+
withKnownClasses(node.attrs, known) as Record<string, unknown>,
|
|
2454
|
+
pastedWith(node.content, known),
|
|
2455
|
+
marks,
|
|
2456
|
+
),
|
|
2457
|
+
);
|
|
2458
|
+
});
|
|
2459
|
+
return Fragment.fromArray(nodes);
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
const RULE_TAG = /^[a-z][a-z0-9-]*$/;
|
|
2463
|
+
|
|
2464
|
+
/**
|
|
2465
|
+
* The document's rules as a stylesheet of its surface: the rules for a tag, then the named styles, as the engine applies
|
|
2466
|
+
* them. A rule the engine refuses draws nothing. Twice the attribute: the surface's own text styles are more specific
|
|
2467
|
+
* than one, and the rules must win. What a tag's rule reaches is the tag itself, or the node view that stands for it.
|
|
2468
|
+
*/
|
|
2469
|
+
function rulesCss(rules: readonly Attributes[], id: string): string {
|
|
2470
|
+
const scope = `[data-astl-rules='${id}']`.repeat(2);
|
|
2471
|
+
const named = (tag: string) => `[data-astl-tag='${tag}']`;
|
|
2472
|
+
const selector = ({ name, for: target }: Attributes): string | null => {
|
|
2473
|
+
if (name !== undefined) return isStyleName(name) ? `${scope} .${CSS.escape(name)}` : null;
|
|
2474
|
+
if (target === undefined || !RULE_TAG.test(target)) return null;
|
|
2475
|
+
if (target === 'astl-doc') return scope;
|
|
2476
|
+
// A picture's node view holds the image: only the view takes the rule, or a width would count twice.
|
|
2477
|
+
if (target === 'img') return `${scope} ${named(target)}`;
|
|
2478
|
+
// A document without pages is its own page, as for the engine.
|
|
2479
|
+
const implicit = target === 'astl-page' ? `, ${scope}:not(:has(${named(target)}))` : '';
|
|
2480
|
+
return `${scope} :is(${target}, ${named(target)})${implicit}`;
|
|
2481
|
+
};
|
|
2482
|
+
const ordered = [...rules].sort((a, b) => Number(a.name !== undefined) - Number(b.name !== undefined));
|
|
2483
|
+
return ordered
|
|
2484
|
+
.flatMap((rule) => {
|
|
2485
|
+
const style = cleanStyle(rule.style ?? '').style;
|
|
2486
|
+
const target = selector(rule);
|
|
2487
|
+
return style === '' || target === null ? [] : [`${target} { ${style}; }`];
|
|
2488
|
+
})
|
|
2489
|
+
.join('\n');
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
/** Editors made so far: each scopes its rules with a number of its own. */
|
|
2493
|
+
let ruleSheets = 0;
|
|
2494
|
+
|
|
2495
|
+
/**
|
|
2496
|
+
* The document's rules on the surface (an adopted stylesheet, rebuilt when they change, undo included), and paste:
|
|
2497
|
+
* parsing cleans what is pasted like any source, and no class stays that the document does not define. Silently: the
|
|
2498
|
+
* author asked for the text, not for a report on another page's styles.
|
|
2499
|
+
*/
|
|
2500
|
+
const rulesExtension: Extension = Extension.create({
|
|
2501
|
+
name: 'astlRules',
|
|
2502
|
+
addProseMirrorPlugins: () => {
|
|
2503
|
+
const id = String(++ruleSheets);
|
|
2504
|
+
return [
|
|
2505
|
+
new Plugin({
|
|
2506
|
+
props: {
|
|
2507
|
+
// The document's own look, on the element that stands for it; the rules' scope.
|
|
2508
|
+
attributes: (state) => {
|
|
2509
|
+
const { style, class: classes } = state.doc.attrs.attributes as Attributes;
|
|
2510
|
+
return {
|
|
2511
|
+
'data-astl-rules': id,
|
|
2512
|
+
...(style === undefined ? {} : { style }),
|
|
2513
|
+
...(classes === undefined ? {} : { class: classes }),
|
|
2514
|
+
};
|
|
2515
|
+
},
|
|
2516
|
+
transformPastedHTML: (html) => inertStyles(html),
|
|
2517
|
+
transformPasted: (slice, view) => {
|
|
2518
|
+
const rules = view.state.doc.attrs.rules as readonly Attributes[];
|
|
2519
|
+
const known = new Set(rules.flatMap((rule) => rule.name ?? []));
|
|
2520
|
+
return new Slice(pastedWith(slice.content, known), slice.openStart, slice.openEnd);
|
|
2521
|
+
},
|
|
2522
|
+
},
|
|
2523
|
+
view: (view) => {
|
|
2524
|
+
const sheet = new CSSStyleSheet();
|
|
2525
|
+
let root: Partial<DocumentOrShadowRoot> | null = null;
|
|
2526
|
+
let shown: unknown = [];
|
|
2527
|
+
const leave = () => {
|
|
2528
|
+
if (root?.adoptedStyleSheets !== undefined)
|
|
2529
|
+
root.adoptedStyleSheets = root.adoptedStyleSheets.filter((one) => one !== sheet);
|
|
2530
|
+
};
|
|
2531
|
+
const show = () => {
|
|
2532
|
+
const rules = view.state.doc.attrs.rules as readonly Attributes[];
|
|
2533
|
+
if (rules !== shown) sheet.replaceSync(rulesCss(rules, id));
|
|
2534
|
+
shown = rules;
|
|
2535
|
+
// Only once there are rules, and again if the editor was moved to another root since.
|
|
2536
|
+
const next = view.dom.getRootNode() as Partial<DocumentOrShadowRoot>;
|
|
2537
|
+
if (rules.length === 0 || next === root || next.adoptedStyleSheets === undefined) return;
|
|
2538
|
+
leave();
|
|
2539
|
+
root = next;
|
|
2540
|
+
next.adoptedStyleSheets = [...next.adoptedStyleSheets, sheet];
|
|
2541
|
+
};
|
|
2542
|
+
show();
|
|
2543
|
+
return { update: show, destroy: leave };
|
|
2544
|
+
},
|
|
2545
|
+
}),
|
|
2546
|
+
];
|
|
2547
|
+
},
|
|
2548
|
+
});
|
|
2549
|
+
|
|
2550
|
+
/** The figure with the cursor: where it sits and its handle show there, as they do on a selected picture. */
|
|
2551
|
+
const currentFigureExtension: Extension = Extension.create({
|
|
2552
|
+
name: 'astlCurrentFigure',
|
|
2553
|
+
addProseMirrorPlugins: () => [
|
|
2554
|
+
new Plugin({
|
|
2555
|
+
props: {
|
|
2556
|
+
decorations: ({ doc, selection }) => {
|
|
2557
|
+
const { $from } = selection;
|
|
2558
|
+
for (let depth = $from.depth; depth > 0; depth--) {
|
|
2559
|
+
if ($from.node(depth).type.name !== 'astlFigure') continue;
|
|
2560
|
+
const figure = Decoration.node($from.before(depth), $from.after(depth), {
|
|
2561
|
+
class: 'astl-figure-current',
|
|
2562
|
+
});
|
|
2563
|
+
return DecorationSet.create(doc, [figure]);
|
|
2564
|
+
}
|
|
2565
|
+
return DecorationSet.empty;
|
|
2566
|
+
},
|
|
2567
|
+
},
|
|
2568
|
+
}),
|
|
2569
|
+
],
|
|
2570
|
+
});
|
|
2571
|
+
|
|
2572
|
+
/**
|
|
2573
|
+
* The TipTap extensions of the content format, for `new Editor({ extensions })`: StarterKit restricted to the rich
|
|
2574
|
+
* text the format allows (no code blocks, rules or trailing paragraph; headings 2 to 4; links with `href` only), the
|
|
2575
|
+
* formatting it adds (`sub`, `sup`, `mark`, `span`, `lang` and `dir`), pictures and figures (shown only when the
|
|
2576
|
+
* authoring's URL policy allows their address), the document, pages (broken and joined from the keyboard and the
|
|
2577
|
+
* page's join button) and a node for every type of `manifests` (default: the authoring's), labelled in the authoring
|
|
2578
|
+
* locale, with the `astlWrap` command of rich blocks.
|
|
2579
|
+
*/
|
|
2580
|
+
/**
|
|
2581
|
+
* The text an inline component names in another element (a drop's word in its bank, `options: { from, tag }` on an
|
|
2582
|
+
* attribute field), for its chip: a node decoration whose spec carries it, so the chip follows edits of that text.
|
|
2583
|
+
*/
|
|
2584
|
+
function referencesExtension(authoring: Authoring, manifests: readonly ComponentManifest[]): Extension {
|
|
2585
|
+
const fields = new Map<string, { readonly name: string; readonly from: string; readonly tag: string }>();
|
|
2586
|
+
for (const m of manifests) {
|
|
2587
|
+
for (const field of authoring.descriptor(m.tag)?.fields ?? []) {
|
|
2588
|
+
if (field.kind === 'attribute' && field.options !== undefined && !fields.has(nodeName(m.tag)))
|
|
2589
|
+
fields.set(nodeName(m.tag), { name: field.name, ...field.options });
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
const decorate = (doc: PMNode): DecorationSet => {
|
|
2593
|
+
if (fields.size === 0) return DecorationSet.empty;
|
|
2594
|
+
const owners = new Map<string, PMNode>();
|
|
2595
|
+
doc.descendants((node) => {
|
|
2596
|
+
const id = (node.attrs.attributes as Attributes | undefined)?.id;
|
|
2597
|
+
if (id !== undefined && !owners.has(id) && !node.isText) owners.set(id, node);
|
|
2598
|
+
return true;
|
|
2599
|
+
});
|
|
2600
|
+
const decorations: Decoration[] = [];
|
|
2601
|
+
doc.descendants((node, pos) => {
|
|
2602
|
+
const field = fields.get(node.type.name);
|
|
2603
|
+
if (field === undefined) return true;
|
|
2604
|
+
const attributes = node.attrs.attributes as Attributes;
|
|
2605
|
+
const owner = owners.get(attributes[field.from] ?? '');
|
|
2606
|
+
const value = attributes[field.name] ?? '';
|
|
2607
|
+
let text: string | null = null;
|
|
2608
|
+
owner?.descendants((child) => {
|
|
2609
|
+
if (text !== null) return false;
|
|
2610
|
+
if (child.type.name === nodeName(field.tag) && (child.attrs.attributes as Attributes).id === value)
|
|
2611
|
+
text = child.textContent.trim();
|
|
2612
|
+
return text === null;
|
|
2613
|
+
});
|
|
2614
|
+
if (owner !== undefined && text === null) {
|
|
2615
|
+
// A bank kept as data: its children as written.
|
|
2616
|
+
for (const kept of (owner.attrs.children as readonly Kept[] | undefined) ?? []) {
|
|
2617
|
+
if (typeof kept !== 'string' && kept.tag === field.tag && kept.attributes.id === value)
|
|
2618
|
+
text = textOf(kept).trim();
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
decorations.push(Decoration.node(pos, pos + node.nodeSize, {}, { [REFERENCE]: text ?? value }));
|
|
2622
|
+
return false;
|
|
2623
|
+
});
|
|
2624
|
+
return DecorationSet.create(doc, decorations);
|
|
2625
|
+
};
|
|
2626
|
+
return Extension.create({
|
|
2627
|
+
name: 'astlReferences',
|
|
2628
|
+
addProseMirrorPlugins: () => [
|
|
2629
|
+
new Plugin<DecorationSet>({
|
|
2630
|
+
state: {
|
|
2631
|
+
init: (_, state) => decorate(state.doc),
|
|
2632
|
+
apply: (tr, previous) => (tr.docChanged ? decorate(tr.doc) : previous),
|
|
2633
|
+
},
|
|
2634
|
+
props: {
|
|
2635
|
+
decorations(state) {
|
|
2636
|
+
return this.getState(state) ?? DecorationSet.empty;
|
|
2637
|
+
},
|
|
2638
|
+
},
|
|
2639
|
+
}),
|
|
2640
|
+
],
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
|
|
2644
|
+
export function astrolabeExtensions(
|
|
2645
|
+
authoring: Authoring,
|
|
2646
|
+
manifests: readonly ComponentManifest[] = authoring.engine.manifests,
|
|
2647
|
+
options: { readonly pictures?: PictureHooks } = {},
|
|
2648
|
+
): Extensions {
|
|
2649
|
+
const hooks = options.pictures;
|
|
2650
|
+
const types = new Map(manifests.map((m) => [nodeName(m.tag), m]));
|
|
2651
|
+
const label = (tag: string) => {
|
|
2652
|
+
const descriptor = authoring.descriptor(tag);
|
|
2653
|
+
if (descriptor === null) return tag;
|
|
2654
|
+
const name = authoring.t(descriptor.manifest.messages, descriptor.label);
|
|
2655
|
+
return name === descriptor.label ? tag : name;
|
|
2656
|
+
};
|
|
2657
|
+
return [
|
|
2658
|
+
StarterKit.configure({
|
|
2659
|
+
document: false,
|
|
2660
|
+
codeBlock: false,
|
|
2661
|
+
horizontalRule: false,
|
|
2662
|
+
trailingNode: false,
|
|
2663
|
+
heading: { levels: [2, 3, 4] },
|
|
2664
|
+
link: { openOnClick: false, HTMLAttributes: { target: null, rel: null, class: null } },
|
|
2665
|
+
}),
|
|
2666
|
+
...formatMarks,
|
|
2667
|
+
contentAttributes,
|
|
2668
|
+
docNode,
|
|
2669
|
+
pageNode(authoring),
|
|
2670
|
+
...layoutNodes,
|
|
2671
|
+
currentLayoutExtension((node) => types.has(node.type.name)),
|
|
2672
|
+
rulesExtension,
|
|
2673
|
+
pagesExtension,
|
|
2674
|
+
pictureNode(authoring, hooks),
|
|
2675
|
+
figureNode(authoring, hooks),
|
|
2676
|
+
currentFigureExtension,
|
|
2677
|
+
...componentNodes(manifests, label, zonesView(authoring), authoring),
|
|
2678
|
+
...helpNodes(authoring),
|
|
2679
|
+
referencesExtension(authoring, manifests),
|
|
2680
|
+
childrenExtension(manifests),
|
|
2681
|
+
richBlocksExtension(authoring, manifests),
|
|
2682
|
+
pastedIdsExtension(authoring, manifests, hooks),
|
|
2683
|
+
blocksExtension(
|
|
2684
|
+
authoring,
|
|
2685
|
+
(node) => types.get(node.type.name) ?? null,
|
|
2686
|
+
nodeName,
|
|
2687
|
+
hooks?.style === undefined ? undefined : () => hooks.style?.('component'),
|
|
2688
|
+
),
|
|
2689
|
+
];
|
|
2690
|
+
}
|