@unbase-app/layer 0.0.0-stage → 2.0.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.
@@ -0,0 +1,1002 @@
1
+ // ============================================================================
2
+ // EDIT — editing a page's text in place, in one place.
3
+ //
4
+ // Two hosts edit text on a page: the layer on the site (`?comment`, the pencil)
5
+ // and the bridge Unbase puts in each canvas frame. They must find the same
6
+ // fields, show the same drafts and behave the same while you type, or a text
7
+ // edited in the editor lands in another field than on the site. So both use
8
+ // this module, as both use src/page for where things are.
9
+ //
10
+ // `editTools` is one self-contained function: the proxy ships it as its own
11
+ // source text (`editTools.toString()`) into pages it does not own, so nothing
12
+ // in its body may reach outside it. Plain JavaScript, typed in index.d.mts, so
13
+ // it runs from node_modules without a build.
14
+ //
15
+ // What is in it:
16
+ //
17
+ // match which text on the page comes from which field of the content
18
+ // map (the rules are below, at the function)
19
+ // values a field's value out of an element and into one, inline
20
+ // fields sanitised to em, strong and a[href]
21
+ // session clicking a field: contenteditable, the caret where you
22
+ // clicked, Enter and Esc, paste as text, no drop, the other
23
+ // copies of the field following as you type
24
+ // documentCss the outline on hover and around the field you type in
25
+ // createEditor the whole of it for a host without React (a canvas frame):
26
+ // matching again as the page changes, drafts over the page,
27
+ // someone else's field locked, the small format bar. Storage is
28
+ // the host's: the editor reports every change and is told the
29
+ // drafts back.
30
+ //
31
+ // Content maps come from the site's integration (src/astro/content-map.mjs), or are
32
+ // built from the repository by Unbase for a site without one (unbase-projects,
33
+ // read_content). The second kind lists its template files in `templates`: text in
34
+ // the code of a page or a component, not in a content file.
35
+ // ============================================================================
36
+
37
+ /** @param {import("./index.mjs").EditToolsOptions} [options] */
38
+ export function editTools(options = {}) {
39
+ const skip = options.skip ?? (() => false);
40
+
41
+ // ── Keys ──
42
+ /** "src/content/verlangens/x.json#/hero/titel" */
43
+ const keyOf = (file, pointer) => `${file}#${pointer}`;
44
+ const splitKey = (key) => {
45
+ const i = key.indexOf("#");
46
+ return { file: key.slice(0, i), pointer: key.slice(i + 1) };
47
+ };
48
+
49
+ // ── The content map ──
50
+ /**
51
+ * LEGACY-NL: the Dutch keys of a content map from before 1.11, per English key. A site's
52
+ * integration writes both until every reader takes the English ones; Unbase's own maps
53
+ * (read_content) and older integrations still write only these. Read, never written here.
54
+ */
55
+ const LEGACY_KEYS = {
56
+ map: {
57
+ files: "bestanden", lists: "lijsten", other: "overig", collections: "collecties", shared: "gedeeld",
58
+ scope: "bereik", templates: "bron", booleans: "waarden", images: "beelden", settings: "instellingen",
59
+ },
60
+ image: { value: "waarde", paths: "paden" },
61
+ settings: { fields: "velden" },
62
+ field: { pointer: "pad", exists: "bestaat", value: "waarde" },
63
+ routes: { dir: "map", fields: "velden" },
64
+ };
65
+ /** A copy of `o` with each key of `table` under its English name, the Dutch one gone. */
66
+ const renamed = (o, table) => {
67
+ if (!o || typeof o !== "object" || Array.isArray(o)) return o;
68
+ const out = { ...o };
69
+ for (const [en, nl] of Object.entries(table)) {
70
+ if (out[en] === undefined && o[nl] !== undefined) out[en] = o[nl];
71
+ delete out[nl];
72
+ }
73
+ return out;
74
+ };
75
+ const eachValue = (o, f) => (o && typeof o === "object" ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)])) : o);
76
+ /**
77
+ * A content map with English keys, whichever it came with (English wins where it has both).
78
+ * Keys this module does not know (another host's) pass through as they are.
79
+ */
80
+ const readMap = (raw) => {
81
+ if (!raw || typeof raw !== "object") return null;
82
+ const map = renamed(raw, LEGACY_KEYS.map);
83
+ map.files ??= {};
84
+ const withFields = (s) => {
85
+ const o = renamed(s, LEGACY_KEYS.settings);
86
+ if (o?.fields) o.fields = eachValue(o.fields, (f) => renamed(f, LEGACY_KEYS.field));
87
+ return o;
88
+ };
89
+ if (map.images) map.images = eachValue(map.images, (file) => eachValue(file, (i) => renamed(i, LEGACY_KEYS.image)));
90
+ if (map.settings) map.settings = eachValue(map.settings, withFields);
91
+ if (map.site) map.site = eachValue(map.site, withFields);
92
+ if (map.routes) map.routes = renamed(map.routes, LEGACY_KEYS.routes);
93
+ return map;
94
+ };
95
+
96
+ // ── Attributes on the page ──
97
+ // What the engine writes on the page it writes under the English name only (2.0). The Dutch name
98
+ // of before 1.11 (LEGACY-NL, the second of each pair) it still reads, as older layers, Unbase's
99
+ // kit and sites write it, and clears with the English one. What the site writes
100
+ // (data-edit-path …) it takes under either name.
101
+ /** The field an element shows, "file#/pointer"; also written by Unbase (proxy/fields.ts, kit). */
102
+ const FIELD = ["data-cm-field", "data-cm-veld"]; // LEGACY-NL: [1]
103
+ /** The field being typed in. */
104
+ const ACTIVE = ["data-cm-active", "data-cm-actief"]; // LEGACY-NL: [1]
105
+ /** Never text: the layer's own elements (the site may mark its own too). */
106
+ const IGNORE = ["data-cm-ignore", "data-cm-negeer"]; // LEGACY-NL: [1]
107
+ /** On <html> while the tool is on. */
108
+ const EDITING = ["data-cm-editing", "data-cm-bewerken"]; // LEGACY-NL: [1]
109
+ /** Written by the site: a container that limits its text to these parts of the file. */
110
+ const EDIT_PATH = ["data-edit-path", "data-edit-pad"]; // LEGACY-NL: [1]
111
+ /** Written by the site: the file a "#/pointer" in data-edit belongs to. */
112
+ const EDIT_SOURCE = ["data-edit-source", "data-edit-bron"]; // LEGACY-NL: [1]
113
+ /** Written by the site: a <meta> naming the shared files this page shows. */
114
+ const SHARED_META = 'meta[name="comment-modus:shared"], meta[name="comment-modus:gedeeld"]'; // LEGACY-NL: gedeeld
115
+ const any = (names) => names.map((n) => `[${n}]`).join(", ");
116
+ const has = (el, names) => names.some((n) => el.hasAttribute(n));
117
+ const read = (el, names) => {
118
+ for (const n of names) if (el?.hasAttribute(n)) return el.getAttribute(n);
119
+ return null;
120
+ };
121
+ const write = (el, names, value) => {
122
+ if (el.getAttribute(names[0]) !== value) el.setAttribute(names[0], value);
123
+ };
124
+ const toggle = (el, names, on) => {
125
+ el.toggleAttribute(names[0], on);
126
+ if (!on) for (const n of names.slice(1)) el.removeAttribute(n);
127
+ };
128
+ const clear = (el, names) => {
129
+ for (const n of names) el.removeAttribute(n);
130
+ };
131
+ /** The nearest attribute of these names on the element or above it. */
132
+ const closestAttr = (el, names) => read(el.closest(any(names)), names);
133
+
134
+ // ── Text ──
135
+ /** Long text does not occur twice by chance: it may stand more than once. */
136
+ const LONG = 40;
137
+ /** So many texts only in that file must be on the page before the file belongs to it. */
138
+ const MIN_SCOPE = 3;
139
+ const MAX_TEXT = 6000;
140
+ const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "SVG", "svg", "TITLE", "HEAD", "IFRAME", "CANVAS", "VIDEO", "AUDIO", "SELECT", "TEXTAREA", "INPUT"]);
141
+ /** Children a field may have. SPAN: a heading animated per word, flattened to text when edited.
142
+ * Anything else in it (an icon, an image, a button) and the element cannot be replaced whole. */
143
+ const FLAT_TAGS = new Set(["SPAN", "BR"]);
144
+ const INLINE_TAGS = new Set(["EM", "STRONG", "A", "B", "I", "BR", "SPAN"]);
145
+ /** Interface, not content: the site's menu, header and footer. */
146
+ const INTERFACE = "nav, footer, [role=navigation], [role=contentinfo], [role=banner], body > header";
147
+
148
+ const normalize = (s) =>
149
+ s
150
+ .normalize("NFC")
151
+ .replace(/[­​-‍⁠]/g, "")
152
+ .replace(/[\s  ]+/g, " ")
153
+ .trim();
154
+
155
+ let decoder = null;
156
+ /** An inline value as it reads on the page: without tags, entities decoded. */
157
+ const visibleText = (value, inline) => {
158
+ if (!inline) return normalize(value);
159
+ const bare = value.replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, "");
160
+ decoder ??= document.createElement("textarea");
161
+ decoder.innerHTML = bare;
162
+ return normalize(decoder.value);
163
+ };
164
+
165
+ /**
166
+ * An element's text as a reader reads it: its textContent, but a line break as a space. A heading
167
+ * that breaks after each sentence ("Eén agenda.<br>Tien verlangens.") reads as its value with
168
+ * spaces, which textContent would run together.
169
+ */
170
+ const readText = (el) => {
171
+ if (!el.querySelector("br")) return el.textContent ?? "";
172
+ let out = "";
173
+ const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
174
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
175
+ if (n.nodeType === Node.TEXT_NODE) out += n.nodeValue;
176
+ else if (n.tagName === "BR") out += " ";
177
+ }
178
+ return out;
179
+ };
180
+
181
+ /** May this element be replaced whole by the value? Only with nothing but text in it (inline: em/strong/a/br too). */
182
+ const simple = (el, inline) => {
183
+ for (const child of el.children) {
184
+ if (!(inline ? INLINE_TAGS : FLAT_TAGS).has(child.tagName)) return false;
185
+ if (child.children.length && !simple(child, inline)) return false;
186
+ }
187
+ return true;
188
+ };
189
+
190
+ /** Never text: the layer itself, the bridge's own, scripts, form fields. */
191
+ const ignored = (el) =>
192
+ SKIP_TAGS.has(el.tagName) || el.id === "comment-modus" || el.id === "comment-modus-schil" || has(el, IGNORE) || skip(el);
193
+
194
+ /** The component an element is in (data-c of the component marker), else the nearest section. The same
195
+ * text twice in one component is one field rendered twice (desktop and mobile, tab and panel). */
196
+ const componentOf = (el) => el.closest("[data-c]") ?? el.closest("section");
197
+
198
+ /**
199
+ * Which text on the page comes from which field.
200
+ *
201
+ * 1. Explicit: an element with data-edit="file#/pointer" (or "#/pointer" under an ancestor with
202
+ * data-edit-source="file") is that field. Always.
203
+ * 2. Text: per element its text (textContent, normalised: whitespace, soft hyphens, nbsp). The
204
+ * deepest element whose whole text equals a value in the map is a candidate. textContent is
205
+ * what the HTML holds, not what CSS makes of it: a heading in capitals (text-transform) or a
206
+ * clamped text (line-clamp) matches.
207
+ * 2b. The site's menu, header and footer (INTERFACE) are interface: there only text from a file
208
+ * with x-interface (the whole site's texts) or from a template file matches, never that of a
209
+ * page or a content template. A nav with data-edit-path is content (the pager on a page).
210
+ * 3. Scope: which files belong to this page? A file with texts only in that file that are on
211
+ * this page, at least MIN_SCOPE of them: a page that shows one title from a file (a menu, an
212
+ * overview) does not make that file editable; a click there would change another page's
213
+ * source. A container with data-edit-path="/quote" limits the text in it to those parts of
214
+ * the file. A shared file (x-shared) belongs to a page with at least MIN_SCOPE of its own
215
+ * texts on it, or one the page names in <meta name="comment-modus:shared">; a text only in
216
+ * that file may stand on the page more than once. A template file (`templates`) is in scope
217
+ * wherever its text is: that text is written in it, so it is what renders there.
218
+ * 4. Unique: one pointer within the scope, and that text on the page once (or long enough not
219
+ * to be chance). Otherwise it is not clickable. Nor is an element with other elements in it
220
+ * (an icon beside the text): saving would break it.
221
+ *
222
+ * A text in a content file and in a template file belongs to the content file: that is how the
223
+ * page read before template files were mapped, so no field moves.
224
+ *
225
+ * What cannot be matched is never saved wrongly: it is just not editable.
226
+ */
227
+ function match(given, root = document.body) {
228
+ const map = readMap(given);
229
+ const inlineSet = new Set(Object.entries(map.inline ?? {}).flatMap(([f, ps]) => ps.map((p) => keyOf(f, p))));
230
+ const source = new Set(map.templates ?? []);
231
+ const isSource = (key) => source.has(splitKey(key).file);
232
+ const valueOf = (key) => {
233
+ const { file, pointer } = splitKey(key);
234
+ return map.files[file]?.[pointer];
235
+ };
236
+
237
+ // ── index: visible text → keys ──
238
+ const index = new Map();
239
+ for (const [file, fields] of Object.entries(map.files)) {
240
+ for (const [pointer, value] of Object.entries(fields)) {
241
+ if (typeof value !== "string") continue;
242
+ const key = keyOf(file, pointer);
243
+ const text = visibleText(value, inlineSet.has(key));
244
+ if (text.length < 2) continue;
245
+ index.set(text, [...(index.get(text) ?? []), key]);
246
+ }
247
+ }
248
+ if (source.size) {
249
+ for (const [text, keys] of index) {
250
+ const content = keys.filter((k) => !isSource(k));
251
+ if (content.length && content.length < keys.length) index.set(text, content);
252
+ }
253
+ }
254
+
255
+ const shared = map.shared ?? {};
256
+ const isShared = (key) => splitKey(key).file in shared;
257
+ /** Plain (false), inline (true), or inline with a styled span in its value ("span"). */
258
+ const inlineOf = (key) => (!inlineSet.has(key) ? false : /<span>/i.test(valueOf(key) ?? "") ? "span" : true);
259
+ const fields = new Map();
260
+ const byElement = new Map();
261
+ const rejected = [];
262
+ const put = (key, el, explicit) => {
263
+ const { file, pointer } = splitKey(key);
264
+ const f = fields.get(key) ?? {
265
+ key, file, pointer, value: valueOf(key) ?? "", inline: inlineOf(key), elements: [], explicit,
266
+ ...(shared[file] ? { shared: shared[file] } : {}),
267
+ };
268
+ f.elements.push(el);
269
+ fields.set(key, f);
270
+ byElement.set(el, f);
271
+ };
272
+
273
+ // ── 1. explicit ──
274
+ const scope = new Set();
275
+ // data-cm-field: an element matched before. A draft may stand in it already, so its text no
276
+ // longer matches; the match holds as long as the element exists.
277
+ for (const el of root.querySelectorAll(`[data-edit], ${any(FIELD)}`)) {
278
+ if (el.closest("#comment-modus") || skip(el)) continue;
279
+ let key = el.getAttribute("data-edit") ?? read(el, FIELD) ?? "";
280
+ if (key.startsWith("#")) key = (closestAttr(el, EDIT_SOURCE) ?? "") + key;
281
+ if (valueOf(key) === undefined) continue;
282
+ put(key, el, el.hasAttribute("data-edit"));
283
+ scope.add(splitKey(key).file);
284
+ }
285
+
286
+ // ── 2. text ──
287
+ const iface = new Set(map.interface ?? []);
288
+ const keysFor = (text, inIface) =>
289
+ inIface ? index.get(text).filter((k) => iface.has(splitKey(k).file) || isSource(k)) : index.get(text);
290
+ const candidates = [];
291
+ const walk = (el, inIface) => {
292
+ if (ignored(el) || el.hasAttribute("data-edit") || has(el, FIELD)) return;
293
+ if (!inIface && el.matches(INTERFACE) && !has(el, EDIT_PATH)) {
294
+ if (!iface.size && !source.size) return;
295
+ inIface = true;
296
+ }
297
+ const raw = readText(el);
298
+ if (!raw.trim()) return;
299
+ if (raw.length <= MAX_TEXT) {
300
+ const text = normalize(raw);
301
+ if (index.has(text) && keysFor(text, inIface).length) candidates.push({ el, text, iface: inIface });
302
+ }
303
+ for (const child of el.children) walk(child, inIface);
304
+ };
305
+ for (const child of root.children) walk(child, false);
306
+ // The deepest: a candidate with a descendant of the same text drops out.
307
+ const deepest = candidates.filter((c) => !candidates.some((d) => d !== c && d.text === c.text && c.el.contains(d.el)));
308
+
309
+ // ── 3. scope ──
310
+ const score = new Map();
311
+ const seen = new Set();
312
+ for (const { text, iface: inIface } of deepest) {
313
+ if (seen.has(`${inIface}${text}`)) continue;
314
+ seen.add(`${inIface}${text}`);
315
+ const files = new Set(keysFor(text, inIface).map((k) => splitKey(k).file));
316
+ if (files.size === 1) {
317
+ const [f] = files;
318
+ score.set(f, (score.get(f) ?? 0) + 1);
319
+ }
320
+ }
321
+ // The bar for a page's file follows the page's own file; a shared file does not count there
322
+ // and needs MIN_SCOPE. A template file belongs wherever its text is.
323
+ const highest = Math.max(0, ...[...score].filter(([f]) => !(f in shared) && !source.has(f)).map(([, n]) => n));
324
+ for (const [f, n] of score) {
325
+ if (source.has(f) || n >= (f in shared ? MIN_SCOPE : Math.max(MIN_SCOPE, highest * 0.25))) scope.add(f);
326
+ }
327
+ for (const m of (root.ownerDocument ?? document).querySelectorAll(SHARED_META)) {
328
+ for (const f of (m.content ?? "").split(/\s+/)) if (f in shared) scope.add(f);
329
+ }
330
+ // What the map itself names (map.scope): a file whoever gives the map knows the page shows.
331
+ for (const f of map.scope ?? []) if (map.files[f]) scope.add(f);
332
+
333
+ // ── 4. unique ──
334
+ // Per text and per data-edit-path: the same text in two bounded containers are two questions.
335
+ const byText = new Map();
336
+ for (const { el, text, iface: inIface } of deepest) {
337
+ const paths = closestAttr(el, EDIT_PATH)?.split(/\s+/).filter(Boolean) ?? null;
338
+ const id = `${text}\u0000${paths?.join(" ") ?? ""}\u0000${inIface}`;
339
+ const group = byText.get(id) ?? { text, paths, iface: inIface, elements: [] };
340
+ group.elements.push(el);
341
+ byText.set(id, group);
342
+ }
343
+ const within = (pointer, paths) => !paths || paths.some((p) => pointer === p || pointer.startsWith(`${p}/`));
344
+ for (const { text, paths, iface: inIface, elements } of byText.values()) {
345
+ const keys = keysFor(text, inIface).filter((k) => scope.has(splitKey(k).file) && !fields.has(k) && within(splitKey(k).pointer, paths));
346
+ if (!keys.length) {
347
+ if (!index.get(text).some((k) => fields.has(k))) rejected.push({ keys: index.get(text), text, reason: "out-of-scope", count: elements.length });
348
+ continue;
349
+ }
350
+ if (keys.length > 1) {
351
+ rejected.push({ keys, text, reason: "ambiguous", count: elements.length });
352
+ continue;
353
+ }
354
+ const oneComponent = elements.every((el) => componentOf(el) !== null && componentOf(el) === componentOf(elements[0]));
355
+ // A label from a shared file found nowhere else in the content ("Reageer" on every vacancy
356
+ // card) is one field in every place; so is a text written once in a template (a loop).
357
+ const ownLabel = (isShared(keys[0]) || isSource(keys[0])) && index.get(text).length === 1;
358
+ if (elements.length > 1 && text.length < LONG && !oneComponent && !ownLabel) {
359
+ rejected.push({ keys, text, reason: "repeated", count: elements.length });
360
+ continue;
361
+ }
362
+ const inline = inlineSet.has(keys[0]);
363
+ const good = elements.filter((el) => simple(el, inline));
364
+ if (!good.length) {
365
+ rejected.push({ keys, text, reason: "structure", count: elements.length });
366
+ continue;
367
+ }
368
+ for (const el of good) put(keys[0], el, false);
369
+ }
370
+
371
+ // The page's own file first ("All fields" opens scope[0]), then the shared ones, then templates.
372
+ const order = (f) => (source.has(f) ? 2 : f in shared ? 1 : 0);
373
+ return { fields, byElement, scope: [...scope].sort((a, b) => order(a) - order(b) || a.localeCompare(b)), rejected };
374
+ }
375
+
376
+ /**
377
+ * The site's own map with the template text Unbase found in its repository. The site's map knows
378
+ * its content files best (schemas, inline fields, lists); the other adds only what is written in
379
+ * the code. Either may be missing.
380
+ */
381
+ const mergeMaps = (ownMap, foundMap) => {
382
+ const own = readMap(ownMap);
383
+ const found = readMap(foundMap);
384
+ if (!found) return own;
385
+ if (!own) return found;
386
+ const out = {
387
+ ...own,
388
+ files: { ...own.files },
389
+ inline: { ...(own.inline ?? {}) },
390
+ shared: { ...(own.shared ?? {}) },
391
+ templates: [...(own.templates ?? [])],
392
+ };
393
+ for (const file of found.templates ?? []) {
394
+ if (file in out.files || !found.files[file]) continue;
395
+ out.files[file] = found.files[file];
396
+ if (found.inline?.[file]) out.inline[file] = found.inline[file];
397
+ if (found.shared?.[file]) out.shared[file] = found.shared[file];
398
+ out.templates.push(file);
399
+ }
400
+ return out;
401
+ };
402
+
403
+ // ── Values ──
404
+ const escape = (s, attribute = false) => {
405
+ const t = s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
406
+ return attribute ? t.replace(/"/g, "&quot;") : t;
407
+ };
408
+ const safeLink = (href) => /^(https?:\/\/|mailto:|tel:|\/(?!\/)|#)/i.test(href) && !/[\s<>"]/.test(href);
409
+
410
+ /** Only em, strong and a[href] (http(s), mailto, tel, relative); b → strong, i → em, br → a space;
411
+ * the rest goes and leaves its text. publish (Unbase) does the same on the server. With `spans`
412
+ * (a field whose value has a styled span) a span stays too, bare: the site's file keeps its
413
+ * class. Not one with a style: that is the browser's own, made while typing. */
414
+ const sanitize = (html, spans = false) => {
415
+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
416
+ const out = (n) => {
417
+ if (n.nodeType === Node.TEXT_NODE) return escape(n.textContent ?? "");
418
+ if (n.nodeType !== Node.ELEMENT_NODE) return "";
419
+ const inner = [...n.childNodes].map(out).join("");
420
+ const tag = n.tagName;
421
+ if (tag === "BR") return " ";
422
+ if (tag === "SPAN" && spans && !n.hasAttribute("style")) return inner.trim() ? `<span>${inner}</span>` : inner;
423
+ if (tag === "EM" || tag === "I") return inner.trim() ? `<em>${inner}</em>` : inner;
424
+ if (tag === "STRONG" || tag === "B") return inner.trim() ? `<strong>${inner}</strong>` : inner;
425
+ if (tag === "A") {
426
+ const href = (n.getAttribute("href") ?? "").trim();
427
+ return safeLink(href) ? `<a href="${escape(href, true)}">${inner}</a>` : inner;
428
+ }
429
+ return inner;
430
+ };
431
+ return [...doc.body.childNodes].map(out).join("").replace(/\s+/g, " ").trim();
432
+ };
433
+
434
+ /**
435
+ * A plain field: the text as typed, whitespace joined. Read as the match reads it (textContent, a
436
+ * line break as a space), not as innerText: that is what CSS makes of it, and a heading in capitals
437
+ * (text-transform) was saved in capitals.
438
+ */
439
+ const plainText = (el) => normalize(readText(el));
440
+ /** A field's value from what its element holds now. */
441
+ const valueFrom = (el, inline) => (inline ? sanitize(el.innerHTML, inline === "span") : plainText(el));
442
+
443
+ /** The tags of an element in order (b as strong, i as em, a with its href), and the runs of text between them. */
444
+ const shape = (root) => {
445
+ const tags = [];
446
+ const runs = [[]];
447
+ const walk = (n) => {
448
+ for (const c of n.childNodes) {
449
+ if (c.nodeType === Node.TEXT_NODE) runs.at(-1).push(c);
450
+ else if (c.nodeType === Node.ELEMENT_NODE) {
451
+ const name = c.tagName === "B" ? "STRONG" : c.tagName === "I" ? "EM" : c.tagName;
452
+ tags.push(name === "A" ? `A ${c.getAttribute("href")}` : name);
453
+ runs.push([]);
454
+ walk(c);
455
+ tags.push(`/${name}`);
456
+ runs.push([]);
457
+ }
458
+ }
459
+ };
460
+ walk(root);
461
+ return { tags: tags.join("\n"), runs };
462
+ };
463
+ /**
464
+ * The value's text into the element's own text nodes when both have the same tags, so a styled span
465
+ * keeps the site's class (the value holds it bare) and the site's nodes stay its own. False when the
466
+ * tags differ, or a run of text has no node to hold it.
467
+ */
468
+ const morph = (el, html) => {
469
+ const t = el.ownerDocument.createElement("template");
470
+ t.innerHTML = html;
471
+ const now = shape(el);
472
+ const want = shape(t.content);
473
+ if (now.tags !== want.tags) return false;
474
+ const texts = want.runs.map((nodes) => nodes.map((n) => n.nodeValue).join(""));
475
+ if (now.runs.some((nodes, i) => !nodes.length && texts[i])) return false;
476
+ now.runs.forEach((nodes, i) => nodes.forEach((n, j) => (n.nodeValue = j ? "" : texts[i])));
477
+ return true;
478
+ };
479
+ /** A value into the element (a draft, or back to the base). */
480
+ const setValue = (el, value, inline) => {
481
+ if (!inline) el.textContent = value;
482
+ else if (inline !== "span" || !morph(el, sanitize(value, true))) el.innerHTML = sanitize(value, inline === "span");
483
+ };
484
+ /** Is this value the same as the base, in substance? (Whitespace does not count.) */
485
+ const sameAs = (value, base, inline) =>
486
+ inline ? sanitize(value, inline === "span") === sanitize(base, inline === "span") : normalize(value) === normalize(base);
487
+
488
+ // ── Session: one field being edited ──
489
+ /** The caret where the click was. */
490
+ const caretAt = (el, x, y) => {
491
+ const doc = el.ownerDocument;
492
+ const sel = doc.getSelection();
493
+ const pos = doc.caretPositionFromPoint?.(x, y);
494
+ const range = pos ? null : doc.caretRangeFromPoint?.(x, y);
495
+ if (!sel || !(pos || range)) return;
496
+ const r = doc.createRange();
497
+ if (pos && el.contains(pos.offsetNode)) r.setStart(pos.offsetNode, pos.offset);
498
+ else if (range && el.contains(range.startContainer)) r.setStart(range.startContainer, range.startOffset);
499
+ else r.selectNodeContents(el);
500
+ r.collapse(true);
501
+ sel.removeAllRanges();
502
+ sel.addRange(r);
503
+ };
504
+
505
+ /** Makes the element editable with `value` in it, flattened to text (inline: em, strong, a). */
506
+ const begin = (el, field, value, x, y) => {
507
+ setValue(el, value, field.inline);
508
+ el.contentEditable = field.inline ? "true" : "plaintext-only";
509
+ if (!field.inline && el.contentEditable !== "plaintext-only") el.contentEditable = "true";
510
+ el.spellcheck = true;
511
+ write(el, ACTIVE, "");
512
+ el.focus({ preventScroll: true });
513
+ if (typeof x === "number" && typeof y === "number") caretAt(el, x, y);
514
+ };
515
+ const end = (el) => {
516
+ el.removeAttribute("contenteditable");
517
+ clear(el, ACTIVE);
518
+ el.removeAttribute("spellcheck");
519
+ };
520
+
521
+ /**
522
+ * The element's events while it is edited: every change (with the field's other copies on the
523
+ * page following), Enter and Esc end it, paste is text, nothing can be dropped in, blur ends it
524
+ * unless `holding()` says the format bar has the focus. Returns the function that stops listening.
525
+ */
526
+ const listen = (el, field, { input, done, holding = () => false }) => {
527
+ const onInput = () => {
528
+ const value = valueFrom(el, field.inline);
529
+ for (const other of field.elements) if (other !== el && other.isConnected) setValue(other, value, field.inline);
530
+ input(value);
531
+ };
532
+ const onKey = (e) => {
533
+ e.stopPropagation(); // the site (carousels, tabs) does not hear these keys
534
+ if (e.key === "Enter" || e.key === "Escape") {
535
+ e.preventDefault();
536
+ el.blur();
537
+ }
538
+ };
539
+ const onPaste = (e) => {
540
+ e.preventDefault();
541
+ const text = (e.clipboardData?.getData("text/plain") ?? "").replace(/\s+/g, " ");
542
+ el.ownerDocument.execCommand("insertText", false, text);
543
+ };
544
+ const onBlur = () => {
545
+ if (!holding()) done();
546
+ };
547
+ const onDrop = (e) => e.preventDefault();
548
+ el.addEventListener("input", onInput);
549
+ el.addEventListener("keydown", onKey);
550
+ el.addEventListener("paste", onPaste);
551
+ el.addEventListener("blur", onBlur);
552
+ el.addEventListener("drop", onDrop);
553
+ return () => {
554
+ el.removeEventListener("input", onInput);
555
+ el.removeEventListener("keydown", onKey);
556
+ el.removeEventListener("paste", onPaste);
557
+ el.removeEventListener("blur", onBlur);
558
+ el.removeEventListener("drop", onDrop);
559
+ };
560
+ };
561
+
562
+ /** Bold or italic on the selection in the field being edited. */
563
+ const format = (command) => document.execCommand(command);
564
+ /** A link on the selection (`range`, saved when the link field opened): none when the address is empty. */
565
+ const applyLink = (el, range, url) => {
566
+ const sel = el.ownerDocument.getSelection();
567
+ el.focus({ preventScroll: true });
568
+ if (range && sel) {
569
+ sel.removeAllRanges();
570
+ sel.addRange(range);
571
+ }
572
+ const href = (url ?? "").trim();
573
+ if (!href) document.execCommand("unlink");
574
+ else if (safeLink(href)) document.execCommand("createLink", false, href);
575
+ };
576
+
577
+ /** On the page itself, outside any shadow root: specific enough to win from the site's classes,
578
+ * without !important. `accent` is the layer's accent (Unbase blue unless the site sets one). */
579
+ const documentCss = (accent = "#034AD8") => {
580
+ const tint = `color-mix(in srgb, ${accent} 6%, transparent)`;
581
+ // Unbase's proxy finds the first rule by this exact text (bridge.ts, QUIET_RULES) and takes its
582
+ // corners, outline and transition out in a canvas frame. It knows this English selector and the
583
+ // Dutch one of before 2.0 (`html[data-cm-bewerken] [data-cm-veld]`); change neither alone.
584
+ return `
585
+ html[data-cm-editing] [data-cm-field] {
586
+ cursor: text; border-radius: 6px;
587
+ outline: 1px solid transparent; outline-offset: 4px;
588
+ transition: outline-color 0.12s ease, background-color 0.12s ease;
589
+ }
590
+ @media (hover: hover) {
591
+ html[data-cm-editing] [data-cm-field]:hover { outline-color: ${accent}; background-color: ${tint}; }
592
+ }
593
+ html[data-cm-editing] [data-cm-field][data-cm-conflict] { outline: 2px dotted ${accent}; }
594
+ html [data-cm-field][data-cm-active] {
595
+ outline: 2px solid ${accent}; outline-offset: 4px; background-color: transparent;
596
+ cursor: text; border-radius: 6px; caret-color: currentColor;
597
+ -webkit-line-clamp: unset; line-clamp: none; overflow: visible;
598
+ }
599
+ html [data-cm-field][data-cm-flash] { outline: 2px solid ${accent}; outline-offset: 4px; transition: outline-color 0.6s ease; }
600
+ `;
601
+ };
602
+
603
+ /** "/rollen/items/2/desc" → "rollen · items · 3 · desc"; a template field by its text ("Over ons", at most 40). */
604
+ const fieldLabel = (file, pointer, base) => {
605
+ if (!/\.json$/i.test(file)) {
606
+ const t = normalize(String(base ?? "").replace(/<[^>]*>/g, ""));
607
+ return t.length > 40 ? `${t.slice(0, 39).trimEnd()}…` : t || pointer;
608
+ }
609
+ return pointer
610
+ .split("/")
611
+ .slice(1)
612
+ .map((d) => d.replace(/~1/g, "/").replace(/~0/g, "~"))
613
+ .map((d) => (/^\d+$/.test(d) ? String(Number(d) + 1) : d))
614
+ .join(" · ");
615
+ };
616
+
617
+ // ── The whole of it, for a host without React ──
618
+ /**
619
+ * Text editing on this page, for a host that keeps the drafts elsewhere (the canvas frame: the app
620
+ * saves them). The editor matches the page, lays drafts over it and edits a field on a click with
621
+ * the tool on; it reports through `emit` and is told the drafts, the published values not yet
622
+ * live, the others' fields and the canvas's zoom.
623
+ */
624
+ function createEditor(opts) {
625
+ const emit = opts.emit ?? (() => {});
626
+ const accent = opts.accent ?? "#034AD8";
627
+ const doc = document;
628
+ const pageOf = () => ({ path: location.pathname + location.search, title: (doc.title.split(/\s+[—–|·-]\s+/)[0] ?? "").trim().slice(0, 300) || location.pathname });
629
+
630
+ let map = null;
631
+ let linked = null;
632
+ let tool = false;
633
+ let drafts = new Map(); // key → { value, base_value, conflict }
634
+ let pending = new Map(); // key → a published value not live yet
635
+ const local = new Map(); // key → typed here or in another frame, not in drafts yet
636
+ const original = new Map(); // element → its HTML before a value went in
637
+ let active = null; // { key, el, field, off }
638
+ let locks = [];
639
+ let scale = 1;
640
+ let holding = false;
641
+
642
+ const mapValue = (key) => {
643
+ const { file, pointer } = splitKey(key);
644
+ const v = map?.files[file]?.[pointer];
645
+ return typeof v === "string" ? v : undefined;
646
+ };
647
+ const targetOf = (key) => local.get(key) ?? drafts.get(key)?.value ?? pending.get(key) ?? null;
648
+ const baseOf = (key) => drafts.get(key)?.base_value ?? pending.get(key) ?? mapValue(key) ?? "";
649
+
650
+ // ── Its own layer: the format bar and the others' fields, in a shadow root ──
651
+ const host = doc.createElement("div");
652
+ write(host, IGNORE, "");
653
+ host.setAttribute("data-unbase-edit", "");
654
+ host.style.cssText = "position:absolute;left:0;top:0;width:0;height:0;z-index:2147483646;pointer-events:none";
655
+ const shadow = host.attachShadow({ mode: "open" });
656
+ const css = doc.createElement("style");
657
+ css.textContent = `
658
+ * { box-sizing: border-box; }
659
+ .bar { position: absolute; display: flex; align-items: center; gap: 2px; padding: 4px; border-radius: 10px;
660
+ background: #ffffff; border: 1px solid #e4e4e7; box-shadow: 0 4px 16px rgb(0 0 0 / 0.12); pointer-events: auto;
661
+ font: 13px/1.3 system-ui, -apple-system, "Segoe UI", sans-serif; color: #18181b; }
662
+ .bar button { width: 32px; height: 32px; display: grid; place-items: center; border: 0; border-radius: 6px; background: transparent; color: #3f3f46; cursor: pointer; }
663
+ .bar button:hover { background: #f4f4f5; color: #18181b; }
664
+ .bar input { width: 240px; height: 32px; padding: 0 10px; border-radius: 6px; border: 1px solid ${accent}; background: #fff; color: #18181b; font: inherit; outline: none; }
665
+ .lock { position: absolute; border-radius: 6px; outline: 2px dashed var(--c); }
666
+ .lock span { position: absolute; left: -16px; top: -18px; width: 28px; height: 28px; border-radius: 999px; display: grid; place-items: center;
667
+ background: var(--c); color: #fff; border: 2px solid #fff; font: 600 11px/1 system-ui, sans-serif; }
668
+ `;
669
+ shadow.append(css);
670
+ const locksBox = doc.createElement("div");
671
+ shadow.append(locksBox);
672
+ let bar = null;
673
+ let savedRange = null;
674
+
675
+ const ICON = {
676
+ bold: '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>',
677
+ italic: '<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>',
678
+ link: '<path d="M9 17H7A5 5 0 0 1 7 7h2"/><path d="M15 7h2a5 5 0 1 1 0 10h-2"/><line x1="8" x2="16" y1="12" y2="12"/>',
679
+ };
680
+ const svg = (paths) => `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
681
+ const labels = opts.labels ?? { bold: "Bold", italic: "Italic", link: "Link", linkPlaceholder: "https://…" };
682
+
683
+ const pageRect = (el) => {
684
+ const r = el.getBoundingClientRect();
685
+ return { x: r.left + scrollX, y: r.top + scrollY, width: r.width, height: r.height };
686
+ };
687
+
688
+ const placeBar = () => {
689
+ if (!bar || !active) return;
690
+ const r = pageRect(active.el);
691
+ const above = r.y - scrollY > 56 / scale;
692
+ const s = 1 / scale;
693
+ bar.style.left = `${Math.max(8, r.x)}px`;
694
+ bar.style.top = above ? `${r.y - 44 * s}px` : `${r.y + r.height + 8 * s}px`;
695
+ bar.style.transform = `scale(${s})`;
696
+ bar.style.transformOrigin = "top left";
697
+ };
698
+
699
+ const showBar = () => {
700
+ hideBar();
701
+ if (!active?.field.inline) return;
702
+ bar = doc.createElement("div");
703
+ bar.className = "bar";
704
+ bar.setAttribute("role", "toolbar");
705
+ const button = (name, run) => {
706
+ const b = doc.createElement("button");
707
+ b.type = "button";
708
+ b.title = labels[name];
709
+ b.setAttribute("aria-label", labels[name]);
710
+ b.innerHTML = svg(ICON[name]);
711
+ // pointerdown, not click: the field keeps its focus and its selection.
712
+ b.addEventListener("pointerdown", (e) => {
713
+ e.preventDefault();
714
+ run();
715
+ });
716
+ return b;
717
+ };
718
+ const buttons = [
719
+ button("bold", () => format("bold")),
720
+ button("italic", () => format("italic")),
721
+ button("link", () => openLink()),
722
+ ];
723
+ bar.append(...buttons);
724
+ shadow.append(bar);
725
+ placeBar();
726
+ };
727
+ const hideBar = () => {
728
+ bar?.remove();
729
+ bar = null;
730
+ };
731
+ const openLink = () => {
732
+ if (!bar || !active) return;
733
+ const sel = doc.getSelection();
734
+ savedRange = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
735
+ const a = sel?.anchorNode?.parentElement?.closest("a");
736
+ holding = true;
737
+ bar.replaceChildren();
738
+ const input = doc.createElement("input");
739
+ input.value = a?.getAttribute("href") ?? "";
740
+ input.placeholder = labels.linkPlaceholder;
741
+ input.setAttribute("aria-label", labels.link);
742
+ let closed = false;
743
+ const close = (apply) => {
744
+ if (closed || !active) return;
745
+ closed = true;
746
+ const el = active.el;
747
+ if (apply) applyLink(el, savedRange, input.value);
748
+ else {
749
+ el.focus({ preventScroll: true });
750
+ if (savedRange) {
751
+ const s = doc.getSelection();
752
+ s?.removeAllRanges();
753
+ s?.addRange(savedRange);
754
+ }
755
+ }
756
+ holding = false;
757
+ showBar();
758
+ };
759
+ input.addEventListener("keydown", (e) => {
760
+ e.stopPropagation();
761
+ if (e.key === "Enter") {
762
+ e.preventDefault();
763
+ close(true);
764
+ }
765
+ if (e.key === "Escape") {
766
+ e.preventDefault();
767
+ close(false);
768
+ }
769
+ });
770
+ input.addEventListener("blur", () => close(true));
771
+ bar.append(input);
772
+ input.focus();
773
+ };
774
+
775
+ const drawLocks = () => {
776
+ locksBox.replaceChildren();
777
+ if (!linked) return;
778
+ for (const lock of locks) {
779
+ const el = linked.fields.get(lock.key)?.elements.find((e) => e.isConnected);
780
+ if (!el) continue;
781
+ const r = pageRect(el);
782
+ const box = doc.createElement("div");
783
+ box.className = "lock";
784
+ box.style.cssText = `left:${r.x - 4}px;top:${r.y - 4}px;width:${r.width + 8}px;height:${r.height + 8}px;--c:${lock.colour ?? accent}`;
785
+ const avatar = doc.createElement("span");
786
+ avatar.textContent = lock.initials ?? "";
787
+ avatar.style.transform = `scale(${1 / scale})`;
788
+ box.append(avatar);
789
+ locksBox.append(box);
790
+ }
791
+ };
792
+
793
+ // ── Drafts over the page ──
794
+ const paint = () => {
795
+ if (!linked) return;
796
+ for (const f of linked.fields.values()) {
797
+ if (active?.key === f.key) continue;
798
+ const target = targetOf(f.key);
799
+ const conflict = Boolean(drafts.get(f.key)?.conflict);
800
+ for (const el of f.elements) {
801
+ if (!el.isConnected) continue;
802
+ el.toggleAttribute("data-cm-conflict", conflict);
803
+ if (target !== null) {
804
+ if (!original.has(el)) original.set(el, el.innerHTML);
805
+ if (!sameAs(valueFrom(el, f.inline), target, f.inline)) setValue(el, target, f.inline);
806
+ } else if (original.has(el)) {
807
+ el.innerHTML = original.get(el);
808
+ original.delete(el);
809
+ }
810
+ }
811
+ }
812
+ drawLocks();
813
+ };
814
+
815
+ const relink = () => {
816
+ if (!map) return;
817
+ linked = match(map);
818
+ for (const [el, f] of linked.byElement) write(el, FIELD, f.key);
819
+ paint();
820
+ emit("fields", { count: linked.fields.size, files: linked.scope, shared: linked.scope.filter((f) => f in (map.shared ?? {})).map((f) => map.shared[f]) });
821
+ };
822
+
823
+ // An island that hydrates later or a panel that opens: again, a moment after it is quiet. What
824
+ // changes inside a matched field or in this layer is the editor itself.
825
+ let timer = 0;
826
+ const observer = new MutationObserver((list) => {
827
+ const foreign = list.some((m) => {
828
+ const t = m.target instanceof Element ? m.target : m.target.parentElement;
829
+ return t && !t.closest(`${any(FIELD)}, [data-unbase-edit], #comment-modus, #comment-modus-schil`) && !skip(t);
830
+ });
831
+ if (!foreign) return;
832
+ clearTimeout(timer);
833
+ timer = setTimeout(relink, 400);
834
+ });
835
+
836
+ const style = doc.createElement("style");
837
+ style.setAttribute("data-unbase-edit", "");
838
+ style.textContent = documentCss(accent);
839
+
840
+ const lockedBy = (key) => locks.find((l) => l.key === key) ?? null;
841
+
842
+ const fieldInfo = (key) => {
843
+ const f = linked?.fields.get(key);
844
+ const { file, pointer } = splitKey(key);
845
+ return { key, file, pointer, inline: Boolean(f?.inline), shared: f?.shared ?? null, template: (map?.templates ?? []).includes(file) };
846
+ };
847
+
848
+ const stop = () => {
849
+ const a = active;
850
+ if (!a) return;
851
+ active = null;
852
+ a.off();
853
+ end(a.el);
854
+ hideBar();
855
+ emit("done", { key: a.key });
856
+ // Nothing changed: the original markup back (the words of a heading animated per word).
857
+ if (targetOf(a.key) === null && original.has(a.el)) {
858
+ a.el.innerHTML = original.get(a.el);
859
+ original.delete(a.el);
860
+ }
861
+ emit("active", { field: null });
862
+ };
863
+
864
+ const start = (el, x, y) => {
865
+ const key = read(el, FIELD);
866
+ const field = key ? linked?.fields.get(key) : undefined;
867
+ if (!field || !key || active?.el === el) return;
868
+ const lock = lockedBy(key);
869
+ if (lock) {
870
+ emit("refused", { key, by: lock.name ?? "" });
871
+ return;
872
+ }
873
+ stop();
874
+ if (!original.has(el)) original.set(el, el.innerHTML);
875
+ begin(el, field, targetOf(key) ?? mapValue(key) ?? "", x, y);
876
+ const off = listen(el, field, {
877
+ input: (value) => {
878
+ local.set(key, value);
879
+ const base = baseOf(key);
880
+ emit("change", { ...fieldInfo(key), value, base, same: sameAs(value, base, field.inline), page: pageOf() });
881
+ placeBar();
882
+ },
883
+ done: stop,
884
+ holding: () => holding,
885
+ });
886
+ active = { key, el, field, off };
887
+ emit("active", { field: { ...fieldInfo(key), rect: pageRect(el) } });
888
+ showBar();
889
+ };
890
+
891
+ const onClick = (e) => {
892
+ if (!tool) return;
893
+ const t = e.target instanceof Element ? e.target : null;
894
+ if (!t || e.composedPath().includes(host)) return;
895
+ const el = t.closest(any(FIELD));
896
+ if (el) {
897
+ e.preventDefault();
898
+ e.stopPropagation();
899
+ start(el, e.clientX, e.clientY);
900
+ return;
901
+ }
902
+ // While editing, a link elsewhere does not take you away.
903
+ if (opts.blockLinks !== false && t.closest("a[href], [role=link]")) {
904
+ e.preventDefault();
905
+ e.stopPropagation();
906
+ }
907
+ };
908
+
909
+ const onResize = () => {
910
+ placeBar();
911
+ drawLocks();
912
+ };
913
+
914
+ doc.head?.append(style);
915
+ doc.documentElement.append(host);
916
+ doc.addEventListener("click", onClick, true);
917
+ addEventListener("resize", onResize);
918
+ if (doc.body) observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
919
+
920
+ return {
921
+ setMap(next) {
922
+ map = readMap(next);
923
+ relink();
924
+ },
925
+ setTool(on) {
926
+ tool = Boolean(on);
927
+ toggle(doc.documentElement, EDITING, tool);
928
+ if (!tool) stop();
929
+ },
930
+ /** The project's drafts, as the host has them (its unsaved typing included). */
931
+ setDrafts(list) {
932
+ drafts = new Map(
933
+ (list ?? []).filter((d) => !d.kind || d.kind === "text").map((d) => [keyOf(d.file, d.pointer), { value: d.value, base_value: d.base_value, conflict: d.conflict ?? null }]),
934
+ );
935
+ // Typing the host has in its drafts now (or that went back to what was there) is theirs again.
936
+ for (const [key, value] of local) {
937
+ if (active?.key === key) continue;
938
+ const d = drafts.get(key);
939
+ const inline = linked?.fields.get(key)?.inline ?? false;
940
+ if (d ? sameAs(d.value, value, inline) : sameAs(value, baseOf(key), inline)) local.delete(key);
941
+ }
942
+ paint();
943
+ },
944
+ /** Published values not live yet: {key: value}. */
945
+ setPending(values) {
946
+ pending = new Map(Object.entries(values ?? {}));
947
+ paint();
948
+ },
949
+ /** What someone types in another frame, before it is a draft; null when they are done. */
950
+ setLocal(key, value) {
951
+ if (active?.key === key) return;
952
+ if (value === null || value === undefined) local.delete(key);
953
+ else local.set(key, value);
954
+ paint();
955
+ },
956
+ /** Fields others are editing: [{ key, name, initials, colour }]. */
957
+ setLocks(list) {
958
+ locks = Array.isArray(list) ? list : [];
959
+ drawLocks();
960
+ },
961
+ /** The canvas's zoom: the bar and the avatars keep their size on screen. */
962
+ setScale(s) {
963
+ scale = s > 0 ? s : 1;
964
+ placeBar();
965
+ drawLocks();
966
+ },
967
+ /** A field flashed; its box on the page (for the host to bring into view), or null. */
968
+ show(key) {
969
+ const el = linked?.fields.get(key)?.elements.find((e) => e.isConnected);
970
+ if (!el) return null;
971
+ el.setAttribute("data-cm-flash", "");
972
+ setTimeout(() => el.removeAttribute("data-cm-flash"), 1600);
973
+ return pageRect(el);
974
+ },
975
+ stop,
976
+ /** Everything back as it was. */
977
+ destroy() {
978
+ stop();
979
+ clearTimeout(timer);
980
+ observer.disconnect();
981
+ doc.removeEventListener("click", onClick, true);
982
+ removeEventListener("resize", onResize);
983
+ for (const [el, html] of original) if (el.isConnected) el.innerHTML = html;
984
+ original.clear();
985
+ for (const el of doc.querySelectorAll(any(FIELD))) {
986
+ clear(el, FIELD);
987
+ el.removeAttribute("data-cm-conflict");
988
+ }
989
+ clear(doc.documentElement, EDITING);
990
+ style.remove();
991
+ host.remove();
992
+ },
993
+ };
994
+ }
995
+
996
+ return {
997
+ keyOf, splitKey, readMap, normalize, visibleText, match, mergeMaps,
998
+ sanitize, safeLink, plainText, valueFrom, setValue, sameAs,
999
+ caretAt, begin, end, listen, format, applyLink, documentCss, fieldLabel,
1000
+ createEditor,
1001
+ };
1002
+ }