@eldrajs/theme-core 0.0.0 → 0.2.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 +311 -0
- package/LICENSE +21 -0
- package/README.md +68 -1
- package/dist/bridge-CLi2P6Wh.js +314 -0
- package/dist/bridge.d.ts +2 -0
- package/dist/bridge.js +2 -0
- package/dist/design-tokens.d.ts +68 -0
- package/dist/design-tokens.js +486 -0
- package/dist/dynamic-route.d.ts +2 -0
- package/dist/dynamic-route.js +3 -0
- package/dist/dynamicRoute-CxXY-Y_8.js +126 -0
- package/dist/dynamicRoute-pRTBoYT6.d.ts +55 -0
- package/dist/i18n.d.ts +107 -0
- package/dist/i18n.js +192 -0
- package/dist/image-framing.d.ts +2 -0
- package/dist/image-framing.js +109 -0
- package/dist/imageFraming-BUZ-yqho.d.ts +51 -0
- package/dist/index-DxrkKyG4.d.ts +488 -0
- package/dist/index.d.ts +449 -0
- package/dist/index.js +1141 -0
- package/dist/layout-CWq_v6ws.d.ts +244 -0
- package/dist/layout.d.ts +2 -0
- package/dist/layout.js +930 -0
- package/dist/links.d.ts +113 -0
- package/dist/links.js +184 -0
- package/dist/overlay-Bgi0tIbN.d.ts +201 -0
- package/dist/overlay-C8-F1jzU.js +2908 -0
- package/dist/overlay.d.ts +2 -0
- package/dist/overlay.js +6 -0
- package/dist/preview-router.d.ts +2 -0
- package/dist/preview-router.js +130 -0
- package/dist/reusable.d.ts +66 -0
- package/dist/reusable.js +92 -0
- package/dist/reusableExpansion-Bqm83nCJ.js +229 -0
- package/dist/reusableExpansion-CXvs_ckx.d.ts +42 -0
- package/dist/stega.d.ts +17 -0
- package/dist/stega.js +69 -0
- package/dist/template-layout.d.ts +3 -0
- package/dist/template-layout.js +3 -0
- package/dist/templateLayout-CpZb6EEg.js +382 -0
- package/dist/templateLayout-MjNs0gbF.d.ts +254 -0
- package/package.json +89 -2
|
@@ -0,0 +1,2908 @@
|
|
|
1
|
+
import { decodeStega, stripStega } from "./stega.js";
|
|
2
|
+
import { l as RICH_TEXT_COMMAND_NAMES } from "./bridge-CLi2P6Wh.js";
|
|
3
|
+
import { framingDrag, framingZoom, imageFramingStyle, parseImageFramingValueAttr, unscaledFrameRect } from "./image-framing.js";
|
|
4
|
+
import { activeLayoutBreakpoint } from "./layout.js";
|
|
5
|
+
//#region src/layoutIdentity.ts
|
|
6
|
+
/**
|
|
7
|
+
* The layout identity of a rendered element: the nearest
|
|
8
|
+
* `[data-eldra-layout-node]` ancestor's node id and, when the placement is a
|
|
9
|
+
* reusable one, its `data-eldra-reusable-placement` id.
|
|
10
|
+
*
|
|
11
|
+
* Both the overlay runtime (block/field clicks, framing) and the §18 in-theme
|
|
12
|
+
* rich-text editor (`theme:rich-text-edited`) must resolve this the same way,
|
|
13
|
+
* so the two share this one implementation rather than each closing over a
|
|
14
|
+
* private copy. Keys are omitted — never set to `undefined` — so a payload
|
|
15
|
+
* built by spreading the result matches the bridge's optional fields exactly.
|
|
16
|
+
*/
|
|
17
|
+
function layoutIdentityOf(element) {
|
|
18
|
+
const layoutNode = element?.closest("[data-eldra-layout-node]") ?? null;
|
|
19
|
+
const layoutNodeId = layoutNode?.getAttribute("data-eldra-layout-node") || void 0;
|
|
20
|
+
const reusablePlacementId = layoutNode?.getAttribute("data-eldra-reusable-placement") || void 0;
|
|
21
|
+
return {
|
|
22
|
+
...layoutNodeId ? { layoutNodeId } : {},
|
|
23
|
+
...reusablePlacementId ? { reusablePlacementId } : {}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/richTextPositions.ts
|
|
28
|
+
/**
|
|
29
|
+
* ProseMirror-compatible document positions for a §18 rich-text field, with
|
|
30
|
+
* no dependency on ProseMirror (nor TipTap, nor any UI library — the theme
|
|
31
|
+
* SDK is a bridge only).
|
|
32
|
+
*
|
|
33
|
+
* §18 v3 makes the theme's own render the editing surface: the operator types
|
|
34
|
+
* in the theme's DOM and the theme reports what happened as positions, which
|
|
35
|
+
* Studio applies to the one headless TipTap editor that owns the document.
|
|
36
|
+
* That only works if both sides agree on the numbering to the character, so
|
|
37
|
+
* the rules below are ProseMirror's, restated:
|
|
38
|
+
*
|
|
39
|
+
* - the `doc`'s content starts at `0`, and the `doc` itself has no tokens;
|
|
40
|
+
* - every non-text node with content **opens** (+1), its children follow, and
|
|
41
|
+
* it **closes** (+1) after them;
|
|
42
|
+
* - a text node occupies `text.length` — UTF-16 code units, which is what
|
|
43
|
+
* ProseMirror counts, so an astral-plane character (an emoji) is 2;
|
|
44
|
+
* - a leaf node (`image`, `hardBreak`, `horizontalRule`, `embed`) occupies 1.
|
|
45
|
+
*
|
|
46
|
+
* `packages/theme-core/test/fixtures/rich-text-positions.fixture.json` pins
|
|
47
|
+
* the numbering for a set of documents and is copied byte-for-byte into
|
|
48
|
+
* Studio's tests, where it is asserted against a real TipTap instance —
|
|
49
|
+
* neither implementation can drift without the other suite failing.
|
|
50
|
+
*
|
|
51
|
+
* The DOM half of the module maps between a DOM point (what a `Selection`
|
|
52
|
+
* gives) and a position, using the `data-eldra-node`/`data-eldra-pos` stamps
|
|
53
|
+
* `buildRichTextTree` puts on **node** elements. Mark elements (`strong`,
|
|
54
|
+
* `em`, `a`, …) and the structural wrappers that are not nodes (`tbody`, the
|
|
55
|
+
* `code` inside a `codeBlock`'s `pre`) carry no stamp and are walked through
|
|
56
|
+
* transparently, which is exactly their status in the document.
|
|
57
|
+
*/
|
|
58
|
+
/** Nodes that occupy exactly one position and have no content. */
|
|
59
|
+
const RICH_TEXT_LEAF_TYPES = [
|
|
60
|
+
"image",
|
|
61
|
+
"hardBreak",
|
|
62
|
+
"horizontalRule",
|
|
63
|
+
"embed"
|
|
64
|
+
];
|
|
65
|
+
const LEAF_TYPES = new Set(RICH_TEXT_LEAF_TYPES);
|
|
66
|
+
/**
|
|
67
|
+
* Ancestor element → mark name, for reading the active marks of a selection
|
|
68
|
+
* straight off the DOM. `span` counts only when it carries the inline style
|
|
69
|
+
* `textStyle` renders (a bare `span` is the wrapper `buildRichTextTree` puts
|
|
70
|
+
* around stray top-level text, not a mark), and `a` splits by the attribute
|
|
71
|
+
* the `fileAttachment` mark renders.
|
|
72
|
+
*/
|
|
73
|
+
const RICH_TEXT_MARK_ELEMENTS = {
|
|
74
|
+
strong: "bold",
|
|
75
|
+
em: "italic",
|
|
76
|
+
s: "strike",
|
|
77
|
+
u: "underline",
|
|
78
|
+
code: "code",
|
|
79
|
+
mark: "highlight",
|
|
80
|
+
span: "textStyle",
|
|
81
|
+
a: "link"
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* A text node's rendered text, stega stripped. Edit mode stega-encodes every
|
|
85
|
+
* text leaf of a rich-text document (`encodeEntryDataStega`), so this is the
|
|
86
|
+
* one definition of "a text node's text" shared by the renderer
|
|
87
|
+
* (`richTextTree.ts`'s `buildNode`) and the position walk below — the DOM
|
|
88
|
+
* must never contain the invisible payload, and a position is a position in
|
|
89
|
+
* the *clean* document Studio holds either way. Non-text nodes have none.
|
|
90
|
+
*/
|
|
91
|
+
function richTextText(node) {
|
|
92
|
+
if (!isNode(node) || node.type !== "text") return "";
|
|
93
|
+
return typeof node.text === "string" ? stripStega(node.text) : "";
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The number of positions a node occupies, including its own open and close
|
|
97
|
+
* tokens. The `doc` is the one node with no tokens, so it is not measured
|
|
98
|
+
* here — `computeRichTextPositions` sums its children instead.
|
|
99
|
+
*/
|
|
100
|
+
function richTextNodeSize(node) {
|
|
101
|
+
if (!isNode(node)) return 0;
|
|
102
|
+
if (node.type === "text") return richTextText(node).length;
|
|
103
|
+
if (typeof node.type === "string" && LEAF_TYPES.has(node.type)) return 1;
|
|
104
|
+
return 2 + contentSize(node.content);
|
|
105
|
+
}
|
|
106
|
+
function contentSize(content) {
|
|
107
|
+
if (!Array.isArray(content)) return 0;
|
|
108
|
+
let size = 0;
|
|
109
|
+
for (const child of content) size += richTextNodeSize(child);
|
|
110
|
+
return size;
|
|
111
|
+
}
|
|
112
|
+
function isNode(value) {
|
|
113
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Walk a TipTap JSON document and return its content size plus every node's
|
|
117
|
+
* open/close position. Non-`doc` input (or a `doc` with no content) is an
|
|
118
|
+
* empty document: `{ size: 0, nodes: [] }`.
|
|
119
|
+
*
|
|
120
|
+
* Text nodes are included, so the fixture pins the whole numbering rather
|
|
121
|
+
* than only the elements the renderer stamps.
|
|
122
|
+
*/
|
|
123
|
+
function computeRichTextPositions(doc) {
|
|
124
|
+
const nodes = [];
|
|
125
|
+
const root = isNode(doc) && doc.type === "doc" ? doc : null;
|
|
126
|
+
if (root === null) return {
|
|
127
|
+
size: 0,
|
|
128
|
+
nodes
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
size: collect(root.content, 0, [], nodes),
|
|
132
|
+
nodes
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Returns the content size of `content`, appending each node it walks. */
|
|
136
|
+
function collect(content, start, path, out) {
|
|
137
|
+
if (!Array.isArray(content)) return 0;
|
|
138
|
+
let pos = start;
|
|
139
|
+
for (let index = 0; index < content.length; index += 1) {
|
|
140
|
+
const child = content[index];
|
|
141
|
+
if (!isNode(child)) continue;
|
|
142
|
+
const childPath = [...path, index];
|
|
143
|
+
const type = typeof child.type === "string" ? child.type : "";
|
|
144
|
+
const size = richTextNodeSize(child);
|
|
145
|
+
out.push({
|
|
146
|
+
path: childPath,
|
|
147
|
+
type,
|
|
148
|
+
pos,
|
|
149
|
+
end: pos + size
|
|
150
|
+
});
|
|
151
|
+
if (type !== "text" && !LEAF_TYPES.has(type)) collect(child.content, pos + 1, childPath, out);
|
|
152
|
+
pos += size;
|
|
153
|
+
}
|
|
154
|
+
return pos - start;
|
|
155
|
+
}
|
|
156
|
+
const POS_ATTR = "data-eldra-pos";
|
|
157
|
+
const NODE_ATTR = "data-eldra-node";
|
|
158
|
+
/**
|
|
159
|
+
* `buildRichTextTree`'s `padEmptyBlocks` marker: a single unstamped
|
|
160
|
+
* `<br data-eldra-pad="">` child `buildRichTextTree` renders for an empty
|
|
161
|
+
* textblock (an empty paragraph, heading, or `codeBlock`'s `code`) so the
|
|
162
|
+
* browser does not collapse it to zero height and the caret has a line to
|
|
163
|
+
* sit on. Not a `hardBreak` — a real one is stamped (`data-eldra-node`) and
|
|
164
|
+
* still occupies one position via the leaf branch below; this occupies none.
|
|
165
|
+
*/
|
|
166
|
+
const RICH_TEXT_PAD_ATTR = "data-eldra-pad";
|
|
167
|
+
function isElement(value) {
|
|
168
|
+
return value !== null && value !== void 0 && value.nodeType === 1;
|
|
169
|
+
}
|
|
170
|
+
function isText(value) {
|
|
171
|
+
return value.nodeType === 3;
|
|
172
|
+
}
|
|
173
|
+
function stampedPos(element) {
|
|
174
|
+
const raw = element.getAttribute(POS_ATTR);
|
|
175
|
+
if (raw === null) return null;
|
|
176
|
+
const value = Number(raw);
|
|
177
|
+
return Number.isInteger(value) && value >= 0 ? value : null;
|
|
178
|
+
}
|
|
179
|
+
function isLeafElement(element) {
|
|
180
|
+
const type = element.getAttribute(NODE_ATTR);
|
|
181
|
+
return type !== null && LEAF_TYPES.has(type);
|
|
182
|
+
}
|
|
183
|
+
/** `padEmptyBlocks`'s zero-width filler — never a node element (it carries
|
|
184
|
+
* no `data-eldra-node`/`data-eldra-pos`), so this must be checked before the
|
|
185
|
+
* generic "unstamped element" branch would otherwise walk into it. */
|
|
186
|
+
function isPadBreak(element) {
|
|
187
|
+
return element.tagName === "BR" && !isNodeElement(element) && element.hasAttribute("data-eldra-pad");
|
|
188
|
+
}
|
|
189
|
+
/** Is this element a node element (as opposed to a mark element, a `tbody`,
|
|
190
|
+
* a `codeBlock`'s inner `code`, or the field root itself)? */
|
|
191
|
+
function isNodeElement(element) {
|
|
192
|
+
return element.hasAttribute(NODE_ATTR) && element.hasAttribute(POS_ATTR);
|
|
193
|
+
}
|
|
194
|
+
function contains(root, node) {
|
|
195
|
+
let current = node;
|
|
196
|
+
while (current !== null) {
|
|
197
|
+
if (current === root) return true;
|
|
198
|
+
current = current.parentNode;
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The nearest stamped node element at or above `node`, stopping at `root`.
|
|
204
|
+
* The walk that computes a position starts from this element's own stamped
|
|
205
|
+
* position, so a long document costs one block's worth of work rather than a
|
|
206
|
+
* full re-count, and a re-stamped tree is authoritative over any cursor this
|
|
207
|
+
* module could keep.
|
|
208
|
+
*/
|
|
209
|
+
function nearestNodeElement(root, node) {
|
|
210
|
+
let current = node;
|
|
211
|
+
while (current !== null && current !== root) {
|
|
212
|
+
if (isElement(current) && isNodeElement(current)) return current;
|
|
213
|
+
current = current.parentNode;
|
|
214
|
+
}
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* A node element's stamped position is where the document says it begins, so
|
|
219
|
+
* both walks jump to it rather than trusting the count of what came before.
|
|
220
|
+
* Without this they would only agree while the rendered tree holds every node
|
|
221
|
+
* the document does — which stops being true the moment the sanitiser refuses
|
|
222
|
+
* one (an unsafe `image.src`), and the two directions would then disagree for
|
|
223
|
+
* every position after the hole.
|
|
224
|
+
*/
|
|
225
|
+
function seedCursorFromStamp(child, state) {
|
|
226
|
+
if (!isElement(child) || !isNodeElement(child)) return;
|
|
227
|
+
const stamped = stampedPos(child);
|
|
228
|
+
if (stamped !== null) state.cursor = stamped;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Walk `container`'s children in document order, advancing `state.cursor` by
|
|
232
|
+
* each child's size, and set `state.found` the moment the walk reaches the
|
|
233
|
+
* target point.
|
|
234
|
+
*
|
|
235
|
+
* A stamped non-leaf element contributes its open token, its content and its
|
|
236
|
+
* close token; a stamped leaf contributes 1; an unstamped element (a mark, a
|
|
237
|
+
* `tbody`, a `codeBlock`'s `code`) is transparent — it is not a node, so it
|
|
238
|
+
* contributes nothing of its own and its children are counted in place.
|
|
239
|
+
*/
|
|
240
|
+
function walk(container, target, state) {
|
|
241
|
+
const children = container.childNodes;
|
|
242
|
+
for (let index = 0; index < children.length; index += 1) {
|
|
243
|
+
const child = children[index];
|
|
244
|
+
seedCursorFromStamp(child, state);
|
|
245
|
+
if (state.found === null && container === target.node && index === target.offset) state.found = state.cursor;
|
|
246
|
+
if (isText(child)) {
|
|
247
|
+
const length = child.data.length;
|
|
248
|
+
if (state.found === null && child === target.node) state.found = state.cursor + Math.min(Math.max(target.offset, 0), length);
|
|
249
|
+
state.cursor += length;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (!isElement(child)) continue;
|
|
253
|
+
if (isPadBreak(child)) {
|
|
254
|
+
if (state.found === null && child === target.node) state.found = state.cursor;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (!isNodeElement(child)) {
|
|
258
|
+
walk(child, target, state);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
if (isLeafElement(child)) {
|
|
262
|
+
if (state.found === null && child === target.node) state.found = state.cursor;
|
|
263
|
+
state.cursor += 1;
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
state.cursor += 1;
|
|
267
|
+
walk(child, target, state);
|
|
268
|
+
state.cursor += 1;
|
|
269
|
+
}
|
|
270
|
+
if (state.found === null && container === target.node && target.offset >= children.length) state.found = state.cursor;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The document position of a DOM point inside a rendered rich-text root — the
|
|
274
|
+
* shape `Selection.anchorNode`/`anchorOffset` and a `Range`'s boundaries come
|
|
275
|
+
* in. Returns null for a point outside `root`, or one the walk cannot reach
|
|
276
|
+
* (a detached node).
|
|
277
|
+
*/
|
|
278
|
+
function resolveDomPosition(root, node, offset) {
|
|
279
|
+
if (!contains(root, node)) return null;
|
|
280
|
+
const host = nearestNodeElement(root, node);
|
|
281
|
+
if (host === null) {
|
|
282
|
+
const state = {
|
|
283
|
+
cursor: 0,
|
|
284
|
+
found: null
|
|
285
|
+
};
|
|
286
|
+
walk(root, {
|
|
287
|
+
node,
|
|
288
|
+
offset
|
|
289
|
+
}, state);
|
|
290
|
+
return state.found;
|
|
291
|
+
}
|
|
292
|
+
const base = stampedPos(host);
|
|
293
|
+
if (base === null) return null;
|
|
294
|
+
if (isLeafElement(host)) return base;
|
|
295
|
+
const state = {
|
|
296
|
+
cursor: base + 1,
|
|
297
|
+
found: null
|
|
298
|
+
};
|
|
299
|
+
walk(host, {
|
|
300
|
+
node,
|
|
301
|
+
offset
|
|
302
|
+
}, state);
|
|
303
|
+
return state.found;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The inverse walk. A position that falls within a text node resolves to that
|
|
307
|
+
* text node and an offset into it — the caret the browser wants; only a
|
|
308
|
+
* position with no text around it (an empty paragraph, the gap beside a leaf
|
|
309
|
+
* with no text neighbour) resolves to an element/child-index boundary.
|
|
310
|
+
*/
|
|
311
|
+
function walkToPoint(container, pos, state) {
|
|
312
|
+
const children = container.childNodes;
|
|
313
|
+
for (let index = 0; index < children.length; index += 1) {
|
|
314
|
+
const child = children[index];
|
|
315
|
+
seedCursorFromStamp(child, state);
|
|
316
|
+
if (isText(child)) {
|
|
317
|
+
const length = child.data.length;
|
|
318
|
+
if (state.found === null && pos >= state.cursor && pos <= state.cursor + length) state.found = {
|
|
319
|
+
node: child,
|
|
320
|
+
offset: pos - state.cursor
|
|
321
|
+
};
|
|
322
|
+
state.cursor += length;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (!isElement(child)) continue;
|
|
326
|
+
if (isPadBreak(child)) {
|
|
327
|
+
if (state.found === null && pos === state.cursor) state.found = {
|
|
328
|
+
node: container,
|
|
329
|
+
offset: index
|
|
330
|
+
};
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (!isNodeElement(child)) {
|
|
334
|
+
walkToPoint(child, pos, state);
|
|
335
|
+
if (state.found !== null) return;
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (isLeafElement(child)) {
|
|
339
|
+
if (state.found === null && pos === state.cursor) state.found = {
|
|
340
|
+
node: container,
|
|
341
|
+
offset: index
|
|
342
|
+
};
|
|
343
|
+
state.cursor += 1;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (state.found === null && pos === state.cursor) state.found = {
|
|
347
|
+
node: container,
|
|
348
|
+
offset: index
|
|
349
|
+
};
|
|
350
|
+
state.cursor += 1;
|
|
351
|
+
walkToPoint(child, pos, state);
|
|
352
|
+
if (state.found !== null) return;
|
|
353
|
+
state.cursor += 1;
|
|
354
|
+
}
|
|
355
|
+
if (state.found === null && pos === state.cursor) state.found = {
|
|
356
|
+
node: container,
|
|
357
|
+
offset: children.length
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* The DOM point for a document position inside a rendered rich-text root, so
|
|
362
|
+
* the theme can put the caret back where Studio says it belongs. Returns null
|
|
363
|
+
* for a position outside the rendered document.
|
|
364
|
+
*/
|
|
365
|
+
function resolveDomPoint(root, pos) {
|
|
366
|
+
if (!Number.isInteger(pos) || pos < 0) return null;
|
|
367
|
+
const state = {
|
|
368
|
+
cursor: 0,
|
|
369
|
+
found: null
|
|
370
|
+
};
|
|
371
|
+
walkToPoint(root, pos, state);
|
|
372
|
+
return state.found;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Both boundaries of a DOM range as document positions. A `Range` is always
|
|
376
|
+
* ordered, so `from <= to`; a boundary outside `root` returns null rather
|
|
377
|
+
* than a half-resolved range.
|
|
378
|
+
*/
|
|
379
|
+
function domRangeToPositions(root, range) {
|
|
380
|
+
const from = resolveDomPosition(root, range.startContainer, range.startOffset);
|
|
381
|
+
if (from === null) return null;
|
|
382
|
+
const to = resolveDomPosition(root, range.endContainer, range.endOffset);
|
|
383
|
+
if (to === null) return null;
|
|
384
|
+
return from <= to ? {
|
|
385
|
+
from,
|
|
386
|
+
to
|
|
387
|
+
} : {
|
|
388
|
+
from: to,
|
|
389
|
+
to: from
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Refresh the `data-eldra-pos` stamps of an already-rendered root against a
|
|
394
|
+
* new document, without replacing any DOM.
|
|
395
|
+
*
|
|
396
|
+
* §18 v3 lets a field's re-render be **deferred** while a native text op is in
|
|
397
|
+
* flight: the browser owns that subtree, and replacing it would take the caret
|
|
398
|
+
* with it. The document underneath still moves — Studio applies the op and
|
|
399
|
+
* echoes the result — so every position after the edit shifts, and a stamp
|
|
400
|
+
* that still says what it said before the operator typed would send the next
|
|
401
|
+
* selection report to the wrong place in the document.
|
|
402
|
+
*
|
|
403
|
+
* Returns false, changing nothing, when the rendered tree and the document
|
|
404
|
+
* disagree on the number or the order of node elements — a node the sanitiser
|
|
405
|
+
* dropped, or a structural change that arrived while deferred. The caller must
|
|
406
|
+
* then fall back to a full re-render, which is the only honest answer: the
|
|
407
|
+
* stamps cannot describe a tree that is not the document's.
|
|
408
|
+
*/
|
|
409
|
+
function restampRichTextPositions(root, doc) {
|
|
410
|
+
const expected = computeRichTextPositions(doc).nodes.filter((node) => node.type !== "text");
|
|
411
|
+
const rendered = root.querySelectorAll(`[${NODE_ATTR}][${POS_ATTR}]`);
|
|
412
|
+
if (rendered.length !== expected.length) return false;
|
|
413
|
+
for (let index = 0; index < expected.length; index += 1) if (rendered[index].getAttribute(NODE_ATTR) !== expected[index].type) return false;
|
|
414
|
+
for (let index = 0; index < expected.length; index += 1) rendered[index].setAttribute(POS_ATTR, String(expected[index].pos));
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* The marks and the block a DOM point sits in, read off the rendered tree —
|
|
419
|
+
* enough for the toolbar's active state, and it needs no schema on the theme
|
|
420
|
+
* side. Marks come from the ancestor mark elements innermost first (the order
|
|
421
|
+
* a text node's own `marks` array is applied in); the block is the nearest
|
|
422
|
+
* stamped node element.
|
|
423
|
+
*
|
|
424
|
+
* Pass the **caret's own node** — `Selection.focusNode`, which is the text
|
|
425
|
+
* node the caret sits in. Passing a block element instead answers for that
|
|
426
|
+
* element's own ancestry, so a caret inside `<strong>` reported as its parent
|
|
427
|
+
* `<p>` would come back with no marks at all and the toolbar would show bold
|
|
428
|
+
* as inactive while the operator is typing in bold.
|
|
429
|
+
*/
|
|
430
|
+
function describeSelectionContext(root, node) {
|
|
431
|
+
const marks = [];
|
|
432
|
+
if (!contains(root, node)) return {
|
|
433
|
+
marks,
|
|
434
|
+
block: null
|
|
435
|
+
};
|
|
436
|
+
let current = isElement(node) ? node : node.parentNode;
|
|
437
|
+
while (isElement(current) && current !== root) {
|
|
438
|
+
if (isNodeElement(current)) return {
|
|
439
|
+
marks,
|
|
440
|
+
block: blockOf(current)
|
|
441
|
+
};
|
|
442
|
+
const mark = richTextMarkNameOf(current);
|
|
443
|
+
if (mark !== null && !marks.includes(mark)) marks.push(mark);
|
|
444
|
+
current = current.parentNode;
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
marks,
|
|
448
|
+
block: null
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* The mark an ancestor element stands for, or null when it is not a mark.
|
|
453
|
+
* Exported because `RICH_TEXT_MARK_ELEMENTS` alone is misleading: three of its
|
|
454
|
+
* entries are conditional — a `span` is `textStyle` only with an inline
|
|
455
|
+
* `style`, an `a` splits by `data-file-attachment`, and a `code` directly
|
|
456
|
+
* inside a `codeBlock`'s `pre` is part of that node rather than an inline
|
|
457
|
+
* `code` mark. Anyone classifying an element must come through here.
|
|
458
|
+
*/
|
|
459
|
+
function richTextMarkNameOf(element) {
|
|
460
|
+
const tag = element.tagName.toLowerCase();
|
|
461
|
+
if (tag === "span") return element.hasAttribute("style") ? "textStyle" : null;
|
|
462
|
+
if (tag === "a") return element.hasAttribute("data-file-attachment") ? "fileAttachment" : "link";
|
|
463
|
+
if (tag === "code") {
|
|
464
|
+
const parent = element.parentElement;
|
|
465
|
+
if (parent !== null && parent.getAttribute(NODE_ATTR) === "codeBlock") return null;
|
|
466
|
+
return "code";
|
|
467
|
+
}
|
|
468
|
+
return RICH_TEXT_MARK_ELEMENTS[tag] ?? null;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* The block descriptor for a stamped node element. `attrs` carries only what
|
|
472
|
+
* the toolbar needs and the DOM actually preserves: a heading's level and a
|
|
473
|
+
* code block's language. Everything else is omitted rather than guessed.
|
|
474
|
+
*/
|
|
475
|
+
function blockOf(element) {
|
|
476
|
+
const type = element.getAttribute(NODE_ATTR) ?? "";
|
|
477
|
+
if (type === "heading") {
|
|
478
|
+
const level = Number(element.tagName.slice(1));
|
|
479
|
+
if (Number.isInteger(level) && level >= 1 && level <= 6) return {
|
|
480
|
+
type,
|
|
481
|
+
attrs: { level }
|
|
482
|
+
};
|
|
483
|
+
return { type };
|
|
484
|
+
}
|
|
485
|
+
if (type === "codeBlock") {
|
|
486
|
+
const className = element.querySelector("code")?.getAttribute("class") ?? "";
|
|
487
|
+
const match = /(?:^|\s)language-(\S+)/.exec(className);
|
|
488
|
+
if (match !== null && match[1].length <= 64) return {
|
|
489
|
+
type,
|
|
490
|
+
attrs: { language: match[1] }
|
|
491
|
+
};
|
|
492
|
+
return { type };
|
|
493
|
+
}
|
|
494
|
+
return { type };
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
497
|
+
//#region src/overlay.ts
|
|
498
|
+
const TEXT_EDIT_DEBOUNCE_MS = 300;
|
|
499
|
+
/**
|
|
500
|
+
* §18 v3: the `beforeinput` inputTypes the theme is willing to let the
|
|
501
|
+
* browser perform itself, so the caret never leaves the theme's own render.
|
|
502
|
+
* Each one still has to pass the "one text run of one node" test in
|
|
503
|
+
* `classifyBeforeInput` — the same name outside that test is a command.
|
|
504
|
+
*/
|
|
505
|
+
const NATIVE_INPUT_TYPES = /* @__PURE__ */ new Set([
|
|
506
|
+
"insertText",
|
|
507
|
+
"insertCompositionText",
|
|
508
|
+
"deleteContentBackward",
|
|
509
|
+
"deleteContentForward",
|
|
510
|
+
"deleteWordBackward",
|
|
511
|
+
"deleteWordForward",
|
|
512
|
+
"deleteContent"
|
|
513
|
+
]);
|
|
514
|
+
const COMMAND_INPUT_TYPES = new Set(RICH_TEXT_COMMAND_NAMES);
|
|
515
|
+
/**
|
|
516
|
+
* A text insertion that failed the "one text run of one node" test still has
|
|
517
|
+
* to happen — the operator typed a character over a selection crossing a mark
|
|
518
|
+
* or a block. The §18 v3 command vocabulary has no `insertText`, and the
|
|
519
|
+
* command that means exactly "replace `from..to` with this plain text" is
|
|
520
|
+
* `insertFromPaste`, so that is what these become. Dropping them instead
|
|
521
|
+
* would silently swallow the keystroke.
|
|
522
|
+
*/
|
|
523
|
+
const TEXT_FALLBACK_COMMANDS = {
|
|
524
|
+
insertText: "insertFromPaste",
|
|
525
|
+
insertCompositionText: "insertFromPaste",
|
|
526
|
+
insertReplacementText: "insertFromPaste"
|
|
527
|
+
};
|
|
528
|
+
/**
|
|
529
|
+
* §18 v3 (floating toolbar follow-up): the command name a `beforeinput`'s
|
|
530
|
+
* `inputType` maps to, independent of whether a position is resolvable at
|
|
531
|
+
* all — `classifyBeforeInput`'s own name resolution (its `COMMAND_INPUT_TYPES`/
|
|
532
|
+
* `TEXT_FALLBACK_COMMANDS` steps, minus the native-range test, which needs a
|
|
533
|
+
* range to test) is exactly this, but it never runs that far when there is no
|
|
534
|
+
* range to classify. Used only to queue a pending intent in that situation;
|
|
535
|
+
* `null` for an inputType with no command name (the same set that classifies
|
|
536
|
+
* `ignore` when positions *are* resolvable) — nothing to queue for those.
|
|
537
|
+
*/
|
|
538
|
+
function commandNameForInputType(inputType) {
|
|
539
|
+
if (COMMAND_INPUT_TYPES.has(inputType)) return inputType;
|
|
540
|
+
return TEXT_FALLBACK_COMMANDS[inputType] ?? null;
|
|
541
|
+
}
|
|
542
|
+
const RICH_TEXT_LEAF_NODE_TYPES = new Set(RICH_TEXT_LEAF_TYPES);
|
|
543
|
+
/** §18 v3 §4.3 bounds, enforced on the way out as well as on the way in: a
|
|
544
|
+
* message the other side would drop is one the theme should never send. */
|
|
545
|
+
const POSITION_MAX = 1e6;
|
|
546
|
+
const RICH_TEXT_TEXT_MAX = 65536;
|
|
547
|
+
const RICH_TEXT_MARKS_MAX = 32;
|
|
548
|
+
const RICH_TEXT_MARK_LENGTH_MAX = 32;
|
|
549
|
+
const RECT_MAX = 1e6;
|
|
550
|
+
function isPosition(value) {
|
|
551
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= POSITION_MAX;
|
|
552
|
+
}
|
|
553
|
+
/** The node element (block or leaf) a DOM point belongs to, bounded by the
|
|
554
|
+
* rich-text root. Mark elements, a table's `tbody` and a code block's `code`
|
|
555
|
+
* are not nodes and carry no stamp, so `closest` walks straight past them. */
|
|
556
|
+
function nodeElementOf(root, node) {
|
|
557
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
558
|
+
if (element === null || !root.contains(element)) return null;
|
|
559
|
+
const found = element.closest("[data-eldra-node][data-eldra-pos]");
|
|
560
|
+
return found !== null && root.contains(found) ? found : null;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* §18 v3: "the target range stays inside one text run of one block", read
|
|
564
|
+
* strictly — every case the theme cannot describe as a pure text change goes
|
|
565
|
+
* to Studio instead.
|
|
566
|
+
*
|
|
567
|
+
* - A **non-collapsed** range must live in a single `Text` node. A selection
|
|
568
|
+
* crossing a mark or a block boundary changes structure, not just text.
|
|
569
|
+
* - A **collapsed** range is native only for an insertion. A collapsed
|
|
570
|
+
* delete is a join: backspace at the start of a run pulls in whatever is
|
|
571
|
+
* before it, which is a structural edit however small it looks.
|
|
572
|
+
* - A collapsed insertion must sit **strictly inside** a text run, not on a
|
|
573
|
+
* boundary with a mark element on the other side. `Rich |<strong>bold` is
|
|
574
|
+
* ambiguous — the browser picks whether the character inherits the mark,
|
|
575
|
+
* and its answer is not the document's — so Studio decides it.
|
|
576
|
+
* - Either way the containing node element must exist and must not be a leaf.
|
|
577
|
+
*/
|
|
578
|
+
function isNativeTextRange(root, inputType, range) {
|
|
579
|
+
const host = nodeElementOf(root, range.startContainer);
|
|
580
|
+
if (host === null || host !== nodeElementOf(root, range.endContainer)) return false;
|
|
581
|
+
if (RICH_TEXT_LEAF_NODE_TYPES.has(host.getAttribute("data-eldra-node") ?? "")) return false;
|
|
582
|
+
if (range.startContainer !== range.endContainer) return false;
|
|
583
|
+
if (range.startContainer.nodeType !== 3) return false;
|
|
584
|
+
const text = range.startContainer;
|
|
585
|
+
if (range.startOffset !== range.endOffset) return true;
|
|
586
|
+
if (inputType !== "insertText" && inputType !== "insertCompositionText") return false;
|
|
587
|
+
return !atMarkBoundary(host, text, range.startOffset);
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Is a collapsed caret sitting where one mark ends and another begins?
|
|
591
|
+
*
|
|
592
|
+
* `Rich |<strong>bold` and `<strong>bold|</strong> more` are the same
|
|
593
|
+
* question from either side: whether the next character inherits the mark is
|
|
594
|
+
* the browser's guess, and its guess is not the document's. The caret is on
|
|
595
|
+
* such a boundary when it is at the edge of a text node that lives **inside** a
|
|
596
|
+
* mark element, or at the edge of a bare run with an element on that side.
|
|
597
|
+
* Wrappers that are not marks — a code block's `code`, a table's `tbody` —
|
|
598
|
+
* are transparent here exactly as they are everywhere else in §18 v3.
|
|
599
|
+
*/
|
|
600
|
+
function atMarkBoundary(host, text, offset) {
|
|
601
|
+
const atStart = offset === 0;
|
|
602
|
+
if (!atStart && offset !== text.data.length) return false;
|
|
603
|
+
const parent = text.parentElement;
|
|
604
|
+
if (parent !== null && parent !== host && richTextMarkNameOf(parent) !== null) return true;
|
|
605
|
+
return isElementNode(atStart ? text.previousSibling : text.nextSibling);
|
|
606
|
+
}
|
|
607
|
+
function isElementNode(node) {
|
|
608
|
+
return node !== null && node.nodeType === 1;
|
|
609
|
+
}
|
|
610
|
+
const IGNORED = {
|
|
611
|
+
kind: "ignore",
|
|
612
|
+
from: 0,
|
|
613
|
+
to: 0
|
|
614
|
+
};
|
|
615
|
+
/**
|
|
616
|
+
* §18 v3 (spec §4.1): decide what a `beforeinput` inside a rich-text root
|
|
617
|
+
* is. Exported so the Playwright stub theme and Studio's tests classify by
|
|
618
|
+
* the same rules the runtime does, rather than a second copy of them.
|
|
619
|
+
*
|
|
620
|
+
* `getTargetRanges()` is the authority — it is the range the browser is about
|
|
621
|
+
* to change, which for a backspace at the start of a paragraph already spans
|
|
622
|
+
* the block boundary and therefore classifies as a command without the
|
|
623
|
+
* runtime having to reason about intent. The current selection is only a
|
|
624
|
+
* fallback for engines (and jsdom) that do not implement it.
|
|
625
|
+
*/
|
|
626
|
+
function classifyBeforeInput(event, root) {
|
|
627
|
+
const name = event.inputType;
|
|
628
|
+
const ranges = typeof event.getTargetRanges === "function" ? event.getTargetRanges() : [];
|
|
629
|
+
const multi = ranges.length > 1;
|
|
630
|
+
const range = ranges[0] ?? currentSelectionRange();
|
|
631
|
+
if (range === null) return IGNORED;
|
|
632
|
+
const positions = domRangeToPositions(root, range);
|
|
633
|
+
if (positions === null) return IGNORED;
|
|
634
|
+
const { from, to } = positions;
|
|
635
|
+
if (!isPosition(from) || !isPosition(to)) return IGNORED;
|
|
636
|
+
if (!multi && NATIVE_INPUT_TYPES.has(name) && isNativeTextRange(root, name, range)) return {
|
|
637
|
+
kind: "native",
|
|
638
|
+
from,
|
|
639
|
+
to
|
|
640
|
+
};
|
|
641
|
+
if (COMMAND_INPUT_TYPES.has(name)) return {
|
|
642
|
+
kind: "command",
|
|
643
|
+
from,
|
|
644
|
+
to,
|
|
645
|
+
name
|
|
646
|
+
};
|
|
647
|
+
const fallback = TEXT_FALLBACK_COMMANDS[name];
|
|
648
|
+
if (fallback !== void 0) return {
|
|
649
|
+
kind: "command",
|
|
650
|
+
from,
|
|
651
|
+
to,
|
|
652
|
+
name: fallback
|
|
653
|
+
};
|
|
654
|
+
return {
|
|
655
|
+
kind: "ignore",
|
|
656
|
+
from,
|
|
657
|
+
to
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function currentSelectionRange() {
|
|
661
|
+
const selection = typeof document.getSelection === "function" ? document.getSelection() : null;
|
|
662
|
+
if (selection === null || selection.rangeCount === 0) return null;
|
|
663
|
+
return selection.getRangeAt(0);
|
|
664
|
+
}
|
|
665
|
+
const STEGA_DELIMITER = "";
|
|
666
|
+
/**
|
|
667
|
+
* `Node.prototype`'s own `textContent` accessor, resolved on first use so that
|
|
668
|
+
* importing this module where there is no DOM stays harmless. `guardRendererText`
|
|
669
|
+
* shadows `textContent` on the field elements it marks and needs the platform
|
|
670
|
+
* pair to read and to write through.
|
|
671
|
+
*/
|
|
672
|
+
let nodeTextContent;
|
|
673
|
+
function platformTextContent() {
|
|
674
|
+
if (nodeTextContent === void 0 && typeof Node !== "undefined") nodeTextContent = Object.getOwnPropertyDescriptor(Node.prototype, "textContent");
|
|
675
|
+
return nodeTextContent;
|
|
676
|
+
}
|
|
677
|
+
/** True only for the duration of a `setFieldText` call. Module scope, not
|
|
678
|
+
* runtime scope: two overlay runtimes over one document install one guard
|
|
679
|
+
* between them, and either one's repair has to pass through it. */
|
|
680
|
+
let writingFieldText = false;
|
|
681
|
+
/**
|
|
682
|
+
* Write a field's whole text as the overlay, past `guardRendererText`'s filter.
|
|
683
|
+
* The overlay's own writes are not renderer echoes: `restoreEditingFocus`
|
|
684
|
+
* repairs a field whose element a renderer pass replaced outright, and that
|
|
685
|
+
* repair has to land exactly when the filter is refusing the stale value it is
|
|
686
|
+
* repairing.
|
|
687
|
+
*/
|
|
688
|
+
function setFieldText(span, value) {
|
|
689
|
+
writingFieldText = true;
|
|
690
|
+
try {
|
|
691
|
+
span.textContent = value;
|
|
692
|
+
} finally {
|
|
693
|
+
writingFieldText = false;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
/** A wheel gesture is considered settled this long after its last event. */
|
|
697
|
+
const FRAMING_WHEEL_SETTLE_MS = 200;
|
|
698
|
+
/** Focal/zoom values are stored and posted at 1e-6 \u2014 far below one device
|
|
699
|
+
* pixel on any frame \u2014 so accumulated drag steps do not leak float drift
|
|
700
|
+
* into the marking attribute or the value Studio persists. */
|
|
701
|
+
const FRAMING_PRECISION = 1e6;
|
|
702
|
+
const roundFramingValue = (value) => ({
|
|
703
|
+
x: Math.round(value.x * FRAMING_PRECISION) / FRAMING_PRECISION,
|
|
704
|
+
y: Math.round(value.y * FRAMING_PRECISION) / FRAMING_PRECISION,
|
|
705
|
+
zoom: Math.round(value.zoom * FRAMING_PRECISION) / FRAMING_PRECISION
|
|
706
|
+
});
|
|
707
|
+
const CHROME_STYLES = `
|
|
708
|
+
.box { position: fixed; pointer-events: none; display: none; border: 0; border-radius: 2px;
|
|
709
|
+
box-shadow: inset 0 0 0 1px #025df3; z-index: 2147483646; }
|
|
710
|
+
.box.hover { outline: 1px dotted #025df3; outline-offset: -1px; box-shadow: none; }
|
|
711
|
+
.box.drop { box-shadow: inset 0 0 0 2px #059669; }
|
|
712
|
+
.box.framing { box-shadow: inset 0 0 0 1px #025df3; z-index: 2147483647; }
|
|
713
|
+
.badge { position: fixed; display: none; pointer-events: none; background: #025df3;
|
|
714
|
+
color: #fff; font: 12px/1.4 system-ui, sans-serif; padding: 2px 6px;
|
|
715
|
+
border-radius: 4px; z-index: 2147483647; }
|
|
716
|
+
`;
|
|
717
|
+
function createOverlayRuntime(opts) {
|
|
718
|
+
const root = opts.root ?? document;
|
|
719
|
+
const eventTarget = root instanceof Document ? root : root;
|
|
720
|
+
let mode = "preview";
|
|
721
|
+
let selectedId = null;
|
|
722
|
+
let selectedLayoutNodeId = null;
|
|
723
|
+
let selectedReusablePlacementId = null;
|
|
724
|
+
let host = null;
|
|
725
|
+
let styleEl = null;
|
|
726
|
+
let hoverBox = null;
|
|
727
|
+
/** The block last reported by onPointerOver, re-read by reposition() on
|
|
728
|
+
* every scroll/resize so the hover box tracks it instead of staying
|
|
729
|
+
* anchored to the rect captured at pointerover time. Cleared when the
|
|
730
|
+
* pointer leaves the document, on setMode's hide-hover branch, and on
|
|
731
|
+
* stop(). */
|
|
732
|
+
let hoveredElement = null;
|
|
733
|
+
let selectedBox = null;
|
|
734
|
+
let dropIndicator = null;
|
|
735
|
+
let framingBox = null;
|
|
736
|
+
let framingBadge = null;
|
|
737
|
+
let dragPayload = null;
|
|
738
|
+
let observer = null;
|
|
739
|
+
let started = false;
|
|
740
|
+
/** Coalesces reportBlocks() calls scheduled by reposition() (bound to
|
|
741
|
+
* window scroll/resize) into at most one per animation frame. Cancelled
|
|
742
|
+
* in stop(); scheduling is a no-op once stopped. */
|
|
743
|
+
let blocksRaf = null;
|
|
744
|
+
/** §17 capability gate: set via setFramingEnabled, negotiated from the
|
|
745
|
+
* editor's editor:hello capabilities. Defaults closed. */
|
|
746
|
+
let framingEnabled = false;
|
|
747
|
+
/** §18 v3 capability gate: set via setRichTextEnabled, negotiated from the
|
|
748
|
+
* `rich-text-inline` capability. Defaults closed. */
|
|
749
|
+
let richTextEnabled = false;
|
|
750
|
+
/** `block-hover` capability gate: set via setBlockHoverEnabled, negotiated
|
|
751
|
+
* from the editor's editor:hello capabilities. Defaults closed. */
|
|
752
|
+
let blockHoverEnabled = false;
|
|
753
|
+
/** The block last *posted* over `theme:block-hovered` — null once the leave
|
|
754
|
+
* message went out. Distinct from `hoveredElement`, which is the theme's
|
|
755
|
+
* own hover-box anchor and moves with every pointerover: comparing the two
|
|
756
|
+
* is what keeps a pointer wandering inside one block from posting again. */
|
|
757
|
+
let reportedHoverElement = null;
|
|
758
|
+
/** Coalesces `theme:block-hovered` posts into at most one per animation
|
|
759
|
+
* frame, like blocksRaf. Cancelled in stop(); scheduling is a no-op once
|
|
760
|
+
* stopped. */
|
|
761
|
+
let hoverReportRaf = null;
|
|
762
|
+
/** Set when the pending frame must post even though the hovered block did
|
|
763
|
+
* not change — a scroll or resize moved its rect under a still-hovered
|
|
764
|
+
* pointer, which no pointer event reports. */
|
|
765
|
+
let hoverGeometryStale = false;
|
|
766
|
+
/**
|
|
767
|
+
* §18 v3 (floating toolbar follow-up): each editable rich-text root's
|
|
768
|
+
* prior inline `white-space`/`word-wrap` declarations, captured the one
|
|
769
|
+
* time `applyRichTextEditable` forces them for editing and restored
|
|
770
|
+
* exactly once the root stops being editable — never re-captured while
|
|
771
|
+
* still editable (a rerender that keeps the marked root, or a `rescan()`
|
|
772
|
+
* that runs this function again with nothing changed, must not overwrite
|
|
773
|
+
* the original with the forced value). Keyed by element, so a rerender
|
|
774
|
+
* that replaces the root simply never restores the detached one — nothing
|
|
775
|
+
* to restore it to matters once it is gone.
|
|
776
|
+
*/
|
|
777
|
+
const richTextPriorWhiteSpace = /* @__PURE__ */ new WeakMap();
|
|
778
|
+
/** §18 v3: the rich-text root Studio's editor is currently active for, if
|
|
779
|
+
* any. While set, reposition() re-asserts the mark once per animation
|
|
780
|
+
* frame. */
|
|
781
|
+
let editingRichTextRoot = null;
|
|
782
|
+
/**
|
|
783
|
+
* The full identity (entry, field, locale, layout placement) of
|
|
784
|
+
* `editingRichTextRoot`, captured from the element itself — via
|
|
785
|
+
* `richTextIdentityOf`, which reads `closest('[data-eldra-layout-node]')`
|
|
786
|
+
* — at the moment it was marked, while it was still attached. A rerender
|
|
787
|
+
* can detach that element before its replacement is found; `closest` on a
|
|
788
|
+
* detached element cannot see its former layout ancestor, so re-deriving
|
|
789
|
+
* the identity from `editingRichTextRoot` at that point would silently
|
|
790
|
+
* drop `layoutNodeId`/`reusablePlacementId` and let `findRichTextRoot`'s
|
|
791
|
+
* unplaced fallback resolve to the *first* placement of the field in
|
|
792
|
+
* document order — the wrong one, on a page that places the same
|
|
793
|
+
* entry+field twice. Both re-find paths (`reassertRichTextEditingRoot`)
|
|
794
|
+
* must use this captured identity instead. */
|
|
795
|
+
let editingRichTextIdentity = null;
|
|
796
|
+
/** Coalesces the editing-root mark re-assert, like blocksRaf. */
|
|
797
|
+
let richTextRaf = null;
|
|
798
|
+
/** Coalesces scheduleRichTextSelectionRepost's re-post, like richTextRaf. */
|
|
799
|
+
let richTextSelectionRepostRaf = null;
|
|
800
|
+
/** §18 v3: the per-field op counter. Keyed by field identity rather than by
|
|
801
|
+
* element, because a rerender replaces the element while the field — and
|
|
802
|
+
* therefore the sequence Studio acks against — is the same one. */
|
|
803
|
+
const richTextRevisions = /* @__PURE__ */ new Map();
|
|
804
|
+
/**
|
|
805
|
+
* §18 v3: the fields whose re-render is deferred, mapped to the latest
|
|
806
|
+
* native op revision the theme posted for them.
|
|
807
|
+
*
|
|
808
|
+
* A field enters this map when the theme posts a native text op — from that
|
|
809
|
+
* moment the browser, not the renderer, owns its DOM — and leaves it only
|
|
810
|
+
* when Studio hands ownership back: an `applied` asking for a re-render, an
|
|
811
|
+
* `applied` from ahead of the theme, a command (which Studio performs, so
|
|
812
|
+
* its result must be rendered), or the edit ending. An
|
|
813
|
+
* `applied { rerender: false }` **confirms** the deferral rather than
|
|
814
|
+
* ending it: Studio is agreeing the theme's DOM is already right, which is
|
|
815
|
+
* precisely the state that has to persist across the debounced write's
|
|
816
|
+
* later content update.
|
|
817
|
+
*/
|
|
818
|
+
const deferredRenders = /* @__PURE__ */ new Map();
|
|
819
|
+
const richTextRenderListeners = /* @__PURE__ */ new Set();
|
|
820
|
+
/** §18 v3: a native `beforeinput` the browser is about to perform — its
|
|
821
|
+
* target range, captured before the DOM moves, and posted on the `input`
|
|
822
|
+
* that follows. */
|
|
823
|
+
let pendingNativeInput = null;
|
|
824
|
+
/** §18 v3: the range a composition replaces, captured on `compositionstart`;
|
|
825
|
+
* the whole composition is posted once, on `compositionend`. */
|
|
826
|
+
let composition = null;
|
|
827
|
+
/**
|
|
828
|
+
* §18 v3 (the floating-toolbar follow-up, generalized and then serialized):
|
|
829
|
+
* an ordered, per-field buffer of the commands a `beforeinput`
|
|
830
|
+
* would have posted while its root could not yet accept one — either not
|
|
831
|
+
* marked editing at all yet (a click immediately followed by
|
|
832
|
+
* typing, before Studio's `editor:rich-text-editing` echo arrives ~14ms
|
|
833
|
+
* later) or marked but with no resolvable selection (the window
|
|
834
|
+
* between the theme's own content-update re-render and
|
|
835
|
+
* `editor:rich-text-applied` restoring the caret).
|
|
836
|
+
*
|
|
837
|
+
* Why one at a time: Studio applies a `theme:rich-text-command` literally at the
|
|
838
|
+
* `from`/`to` it was posted with — no position tracking between messages —
|
|
839
|
+
* so flushing more than one entry at the *same* frozen position reverses
|
|
840
|
+
* typed order and misplaces a later structural command. Only one entry is
|
|
841
|
+
* ever in flight: `awaitingRevision` is the revision of the entry most
|
|
842
|
+
* recently posted but not yet acked, or `null` once nothing has posted at
|
|
843
|
+
* all for the current buffer. The *next* entry posts only once
|
|
844
|
+
* `restoreRichTextSelection` runs for a revision at or beyond it (`>=`, not
|
|
845
|
+
* `===`; see `flushNextPendingRichTextIntent`) — an ack strictly behind it
|
|
846
|
+
* neither advances nor posts. A run of plain typed characters (`insertText`)
|
|
847
|
+
* coalesces into one entry while queuing (`queueRichTextIntent`), so the
|
|
848
|
+
* common case (typing) still reaches Studio as a single command, not N
|
|
849
|
+
* serialized round trips.
|
|
850
|
+
*
|
|
851
|
+
* Flushed by whichever of two triggers comes first: the root being marked
|
|
852
|
+
* editing (`setRichTextEditing`'s `applyRichTextEditing(element, true)`)
|
|
853
|
+
* or `restoreRichTextSelection` actually placing a selection. At most 64
|
|
854
|
+
* entries — coalescing keeps this small in practice — a further one drops
|
|
855
|
+
* the oldest (logged via `console.debug`), so a runaway burst never blocks
|
|
856
|
+
* new input. Cleared on blur, on the editing mark coming off (deactivate,
|
|
857
|
+
* a mode change, `stop()`, or the root vanishing — all of which route
|
|
858
|
+
* through `unmarkRichTextEditing`), so a stale buffer can never flush
|
|
859
|
+
* against an unrelated later selection, and dropping the rest of an
|
|
860
|
+
* in-flight sequence is exactly that: a blur mid-sequence clears whatever
|
|
861
|
+
* had not posted yet.
|
|
862
|
+
*/
|
|
863
|
+
let pendingRichTextIntents = null;
|
|
864
|
+
/** §18 v3: the field the last selection report named, so leaving it can post
|
|
865
|
+
* exactly one blur. */
|
|
866
|
+
let reportedSelectionField = null;
|
|
867
|
+
/**
|
|
868
|
+
* §18 v3 (floating toolbar): the last real anchor/head reported for each
|
|
869
|
+
* field, keyed like `richTextRevisions`. Read back when the DOM selection
|
|
870
|
+
* has no range (e.g. `removeAllRanges()` after a re-render or a
|
|
871
|
+
* programmatic change) but the editing root still has document focus — the
|
|
872
|
+
* floating toolbar has nowhere else to get a position from, and the field
|
|
873
|
+
* has not actually been left.
|
|
874
|
+
*/
|
|
875
|
+
const lastRichTextPositions = /* @__PURE__ */ new Map();
|
|
876
|
+
/** Coalesces selectionchange reports to one per animation frame. */
|
|
877
|
+
let selectionRaf = null;
|
|
878
|
+
let activeEdit = null;
|
|
879
|
+
const debounceTimers = /* @__PURE__ */ new Map();
|
|
880
|
+
/**
|
|
881
|
+
* Per field (`entryId|fieldPath|locale`), the value the overlay last posted
|
|
882
|
+
* as `theme:text-edited` and has not yet seen the editor echo back. See
|
|
883
|
+
* `hasUnacknowledgedTextEdit`.
|
|
884
|
+
*/
|
|
885
|
+
const postedText = /* @__PURE__ */ new Map();
|
|
886
|
+
let framing = null;
|
|
887
|
+
function rectOf(element) {
|
|
888
|
+
const rect = element.getBoundingClientRect();
|
|
889
|
+
return {
|
|
890
|
+
x: rect.x,
|
|
891
|
+
y: rect.y,
|
|
892
|
+
width: rect.width,
|
|
893
|
+
height: rect.height
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
function mountHost() {
|
|
897
|
+
host = document.createElement("div");
|
|
898
|
+
host.setAttribute("data-eldra-overlay-host", "");
|
|
899
|
+
const shadow = host.attachShadow({ mode: "closed" });
|
|
900
|
+
const style = document.createElement("style");
|
|
901
|
+
style.textContent = CHROME_STYLES;
|
|
902
|
+
styleEl = style;
|
|
903
|
+
hoverBox = document.createElement("div");
|
|
904
|
+
hoverBox.className = "box hover";
|
|
905
|
+
selectedBox = document.createElement("div");
|
|
906
|
+
selectedBox.className = "box";
|
|
907
|
+
dropIndicator = document.createElement("div");
|
|
908
|
+
dropIndicator.className = "box drop";
|
|
909
|
+
framingBox = document.createElement("div");
|
|
910
|
+
framingBox.className = "box framing";
|
|
911
|
+
framingBadge = document.createElement("div");
|
|
912
|
+
framingBadge.className = "badge";
|
|
913
|
+
shadow.append(style, hoverBox, selectedBox, dropIndicator, framingBox, framingBadge);
|
|
914
|
+
document.body.appendChild(host);
|
|
915
|
+
}
|
|
916
|
+
function positionBox(box, element) {
|
|
917
|
+
if (element === null || mode !== "edit") {
|
|
918
|
+
box.style.display = "none";
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
const rect = element.getBoundingClientRect();
|
|
922
|
+
Object.assign(box.style, {
|
|
923
|
+
display: "block",
|
|
924
|
+
left: `${rect.x}px`,
|
|
925
|
+
top: `${rect.y}px`,
|
|
926
|
+
width: `${rect.width}px`,
|
|
927
|
+
height: `${rect.height}px`
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
function selectedElement() {
|
|
931
|
+
if (selectedLayoutNodeId !== null) {
|
|
932
|
+
const escapedNodeId = escapeAttributeValue(selectedLayoutNodeId);
|
|
933
|
+
const escapedReusablePlacementId = selectedReusablePlacementId === null ? null : escapeAttributeValue(selectedReusablePlacementId);
|
|
934
|
+
const selector = escapedReusablePlacementId === null ? `[data-eldra-layout-node="${escapedNodeId}"]` : `[data-eldra-layout-node="${escapedNodeId}"][data-eldra-reusable-placement="${escapedReusablePlacementId}"]`;
|
|
935
|
+
const placement = root.querySelector(selector);
|
|
936
|
+
if (placement !== null) return placement;
|
|
937
|
+
}
|
|
938
|
+
if (selectedId === null) return null;
|
|
939
|
+
const escaped = escapeAttributeValue(selectedId);
|
|
940
|
+
return root.querySelector(`[data-eldra-block="${escaped}"]`);
|
|
941
|
+
}
|
|
942
|
+
function escapeAttributeValue(value) {
|
|
943
|
+
return globalThis.CSS?.escape(value) ?? value.replace(/["\\]/g, "\\$&");
|
|
944
|
+
}
|
|
945
|
+
function framingImageFor(target) {
|
|
946
|
+
return target.closest("img[data-eldra-framing]");
|
|
947
|
+
}
|
|
948
|
+
/** Behaviour item 1: the image's own block is selected, or (when no layout
|
|
949
|
+
* node is selected) the image marks itself with the selected entry id. */
|
|
950
|
+
function ownsSelectedBlock(image) {
|
|
951
|
+
const block = image.closest("[data-eldra-block]");
|
|
952
|
+
if (block !== null && block === selectedElement()) return true;
|
|
953
|
+
if (selectedLayoutNodeId === null && selectedId !== null) return image.getAttribute("data-eldra-framing-entry") === selectedId;
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
function findFramingImage(entryId, fieldPath) {
|
|
957
|
+
const escapedField = escapeAttributeValue(fieldPath);
|
|
958
|
+
const escapedEntry = escapeAttributeValue(entryId);
|
|
959
|
+
return root.querySelector(`img[data-eldra-framing="${escapedField}"][data-eldra-framing-entry="${escapedEntry}"]`);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* §18 v3: the rich-text root a message names. Resolved by attributes (not
|
|
963
|
+
* a remembered node) because a rerender replaces the element while keeping
|
|
964
|
+
* `data-eldra-entry` / `-field` / `-locale` — the same reason framing
|
|
965
|
+
* re-resolves its image in rescan(). `locale` is compared against the
|
|
966
|
+
* attribute, which the renderer omits entirely for an unlocalized field,
|
|
967
|
+
* so `null` matches exactly that case.
|
|
968
|
+
*/
|
|
969
|
+
function findRichTextRoot(entryId, fieldPath, locale, layoutNodeId, reusablePlacementId) {
|
|
970
|
+
const selector = `[data-eldra-rich-text][data-eldra-field="${escapeAttributeValue(fieldPath)}"][data-eldra-entry="${escapeAttributeValue(entryId)}"]`;
|
|
971
|
+
let fallback = null;
|
|
972
|
+
for (const candidate of root.querySelectorAll(selector)) {
|
|
973
|
+
if (candidate.getAttribute("data-eldra-locale") !== locale) continue;
|
|
974
|
+
const identity = layoutIdentityOf(candidate);
|
|
975
|
+
if (layoutNodeId !== void 0 && identity.layoutNodeId !== layoutNodeId) continue;
|
|
976
|
+
if (reusablePlacementId !== void 0 && identity.reusablePlacementId !== reusablePlacementId) continue;
|
|
977
|
+
if (layoutNodeId === void 0 && reusablePlacementId === void 0) {
|
|
978
|
+
fallback ??= candidate;
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
return candidate;
|
|
982
|
+
}
|
|
983
|
+
return fallback;
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* §18 v3: mark (or unmark) a root as the one Studio is editing. That is the
|
|
987
|
+
* whole of it. I17 hid the root's children behind Studio's overlay editor;
|
|
988
|
+
* v3 edits the theme's own render in place, so hiding it would hide the very
|
|
989
|
+
* text the operator is typing into.
|
|
990
|
+
*/
|
|
991
|
+
function applyRichTextEditing(element, active) {
|
|
992
|
+
if (active) element.setAttribute("data-eldra-rich-text-editing", "");
|
|
993
|
+
else element.removeAttribute("data-eldra-rich-text-editing");
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Every rich-text root is `contenteditable` throughout edit mode, but that
|
|
997
|
+
* is not the same as Studio actually editing it: `setRichTextEditing`
|
|
998
|
+
* arrives asynchronously (Studio's headless editor negotiates the field
|
|
999
|
+
* before it marks the root), so there is a window — and, if the first
|
|
1000
|
+
* activation message is ever dropped, an unbounded one — where a root
|
|
1001
|
+
* accepts focus and keystrokes with no document behind them on Studio's
|
|
1002
|
+
* side. `onBeforeInput`/`onCompositionStart` must fail closed on that
|
|
1003
|
+
* window exactly as they fail closed on an unnameable inputType.
|
|
1004
|
+
*/
|
|
1005
|
+
function isRichTextEditingActive(element) {
|
|
1006
|
+
return element.hasAttribute("data-eldra-rich-text-editing");
|
|
1007
|
+
}
|
|
1008
|
+
/** Unmark whatever is currently marked, including a root a rerender
|
|
1009
|
+
* replaced while the mark was on it. Posts nothing, and says nothing about
|
|
1010
|
+
* whose render is deferred — the two are separate questions. */
|
|
1011
|
+
function unmarkRichTextEditing() {
|
|
1012
|
+
if (richTextRaf !== null) {
|
|
1013
|
+
cancelAnimationFrame(richTextRaf);
|
|
1014
|
+
richTextRaf = null;
|
|
1015
|
+
}
|
|
1016
|
+
const current = editingRichTextRoot;
|
|
1017
|
+
editingRichTextRoot = null;
|
|
1018
|
+
editingRichTextIdentity = null;
|
|
1019
|
+
pendingRichTextIntents = null;
|
|
1020
|
+
if (current !== null && !current.isConnected) applyRichTextEditing(current, false);
|
|
1021
|
+
for (const marked of root.querySelectorAll("[data-eldra-rich-text-editing]")) applyRichTextEditing(marked, false);
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Unmark **and** hand every field back to the renderer. This is the whole
|
|
1025
|
+
* session ending — leaving edit mode, the capability closing, teardown —
|
|
1026
|
+
* where nothing on the page is being typed into any more. Studio closing one
|
|
1027
|
+
* field is not this: see `setRichTextEditing`, which releases only that one,
|
|
1028
|
+
* so a native op still in flight in another placement is not thrown away.
|
|
1029
|
+
*/
|
|
1030
|
+
function clearRichTextEditing() {
|
|
1031
|
+
unmarkRichTextEditing();
|
|
1032
|
+
releaseAllRichTextRenders();
|
|
1033
|
+
}
|
|
1034
|
+
/**
|
|
1035
|
+
* §18 v3: the editing mark must be on whichever element is *currently*
|
|
1036
|
+
* live for the active field, even when a rerender replaced it outright.
|
|
1037
|
+
* Two callers need this, on two different schedules:
|
|
1038
|
+
*
|
|
1039
|
+
* - `scheduleRichTextSync` (below), coalesced to one frame — the same
|
|
1040
|
+
* treatment scheduleReportBlocks() gives block geometry, so a scroll
|
|
1041
|
+
* burst does not flood the main thread;
|
|
1042
|
+
* - `applyRichTextEditable`, called synchronously from `rescan()` on every
|
|
1043
|
+
* `editor:content-update`, which cannot wait a frame: a keystroke can
|
|
1044
|
+
* arrive before the next paint, and `onBeforeInput`'s activation gate
|
|
1045
|
+
* would otherwise prevent it as if Studio had never activated the field.
|
|
1046
|
+
*/
|
|
1047
|
+
function reassertRichTextEditingRoot() {
|
|
1048
|
+
const current = editingRichTextRoot;
|
|
1049
|
+
const identity = editingRichTextIdentity;
|
|
1050
|
+
if (current === null || identity === null) return;
|
|
1051
|
+
if (current.isConnected) {
|
|
1052
|
+
applyRichTextEditing(current, true);
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
const live = findRichTextRoot(identity.entryId, identity.fieldPath, identity.locale, identity.layoutNodeId, identity.reusablePlacementId);
|
|
1056
|
+
if (live === null) {
|
|
1057
|
+
clearRichTextEditing();
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
applyRichTextEditing(current, false);
|
|
1061
|
+
editingRichTextRoot = live;
|
|
1062
|
+
applyRichTextEditing(live, true);
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* §18 v3: while Studio edits a field, re-assert the mark on the live root —
|
|
1066
|
+
* coalesced to one frame, the same treatment scheduleReportBlocks() gives
|
|
1067
|
+
* block geometry, so a scroll burst does not flood the main thread.
|
|
1068
|
+
*/
|
|
1069
|
+
function scheduleRichTextSync() {
|
|
1070
|
+
if (!started || editingRichTextRoot === null || richTextRaf !== null) return;
|
|
1071
|
+
richTextRaf = requestAnimationFrame(() => {
|
|
1072
|
+
richTextRaf = null;
|
|
1073
|
+
reassertRichTextEditingRoot();
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
/** The arguments `findRichTextRoot` takes, from a (possibly detached) root —
|
|
1077
|
+
* so a rerender is followed by identity, placement included. */
|
|
1078
|
+
function richTextLookup(element) {
|
|
1079
|
+
const identity = richTextIdentityOf(element);
|
|
1080
|
+
return [
|
|
1081
|
+
identity.entryId,
|
|
1082
|
+
identity.fieldPath,
|
|
1083
|
+
identity.locale,
|
|
1084
|
+
identity.layoutNodeId,
|
|
1085
|
+
identity.reusablePlacementId
|
|
1086
|
+
];
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* The editing surface. In edit mode with the negotiated `rich-text-inline`
|
|
1090
|
+
* capability every rich-text root becomes `contenteditable` — exactly like
|
|
1091
|
+
* the plain-text spans `applyEditable` handles, which is the point: rich
|
|
1092
|
+
* text is edited the way plain text already is. `spellcheck` is off because
|
|
1093
|
+
* the squiggles would be drawn over a document Studio owns and the theme
|
|
1094
|
+
* cannot correct.
|
|
1095
|
+
*
|
|
1096
|
+
* Outside edit mode, or without the capability, both attributes go: a
|
|
1097
|
+
* published page must never be editable, and a theme must never hand a
|
|
1098
|
+
* caret to an editor that cannot receive what is done with it.
|
|
1099
|
+
*/
|
|
1100
|
+
const RICH_TEXT_WHITE_SPACE_PROP = "white-space";
|
|
1101
|
+
const RICH_TEXT_WORD_WRAP_PROP = "word-wrap";
|
|
1102
|
+
function setOrRemoveStyleProp(element, prop, value) {
|
|
1103
|
+
if (value === "") element.style.removeProperty(prop);
|
|
1104
|
+
else element.style.setProperty(prop, value);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* §18 v3 (floating toolbar follow-up): ProseMirror's own stylesheet sets
|
|
1108
|
+
* `white-space: pre-wrap` and `word-wrap: break-word` on its editable
|
|
1109
|
+
* root, so a run of consecutive spaces and a trailing space both render
|
|
1110
|
+
* (and take up a line box) exactly as Studio's headless editor sees them.
|
|
1111
|
+
* Normal `white-space` collapses that — a paragraph ending in spaces (or
|
|
1112
|
+
* holding nothing else) renders as if it were empty — which is the same
|
|
1113
|
+
* root cause that let a Backspace-join eat real content and a keystroke
|
|
1114
|
+
* land in the previous paragraph: the DOM's caret position and the
|
|
1115
|
+
* document's position had quietly stopped agreeing. Applied as an inline
|
|
1116
|
+
* style rather than a stylesheet rule the theme would have to carry;
|
|
1117
|
+
* captured once per element so `restoreRichTextWhiteSpace` can put back
|
|
1118
|
+
* whatever the theme's own render had there, not just clear it.
|
|
1119
|
+
*
|
|
1120
|
+
* Accepted consequence: `pre-wrap` also preserves a literal `\n` inside a
|
|
1121
|
+
* text leaf's string as a visible line break. The document schema never
|
|
1122
|
+
* emits one — a line break is a `hardBreak` node, not a character inside
|
|
1123
|
+
* text — but nothing here strips or rejects one if it somehow arrives (a
|
|
1124
|
+
* paste that bypassed normalization, say). That is out of the normal
|
|
1125
|
+
* schema path and not specifically guarded against; the character still
|
|
1126
|
+
* counts as an ordinary position like any other (see
|
|
1127
|
+
* `richTextPositions.ts`'s `richTextNodeSize`/`resolveDomPosition`, which
|
|
1128
|
+
* have no special case for it).
|
|
1129
|
+
*/
|
|
1130
|
+
function applyRichTextWhiteSpace(element) {
|
|
1131
|
+
if (richTextPriorWhiteSpace.has(element)) return;
|
|
1132
|
+
richTextPriorWhiteSpace.set(element, {
|
|
1133
|
+
whiteSpace: element.style.getPropertyValue(RICH_TEXT_WHITE_SPACE_PROP),
|
|
1134
|
+
wordWrap: element.style.getPropertyValue(RICH_TEXT_WORD_WRAP_PROP)
|
|
1135
|
+
});
|
|
1136
|
+
element.style.setProperty(RICH_TEXT_WHITE_SPACE_PROP, "pre-wrap");
|
|
1137
|
+
element.style.setProperty(RICH_TEXT_WORD_WRAP_PROP, "break-word");
|
|
1138
|
+
}
|
|
1139
|
+
/** The inverse of `applyRichTextWhiteSpace`: restores exactly the two
|
|
1140
|
+
* declarations it changed, to whatever they were before — including
|
|
1141
|
+
* nothing, which removes them rather than leaving an empty string behind. */
|
|
1142
|
+
function restoreRichTextWhiteSpace(element) {
|
|
1143
|
+
const prior = richTextPriorWhiteSpace.get(element);
|
|
1144
|
+
if (prior === void 0) return;
|
|
1145
|
+
richTextPriorWhiteSpace.delete(element);
|
|
1146
|
+
setOrRemoveStyleProp(element, RICH_TEXT_WHITE_SPACE_PROP, prior.whiteSpace);
|
|
1147
|
+
setOrRemoveStyleProp(element, RICH_TEXT_WORD_WRAP_PROP, prior.wordWrap);
|
|
1148
|
+
}
|
|
1149
|
+
function applyRichTextEditable() {
|
|
1150
|
+
const editable = mode === "edit" && richTextEnabled;
|
|
1151
|
+
for (const element of root.querySelectorAll("[data-eldra-rich-text]")) if (editable) {
|
|
1152
|
+
element.setAttribute("contenteditable", "true");
|
|
1153
|
+
element.setAttribute("spellcheck", "false");
|
|
1154
|
+
applyRichTextWhiteSpace(element);
|
|
1155
|
+
} else {
|
|
1156
|
+
element.removeAttribute("contenteditable");
|
|
1157
|
+
element.removeAttribute("spellcheck");
|
|
1158
|
+
restoreRichTextWhiteSpace(element);
|
|
1159
|
+
}
|
|
1160
|
+
if (editable) reassertRichTextEditingRoot();
|
|
1161
|
+
else {
|
|
1162
|
+
pendingNativeInput = null;
|
|
1163
|
+
composition = null;
|
|
1164
|
+
reportedSelectionField = null;
|
|
1165
|
+
releaseAllRichTextRenders();
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
/** The rich-text root a DOM node sits in, but only while that root is a live
|
|
1169
|
+
* editing surface — so a stale selection in a preview-mode page, or one in a
|
|
1170
|
+
* theme whose editor never negotiated the capability, reports nothing. */
|
|
1171
|
+
function editableRichTextRootOf(node) {
|
|
1172
|
+
if (node === null || mode !== "edit" || !richTextEnabled) return null;
|
|
1173
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
1174
|
+
if (element === null) return null;
|
|
1175
|
+
const found = element.closest("[data-eldra-rich-text][contenteditable=\"true\"]");
|
|
1176
|
+
if (found === null) return null;
|
|
1177
|
+
const scope = root instanceof Document ? root.documentElement : root;
|
|
1178
|
+
return scope === null || scope.contains(found) ? found : null;
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* §18 v3: a field's identity as a map key. The layout identity is part of
|
|
1182
|
+
* it, not decoration: the same entry can be placed twice on a page (a layout
|
|
1183
|
+
* node, a reusable placement), and those two renders are two independent
|
|
1184
|
+
* editing surfaces. Keying only by entry/field/locale would let a native op
|
|
1185
|
+
* in one defer — and re-stamp, and ack — the other.
|
|
1186
|
+
*
|
|
1187
|
+
* NUL cannot appear in an attribute value, so no combination can collide
|
|
1188
|
+
* with another by accident.
|
|
1189
|
+
*/
|
|
1190
|
+
function richTextKey(identity) {
|
|
1191
|
+
return [
|
|
1192
|
+
identity.entryId,
|
|
1193
|
+
identity.fieldPath,
|
|
1194
|
+
identity.locale ?? "",
|
|
1195
|
+
identity.layoutNodeId ?? "",
|
|
1196
|
+
identity.reusablePlacementId ?? ""
|
|
1197
|
+
].join("\0");
|
|
1198
|
+
}
|
|
1199
|
+
/** The full identity of a rendered root, marking attributes included. */
|
|
1200
|
+
function richTextIdentityOf(element) {
|
|
1201
|
+
return {
|
|
1202
|
+
...metadataOf(element),
|
|
1203
|
+
...layoutIdentityOf(element)
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
function richTextKeyOf(element) {
|
|
1207
|
+
return richTextKey(richTextIdentityOf(element));
|
|
1208
|
+
}
|
|
1209
|
+
function revisionOf(key) {
|
|
1210
|
+
return richTextRevisions.get(key) ?? 0;
|
|
1211
|
+
}
|
|
1212
|
+
function nextRevision(key) {
|
|
1213
|
+
const revision = revisionOf(key) + 1;
|
|
1214
|
+
richTextRevisions.set(key, revision);
|
|
1215
|
+
return revision;
|
|
1216
|
+
}
|
|
1217
|
+
function notifyRichTextRenderState(identity, deferred) {
|
|
1218
|
+
if (richTextRenderListeners.size === 0) return;
|
|
1219
|
+
const change = {
|
|
1220
|
+
...identity,
|
|
1221
|
+
deferred
|
|
1222
|
+
};
|
|
1223
|
+
for (const listener of richTextRenderListeners) listener(change);
|
|
1224
|
+
}
|
|
1225
|
+
/** The browser now owns this field's DOM; a binding must stop replacing it. */
|
|
1226
|
+
function deferRichTextRender(identity, revision) {
|
|
1227
|
+
const key = richTextKey(identity);
|
|
1228
|
+
const already = deferredRenders.has(key);
|
|
1229
|
+
deferredRenders.set(key, {
|
|
1230
|
+
meta: identity,
|
|
1231
|
+
revision
|
|
1232
|
+
});
|
|
1233
|
+
if (!already) notifyRichTextRenderState(identity, true);
|
|
1234
|
+
}
|
|
1235
|
+
/** Hand the field back to the renderer. */
|
|
1236
|
+
function releaseRichTextRender(key) {
|
|
1237
|
+
const entry = deferredRenders.get(key);
|
|
1238
|
+
if (entry === void 0) return false;
|
|
1239
|
+
deferredRenders.delete(key);
|
|
1240
|
+
notifyRichTextRenderState(entry.meta, false);
|
|
1241
|
+
return true;
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Release one field's deferral. An identity that names no placement matches
|
|
1245
|
+
* every placement of that field: a message can legitimately arrive without
|
|
1246
|
+
* one (Studio need not know which of two renders the theme used), and a
|
|
1247
|
+
* deferral that nothing can name would outlive its root.
|
|
1248
|
+
*/
|
|
1249
|
+
function releaseRichTextRenderFor(identity) {
|
|
1250
|
+
if (releaseRichTextRender(richTextKey(identity))) return true;
|
|
1251
|
+
if (identity.layoutNodeId !== void 0 || identity.reusablePlacementId !== void 0) return false;
|
|
1252
|
+
const matching = [];
|
|
1253
|
+
for (const [key, { meta }] of deferredRenders) if (meta.entryId === identity.entryId && meta.fieldPath === identity.fieldPath && meta.locale === identity.locale) matching.push(key);
|
|
1254
|
+
let released = false;
|
|
1255
|
+
for (const key of matching) released = releaseRichTextRender(key) || released;
|
|
1256
|
+
return released;
|
|
1257
|
+
}
|
|
1258
|
+
function releaseAllRichTextRenders() {
|
|
1259
|
+
if (deferredRenders.size === 0) return;
|
|
1260
|
+
const entries = [...deferredRenders.values()];
|
|
1261
|
+
deferredRenders.clear();
|
|
1262
|
+
for (const entry of entries) notifyRichTextRenderState(entry.meta, false);
|
|
1263
|
+
}
|
|
1264
|
+
/** 4.3: `text` is bounded at 64 KiB. Cut on a code-unit boundary rather
|
|
1265
|
+
* than mid-surrogate, so the other side never receives a lone half. */
|
|
1266
|
+
function boundedText(value) {
|
|
1267
|
+
if (value.length <= RICH_TEXT_TEXT_MAX) return value;
|
|
1268
|
+
const cut = value.slice(0, RICH_TEXT_TEXT_MAX);
|
|
1269
|
+
const last = cut.charCodeAt(cut.length - 1);
|
|
1270
|
+
return last >= 55296 && last <= 56319 ? cut.slice(0, -1) : cut;
|
|
1271
|
+
}
|
|
1272
|
+
function boundedMarks(marks) {
|
|
1273
|
+
return marks.slice(0, RICH_TEXT_MARKS_MAX).filter((mark) => mark.length <= RICH_TEXT_MARK_LENGTH_MAX);
|
|
1274
|
+
}
|
|
1275
|
+
function boundedRect(rect) {
|
|
1276
|
+
if (rect === null) return null;
|
|
1277
|
+
return [
|
|
1278
|
+
rect.x,
|
|
1279
|
+
rect.y,
|
|
1280
|
+
rect.width,
|
|
1281
|
+
rect.height
|
|
1282
|
+
].every((value) => Number.isFinite(value) && Math.abs(value) <= RECT_MAX) ? rect : null;
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* §18 v3: report the selection inside a rich-text root as document
|
|
1286
|
+
* positions, plus the marks and the block the toolbar needs — both read off
|
|
1287
|
+
* the DOM, which is all the theme knows and all Studio needs to light the
|
|
1288
|
+
* toolbar. Leaving a root posts exactly one blur (`anchor: null`).
|
|
1289
|
+
*/
|
|
1290
|
+
function reportRichTextSelection() {
|
|
1291
|
+
const selection = typeof document.getSelection === "function" ? document.getSelection() : null;
|
|
1292
|
+
const focusNode = selection?.focusNode ?? null;
|
|
1293
|
+
const element = editableRichTextRootOf(focusNode);
|
|
1294
|
+
if (element === null || selection === null || focusNode === null) {
|
|
1295
|
+
reportRetainedFocusOrBlur();
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
const anchorNode = selection.anchorNode ?? focusNode;
|
|
1299
|
+
if (editableRichTextRootOf(anchorNode) !== element) {
|
|
1300
|
+
postRichTextBlur();
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
const anchor = resolveDomPosition(element, anchorNode, selection.anchorOffset);
|
|
1304
|
+
const head = resolveDomPosition(element, focusNode, selection.focusOffset);
|
|
1305
|
+
if (!isPosition(anchor) || !isPosition(head)) return;
|
|
1306
|
+
const identity = richTextIdentityOf(element);
|
|
1307
|
+
const context = describeSelectionContext(element, focusNode);
|
|
1308
|
+
let rect = null;
|
|
1309
|
+
if (selection.rangeCount > 0) {
|
|
1310
|
+
const box = selection.getRangeAt(0).getBoundingClientRect?.();
|
|
1311
|
+
if (box !== void 0) rect = {
|
|
1312
|
+
x: box.x,
|
|
1313
|
+
y: box.y,
|
|
1314
|
+
width: box.width,
|
|
1315
|
+
height: box.height
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
const key = richTextKey(identity);
|
|
1319
|
+
reportedSelectionField = identity;
|
|
1320
|
+
lastRichTextPositions.set(key, {
|
|
1321
|
+
anchor,
|
|
1322
|
+
head
|
|
1323
|
+
});
|
|
1324
|
+
opts.post("theme:rich-text-selection", {
|
|
1325
|
+
...identity,
|
|
1326
|
+
anchor,
|
|
1327
|
+
head,
|
|
1328
|
+
rect: boundedRect(rect),
|
|
1329
|
+
rootRect: boundedRect(rectOf(element)),
|
|
1330
|
+
marks: boundedMarks(context.marks),
|
|
1331
|
+
block: context.block,
|
|
1332
|
+
revision: revisionOf(key)
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* §18 v3 (floating toolbar): the DOM selection could not be resolved to a
|
|
1337
|
+
* position, but the editing root itself may still hold document focus —
|
|
1338
|
+
* `removeAllRanges()` after a re-render or a programmatic change does
|
|
1339
|
+
* exactly this without the operator leaving the field. In that case report
|
|
1340
|
+
* the root is still being edited, at its last known positions (0/0 if none
|
|
1341
|
+
* were ever reported), with no caret rect but a `rootRect` so the floating
|
|
1342
|
+
* toolbar has somewhere to sit. Blur in every other case: the root is not
|
|
1343
|
+
* the one Studio is editing, it is not marked editing, or it does not have
|
|
1344
|
+
* focus at all — the operator actually left.
|
|
1345
|
+
*/
|
|
1346
|
+
function reportRetainedFocusOrBlur() {
|
|
1347
|
+
const active = document.activeElement;
|
|
1348
|
+
if (active instanceof HTMLElement && active === editingRichTextRoot && isRichTextEditingActive(active)) {
|
|
1349
|
+
const identity = richTextIdentityOf(active);
|
|
1350
|
+
const key = richTextKey(identity);
|
|
1351
|
+
const last = lastRichTextPositions.get(key) ?? {
|
|
1352
|
+
anchor: 0,
|
|
1353
|
+
head: 0
|
|
1354
|
+
};
|
|
1355
|
+
reportedSelectionField = identity;
|
|
1356
|
+
opts.post("theme:rich-text-selection", {
|
|
1357
|
+
...identity,
|
|
1358
|
+
anchor: last.anchor,
|
|
1359
|
+
head: last.head,
|
|
1360
|
+
rect: null,
|
|
1361
|
+
rootRect: boundedRect(rectOf(active)),
|
|
1362
|
+
marks: [],
|
|
1363
|
+
block: null,
|
|
1364
|
+
revision: revisionOf(key)
|
|
1365
|
+
});
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
postRichTextBlur();
|
|
1369
|
+
}
|
|
1370
|
+
function postRichTextBlur() {
|
|
1371
|
+
pendingRichTextIntents = null;
|
|
1372
|
+
const identity = reportedSelectionField;
|
|
1373
|
+
if (identity === null) return;
|
|
1374
|
+
reportedSelectionField = null;
|
|
1375
|
+
releaseRichTextRender(richTextKey(identity));
|
|
1376
|
+
opts.post("theme:rich-text-selection", {
|
|
1377
|
+
...identity,
|
|
1378
|
+
anchor: null,
|
|
1379
|
+
head: null,
|
|
1380
|
+
rect: null,
|
|
1381
|
+
rootRect: null,
|
|
1382
|
+
marks: [],
|
|
1383
|
+
block: null,
|
|
1384
|
+
revision: revisionOf(richTextKey(identity))
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Re-post the selection while a root is being edited — the floating
|
|
1389
|
+
* toolbar tracks the operator's selection, so a scroll or resize inside
|
|
1390
|
+
* the iframe (which produces no DOM mutation the MutationObserver would
|
|
1391
|
+
* see) must still refresh `rect`/`rootRect`. Coalesced to one post per
|
|
1392
|
+
* animation frame via `reposition()`, the same treatment
|
|
1393
|
+
* `scheduleReportBlocks`/`scheduleRichTextSync` give their own geometry.
|
|
1394
|
+
* Posts nothing when no root is being edited, or when the current DOM
|
|
1395
|
+
* selection is not inside the one being edited — Studio owns the toolbar's
|
|
1396
|
+
* fate in that case, not a stale re-post.
|
|
1397
|
+
*/
|
|
1398
|
+
function scheduleRichTextSelectionRepost() {
|
|
1399
|
+
if (!started || editingRichTextRoot === null || richTextSelectionRepostRaf !== null) return;
|
|
1400
|
+
richTextSelectionRepostRaf = requestAnimationFrame(() => {
|
|
1401
|
+
richTextSelectionRepostRaf = null;
|
|
1402
|
+
const target = editingRichTextRoot;
|
|
1403
|
+
if (target === null) return;
|
|
1404
|
+
const focusNode = (typeof document.getSelection === "function" ? document.getSelection() : null)?.focusNode ?? null;
|
|
1405
|
+
const insideRoot = focusNode !== null && target.contains(focusNode);
|
|
1406
|
+
const retainedFocus = !insideRoot && document.activeElement === target;
|
|
1407
|
+
if (!insideRoot && !retainedFocus) return;
|
|
1408
|
+
reportRichTextSelection();
|
|
1409
|
+
});
|
|
1410
|
+
}
|
|
1411
|
+
function onSelectionChange() {
|
|
1412
|
+
if (!started || selectionRaf !== null) return;
|
|
1413
|
+
selectionRaf = requestAnimationFrame(() => {
|
|
1414
|
+
selectionRaf = null;
|
|
1415
|
+
reportRichTextSelection();
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* §18 v3: the one place the theme decides whether the browser or Studio
|
|
1420
|
+
* performs an edit. A native op runs and is reported afterwards; everything
|
|
1421
|
+
* else is prevented and forwarded as an intent.
|
|
1422
|
+
*/
|
|
1423
|
+
function onBeforeInput(event) {
|
|
1424
|
+
if (!isInputEvent(event)) return;
|
|
1425
|
+
const element = editableRichTextRootOf(event.target instanceof Node ? event.target : null);
|
|
1426
|
+
if (element === null) return;
|
|
1427
|
+
if (!isRichTextEditingActive(element)) {
|
|
1428
|
+
event.preventDefault();
|
|
1429
|
+
pendingNativeInput = null;
|
|
1430
|
+
composition = null;
|
|
1431
|
+
const key = richTextKeyOf(element);
|
|
1432
|
+
const isFreshRun = pendingRichTextIntents === null || pendingRichTextIntents.key !== key;
|
|
1433
|
+
queueRichTextIntent(key, event);
|
|
1434
|
+
if (isFreshRun) reportRichTextSelection();
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
const key = richTextKeyOf(element);
|
|
1438
|
+
const verdict = classifyBeforeInput(event, element);
|
|
1439
|
+
if (verdict.kind === "native") {
|
|
1440
|
+
if (event.isComposing === true || event.inputType === "insertCompositionText") {
|
|
1441
|
+
pendingNativeInput = null;
|
|
1442
|
+
composition ??= {
|
|
1443
|
+
key,
|
|
1444
|
+
root: element,
|
|
1445
|
+
from: verdict.from,
|
|
1446
|
+
to: verdict.to
|
|
1447
|
+
};
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
pendingNativeInput = {
|
|
1451
|
+
key,
|
|
1452
|
+
root: element,
|
|
1453
|
+
from: verdict.from,
|
|
1454
|
+
to: verdict.to,
|
|
1455
|
+
data: typeof event.data === "string" ? event.data : ""
|
|
1456
|
+
};
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
if (verdict === IGNORED && document.activeElement === element) {
|
|
1460
|
+
event.preventDefault();
|
|
1461
|
+
pendingNativeInput = null;
|
|
1462
|
+
if (composition !== null && composition.key === key) composition = null;
|
|
1463
|
+
queueRichTextIntent(key, event);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
event.preventDefault();
|
|
1467
|
+
pendingNativeInput = null;
|
|
1468
|
+
if (composition !== null && composition.key === key) composition = null;
|
|
1469
|
+
if (verdict.kind === "ignore") return;
|
|
1470
|
+
const name = verdict.name;
|
|
1471
|
+
const text = commandText(event, name);
|
|
1472
|
+
if (text === "" && (name === "insertFromPaste" || name === "insertFromDrop")) return;
|
|
1473
|
+
releaseRichTextRender(key);
|
|
1474
|
+
opts.post("theme:rich-text-command", {
|
|
1475
|
+
...richTextIdentityOf(element),
|
|
1476
|
+
name,
|
|
1477
|
+
from: verdict.from,
|
|
1478
|
+
to: verdict.to,
|
|
1479
|
+
...text === null ? {} : { text: boundedText(text) },
|
|
1480
|
+
revision: nextRevision(key)
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1483
|
+
/** A paste or a drop — including a keystroke that became one (see
|
|
1484
|
+
* `TEXT_FALLBACK_COMMANDS`) — carries the plain text Studio inserts; every
|
|
1485
|
+
* other command carries none, because its meaning is its name. */
|
|
1486
|
+
function commandText(event, name) {
|
|
1487
|
+
if (name !== "insertFromPaste" && name !== "insertFromDrop") return null;
|
|
1488
|
+
const transferred = event.dataTransfer?.getData("text/plain");
|
|
1489
|
+
if (typeof transferred === "string" && transferred !== "") return transferred;
|
|
1490
|
+
return typeof event.data === "string" ? event.data : "";
|
|
1491
|
+
}
|
|
1492
|
+
const RICH_TEXT_INTENT_BUFFER_MAX = 64;
|
|
1493
|
+
/**
|
|
1494
|
+
* §18 v3 (the floating-toolbar follow-up, generalized and then serialized):
|
|
1495
|
+
* append the command `event`'s `inputType` maps to onto `key`'s
|
|
1496
|
+
* ordered buffer, for `flushNextPendingRichTextIntent` to post one at a
|
|
1497
|
+
* time once the root can accept them. Nothing is queued for an inputType
|
|
1498
|
+
* with no command name — the same ones `classifyBeforeInput` would call
|
|
1499
|
+
* `ignore` even with a resolvable position, so there is nothing to lose —
|
|
1500
|
+
* nor for a composition-sourced event (`isComposing`/
|
|
1501
|
+
* `insertCompositionText`): `onCompositionStart` already refuses to start
|
|
1502
|
+
* a composition on a root in either state this is called from, so this is
|
|
1503
|
+
* only the defensive fallback for an engine that does not honor that
|
|
1504
|
+
* `preventDefault()`, and a composition has no meaningful, complete text
|
|
1505
|
+
* to queue piecemeal anyway.
|
|
1506
|
+
*
|
|
1507
|
+
* A run of plain typed characters (`inputType === 'insertText'`)
|
|
1508
|
+
* coalesces into the buffer's last entry, concatenating text, rather than
|
|
1509
|
+
* pushing a new one — Studio applies each posted command literally at the
|
|
1510
|
+
* `from`/`to` it carries, so N one-character entries flushed one at a time
|
|
1511
|
+
* would each land at the same (by-then stale) position and reverse the
|
|
1512
|
+
* typed order (`a`,`b`,`c` → `cba`). A real paste/drop (or anything else)
|
|
1513
|
+
* never coalesces with a neighbor; it ends the run.
|
|
1514
|
+
*/
|
|
1515
|
+
function queueRichTextIntent(key, event) {
|
|
1516
|
+
if (event.isComposing === true || event.inputType === "insertCompositionText") return;
|
|
1517
|
+
const name = commandNameForInputType(event.inputType);
|
|
1518
|
+
if (name === null) return;
|
|
1519
|
+
const text = commandText(event, name);
|
|
1520
|
+
if (text === "" && (name === "insertFromPaste" || name === "insertFromDrop")) return;
|
|
1521
|
+
if (pendingRichTextIntents === null || pendingRichTextIntents.key !== key) pendingRichTextIntents = {
|
|
1522
|
+
key,
|
|
1523
|
+
entries: [],
|
|
1524
|
+
awaitingRevision: null
|
|
1525
|
+
};
|
|
1526
|
+
const entries = pendingRichTextIntents.entries;
|
|
1527
|
+
const coalescable = event.inputType === "insertText";
|
|
1528
|
+
const last = entries[entries.length - 1];
|
|
1529
|
+
if (coalescable && last !== void 0 && last.coalescable && text !== null) {
|
|
1530
|
+
last.text = `${last.text ?? ""}${text}`;
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
if (entries.length >= RICH_TEXT_INTENT_BUFFER_MAX) {
|
|
1534
|
+
const dropped = entries.shift();
|
|
1535
|
+
console.debug("[eldra] rich-text: pending intent buffer full (64); dropping the oldest queued intent", {
|
|
1536
|
+
key,
|
|
1537
|
+
dropped: dropped === void 0 ? dropped : {
|
|
1538
|
+
...dropped,
|
|
1539
|
+
...dropped.text === void 0 ? {} : { text: boundedText(dropped.text) }
|
|
1540
|
+
}
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1543
|
+
entries.push({
|
|
1544
|
+
name,
|
|
1545
|
+
coalescable,
|
|
1546
|
+
...text === null ? {} : { text }
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
/** The browser has performed the edit; report it against the range captured
|
|
1550
|
+
* before the DOM moved. */
|
|
1551
|
+
function postNativeRichTextInput(pending, text) {
|
|
1552
|
+
const element = pending.root.isConnected ? pending.root : findRichTextRoot(...richTextLookup(pending.root));
|
|
1553
|
+
if (element === null) return;
|
|
1554
|
+
const revision = nextRevision(pending.key);
|
|
1555
|
+
deferRichTextRender(richTextIdentityOf(element), revision);
|
|
1556
|
+
opts.post("theme:rich-text-input", {
|
|
1557
|
+
...richTextIdentityOf(element),
|
|
1558
|
+
from: pending.from,
|
|
1559
|
+
to: pending.to,
|
|
1560
|
+
text: boundedText(text),
|
|
1561
|
+
revision
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
function onCompositionStart(event) {
|
|
1565
|
+
const element = editableRichTextRootOf(event.target instanceof Node ? event.target : null);
|
|
1566
|
+
if (element === null) return;
|
|
1567
|
+
if (!isRichTextEditingActive(element)) {
|
|
1568
|
+
if (isCompositionEvent(event)) event.preventDefault();
|
|
1569
|
+
pendingNativeInput = null;
|
|
1570
|
+
composition = null;
|
|
1571
|
+
reportRichTextSelection();
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
const range = currentSelectionRange();
|
|
1575
|
+
if (range === null) {
|
|
1576
|
+
if (document.activeElement === element && isCompositionEvent(event)) event.preventDefault();
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
if (!isNativeTextRange(element, "insertCompositionText", range)) return;
|
|
1580
|
+
const positions = domRangeToPositions(element, range);
|
|
1581
|
+
if (positions === null || !isPosition(positions.from) || !isPosition(positions.to)) return;
|
|
1582
|
+
composition = {
|
|
1583
|
+
key: richTextKeyOf(element),
|
|
1584
|
+
root: element,
|
|
1585
|
+
from: positions.from,
|
|
1586
|
+
to: positions.to
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
function onCompositionEnd(event) {
|
|
1590
|
+
const pending = composition;
|
|
1591
|
+
composition = null;
|
|
1592
|
+
pendingNativeInput = null;
|
|
1593
|
+
if (pending === null) return;
|
|
1594
|
+
postNativeRichTextInput(pending, isCompositionEvent(event) && typeof event.data === "string" ? event.data : "");
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* §18 v3: Studio's answer to an `editor:content-update` for the active
|
|
1598
|
+
* field. When it acks a native op the theme performed and asks for no
|
|
1599
|
+
* re-render, the DOM already shows the edit: touching it — or the selection
|
|
1600
|
+
* — would take the caret away from the operator mid-word. Otherwise the
|
|
1601
|
+
* content update has re-rendered the root and the caret has to be put back
|
|
1602
|
+
* where Studio says the document's selection is.
|
|
1603
|
+
*/
|
|
1604
|
+
function acceptRichTextApplied(message) {
|
|
1605
|
+
if (!richTextEnabled || mode !== "edit") return;
|
|
1606
|
+
if (!isPosition(message.anchor) || !isPosition(message.head)) return;
|
|
1607
|
+
if (!Number.isInteger(message.revision) || message.revision < 0) return;
|
|
1608
|
+
const element = findRichTextRoot(message.entryId, message.fieldPath, message.locale, message.layoutNodeId, message.reusablePlacementId);
|
|
1609
|
+
const key = element === null ? richTextKey(message) : richTextKeyOf(element);
|
|
1610
|
+
const deferredAt = deferredRenders.get(key)?.revision;
|
|
1611
|
+
if (deferredAt !== void 0 && message.rerender === false && message.revision <= deferredAt) return;
|
|
1612
|
+
if (!releaseRichTextRender(key)) releaseRichTextRenderFor(message);
|
|
1613
|
+
if (element === null) return;
|
|
1614
|
+
queueMicrotask(() => {
|
|
1615
|
+
if (!element.isConnected) return;
|
|
1616
|
+
restoreRichTextSelection(element, message.anchor, message.head, message.revision);
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* §18 v3 (the floating-toolbar follow-up, generalized and then serialized;
|
|
1621
|
+
* release on `>=`, not `===`): post exactly the next
|
|
1622
|
+
* entry of `element`'s queued buffer, if it is this trigger's turn —
|
|
1623
|
+
* Studio applies a `theme:rich-text-command` literally at the `from`/`to`
|
|
1624
|
+
* it carries, with no position tracking between messages, so more than one
|
|
1625
|
+
* in flight at once would land at the same (by-then stale) position.
|
|
1626
|
+
* `ackRevision` is the revision the calling `restoreRichTextSelection` ran
|
|
1627
|
+
* for (`null` for the mark-time trigger, which carries no ack of its own):
|
|
1628
|
+
* it is this trigger's turn when nothing has posted for the buffer yet
|
|
1629
|
+
* (`awaitingRevision === null` — the first entry, whichever of the two
|
|
1630
|
+
* triggers gets there first) or when the ack is at or beyond the entry most
|
|
1631
|
+
* recently posted (`ackRevision >= awaitingRevision`). Studio's self-heal
|
|
1632
|
+
* path can answer a refused op with its *current* revision rather than the
|
|
1633
|
+
* one that was awaited, and a later ack can supersede an earlier one in
|
|
1634
|
+
* flight — either arrives strictly ahead, never behind, so `>=` (not
|
|
1635
|
+
* `===`) is what "Studio has caught up" actually means; an ack strictly
|
|
1636
|
+
* behind the awaited revision is stale and neither advances nor posts. A
|
|
1637
|
+
* no-op when nothing is queued — including the common Studio-first case
|
|
1638
|
+
* (marked before the operator ever types) — or when what is queued belongs
|
|
1639
|
+
* to a different field.
|
|
1640
|
+
*/
|
|
1641
|
+
function flushNextPendingRichTextIntent(element, from, to, ackRevision) {
|
|
1642
|
+
const pending = pendingRichTextIntents;
|
|
1643
|
+
if (pending === null) return;
|
|
1644
|
+
const key = richTextKeyOf(element);
|
|
1645
|
+
if (pending.key !== key) return;
|
|
1646
|
+
if (pending.awaitingRevision !== null && (ackRevision === null || ackRevision < pending.awaitingRevision)) return;
|
|
1647
|
+
const next = pending.entries.shift();
|
|
1648
|
+
if (next === void 0) {
|
|
1649
|
+
pendingRichTextIntents = null;
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
releaseRichTextRender(key);
|
|
1653
|
+
const revision = nextRevision(key);
|
|
1654
|
+
if (pending.entries.length === 0) pendingRichTextIntents = null;
|
|
1655
|
+
else pending.awaitingRevision = revision;
|
|
1656
|
+
opts.post("theme:rich-text-command", {
|
|
1657
|
+
...richTextIdentityOf(element),
|
|
1658
|
+
name: next.name,
|
|
1659
|
+
from,
|
|
1660
|
+
to,
|
|
1661
|
+
...next.text === void 0 ? {} : { text: boundedText(next.text) },
|
|
1662
|
+
revision
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* §18 v3 (the floating-toolbar follow-up): flush `element`'s queued
|
|
1667
|
+
* buffer against whatever the DOM selection already is inside it, for the
|
|
1668
|
+
* "root just got marked editing" trigger — `editor:rich-text-editing`
|
|
1669
|
+
* carries no position. The keystrokes that filled the buffer were
|
|
1670
|
+
* prevented, so the DOM text never moved, but the caret is still exactly
|
|
1671
|
+
* where the operator clicked or last typed toward, so this is the position
|
|
1672
|
+
* the queued commands belong at. A no-op (skips resolving a position at
|
|
1673
|
+
* all) when nothing is queued for this field.
|
|
1674
|
+
*/
|
|
1675
|
+
function flushPendingRichTextIntentsHere(element) {
|
|
1676
|
+
if (pendingRichTextIntents === null || pendingRichTextIntents.key !== richTextKeyOf(element)) return;
|
|
1677
|
+
const selection = typeof document.getSelection === "function" ? document.getSelection() : null;
|
|
1678
|
+
const focusNode = selection?.focusNode ?? null;
|
|
1679
|
+
if (selection === null || focusNode === null) return;
|
|
1680
|
+
const anchor = resolveDomPosition(element, selection.anchorNode ?? focusNode, selection.anchorOffset);
|
|
1681
|
+
const head = resolveDomPosition(element, focusNode, selection.focusOffset);
|
|
1682
|
+
if (!isPosition(anchor) || !isPosition(head)) return;
|
|
1683
|
+
flushNextPendingRichTextIntent(element, Math.min(anchor, head), Math.max(anchor, head), null);
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Put the caret (or the range) back at the document positions Studio
|
|
1687
|
+
* reports, after a re-render replaced the nodes it used to live in.
|
|
1688
|
+
* `ackRevision` is the revision of the `editor:rich-text-applied` this
|
|
1689
|
+
* restore is running for — passed through to
|
|
1690
|
+
* `flushNextPendingRichTextIntent`, which uses it to decide whether this
|
|
1691
|
+
* is the ack the next queued entry, if any, was waiting on.
|
|
1692
|
+
*/
|
|
1693
|
+
function restoreRichTextSelection(element, anchor, head, ackRevision) {
|
|
1694
|
+
const selection = typeof document.getSelection === "function" ? document.getSelection() : null;
|
|
1695
|
+
if (selection === null) return;
|
|
1696
|
+
const end = resolveDomPosition(element, element, element.childNodes.length) ?? 0;
|
|
1697
|
+
const clamp = (value) => Math.min(Math.max(value, 0), end);
|
|
1698
|
+
const from = clamp(Math.min(anchor, head));
|
|
1699
|
+
const to = clamp(Math.max(anchor, head));
|
|
1700
|
+
const start = resolveDomPoint(element, from);
|
|
1701
|
+
const finish = resolveDomPoint(element, to);
|
|
1702
|
+
if (start === null || finish === null) return;
|
|
1703
|
+
if ((typeof document.hasFocus === "function" ? document.hasFocus() : true) && document.activeElement !== element) element.focus?.({ preventScroll: true });
|
|
1704
|
+
const range = document.createRange();
|
|
1705
|
+
try {
|
|
1706
|
+
range.setStart(start.node, start.offset);
|
|
1707
|
+
range.setEnd(finish.node, finish.offset);
|
|
1708
|
+
} catch {
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
selection.removeAllRanges();
|
|
1712
|
+
selection.addRange(range);
|
|
1713
|
+
flushNextPendingRichTextIntent(element, from, to, ackRevision);
|
|
1714
|
+
}
|
|
1715
|
+
/** Put the caret at the very end of a root's content, for `locate`. */
|
|
1716
|
+
function placeCaretAtEnd(element) {
|
|
1717
|
+
const selection = typeof document.getSelection === "function" ? document.getSelection() : null;
|
|
1718
|
+
if (selection === null) return;
|
|
1719
|
+
const range = document.createRange();
|
|
1720
|
+
range.selectNodeContents(element);
|
|
1721
|
+
range.collapse(false);
|
|
1722
|
+
selection.removeAllRanges();
|
|
1723
|
+
selection.addRange(range);
|
|
1724
|
+
}
|
|
1725
|
+
function isInputEvent(event) {
|
|
1726
|
+
return typeof event.inputType === "string";
|
|
1727
|
+
}
|
|
1728
|
+
function isCompositionEvent(event) {
|
|
1729
|
+
return "data" in event;
|
|
1730
|
+
}
|
|
1731
|
+
function postFramingTarget() {
|
|
1732
|
+
if (framing === null) return;
|
|
1733
|
+
const rect = unscaledFrameRect(rectOf(framing.image), framing.value);
|
|
1734
|
+
opts.post("theme:framing-target", {
|
|
1735
|
+
entryId: framing.entryId,
|
|
1736
|
+
fieldPath: framing.fieldPath,
|
|
1737
|
+
rect
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
function postFraming(final) {
|
|
1741
|
+
if (framing === null) return;
|
|
1742
|
+
opts.post("theme:framing-changed", {
|
|
1743
|
+
entryId: framing.entryId,
|
|
1744
|
+
fieldPath: framing.fieldPath,
|
|
1745
|
+
framing: { ...framing.value },
|
|
1746
|
+
final
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
/** True while the live gesture's settled value has not been posted yet: an
|
|
1750
|
+
* active pointer drag, a throttled live post waiting for its frame, or the
|
|
1751
|
+
* wheel's settle timer. Outside that window the editor's draft is the
|
|
1752
|
+
* authority on the framing value. */
|
|
1753
|
+
function framingGestureInFlight() {
|
|
1754
|
+
return framing !== null && (framing.drag !== null || framing.raf !== null || framing.wheelTimer !== null);
|
|
1755
|
+
}
|
|
1756
|
+
/** Item 7: one rAF at a time carries a live (final: false) post; final: true
|
|
1757
|
+
* cancels any pending frame and posts synchronously. */
|
|
1758
|
+
function scheduleFramingPost(final) {
|
|
1759
|
+
if (framing === null) return;
|
|
1760
|
+
if (final) {
|
|
1761
|
+
if (framing.raf !== null) {
|
|
1762
|
+
cancelAnimationFrame(framing.raf);
|
|
1763
|
+
framing.raf = null;
|
|
1764
|
+
}
|
|
1765
|
+
postFraming(true);
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
if (framing.raf !== null) return;
|
|
1769
|
+
framing.raf = requestAnimationFrame(() => {
|
|
1770
|
+
if (framing === null) return;
|
|
1771
|
+
framing.raf = null;
|
|
1772
|
+
postFraming(false);
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
function positionFramingChrome() {
|
|
1776
|
+
if (framing === null || framingBox === null || framingBadge === null) return;
|
|
1777
|
+
const rect = unscaledFrameRect(rectOf(framing.image), framing.value);
|
|
1778
|
+
Object.assign(framingBox.style, {
|
|
1779
|
+
display: "block",
|
|
1780
|
+
left: `${rect.x}px`,
|
|
1781
|
+
top: `${rect.y}px`,
|
|
1782
|
+
width: `${rect.width}px`,
|
|
1783
|
+
height: `${rect.height}px`
|
|
1784
|
+
});
|
|
1785
|
+
Object.assign(framingBadge.style, {
|
|
1786
|
+
display: "block",
|
|
1787
|
+
left: `${rect.x + 4}px`,
|
|
1788
|
+
top: `${rect.y + 4}px`
|
|
1789
|
+
});
|
|
1790
|
+
}
|
|
1791
|
+
/** Item 6: apply the CSS (kebab-case props via setProperty), the marking
|
|
1792
|
+
* attribute Studio persists, the badge text and reposition the chrome. */
|
|
1793
|
+
function applyFraming() {
|
|
1794
|
+
if (framing === null) return;
|
|
1795
|
+
const image = framing.image;
|
|
1796
|
+
const style = imageFramingStyle(framing.value);
|
|
1797
|
+
for (const [prop, value] of Object.entries(style)) image.style.setProperty(prop, value);
|
|
1798
|
+
if (!("transform" in style)) image.style.removeProperty("transform");
|
|
1799
|
+
if (!("transform-origin" in style)) image.style.removeProperty("transform-origin");
|
|
1800
|
+
image.dataset.eldraFramingValue = `${framing.value.x},${framing.value.y},${framing.value.zoom}`;
|
|
1801
|
+
if (framingBadge !== null) framingBadge.textContent = `${framing.value.zoom.toFixed(1)}x`;
|
|
1802
|
+
positionFramingChrome();
|
|
1803
|
+
}
|
|
1804
|
+
function onFramingPointerDown(event) {
|
|
1805
|
+
if (framing === null || event.button !== 0) return;
|
|
1806
|
+
event.preventDefault();
|
|
1807
|
+
framing.drag = {
|
|
1808
|
+
x: event.clientX,
|
|
1809
|
+
y: event.clientY
|
|
1810
|
+
};
|
|
1811
|
+
const image = framing.image;
|
|
1812
|
+
if (typeof image.setPointerCapture === "function") try {
|
|
1813
|
+
image.setPointerCapture(event.pointerId);
|
|
1814
|
+
} catch {}
|
|
1815
|
+
window.addEventListener("pointermove", onFramingPointerMove, true);
|
|
1816
|
+
window.addEventListener("pointerup", onFramingPointerUp, true);
|
|
1817
|
+
window.addEventListener("pointercancel", onFramingPointerUp, true);
|
|
1818
|
+
}
|
|
1819
|
+
function onFramingPointerMove(event) {
|
|
1820
|
+
if (framing === null || framing.drag === null) return;
|
|
1821
|
+
const dx = event.clientX - framing.drag.x;
|
|
1822
|
+
const dy = event.clientY - framing.drag.y;
|
|
1823
|
+
framing.drag = {
|
|
1824
|
+
x: event.clientX,
|
|
1825
|
+
y: event.clientY
|
|
1826
|
+
};
|
|
1827
|
+
const frame = unscaledFrameRect(rectOf(framing.image), framing.value);
|
|
1828
|
+
framing.value = roundFramingValue(framingDrag(framing.value, dx, dy, frame.width, frame.height));
|
|
1829
|
+
applyFraming();
|
|
1830
|
+
scheduleFramingPost(false);
|
|
1831
|
+
}
|
|
1832
|
+
function onFramingPointerUp() {
|
|
1833
|
+
if (framing === null) return;
|
|
1834
|
+
framing.drag = null;
|
|
1835
|
+
window.removeEventListener("pointermove", onFramingPointerMove, true);
|
|
1836
|
+
window.removeEventListener("pointerup", onFramingPointerUp, true);
|
|
1837
|
+
window.removeEventListener("pointercancel", onFramingPointerUp, true);
|
|
1838
|
+
scheduleFramingPost(true);
|
|
1839
|
+
}
|
|
1840
|
+
function onFramingWheel(event) {
|
|
1841
|
+
if (framing === null) return;
|
|
1842
|
+
event.preventDefault();
|
|
1843
|
+
framing.value = roundFramingValue(framingZoom(framing.value, event.deltaY));
|
|
1844
|
+
applyFraming();
|
|
1845
|
+
scheduleFramingPost(false);
|
|
1846
|
+
if (framing.wheelTimer !== null) clearTimeout(framing.wheelTimer);
|
|
1847
|
+
framing.wheelTimer = setTimeout(() => {
|
|
1848
|
+
if (framing === null) return;
|
|
1849
|
+
framing.wheelTimer = null;
|
|
1850
|
+
scheduleFramingPost(true);
|
|
1851
|
+
}, FRAMING_WHEEL_SETTLE_MS);
|
|
1852
|
+
}
|
|
1853
|
+
function onFramingKeyDown(event) {
|
|
1854
|
+
if (event.key === "Escape") exitFraming();
|
|
1855
|
+
}
|
|
1856
|
+
function attachFramingListeners(image) {
|
|
1857
|
+
image.addEventListener("pointerdown", onFramingPointerDown, true);
|
|
1858
|
+
image.addEventListener("wheel", onFramingWheel, {
|
|
1859
|
+
passive: false,
|
|
1860
|
+
capture: true
|
|
1861
|
+
});
|
|
1862
|
+
document.addEventListener("keydown", onFramingKeyDown, true);
|
|
1863
|
+
}
|
|
1864
|
+
function detachFramingListeners(image) {
|
|
1865
|
+
image.removeEventListener("pointerdown", onFramingPointerDown, true);
|
|
1866
|
+
image.removeEventListener("wheel", onFramingWheel, true);
|
|
1867
|
+
document.removeEventListener("keydown", onFramingKeyDown, true);
|
|
1868
|
+
}
|
|
1869
|
+
/** Item 9/1: enter framing for a resolved image (no selection precondition
|
|
1870
|
+
* for setFramingMode; the click-entry path checks ownership itself).
|
|
1871
|
+
* Guarded the same way positionBox gates chrome: framing never arms outside
|
|
1872
|
+
* edit mode, and never arms once the runtime is stopped (setFramingMode can
|
|
1873
|
+
* be called before start() / after stop() by a caller that hasn't noticed
|
|
1874
|
+
* yet) — stop() itself never releases listeners armed after it ran. */
|
|
1875
|
+
function enterFraming(image) {
|
|
1876
|
+
if (!started || mode !== "edit" || !framingEnabled) return;
|
|
1877
|
+
if (framing !== null) exitFraming({ post: false });
|
|
1878
|
+
framing = {
|
|
1879
|
+
entryId: image.getAttribute("data-eldra-framing-entry") ?? "",
|
|
1880
|
+
fieldPath: image.getAttribute("data-eldra-framing") ?? "",
|
|
1881
|
+
image,
|
|
1882
|
+
value: parseImageFramingValueAttr(image.dataset.eldraFramingValue),
|
|
1883
|
+
drag: null,
|
|
1884
|
+
raf: null,
|
|
1885
|
+
wheelTimer: null
|
|
1886
|
+
};
|
|
1887
|
+
attachFramingListeners(image);
|
|
1888
|
+
applyFraming();
|
|
1889
|
+
postFramingTarget();
|
|
1890
|
+
}
|
|
1891
|
+
/** Item 8: leave framing from any of its exits (Escape, outside click,
|
|
1892
|
+
* selection change, preview mode, setFramingMode(null), stop()).
|
|
1893
|
+
* `post: false` is for the retarget path only (see enterFraming): it still
|
|
1894
|
+
* finalizes an in-flight drag's value, hides chrome and releases listeners,
|
|
1895
|
+
* it just skips the {entryId: null} target post.
|
|
1896
|
+
* `silent: true` is for setFramingEnabled(false) mid-session: the editor
|
|
1897
|
+
* stopped advertising `image-framing`, so per contract §17 the overlay must
|
|
1898
|
+
* post nothing at all — not even the drag's finalizing theme:framing-changed. */
|
|
1899
|
+
function exitFraming(options = {}) {
|
|
1900
|
+
if (framing === null) return;
|
|
1901
|
+
const silent = options.silent === true;
|
|
1902
|
+
const post = !silent && options.post !== false;
|
|
1903
|
+
if (framing.drag !== null) {
|
|
1904
|
+
framing.drag = null;
|
|
1905
|
+
window.removeEventListener("pointermove", onFramingPointerMove, true);
|
|
1906
|
+
window.removeEventListener("pointerup", onFramingPointerUp, true);
|
|
1907
|
+
window.removeEventListener("pointercancel", onFramingPointerUp, true);
|
|
1908
|
+
if (framing.raf !== null) {
|
|
1909
|
+
cancelAnimationFrame(framing.raf);
|
|
1910
|
+
framing.raf = null;
|
|
1911
|
+
}
|
|
1912
|
+
if (!silent) postFraming(true);
|
|
1913
|
+
}
|
|
1914
|
+
if (framing.raf !== null) {
|
|
1915
|
+
cancelAnimationFrame(framing.raf);
|
|
1916
|
+
framing.raf = null;
|
|
1917
|
+
}
|
|
1918
|
+
if (framing.wheelTimer !== null) {
|
|
1919
|
+
clearTimeout(framing.wheelTimer);
|
|
1920
|
+
framing.wheelTimer = null;
|
|
1921
|
+
}
|
|
1922
|
+
if (framingBox !== null) framingBox.style.display = "none";
|
|
1923
|
+
if (framingBadge !== null) framingBadge.style.display = "none";
|
|
1924
|
+
if (post) opts.post("theme:framing-target", { entryId: null });
|
|
1925
|
+
detachFramingListeners(framing.image);
|
|
1926
|
+
framing = null;
|
|
1927
|
+
}
|
|
1928
|
+
function scanRoot() {
|
|
1929
|
+
return root instanceof Document ? root.body : root;
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* §4.2 perf: a rich-text root is undecorated — `decorateStegaTextNodes`
|
|
1933
|
+
* skips everything under `[data-eldra-rich-text]` — yet the theme rewrites
|
|
1934
|
+
* that subtree on every `editor:content-update` echo, which while Studio is
|
|
1935
|
+
* editing arrives on roughly every keystroke. Those records can never
|
|
1936
|
+
* produce decoration work, and `decorateStegaTextNodes` walks the whole
|
|
1937
|
+
* document, so when every record in a batch is inside such a root, drop the
|
|
1938
|
+
* batch instead of re-walking the page. A batch that also touches anything
|
|
1939
|
+
* else still decorates as before.
|
|
1940
|
+
*/
|
|
1941
|
+
function onMutations(records) {
|
|
1942
|
+
if (records.length > 0 && records.every((record) => insideRichTextRoot(record.target))) return;
|
|
1943
|
+
decorateStegaTextNodes();
|
|
1944
|
+
}
|
|
1945
|
+
function insideRichTextRoot(node) {
|
|
1946
|
+
return (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement)?.closest("[data-eldra-rich-text]") != null;
|
|
1947
|
+
}
|
|
1948
|
+
function decorateStegaTextNodes() {
|
|
1949
|
+
const walker = document.createTreeWalker(scanRoot(), NodeFilter.SHOW_TEXT);
|
|
1950
|
+
const targets = [];
|
|
1951
|
+
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
|
|
1952
|
+
const text = node;
|
|
1953
|
+
if (!text.data.includes(STEGA_DELIMITER)) continue;
|
|
1954
|
+
if (text.parentElement?.closest("[data-eldra-rich-text]") != null) continue;
|
|
1955
|
+
targets.push(text);
|
|
1956
|
+
}
|
|
1957
|
+
for (const text of targets) {
|
|
1958
|
+
const { cleaned, meta } = decodeStega(text.data);
|
|
1959
|
+
if (meta === null) continue;
|
|
1960
|
+
const existing = text.parentElement?.closest("[data-eldra-field]") ?? null;
|
|
1961
|
+
if (existing !== null) {
|
|
1962
|
+
existing.setAttribute("data-eldra-field", meta.fieldPath);
|
|
1963
|
+
existing.setAttribute("data-eldra-entry", meta.entryId);
|
|
1964
|
+
if (meta.locale !== null) existing.setAttribute("data-eldra-locale", meta.locale);
|
|
1965
|
+
else existing.removeAttribute("data-eldra-locale");
|
|
1966
|
+
text.data = cleaned;
|
|
1967
|
+
applyEditable(existing);
|
|
1968
|
+
continue;
|
|
1969
|
+
}
|
|
1970
|
+
const parent = text.parentElement;
|
|
1971
|
+
if (parent !== null && parent.childNodes.length === 1) {
|
|
1972
|
+
parent.setAttribute("data-eldra-field", meta.fieldPath);
|
|
1973
|
+
parent.setAttribute("data-eldra-entry", meta.entryId);
|
|
1974
|
+
if (meta.locale !== null) parent.setAttribute("data-eldra-locale", meta.locale);
|
|
1975
|
+
text.data = cleaned;
|
|
1976
|
+
applyEditable(parent);
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
const span = document.createElement("span");
|
|
1980
|
+
span.setAttribute("data-eldra-field", meta.fieldPath);
|
|
1981
|
+
span.setAttribute("data-eldra-entry", meta.entryId);
|
|
1982
|
+
if (meta.locale !== null) span.setAttribute("data-eldra-locale", meta.locale);
|
|
1983
|
+
text.before(span);
|
|
1984
|
+
span.append(text);
|
|
1985
|
+
text.data = cleaned;
|
|
1986
|
+
applyEditable(span);
|
|
1987
|
+
}
|
|
1988
|
+
restoreEditingFocus();
|
|
1989
|
+
}
|
|
1990
|
+
function metadataOf(span) {
|
|
1991
|
+
return {
|
|
1992
|
+
entryId: span.getAttribute("data-eldra-entry") ?? "",
|
|
1993
|
+
fieldPath: span.getAttribute("data-eldra-field") ?? "",
|
|
1994
|
+
locale: span.getAttribute("data-eldra-locale")
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
function caretOffsetWithin(span) {
|
|
1998
|
+
const selection = document.getSelection();
|
|
1999
|
+
if (selection === null || selection.rangeCount === 0 || !selection.focusNode || !span.contains(selection.focusNode)) return span.textContent?.length ?? 0;
|
|
2000
|
+
const range = document.createRange();
|
|
2001
|
+
range.selectNodeContents(span);
|
|
2002
|
+
try {
|
|
2003
|
+
range.setEnd(selection.focusNode, selection.focusOffset);
|
|
2004
|
+
return range.toString().length;
|
|
2005
|
+
} catch {
|
|
2006
|
+
return span.textContent?.length ?? 0;
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
function rememberEditing(span, dirty = false) {
|
|
2010
|
+
activeEdit = {
|
|
2011
|
+
meta: metadataOf(span),
|
|
2012
|
+
caretOffset: caretOffsetWithin(span),
|
|
2013
|
+
value: stripStega(span.textContent ?? ""),
|
|
2014
|
+
dirty,
|
|
2015
|
+
element: span,
|
|
2016
|
+
node: span.firstChild
|
|
2017
|
+
};
|
|
2018
|
+
}
|
|
2019
|
+
function sameTextField(a, b) {
|
|
2020
|
+
return a.entryId === b.entryId && a.fieldPath === b.fieldPath && a.locale === b.locale;
|
|
2021
|
+
}
|
|
2022
|
+
function textEditKey(meta) {
|
|
2023
|
+
return `${meta.entryId}|${meta.fieldPath}|${meta.locale ?? ""}`;
|
|
2024
|
+
}
|
|
2025
|
+
/** The field `meta` names still has its own `theme:text-edited` debounce
|
|
2026
|
+
* armed, so the editor has not been told about the keystrokes in it at all.
|
|
2027
|
+
* Matched by metadata rather than element identity on purpose: a renderer
|
|
2028
|
+
* pass can replace the element between the keystroke and the flush, and the
|
|
2029
|
+
* pending timer is still the same edit. */
|
|
2030
|
+
function hasPendingTextEdit(meta) {
|
|
2031
|
+
for (const span of debounceTimers.keys()) if (sameTextField(metadataOf(span), meta)) return true;
|
|
2032
|
+
return false;
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* True while the editor cannot yet have a draft that describes what the
|
|
2036
|
+
* operator has typed into `meta`'s field, which is the window in which the
|
|
2037
|
+
* overlay — not the editor — owns that field's text. Two halves:
|
|
2038
|
+
*
|
|
2039
|
+
* - the field's `theme:text-edited` debounce is still armed, so the editor
|
|
2040
|
+
* has not been told anything yet; and
|
|
2041
|
+
* - a posted value is still waiting to be echoed back. The round trip is
|
|
2042
|
+
* not bounded by anything the theme controls (the editor debounces its
|
|
2043
|
+
* own content update, then the draft write and the re-render take as long
|
|
2044
|
+
* as the operator's machine and network take), so "wait for the debounce
|
|
2045
|
+
* to flush" is not enough on its own: an echo that arrives after the next
|
|
2046
|
+
* keystroke has already flushed still carries the older draft, and
|
|
2047
|
+
* applying it deletes that keystroke. Ownership therefore ends on the
|
|
2048
|
+
* acknowledgement itself — `acceptTextEditEcho` sees the posted value come
|
|
2049
|
+
* back — and not on a timer.
|
|
2050
|
+
*
|
|
2051
|
+
* The posted half is held only while the operator is still editing this
|
|
2052
|
+
* field in this frame, so a write the editor silently refuses cannot own the
|
|
2053
|
+
* field forever: moving the caret elsewhere, or focus leaving the preview,
|
|
2054
|
+
* hands it back.
|
|
2055
|
+
*/
|
|
2056
|
+
function hasUnacknowledgedTextEdit(meta) {
|
|
2057
|
+
if (hasPendingTextEdit(meta)) return true;
|
|
2058
|
+
if (!postedText.has(textEditKey(meta))) return false;
|
|
2059
|
+
return (typeof document.hasFocus === "function" ? document.hasFocus() : true) && activeEdit !== null && sameTextField(activeEdit.meta, meta);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Whether an `editor:content-update` may write `value` over `meta`'s field.
|
|
2063
|
+
* A posted value coming back is the acknowledgement this has been waiting
|
|
2064
|
+
* for, and retires it — but only that one: anything typed since keeps the
|
|
2065
|
+
* field, which is why the answer is re-derived afterwards rather than
|
|
2066
|
+
* returned from inside the branch.
|
|
2067
|
+
*/
|
|
2068
|
+
function acceptTextEditEcho(meta, value) {
|
|
2069
|
+
const key = textEditKey(meta);
|
|
2070
|
+
if (postedText.get(key) === value) postedText.delete(key);
|
|
2071
|
+
return !hasUnacknowledgedTextEdit(meta);
|
|
2072
|
+
}
|
|
2073
|
+
function restoreEditingFocus() {
|
|
2074
|
+
if (mode !== "edit" || activeEdit === null) return;
|
|
2075
|
+
const replacement = [...root.querySelectorAll("[data-eldra-field]")].find((span) => {
|
|
2076
|
+
const meta = metadataOf(span);
|
|
2077
|
+
return meta.entryId === activeEdit?.meta.entryId && meta.fieldPath === activeEdit.meta.fieldPath;
|
|
2078
|
+
});
|
|
2079
|
+
if (replacement === void 0) return;
|
|
2080
|
+
const { caretOffset, value } = activeEdit;
|
|
2081
|
+
const dirty = activeEdit.dirty || hasUnacknowledgedTextEdit(activeEdit.meta);
|
|
2082
|
+
const acknowledged = replacement.textContent === value;
|
|
2083
|
+
const sameNodes = activeEdit.element === replacement && activeEdit.node !== null && activeEdit.node === replacement.firstChild;
|
|
2084
|
+
const rewrote = dirty && !acknowledged && !sameNodes;
|
|
2085
|
+
if (rewrote) setFieldText(replacement, value);
|
|
2086
|
+
const focused = typeof document.hasFocus === "function" ? document.hasFocus() : true;
|
|
2087
|
+
const selection = document.getSelection();
|
|
2088
|
+
const caretNode = selection === null ? null : selection.focusNode;
|
|
2089
|
+
if (!rewrote && sameNodes && caretNode !== null && replacement.contains(caretNode)) {
|
|
2090
|
+
activeEdit = {
|
|
2091
|
+
meta: metadataOf(replacement),
|
|
2092
|
+
caretOffset: caretOffsetWithin(replacement),
|
|
2093
|
+
value,
|
|
2094
|
+
dirty,
|
|
2095
|
+
element: replacement,
|
|
2096
|
+
node: replacement.firstChild
|
|
2097
|
+
};
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2100
|
+
if (focused && document.activeElement !== replacement) replacement.focus({ preventScroll: true });
|
|
2101
|
+
if (selection === null) return;
|
|
2102
|
+
const range = document.createRange();
|
|
2103
|
+
const text = replacement.firstChild;
|
|
2104
|
+
const offset = Math.min(caretOffset, replacement.textContent?.length ?? 0);
|
|
2105
|
+
if (text?.nodeType === Node.TEXT_NODE) range.setStart(text, offset);
|
|
2106
|
+
else range.selectNodeContents(replacement);
|
|
2107
|
+
range.collapse(true);
|
|
2108
|
+
selection.removeAllRanges();
|
|
2109
|
+
selection.addRange(range);
|
|
2110
|
+
activeEdit = {
|
|
2111
|
+
meta: metadataOf(replacement),
|
|
2112
|
+
caretOffset: offset,
|
|
2113
|
+
value,
|
|
2114
|
+
dirty: dirty && !acknowledged,
|
|
2115
|
+
element: replacement,
|
|
2116
|
+
node: replacement.firstChild
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
function applyEditable(span) {
|
|
2120
|
+
if (span.hasAttribute("data-eldra-rich-text")) return;
|
|
2121
|
+
if (mode === "edit") {
|
|
2122
|
+
span.setAttribute("contenteditable", "true");
|
|
2123
|
+
guardRendererText(span);
|
|
2124
|
+
} else {
|
|
2125
|
+
span.removeAttribute("contenteditable");
|
|
2126
|
+
unguardRendererText(span);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* A renderer re-states a field's text on every `editor:content-update`, and
|
|
2131
|
+
* for a field whose whole content is one text run that is
|
|
2132
|
+
* `element.textContent = value` (Vue's `setElementText`; the same call in
|
|
2133
|
+
* every framework whose text patch writes a string child). The browser
|
|
2134
|
+
* answers it by **replacing the text node**, and with it goes the native
|
|
2135
|
+
* undo stack of the contenteditable it lives in: the operator loses ⌘Z for
|
|
2136
|
+
* everything they typed before that echo. Autosave guarantees at least one
|
|
2137
|
+
* echo, which is why undo appeared to work only until the page was saved.
|
|
2138
|
+
*
|
|
2139
|
+
* Two kinds of echo reach a field the operator is editing, and neither has
|
|
2140
|
+
* anything to say to the DOM.
|
|
2141
|
+
*
|
|
2142
|
+
* An echo that re-states the text already on screen. The string the renderer
|
|
2143
|
+
* holds carries the stega payload (`entryId`/`fieldPath`/`locale`), which
|
|
2144
|
+
* `decorateStegaTextNodes` strips out of the DOM, so it never equals the live
|
|
2145
|
+
* text and the renderer's own "did this change?" check cannot see that it did
|
|
2146
|
+
* not. Removing the payload from both sides before comparing makes that echo
|
|
2147
|
+
* the no-op it already was.
|
|
2148
|
+
*
|
|
2149
|
+
* An echo that is simply behind. While `hasUnacknowledgedTextEdit` holds, the
|
|
2150
|
+
* editor cannot have a draft that describes what the operator has typed, so
|
|
2151
|
+
* the renderer's value is stale by construction — `reconcileExternalDrafts`
|
|
2152
|
+
* already refuses it and `restoreEditingFocus` already undoes it. Refusing it
|
|
2153
|
+
* here instead means it never reaches the text node in the first place: the
|
|
2154
|
+
* repair afterwards cost the operator the node, the caret and the undo stack
|
|
2155
|
+
* every time.
|
|
2156
|
+
*
|
|
2157
|
+
* Scoped to the field elements the overlay has marked, and installed only in
|
|
2158
|
+
* edit mode: a published page, and a preview that is not editing, keep the
|
|
2159
|
+
* platform setter untouched. The overlay's own repair writes go through
|
|
2160
|
+
* `setFieldText`, which is not an echo and is not filtered.
|
|
2161
|
+
*/
|
|
2162
|
+
const guardedFields = /* @__PURE__ */ new WeakSet();
|
|
2163
|
+
function guardRendererText(span) {
|
|
2164
|
+
if (guardedFields.has(span)) return;
|
|
2165
|
+
const read = platformTextContent()?.get;
|
|
2166
|
+
const write = platformTextContent()?.set;
|
|
2167
|
+
if (read === void 0 || write === void 0) return;
|
|
2168
|
+
Object.defineProperty(span, "textContent", {
|
|
2169
|
+
configurable: true,
|
|
2170
|
+
enumerable: false,
|
|
2171
|
+
get() {
|
|
2172
|
+
return read.call(this);
|
|
2173
|
+
},
|
|
2174
|
+
set(value) {
|
|
2175
|
+
if (writingFieldText) {
|
|
2176
|
+
write.call(this, value);
|
|
2177
|
+
return;
|
|
2178
|
+
}
|
|
2179
|
+
if (stripStega(value === null || value === void 0 ? "" : String(value)) === stripStega(read.call(this) ?? "")) return;
|
|
2180
|
+
if (hasUnacknowledgedTextEdit(metadataOf(this))) return;
|
|
2181
|
+
write.call(this, value);
|
|
2182
|
+
}
|
|
2183
|
+
});
|
|
2184
|
+
guardedFields.add(span);
|
|
2185
|
+
}
|
|
2186
|
+
function unguardRendererText(span) {
|
|
2187
|
+
if (!guardedFields.has(span)) return;
|
|
2188
|
+
Reflect.deleteProperty(span, "textContent");
|
|
2189
|
+
guardedFields.delete(span);
|
|
2190
|
+
}
|
|
2191
|
+
function ownValueAtPath(value, path) {
|
|
2192
|
+
let current = value;
|
|
2193
|
+
for (const segment of path.split(".")) {
|
|
2194
|
+
if (segment === "" || segment === "__proto__" || segment === "prototype" || segment === "constructor" || typeof current !== "object" || current === null || !Object.prototype.hasOwnProperty.call(current, segment)) return;
|
|
2195
|
+
current = current[segment];
|
|
2196
|
+
}
|
|
2197
|
+
return current;
|
|
2198
|
+
}
|
|
2199
|
+
function reconcileExternalDrafts(drafts, entryIds) {
|
|
2200
|
+
const accepted = new Set(entryIds);
|
|
2201
|
+
root.querySelectorAll("[data-eldra-entry][data-eldra-field]").forEach((field) => {
|
|
2202
|
+
if (field.closest("[data-eldra-template-block]") !== null) return;
|
|
2203
|
+
if (field.closest("[data-eldra-rich-text]") !== null) return;
|
|
2204
|
+
const meta = metadataOf(field);
|
|
2205
|
+
if (!accepted.has(meta.entryId)) return;
|
|
2206
|
+
if (!Object.prototype.hasOwnProperty.call(drafts, meta.entryId)) return;
|
|
2207
|
+
const draft = drafts[meta.entryId];
|
|
2208
|
+
if (draft === void 0) return;
|
|
2209
|
+
const value = ownValueAtPath(draft, meta.fieldPath);
|
|
2210
|
+
if (typeof value !== "string") return;
|
|
2211
|
+
const cleaned = stripStega(value);
|
|
2212
|
+
if (!acceptTextEditEcho(meta, cleaned)) return;
|
|
2213
|
+
const text = field.firstChild;
|
|
2214
|
+
if (field.childNodes.length !== 1 || text?.nodeType !== Node.TEXT_NODE) return;
|
|
2215
|
+
const textNode = text;
|
|
2216
|
+
if (textNode.data !== cleaned) textNode.data = cleaned;
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
const XLINK_NS = "http://www.w3.org/1999/xlink";
|
|
2220
|
+
/** The href this element navigates through, however it is authored: the
|
|
2221
|
+
* plain `href` attribute, or — legacy SVG (`<a xlink:href="…">`, still
|
|
2222
|
+
* valid outside SVG2) — the `xlink:href` attribute in the XLink
|
|
2223
|
+
* namespace. `null` when neither is present. */
|
|
2224
|
+
function hrefValueOf(element) {
|
|
2225
|
+
if (element.hasAttribute("href")) return element.getAttribute("href");
|
|
2226
|
+
return element.getAttributeNS(XLINK_NS, "href");
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* Navigation guard: the first element (innermost first, walking up through
|
|
2230
|
+
* shadow boundaries) in `event`'s composed path that carries an `href` —
|
|
2231
|
+
* an `a[href]`, an `area[href]`, a legacy SVG `<a xlink:href>`, or
|
|
2232
|
+
* anything else authored with a plain or XLink `href`. `composedPath()`
|
|
2233
|
+
* rather than `event.target`/bubbling ancestors because the overlay host
|
|
2234
|
+
* is a closed shadow root; a click that lands on shadow content still
|
|
2235
|
+
* needs the theme's own light-DOM anchors it passed through on the way
|
|
2236
|
+
* out.
|
|
2237
|
+
*/
|
|
2238
|
+
function hrefElementInPath(event) {
|
|
2239
|
+
const path = typeof event.composedPath === "function" ? event.composedPath() : [];
|
|
2240
|
+
for (const node of path) if (node instanceof Element && hrefValueOf(node) !== null) return node;
|
|
2241
|
+
return null;
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* §18-adjacent (navigation guard): while the preview bridge is connected —
|
|
2245
|
+
* `start()` through `stop()`, covering both `edit` and `preview` mode —
|
|
2246
|
+
* Studio owns navigation, not the embedded iframe. A click that would
|
|
2247
|
+
* follow a link's href (however it got there: a plain click, a modifier
|
|
2248
|
+
* click that would normally open a new tab) is prevented outright;
|
|
2249
|
+
* nothing here special-cases the button or modifier keys, so every one of
|
|
2250
|
+
* those is caught by the same unconditional preventDefault. A real middle
|
|
2251
|
+
* click never reaches this as a `click` at all — the browser fires
|
|
2252
|
+
* `auxclick` for any non-primary button instead — so this same handler is
|
|
2253
|
+
* also registered for `auxclick` (see `start()`), not just `click`. An
|
|
2254
|
+
* anchor inside a rich-text root being edited is not exempted either —
|
|
2255
|
+
* putting the caret in a link's text must not navigate, the same as
|
|
2256
|
+
* anywhere else in the document.
|
|
2257
|
+
*
|
|
2258
|
+
* Registered on `document` — not `eventTarget` — because a nav bar or
|
|
2259
|
+
* footer link is not necessarily inside whatever subtree a scoped `root`
|
|
2260
|
+
* overlay instance scans; the guard's job is the whole embedded page, not
|
|
2261
|
+
* just the blocks the overlay decorates.
|
|
2262
|
+
*
|
|
2263
|
+
* Deliberately does not stop propagation: `onClick` below still needs to
|
|
2264
|
+
* run for its own selection bookkeeping (`theme:block-clicked` /
|
|
2265
|
+
* `theme:field-clicked`) even when the click also happened to land on a
|
|
2266
|
+
* link — the navigation is prevented first, then the existing handling
|
|
2267
|
+
* runs exactly as it would without a href present. (`onClick` itself is
|
|
2268
|
+
* only ever wired to `click`, so this is moot for the `auxclick` case —
|
|
2269
|
+
* there is nothing downstream to let run — but the same function handles
|
|
2270
|
+
* both events, so the same non-stopping behavior applies to both.)
|
|
2271
|
+
*
|
|
2272
|
+
* Out of scope: a `window.location` change the theme's own JS makes
|
|
2273
|
+
* directly (a router push, an imperative redirect) is not a navigation
|
|
2274
|
+
* this guard sees at all — it only ever intercepts the DOM events a link
|
|
2275
|
+
* click or a form submission dispatch. Studio moves the embedded preview
|
|
2276
|
+
* between pages via its own `editor:navigate` message instead.
|
|
2277
|
+
*/
|
|
2278
|
+
function onNavigationClick(event) {
|
|
2279
|
+
const element = hrefElementInPath(event);
|
|
2280
|
+
if (element === null) return;
|
|
2281
|
+
event.preventDefault();
|
|
2282
|
+
console.debug("[eldra] navigation prevented", hrefValueOf(element));
|
|
2283
|
+
}
|
|
2284
|
+
/** Navigation guard (submit half): a form posting/navigating the embedded
|
|
2285
|
+
* iframe is exactly the same problem a link click is — prevented
|
|
2286
|
+
* unconditionally while the bridge is connected. */
|
|
2287
|
+
function onNavigationSubmit(event) {
|
|
2288
|
+
event.preventDefault();
|
|
2289
|
+
}
|
|
2290
|
+
function onClick(event) {
|
|
2291
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
2292
|
+
if (target === null) return;
|
|
2293
|
+
if (mode === "edit") {
|
|
2294
|
+
const framed = framingEnabled ? framingImageFor(target) : null;
|
|
2295
|
+
if (framed !== null && ownsSelectedBlock(framed)) {
|
|
2296
|
+
if (framing === null || framing.image !== framed) enterFraming(framed);
|
|
2297
|
+
event.preventDefault();
|
|
2298
|
+
event.stopPropagation();
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
if (framing !== null && !framing.image.contains(target)) exitFraming();
|
|
2302
|
+
}
|
|
2303
|
+
const field = target.closest("[data-eldra-field]");
|
|
2304
|
+
const richTextRoot = field !== null && field.hasAttribute("data-eldra-rich-text") ? field : null;
|
|
2305
|
+
if (richTextRoot !== null && mode === "edit") {
|
|
2306
|
+
const block = richTextRoot.closest("[data-eldra-block]");
|
|
2307
|
+
if (block !== null && block === selectedElement()) {
|
|
2308
|
+
opts.post("theme:field-clicked", {
|
|
2309
|
+
...metadataOf(richTextRoot),
|
|
2310
|
+
...layoutIdentityOf(richTextRoot),
|
|
2311
|
+
rect: rectOf(richTextRoot)
|
|
2312
|
+
});
|
|
2313
|
+
event.preventDefault();
|
|
2314
|
+
return;
|
|
2315
|
+
}
|
|
2316
|
+
} else if (field !== null) {
|
|
2317
|
+
opts.post("theme:field-clicked", {
|
|
2318
|
+
...metadataOf(field),
|
|
2319
|
+
...layoutIdentityOf(field),
|
|
2320
|
+
rect: rectOf(field)
|
|
2321
|
+
});
|
|
2322
|
+
if (mode === "edit") return;
|
|
2323
|
+
}
|
|
2324
|
+
const block = target.closest("[data-eldra-block]");
|
|
2325
|
+
if (block === null) return;
|
|
2326
|
+
const layoutNode = target.closest("[data-eldra-layout-node]") ?? block.closest("[data-eldra-layout-node]");
|
|
2327
|
+
const layoutNodeId = layoutNode?.getAttribute("data-eldra-layout-node") || void 0;
|
|
2328
|
+
const reusablePlacementId = layoutNode?.getAttribute("data-eldra-reusable-placement") || void 0;
|
|
2329
|
+
opts.post("theme:block-clicked", {
|
|
2330
|
+
entryId: block.getAttribute("data-eldra-block") ?? "",
|
|
2331
|
+
schemaApiId: block.getAttribute("data-eldra-schema") ?? "",
|
|
2332
|
+
rect: rectOf(block),
|
|
2333
|
+
...layoutNodeId ? { layoutNodeId } : {},
|
|
2334
|
+
...reusablePlacementId ? { reusablePlacementId } : {},
|
|
2335
|
+
...hiddenAtBreakpoint(block)
|
|
2336
|
+
});
|
|
2337
|
+
if (mode === "edit") {
|
|
2338
|
+
event.preventDefault();
|
|
2339
|
+
event.stopPropagation();
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
function onPointerOver(event) {
|
|
2343
|
+
const block = (event.target instanceof Element ? event.target : null)?.closest("[data-eldra-block]") ?? null;
|
|
2344
|
+
hoveredElement = block;
|
|
2345
|
+
if (hoverBox !== null) positionBox(hoverBox, block);
|
|
2346
|
+
scheduleHoverReport("change");
|
|
2347
|
+
}
|
|
2348
|
+
/** Clears the tracked hover once the pointer actually leaves the document
|
|
2349
|
+
* (relatedTarget null on the bubbled pointerout), so a stale hover does
|
|
2350
|
+
* not get re-anchored by the next scroll/resize. */
|
|
2351
|
+
function onPointerOut(event) {
|
|
2352
|
+
if (event.relatedTarget !== null) return;
|
|
2353
|
+
hoveredElement = null;
|
|
2354
|
+
if (hoverBox !== null) positionBox(hoverBox, null);
|
|
2355
|
+
scheduleHoverReport("change");
|
|
2356
|
+
}
|
|
2357
|
+
function layoutNodes() {
|
|
2358
|
+
return [...root.querySelectorAll("[data-eldra-layout-node]")];
|
|
2359
|
+
}
|
|
2360
|
+
function resolveSlotMarker(clientX, clientY) {
|
|
2361
|
+
const markers = root.querySelectorAll("[data-eldra-slot-marker]");
|
|
2362
|
+
for (const marker of markers) {
|
|
2363
|
+
const rect = marker.getBoundingClientRect();
|
|
2364
|
+
if (rect.width <= 0 || rect.height <= 0) continue;
|
|
2365
|
+
if (clientX < rect.left || clientX > rect.right || clientY < rect.top || clientY > rect.bottom) continue;
|
|
2366
|
+
const layoutNodeId = marker.getAttribute("data-eldra-layout-node-id") ?? "";
|
|
2367
|
+
const slotId = marker.getAttribute("data-eldra-slot-id") ?? "";
|
|
2368
|
+
if (layoutNodeId === "" || slotId === "") continue;
|
|
2369
|
+
return {
|
|
2370
|
+
layoutNodeId,
|
|
2371
|
+
placement: "inside",
|
|
2372
|
+
rect: rectOf(marker),
|
|
2373
|
+
slotId
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
return null;
|
|
2377
|
+
}
|
|
2378
|
+
function resolveCanvasPlacement(clientX, clientY) {
|
|
2379
|
+
const slotTarget = resolveSlotMarker(clientX, clientY);
|
|
2380
|
+
if (slotTarget !== null) return slotTarget;
|
|
2381
|
+
const nodes = [...layoutNodes()].reverse().filter((node) => {
|
|
2382
|
+
const rect = node.getBoundingClientRect();
|
|
2383
|
+
return rect.width > 0 && rect.height > 0;
|
|
2384
|
+
});
|
|
2385
|
+
let hit = null;
|
|
2386
|
+
for (const node of nodes) {
|
|
2387
|
+
const rect = node.getBoundingClientRect();
|
|
2388
|
+
if (clientY >= rect.top && clientY <= rect.bottom && clientX >= rect.left && clientX <= rect.right) {
|
|
2389
|
+
hit = node;
|
|
2390
|
+
break;
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
if (!hit) return null;
|
|
2394
|
+
const rect = hit.getBoundingClientRect();
|
|
2395
|
+
const ratio = (clientY - rect.top) / Math.max(rect.height, 1);
|
|
2396
|
+
if ((hit.querySelector("[data-eldra-layout-node]") !== null || hit.children.length > 0) && ratio >= .25 && ratio <= .75) return {
|
|
2397
|
+
layoutNodeId: hit.getAttribute("data-eldra-layout-node") ?? "",
|
|
2398
|
+
placement: "inside",
|
|
2399
|
+
rect: rectOf(hit)
|
|
2400
|
+
};
|
|
2401
|
+
return {
|
|
2402
|
+
layoutNodeId: hit.getAttribute("data-eldra-layout-node") ?? "",
|
|
2403
|
+
placement: ratio < .5 ? "before" : "after",
|
|
2404
|
+
rect: rectOf(hit)
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
function positionDropIndicator(target) {
|
|
2408
|
+
if (!dropIndicator) return;
|
|
2409
|
+
if (target.placement === "inside") {
|
|
2410
|
+
positionBox(dropIndicator, null);
|
|
2411
|
+
return;
|
|
2412
|
+
}
|
|
2413
|
+
Object.assign(dropIndicator.style, {
|
|
2414
|
+
display: "block",
|
|
2415
|
+
left: `${target.rect.x}px`,
|
|
2416
|
+
top: `${target.placement === "before" ? target.rect.y : target.rect.y + target.rect.height}px`,
|
|
2417
|
+
width: `${target.rect.width}px`,
|
|
2418
|
+
height: "2px"
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
function clearDropIndicator() {
|
|
2422
|
+
if (dropIndicator) dropIndicator.style.display = "none";
|
|
2423
|
+
}
|
|
2424
|
+
function onDragPointerMove(event) {
|
|
2425
|
+
if (!dragPayload) return;
|
|
2426
|
+
const target = resolveCanvasPlacement(event.clientX, event.clientY);
|
|
2427
|
+
opts.post("theme:drop-candidate", target);
|
|
2428
|
+
if (target) positionDropIndicator(target);
|
|
2429
|
+
else clearDropIndicator();
|
|
2430
|
+
}
|
|
2431
|
+
function onDragPointerUp(event) {
|
|
2432
|
+
if (!dragPayload) return;
|
|
2433
|
+
const target = resolveCanvasPlacement(event.clientX, event.clientY);
|
|
2434
|
+
if (target) opts.post("theme:node-dropped", {
|
|
2435
|
+
payload: dragPayload,
|
|
2436
|
+
layoutNodeId: target.layoutNodeId,
|
|
2437
|
+
placement: target.placement,
|
|
2438
|
+
...target.slotId !== void 0 ? { slotId: target.slotId } : {}
|
|
2439
|
+
});
|
|
2440
|
+
dragPayload = null;
|
|
2441
|
+
clearDropIndicator();
|
|
2442
|
+
window.removeEventListener("pointermove", onDragPointerMove, true);
|
|
2443
|
+
window.removeEventListener("pointerup", onDragPointerUp, true);
|
|
2444
|
+
}
|
|
2445
|
+
function onInput(event) {
|
|
2446
|
+
const target = elementTargetOf(event);
|
|
2447
|
+
if (target?.closest("[data-eldra-rich-text]") != null) {
|
|
2448
|
+
onRichTextInput(event);
|
|
2449
|
+
return;
|
|
2450
|
+
}
|
|
2451
|
+
const span = target?.closest("[data-eldra-field]") ?? null;
|
|
2452
|
+
if (span === null || mode !== "edit") return;
|
|
2453
|
+
rememberEditing(span, true);
|
|
2454
|
+
const pending = debounceTimers.get(span);
|
|
2455
|
+
if (pending !== void 0) clearTimeout(pending);
|
|
2456
|
+
debounceTimers.set(span, setTimeout(() => {
|
|
2457
|
+
debounceTimers.delete(span);
|
|
2458
|
+
const meta = metadataOf(span);
|
|
2459
|
+
const value = stripStega(span.textContent ?? "");
|
|
2460
|
+
postedText.set(textEditKey(meta), value);
|
|
2461
|
+
opts.post("theme:text-edited", {
|
|
2462
|
+
...meta,
|
|
2463
|
+
...layoutIdentityOf(span),
|
|
2464
|
+
value
|
|
2465
|
+
});
|
|
2466
|
+
}, TEXT_EDIT_DEBOUNCE_MS));
|
|
2467
|
+
}
|
|
2468
|
+
/** An event's target as an element: a DOM event inside a contenteditable
|
|
2469
|
+
* names the element in browsers, but a text node is a legal target and
|
|
2470
|
+
* `closest` only exists on elements. */
|
|
2471
|
+
function elementTargetOf(event) {
|
|
2472
|
+
const node = event.target instanceof Node ? event.target : null;
|
|
2473
|
+
if (node === null) return null;
|
|
2474
|
+
return node.nodeType === 1 ? node : node.parentElement;
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* §18 v3: the browser has just performed the edit classified as native in
|
|
2478
|
+
* `beforeinput`. Report it against the range captured there — the DOM has
|
|
2479
|
+
* already moved, so re-reading it now would describe the result rather than
|
|
2480
|
+
* the change. A composition reports on `compositionend` only, never here.
|
|
2481
|
+
*/
|
|
2482
|
+
function onRichTextInput(event) {
|
|
2483
|
+
const pending = pendingNativeInput;
|
|
2484
|
+
if (pending === null) return;
|
|
2485
|
+
if (isInputEvent(event) && event.isComposing === true) return;
|
|
2486
|
+
const element = editableRichTextRootOf(event.target instanceof Node ? event.target : null);
|
|
2487
|
+
pendingNativeInput = null;
|
|
2488
|
+
if (element === null || richTextKeyOf(element) !== pending.key || !isRichTextEditingActive(element)) return;
|
|
2489
|
+
postNativeRichTextInput(pending, isInputEvent(event) && typeof event.data === "string" ? event.data : pending.data);
|
|
2490
|
+
}
|
|
2491
|
+
function onFocusIn(event) {
|
|
2492
|
+
const target = elementTargetOf(event);
|
|
2493
|
+
const richTextRoot = target?.closest("[data-eldra-rich-text]") ?? null;
|
|
2494
|
+
if (richTextRoot !== null) {
|
|
2495
|
+
activeEdit = null;
|
|
2496
|
+
if (!isRichTextEditingActive(richTextRoot)) reportRichTextSelection();
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
const span = target?.closest("[data-eldra-field]") ?? null;
|
|
2500
|
+
if (span !== null && mode === "edit") rememberEditing(span);
|
|
2501
|
+
else activeEdit = null;
|
|
2502
|
+
}
|
|
2503
|
+
/**
|
|
2504
|
+
* §18 v3 (floating toolbar): focus leaving an editable root to somewhere
|
|
2505
|
+
* else *in this document* is a blur — the toolbar has nothing left to float
|
|
2506
|
+
* over. `relatedTarget === null` means focus left the iframe window
|
|
2507
|
+
* entirely (typically to Studio's own floating toolbar after a command);
|
|
2508
|
+
* that is not a blur, and Studio — not the theme — decides what happens
|
|
2509
|
+
* next, so nothing is posted. `relatedTarget` inside the same root (an
|
|
2510
|
+
* interactive descendant, e.g. a link) is not a departure either. Focus
|
|
2511
|
+
* coming back later reports a normal selection through the existing
|
|
2512
|
+
* focusin/selectionchange paths.
|
|
2513
|
+
*/
|
|
2514
|
+
function onFocusOut(event) {
|
|
2515
|
+
const richTextRoot = editableRichTextRootOf(elementTargetOf(event));
|
|
2516
|
+
if (richTextRoot === null) return;
|
|
2517
|
+
const relatedTarget = event.relatedTarget;
|
|
2518
|
+
if (relatedTarget === null) return;
|
|
2519
|
+
if (relatedTarget instanceof Node && richTextRoot.contains(relatedTarget)) return;
|
|
2520
|
+
postRichTextBlur();
|
|
2521
|
+
}
|
|
2522
|
+
function reposition() {
|
|
2523
|
+
if (hoveredElement !== null && !hoveredElement.isConnected) hoveredElement = null;
|
|
2524
|
+
if (hoverBox !== null) positionBox(hoverBox, hoveredElement);
|
|
2525
|
+
if (selectedBox !== null) positionBox(selectedBox, selectedElement());
|
|
2526
|
+
if (framing !== null) positionFramingChrome();
|
|
2527
|
+
scheduleReportBlocks();
|
|
2528
|
+
scheduleHoverReport("geometry");
|
|
2529
|
+
scheduleRichTextSync();
|
|
2530
|
+
scheduleRichTextSelectionRepost();
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Report the hovered block to the editor, coalesced to one post per
|
|
2534
|
+
* animation frame so a pointer sweep or a scroll burst does not flood the
|
|
2535
|
+
* bridge. `reason` separates the two callers: a pointer event ('change')
|
|
2536
|
+
* posts only when the hovered block is a different one, while 'geometry' —
|
|
2537
|
+
* every `reposition()`, so a scroll or resize but equally a selection
|
|
2538
|
+
* change or a rerender — re-posts the same block's rect, which may well be
|
|
2539
|
+
* the rect already sent. Either way, with nothing hovered the only post
|
|
2540
|
+
* left to make is the leave message.
|
|
2541
|
+
*/
|
|
2542
|
+
function scheduleHoverReport(reason) {
|
|
2543
|
+
if (!started || !blockHoverEnabled || mode !== "edit") return;
|
|
2544
|
+
if (hoveredElement === null) {
|
|
2545
|
+
if (reportedHoverElement === null) return;
|
|
2546
|
+
} else if (reason === "geometry") hoverGeometryStale = true;
|
|
2547
|
+
else if (hoveredElement === reportedHoverElement && !hoverGeometryStale) return;
|
|
2548
|
+
if (hoverReportRaf !== null) return;
|
|
2549
|
+
hoverReportRaf = requestAnimationFrame(() => {
|
|
2550
|
+
hoverReportRaf = null;
|
|
2551
|
+
const stale = hoverGeometryStale;
|
|
2552
|
+
hoverGeometryStale = false;
|
|
2553
|
+
reportHoveredBlock(stale);
|
|
2554
|
+
});
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* Posts the hovered block's identity and rect, or `null` once a block that
|
|
2558
|
+
* was reported stops being hovered. `refreshGeometry` is the scroll/resize
|
|
2559
|
+
* path: the block is unchanged but its rect is not, so the dedupe against
|
|
2560
|
+
* `reportedHoverElement` must not swallow the post.
|
|
2561
|
+
*
|
|
2562
|
+
* A rerender can detach the hovered node without any pointerout (the same
|
|
2563
|
+
* case `reposition()` guards for the hover box), so a disconnected element
|
|
2564
|
+
* counts as no hover and posts the leave message.
|
|
2565
|
+
*/
|
|
2566
|
+
function reportHoveredBlock(refreshGeometry) {
|
|
2567
|
+
if (!started || !blockHoverEnabled || mode !== "edit") return;
|
|
2568
|
+
const block = hoveredElement !== null && hoveredElement.isConnected ? hoveredElement : null;
|
|
2569
|
+
if (block === null && reportedHoverElement === null) return;
|
|
2570
|
+
if (block === reportedHoverElement && !refreshGeometry) return;
|
|
2571
|
+
reportedHoverElement = block;
|
|
2572
|
+
if (block === null) {
|
|
2573
|
+
opts.post("theme:block-hovered", null);
|
|
2574
|
+
return;
|
|
2575
|
+
}
|
|
2576
|
+
opts.post("theme:block-hovered", {
|
|
2577
|
+
entryId: block.getAttribute("data-eldra-block") ?? "",
|
|
2578
|
+
rect: rectOf(block),
|
|
2579
|
+
...layoutIdentityOf(block)
|
|
2580
|
+
});
|
|
2581
|
+
}
|
|
2582
|
+
/** Forget the reported hover without posting a leave message — for the
|
|
2583
|
+
* transitions Studio itself drove (a mode change, the capability closing,
|
|
2584
|
+
* teardown), where the other side either knows already or cannot receive
|
|
2585
|
+
* the post at all. */
|
|
2586
|
+
function forgetReportedHover() {
|
|
2587
|
+
reportedHoverElement = null;
|
|
2588
|
+
hoverGeometryStale = false;
|
|
2589
|
+
if (hoverReportRaf !== null) {
|
|
2590
|
+
cancelAnimationFrame(hoverReportRaf);
|
|
2591
|
+
hoverReportRaf = null;
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
/** Studio anchors its floating chrome to block rects reported over
|
|
2595
|
+
* `theme:blocks-rendered`; the iframe can scroll (or be resized)
|
|
2596
|
+
* internally without any DOM mutation the MutationObserver would catch,
|
|
2597
|
+
* so reposition() (bound to window scroll/resize) also re-reports block
|
|
2598
|
+
* geometry here — coalesced to one post per animation frame so a
|
|
2599
|
+
* scroll burst does not flood the bridge. */
|
|
2600
|
+
function scheduleReportBlocks() {
|
|
2601
|
+
if (!started || blocksRaf !== null) return;
|
|
2602
|
+
blocksRaf = requestAnimationFrame(() => {
|
|
2603
|
+
blocksRaf = null;
|
|
2604
|
+
reportBlocks();
|
|
2605
|
+
});
|
|
2606
|
+
}
|
|
2607
|
+
function reportBlocks() {
|
|
2608
|
+
const blocks = [...root.querySelectorAll("[data-eldra-block]")].map((block) => {
|
|
2609
|
+
const layoutNode = block.closest("[data-eldra-layout-node]");
|
|
2610
|
+
const layoutNodeId = layoutNode?.getAttribute("data-eldra-layout-node") || void 0;
|
|
2611
|
+
const reusablePlacementId = layoutNode?.getAttribute("data-eldra-reusable-placement") || void 0;
|
|
2612
|
+
return {
|
|
2613
|
+
entryId: block.getAttribute("data-eldra-block") ?? "",
|
|
2614
|
+
rect: rectOf(block),
|
|
2615
|
+
...layoutNodeId ? { layoutNodeId } : {},
|
|
2616
|
+
...reusablePlacementId ? { reusablePlacementId } : {},
|
|
2617
|
+
...hiddenAtBreakpoint(block)
|
|
2618
|
+
};
|
|
2619
|
+
});
|
|
2620
|
+
opts.post("theme:blocks-rendered", { blocks });
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Is *this* element's own layout node hidden at the breakpoint currently in
|
|
2624
|
+
* force? Strictly own-node: a block inside a hidden container reports
|
|
2625
|
+
* nothing, because unhiding it is a different act from unhiding its parent
|
|
2626
|
+
* and Studio needs to tell the two apart.
|
|
2627
|
+
*
|
|
2628
|
+
* `data-eldra-hidden` is the node's own list of hidden breakpoints, put
|
|
2629
|
+
* there by the framework binding at render time; `activeLayoutBreakpoint`
|
|
2630
|
+
* resolves the viewport against the same three ranges the layout CSS wrote
|
|
2631
|
+
* its `@media` blocks with. Reading `display` instead would not work in edit
|
|
2632
|
+
* mode, which is the only mode that asks: there the node is deliberately
|
|
2633
|
+
* still displayed.
|
|
2634
|
+
*
|
|
2635
|
+
* Spread into a payload, so a visible block's message is byte-identical to
|
|
2636
|
+
* what it was before this field existed.
|
|
2637
|
+
*/
|
|
2638
|
+
function hiddenAtBreakpoint(element) {
|
|
2639
|
+
const hidden = element.getAttribute("data-eldra-hidden");
|
|
2640
|
+
if (hidden === null) return {};
|
|
2641
|
+
const active = activeLayoutBreakpoint(window.innerWidth, opts.breakpoints);
|
|
2642
|
+
return hidden.split(" ").includes(active) ? { hiddenAtBreakpoint: true } : {};
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Edit mode keeps a breakpoint-hidden node on the canvas so the author can
|
|
2646
|
+
* still see and select it. The layout CSS gates its `display:none` on
|
|
2647
|
+
* `:not([data-eldra-edit-mode])` and dims the node when that attribute is
|
|
2648
|
+
* there, so all this has to do is put the attribute on the nodes a framework
|
|
2649
|
+
* binding marked `data-eldra-hidden` — after mount, like every other overlay
|
|
2650
|
+
* decoration, never during render, so server and client agree on the DOM.
|
|
2651
|
+
*
|
|
2652
|
+
* The name says *mode*, not "this element is being edited": the marker means
|
|
2653
|
+
* "the canvas is in edit mode, so do not hide me". `data-eldra-rich-text-editing`
|
|
2654
|
+
* is the one that marks an element actually under edit.
|
|
2655
|
+
*/
|
|
2656
|
+
function applyHiddenEditing() {
|
|
2657
|
+
const editing = started && mode === "edit";
|
|
2658
|
+
for (const element of root.querySelectorAll("[data-eldra-hidden]")) if (editing) element.setAttribute("data-eldra-edit-mode", "");
|
|
2659
|
+
else element.removeAttribute("data-eldra-edit-mode");
|
|
2660
|
+
}
|
|
2661
|
+
return {
|
|
2662
|
+
start() {
|
|
2663
|
+
if (started) return;
|
|
2664
|
+
started = true;
|
|
2665
|
+
mountHost();
|
|
2666
|
+
decorateStegaTextNodes();
|
|
2667
|
+
applyRichTextEditable();
|
|
2668
|
+
applyHiddenEditing();
|
|
2669
|
+
reportBlocks();
|
|
2670
|
+
document.addEventListener("click", onNavigationClick, true);
|
|
2671
|
+
document.addEventListener("auxclick", onNavigationClick, true);
|
|
2672
|
+
document.addEventListener("submit", onNavigationSubmit, true);
|
|
2673
|
+
eventTarget.addEventListener("click", onClick, true);
|
|
2674
|
+
eventTarget.addEventListener("pointerover", onPointerOver, true);
|
|
2675
|
+
eventTarget.addEventListener("pointerout", onPointerOut, true);
|
|
2676
|
+
eventTarget.addEventListener("input", onInput, true);
|
|
2677
|
+
eventTarget.addEventListener("focusin", onFocusIn, true);
|
|
2678
|
+
eventTarget.addEventListener("focusout", onFocusOut, true);
|
|
2679
|
+
eventTarget.addEventListener("beforeinput", onBeforeInput, true);
|
|
2680
|
+
eventTarget.addEventListener("compositionstart", onCompositionStart, true);
|
|
2681
|
+
eventTarget.addEventListener("compositionend", onCompositionEnd, true);
|
|
2682
|
+
document.addEventListener("selectionchange", onSelectionChange);
|
|
2683
|
+
window.addEventListener("scroll", reposition, true);
|
|
2684
|
+
window.addEventListener("resize", reposition);
|
|
2685
|
+
observer = new MutationObserver(onMutations);
|
|
2686
|
+
observer.observe(scanRoot(), {
|
|
2687
|
+
childList: true,
|
|
2688
|
+
characterData: true,
|
|
2689
|
+
subtree: true
|
|
2690
|
+
});
|
|
2691
|
+
},
|
|
2692
|
+
stop() {
|
|
2693
|
+
if (!started) return;
|
|
2694
|
+
started = false;
|
|
2695
|
+
exitFraming();
|
|
2696
|
+
clearRichTextEditing();
|
|
2697
|
+
mode = "preview";
|
|
2698
|
+
applyRichTextEditable();
|
|
2699
|
+
applyHiddenEditing();
|
|
2700
|
+
richTextRevisions.clear();
|
|
2701
|
+
releaseAllRichTextRenders();
|
|
2702
|
+
if (blocksRaf !== null) {
|
|
2703
|
+
cancelAnimationFrame(blocksRaf);
|
|
2704
|
+
blocksRaf = null;
|
|
2705
|
+
}
|
|
2706
|
+
if (selectionRaf !== null) {
|
|
2707
|
+
cancelAnimationFrame(selectionRaf);
|
|
2708
|
+
selectionRaf = null;
|
|
2709
|
+
}
|
|
2710
|
+
if (richTextSelectionRepostRaf !== null) {
|
|
2711
|
+
cancelAnimationFrame(richTextSelectionRepostRaf);
|
|
2712
|
+
richTextSelectionRepostRaf = null;
|
|
2713
|
+
}
|
|
2714
|
+
observer?.disconnect();
|
|
2715
|
+
observer = null;
|
|
2716
|
+
document.removeEventListener("click", onNavigationClick, true);
|
|
2717
|
+
document.removeEventListener("auxclick", onNavigationClick, true);
|
|
2718
|
+
document.removeEventListener("submit", onNavigationSubmit, true);
|
|
2719
|
+
eventTarget.removeEventListener("click", onClick, true);
|
|
2720
|
+
eventTarget.removeEventListener("pointerover", onPointerOver, true);
|
|
2721
|
+
eventTarget.removeEventListener("pointerout", onPointerOut, true);
|
|
2722
|
+
eventTarget.removeEventListener("input", onInput, true);
|
|
2723
|
+
eventTarget.removeEventListener("focusin", onFocusIn, true);
|
|
2724
|
+
eventTarget.removeEventListener("focusout", onFocusOut, true);
|
|
2725
|
+
eventTarget.removeEventListener("beforeinput", onBeforeInput, true);
|
|
2726
|
+
eventTarget.removeEventListener("compositionstart", onCompositionStart, true);
|
|
2727
|
+
eventTarget.removeEventListener("compositionend", onCompositionEnd, true);
|
|
2728
|
+
document.removeEventListener("selectionchange", onSelectionChange);
|
|
2729
|
+
window.removeEventListener("scroll", reposition, true);
|
|
2730
|
+
window.removeEventListener("resize", reposition);
|
|
2731
|
+
window.removeEventListener("pointermove", onDragPointerMove, true);
|
|
2732
|
+
window.removeEventListener("pointerup", onDragPointerUp, true);
|
|
2733
|
+
dragPayload = null;
|
|
2734
|
+
host?.remove();
|
|
2735
|
+
host = null;
|
|
2736
|
+
styleEl = null;
|
|
2737
|
+
hoverBox = null;
|
|
2738
|
+
hoveredElement = null;
|
|
2739
|
+
forgetReportedHover();
|
|
2740
|
+
selectedBox = null;
|
|
2741
|
+
dropIndicator = null;
|
|
2742
|
+
framingBox = null;
|
|
2743
|
+
framingBadge = null;
|
|
2744
|
+
for (const timer of debounceTimers.values()) clearTimeout(timer);
|
|
2745
|
+
debounceTimers.clear();
|
|
2746
|
+
postedText.clear();
|
|
2747
|
+
activeEdit = null;
|
|
2748
|
+
root.querySelectorAll("[data-eldra-field]").forEach(unguardRendererText);
|
|
2749
|
+
},
|
|
2750
|
+
setMode(nextMode) {
|
|
2751
|
+
mode = nextMode;
|
|
2752
|
+
if (nextMode !== "edit") postedText.clear();
|
|
2753
|
+
if (nextMode !== "edit") exitFraming();
|
|
2754
|
+
if (nextMode !== "edit") clearRichTextEditing();
|
|
2755
|
+
root.querySelectorAll("[data-eldra-field]").forEach(applyEditable);
|
|
2756
|
+
applyRichTextEditable();
|
|
2757
|
+
applyHiddenEditing();
|
|
2758
|
+
reposition();
|
|
2759
|
+
hoveredElement = null;
|
|
2760
|
+
if (hoverBox !== null) positionBox(hoverBox, null);
|
|
2761
|
+
forgetReportedHover();
|
|
2762
|
+
},
|
|
2763
|
+
setSelected(entryId, layoutNodeId, reusablePlacementId) {
|
|
2764
|
+
selectedId = entryId;
|
|
2765
|
+
selectedLayoutNodeId = entryId === null ? null : layoutNodeId ?? null;
|
|
2766
|
+
selectedReusablePlacementId = entryId === null ? null : reusablePlacementId ?? null;
|
|
2767
|
+
if (framing !== null && (entryId === null || entryId !== framing.entryId)) exitFraming();
|
|
2768
|
+
reposition();
|
|
2769
|
+
},
|
|
2770
|
+
acceptExternalUpdate(entryIds) {
|
|
2771
|
+
if (activeEdit === null || !entryIds.includes(activeEdit.meta.entryId)) return;
|
|
2772
|
+
activeEdit = {
|
|
2773
|
+
...activeEdit,
|
|
2774
|
+
dirty: false
|
|
2775
|
+
};
|
|
2776
|
+
},
|
|
2777
|
+
reconcileExternalDrafts,
|
|
2778
|
+
rescan() {
|
|
2779
|
+
decorateStegaTextNodes();
|
|
2780
|
+
applyRichTextEditable();
|
|
2781
|
+
applyHiddenEditing();
|
|
2782
|
+
if (framing !== null && !framing.image.isConnected) {
|
|
2783
|
+
const replacement = findFramingImage(framing.entryId, framing.fieldPath);
|
|
2784
|
+
if (replacement === null) exitFraming();
|
|
2785
|
+
else {
|
|
2786
|
+
detachFramingListeners(framing.image);
|
|
2787
|
+
framing.image = replacement;
|
|
2788
|
+
attachFramingListeners(replacement);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
if (framing !== null) {
|
|
2792
|
+
if (framingGestureInFlight()) applyFraming();
|
|
2793
|
+
else {
|
|
2794
|
+
framing.value = parseImageFramingValueAttr(framing.image.dataset.eldraFramingValue);
|
|
2795
|
+
if (framingBadge !== null) framingBadge.textContent = `${framing.value.zoom.toFixed(1)}x`;
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
reposition();
|
|
2799
|
+
reportBlocks();
|
|
2800
|
+
},
|
|
2801
|
+
setFramingMode(target) {
|
|
2802
|
+
if (target === null) {
|
|
2803
|
+
exitFraming();
|
|
2804
|
+
return;
|
|
2805
|
+
}
|
|
2806
|
+
if (!framingEnabled) return;
|
|
2807
|
+
const image = findFramingImage(target.entryId, target.fieldPath);
|
|
2808
|
+
if (image === null) return;
|
|
2809
|
+
enterFraming(image);
|
|
2810
|
+
},
|
|
2811
|
+
setFramingEnabled(enabled) {
|
|
2812
|
+
framingEnabled = enabled;
|
|
2813
|
+
if (!enabled) exitFraming({ silent: true });
|
|
2814
|
+
},
|
|
2815
|
+
setBlockHoverEnabled(enabled) {
|
|
2816
|
+
blockHoverEnabled = enabled;
|
|
2817
|
+
if (!enabled) forgetReportedHover();
|
|
2818
|
+
},
|
|
2819
|
+
setRichTextEditing(target, active) {
|
|
2820
|
+
if (!richTextEnabled) return;
|
|
2821
|
+
if (!active) {
|
|
2822
|
+
unmarkRichTextEditing();
|
|
2823
|
+
releaseRichTextRenderFor(target);
|
|
2824
|
+
return;
|
|
2825
|
+
}
|
|
2826
|
+
const element = findRichTextRoot(target.entryId, target.fieldPath, target.locale, target.layoutNodeId, target.reusablePlacementId);
|
|
2827
|
+
if (element === null) {
|
|
2828
|
+
unmarkRichTextEditing();
|
|
2829
|
+
releaseRichTextRenderFor(target);
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2832
|
+
if (editingRichTextRoot !== null && editingRichTextRoot !== element) {
|
|
2833
|
+
const leaving = richTextIdentityOf(editingRichTextRoot);
|
|
2834
|
+
unmarkRichTextEditing();
|
|
2835
|
+
releaseRichTextRenderFor(leaving);
|
|
2836
|
+
}
|
|
2837
|
+
editingRichTextRoot = element;
|
|
2838
|
+
editingRichTextIdentity = richTextIdentityOf(element);
|
|
2839
|
+
applyRichTextEditing(element, true);
|
|
2840
|
+
flushPendingRichTextIntentsHere(element);
|
|
2841
|
+
},
|
|
2842
|
+
acceptRichTextApplied,
|
|
2843
|
+
isRichTextRenderDeferred(identity) {
|
|
2844
|
+
if (deferredRenders.has(richTextKey(identity))) return true;
|
|
2845
|
+
if (identity.layoutNodeId !== void 0 || identity.reusablePlacementId !== void 0) return false;
|
|
2846
|
+
for (const { meta } of deferredRenders.values()) if (meta.entryId === identity.entryId && meta.fieldPath === identity.fieldPath && meta.locale === identity.locale) return true;
|
|
2847
|
+
return false;
|
|
2848
|
+
},
|
|
2849
|
+
onRichTextRenderState(listener) {
|
|
2850
|
+
richTextRenderListeners.add(listener);
|
|
2851
|
+
return () => {
|
|
2852
|
+
richTextRenderListeners.delete(listener);
|
|
2853
|
+
};
|
|
2854
|
+
},
|
|
2855
|
+
locateRichText(target) {
|
|
2856
|
+
if (!richTextEnabled) return;
|
|
2857
|
+
const element = findRichTextRoot(target.entryId, target.fieldPath, target.locale, target.layoutNodeId, target.reusablePlacementId);
|
|
2858
|
+
if (element === null) return;
|
|
2859
|
+
element.scrollIntoView?.({ block: "nearest" });
|
|
2860
|
+
if (mode !== "edit" || !richTextEnabled) return;
|
|
2861
|
+
element.focus?.({ preventScroll: true });
|
|
2862
|
+
placeCaretAtEnd(element);
|
|
2863
|
+
},
|
|
2864
|
+
setRichTextEnabled(enabled) {
|
|
2865
|
+
richTextEnabled = enabled;
|
|
2866
|
+
if (!enabled) clearRichTextEditing();
|
|
2867
|
+
applyRichTextEditable();
|
|
2868
|
+
},
|
|
2869
|
+
setDragPayload(payload) {
|
|
2870
|
+
dragPayload = payload;
|
|
2871
|
+
clearDropIndicator();
|
|
2872
|
+
if (payload === null) {
|
|
2873
|
+
window.removeEventListener("pointermove", onDragPointerMove, true);
|
|
2874
|
+
window.removeEventListener("pointerup", onDragPointerUp, true);
|
|
2875
|
+
} else {
|
|
2876
|
+
window.addEventListener("pointermove", onDragPointerMove, true);
|
|
2877
|
+
window.addEventListener("pointerup", onDragPointerUp, true);
|
|
2878
|
+
}
|
|
2879
|
+
},
|
|
2880
|
+
chromeStyles() {
|
|
2881
|
+
return styleEl?.textContent ?? CHROME_STYLES;
|
|
2882
|
+
},
|
|
2883
|
+
chromeState() {
|
|
2884
|
+
const parsePx = (value) => parseFloat(value) || 0;
|
|
2885
|
+
return {
|
|
2886
|
+
hover: {
|
|
2887
|
+
display: hoverBox?.style.display === "block" ? "block" : "none",
|
|
2888
|
+
rect: {
|
|
2889
|
+
x: parsePx(hoverBox?.style.left ?? ""),
|
|
2890
|
+
y: parsePx(hoverBox?.style.top ?? ""),
|
|
2891
|
+
width: parsePx(hoverBox?.style.width ?? ""),
|
|
2892
|
+
height: parsePx(hoverBox?.style.height ?? "")
|
|
2893
|
+
}
|
|
2894
|
+
},
|
|
2895
|
+
selected: selectedBox?.style.display === "block" ? "block" : "none",
|
|
2896
|
+
framing: framingBox?.style.display === "block" ? "block" : "none",
|
|
2897
|
+
frameRect: {
|
|
2898
|
+
x: parsePx(framingBox?.style.left ?? ""),
|
|
2899
|
+
y: parsePx(framingBox?.style.top ?? ""),
|
|
2900
|
+
width: parsePx(framingBox?.style.width ?? ""),
|
|
2901
|
+
height: parsePx(framingBox?.style.height ?? "")
|
|
2902
|
+
}
|
|
2903
|
+
};
|
|
2904
|
+
}
|
|
2905
|
+
};
|
|
2906
|
+
}
|
|
2907
|
+
//#endregion
|
|
2908
|
+
export { RICH_TEXT_PAD_ATTR as a, domRangeToPositions as c, restampRichTextPositions as d, richTextMarkNameOf as f, layoutIdentityOf as h, RICH_TEXT_MARK_ELEMENTS as i, resolveDomPoint as l, richTextText as m, createOverlayRuntime as n, computeRichTextPositions as o, richTextNodeSize as p, RICH_TEXT_LEAF_TYPES as r, describeSelectionContext as s, classifyBeforeInput as t, resolveDomPosition as u };
|