@alien6-studio/elea-content-editor 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +220 -2
- package/dist/AddBlockButton.d.ts +16 -0
- package/dist/AddBlockButton.d.ts.map +1 -0
- package/dist/AddBlockButton.js +103 -0
- package/dist/AddBlockButton.js.map +1 -0
- package/dist/BlockEditor.d.ts +46 -0
- package/dist/BlockEditor.d.ts.map +1 -0
- package/dist/BlockEditor.js +397 -0
- package/dist/BlockEditor.js.map +1 -0
- package/dist/ContentEditor.d.ts +59 -0
- package/dist/ContentEditor.d.ts.map +1 -0
- package/dist/ContentEditor.js +460 -0
- package/dist/ContentEditor.js.map +1 -0
- package/dist/EditorPreview.d.ts +12 -0
- package/dist/EditorPreview.d.ts.map +1 -0
- package/dist/EditorPreview.js +10 -0
- package/dist/EditorPreview.js.map +1 -0
- package/dist/MarkdownEditor.d.ts +14 -0
- package/dist/MarkdownEditor.d.ts.map +1 -0
- package/dist/MarkdownEditor.js +30 -0
- package/dist/MarkdownEditor.js.map +1 -0
- package/dist/QuickAddButtons.d.ts +10 -0
- package/dist/QuickAddButtons.d.ts.map +1 -0
- package/dist/QuickAddButtons.js +19 -0
- package/dist/QuickAddButtons.js.map +1 -0
- package/dist/RichTextField.d.ts +72 -0
- package/dist/RichTextField.d.ts.map +1 -0
- package/dist/RichTextField.js +1008 -0
- package/dist/RichTextField.js.map +1 -0
- package/dist/RichTextInput.d.ts +12 -0
- package/dist/RichTextInput.d.ts.map +1 -0
- package/dist/RichTextInput.js +148 -0
- package/dist/RichTextInput.js.map +1 -0
- package/dist/SlashMenu.d.ts +27 -0
- package/dist/SlashMenu.d.ts.map +1 -0
- package/dist/SlashMenu.js +59 -0
- package/dist/SlashMenu.js.map +1 -0
- package/dist/Toolbar.d.ts +15 -0
- package/dist/Toolbar.d.ts.map +1 -0
- package/dist/Toolbar.js +27 -0
- package/dist/Toolbar.js.map +1 -0
- package/dist/VirtualizedBlockList.d.ts +40 -0
- package/dist/VirtualizedBlockList.d.ts.map +1 -0
- package/dist/VirtualizedBlockList.js +51 -0
- package/dist/VirtualizedBlockList.js.map +1 -0
- package/dist/blockPaste.d.ts +17 -0
- package/dist/blockPaste.d.ts.map +1 -0
- package/dist/blockPaste.js +50 -0
- package/dist/blockPaste.js.map +1 -0
- package/dist/blocks/AttachmentBlock.d.ts +3 -0
- package/dist/blocks/AttachmentBlock.d.ts.map +1 -0
- package/dist/blocks/AttachmentBlock.js +55 -0
- package/dist/blocks/AttachmentBlock.js.map +1 -0
- package/dist/blocks/ImageBlock.d.ts +14 -0
- package/dist/blocks/ImageBlock.d.ts.map +1 -0
- package/dist/blocks/ImageBlock.js +153 -0
- package/dist/blocks/ImageBlock.js.map +1 -0
- package/dist/blocks/MediaActions.d.ts +15 -0
- package/dist/blocks/MediaActions.d.ts.map +1 -0
- package/dist/blocks/MediaActions.js +7 -0
- package/dist/blocks/MediaActions.js.map +1 -0
- package/dist/blocks/VideoBlock.d.ts +3 -0
- package/dist/blocks/VideoBlock.d.ts.map +1 -0
- package/dist/blocks/VideoBlock.js +47 -0
- package/dist/blocks/VideoBlock.js.map +1 -0
- package/dist/blocks/cropper.d.ts +16 -0
- package/dist/blocks/cropper.d.ts.map +1 -0
- package/dist/blocks/cropper.js +28 -0
- package/dist/blocks/cropper.js.map +1 -0
- package/dist/bundle.css +7 -0
- package/dist/caret.d.ts +13 -0
- package/dist/caret.d.ts.map +1 -0
- package/dist/caret.js +52 -0
- package/dist/caret.js.map +1 -0
- package/dist/clipboardHtml.d.ts +4 -0
- package/dist/clipboardHtml.d.ts.map +1 -0
- package/dist/clipboardHtml.js +18 -0
- package/dist/clipboardHtml.js.map +1 -0
- package/dist/editorChrome.d.ts +53 -0
- package/dist/editorChrome.d.ts.map +1 -0
- package/dist/editorChrome.js +35 -0
- package/dist/editorChrome.js.map +1 -0
- package/dist/hooks/useBlockDrag.d.ts +26 -0
- package/dist/hooks/useBlockDrag.d.ts.map +1 -0
- package/dist/hooks/useBlockDrag.js +57 -0
- package/dist/hooks/useBlockDrag.js.map +1 -0
- package/dist/hooks/useBlockFocus.d.ts +13 -0
- package/dist/hooks/useBlockFocus.d.ts.map +1 -0
- package/dist/hooks/useBlockFocus.js +95 -0
- package/dist/hooks/useBlockFocus.js.map +1 -0
- package/dist/hooks/useBlockManagement.d.ts +27 -0
- package/dist/hooks/useBlockManagement.d.ts.map +1 -0
- package/dist/hooks/useBlockManagement.js +120 -0
- package/dist/hooks/useBlockManagement.js.map +1 -0
- package/dist/hooks/useBlockSelection.d.ts +30 -0
- package/dist/hooks/useBlockSelection.d.ts.map +1 -0
- package/dist/hooks/useBlockSelection.js +166 -0
- package/dist/hooks/useBlockSelection.js.map +1 -0
- package/dist/hooks/useBlockVisibility.d.ts +10 -0
- package/dist/hooks/useBlockVisibility.d.ts.map +1 -0
- package/dist/hooks/useBlockVisibility.js +48 -0
- package/dist/hooks/useBlockVisibility.js.map +1 -0
- package/dist/hooks/useDocumentHistory.d.ts +29 -0
- package/dist/hooks/useDocumentHistory.d.ts.map +1 -0
- package/dist/hooks/useDocumentHistory.js +75 -0
- package/dist/hooks/useDocumentHistory.js.map +1 -0
- package/dist/hooks/useTextareaResize.d.ts +6 -0
- package/dist/hooks/useTextareaResize.d.ts.map +1 -0
- package/dist/hooks/useTextareaResize.js +30 -0
- package/dist/hooks/useTextareaResize.js.map +1 -0
- package/dist/icons.d.ts +29 -0
- package/dist/icons.d.ts.map +1 -0
- package/dist/icons.js +38 -0
- package/dist/icons.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/listCommands.d.ts +11 -0
- package/dist/listCommands.d.ts.map +1 -0
- package/dist/listCommands.js +190 -0
- package/dist/listCommands.js.map +1 -0
- package/dist/listHtml.d.ts +20 -0
- package/dist/listHtml.d.ts.map +1 -0
- package/dist/listHtml.js +108 -0
- package/dist/listHtml.js.map +1 -0
- package/dist/markdownSource.d.ts +40 -0
- package/dist/markdownSource.d.ts.map +1 -0
- package/dist/markdownSource.js +205 -0
- package/dist/markdownSource.js.map +1 -0
- package/dist/parts.d.ts +34 -0
- package/dist/parts.d.ts.map +1 -0
- package/dist/parts.js +68 -0
- package/dist/parts.js.map +1 -0
- package/dist/paste.d.ts +21 -0
- package/dist/paste.d.ts.map +1 -0
- package/dist/paste.js +273 -0
- package/dist/paste.js.map +1 -0
- package/dist/provider.d.ts +84 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +16 -0
- package/dist/provider.js.map +1 -0
- package/dist/selection.d.ts +17 -0
- package/dist/selection.d.ts.map +1 -0
- package/dist/selection.js +88 -0
- package/dist/selection.js.map +1 -0
- package/dist/styles.css +668 -0
- package/package.json +64 -4
|
@@ -0,0 +1,1008 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { applyLinkTarget, documentToHtml, resolveLinkUrl } from "@alien6-studio/elea-content";
|
|
4
|
+
import { parseClipboard } from "./paste.js";
|
|
5
|
+
import { copyBlock } from "./selection.js";
|
|
6
|
+
import { editableHtml } from "./caret.js";
|
|
7
|
+
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
|
|
8
|
+
import { createPortal } from "react-dom";
|
|
9
|
+
import { useSurfaceScope } from "@alien6-studio/elea-ui";
|
|
10
|
+
import { CheckIcon, CloseIcon } from "./icons.js";
|
|
11
|
+
import { useContentServices } from "./provider.js";
|
|
12
|
+
export const EMPTY_FORMATS = {
|
|
13
|
+
bold: false, italic: false, underline: false,
|
|
14
|
+
h1: false, h2: false, h3: false, h4: false, h5: false, h6: false,
|
|
15
|
+
blockquote: false, ul: false, ol: false,
|
|
16
|
+
};
|
|
17
|
+
const BLOCK_TAGS = new Set(["P", "DIV", "H1", "H2", "H3", "H4", "H5", "H6", "BLOCKQUOTE", "LI"]);
|
|
18
|
+
const OUTER_BLOCK_TAGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6", "blockquote"]);
|
|
19
|
+
const UNWRAP_TAGS = new Set(["STRONG", "EM", "U", "A", "MARK", "SPAN", "H1", "H2", "H3", "H4", "H5", "H6", "BLOCKQUOTE"]);
|
|
20
|
+
function elementOf(node) {
|
|
21
|
+
if (!node)
|
|
22
|
+
return null;
|
|
23
|
+
return node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
|
|
24
|
+
}
|
|
25
|
+
const BLOCK_CONTAINERS = "li, p, h1, h2, h3, h4, h5, h6, blockquote, div";
|
|
26
|
+
function addCaretPlaceholder(br) {
|
|
27
|
+
const sentinel = document.createElement("br");
|
|
28
|
+
sentinel.dataset.eleaCaret = "";
|
|
29
|
+
br.after(sentinel);
|
|
30
|
+
return sentinel;
|
|
31
|
+
}
|
|
32
|
+
function paragraphHtml(element) {
|
|
33
|
+
return element.textContent || element.querySelector("br:not([data-elea-caret]),img,hr") ? editableHtml(element) : "";
|
|
34
|
+
}
|
|
35
|
+
const BLOCK_SELECTOR = "div,p,h1,h2,h3,h4,h5,h6,ol,ul,li,blockquote,pre,hr,table,figure";
|
|
36
|
+
const isBlockNode = (node) => node instanceof Element && node.matches(BLOCK_SELECTOR);
|
|
37
|
+
/** The bare inline run around the target among sibling nodes, as a [start, end) pair. */
|
|
38
|
+
function inlineRun(contents, target) {
|
|
39
|
+
const index = contents.findIndex(child => child === target || child.contains(target));
|
|
40
|
+
if (index < 0 || isBlockNode(contents[index]))
|
|
41
|
+
return null;
|
|
42
|
+
let first = index;
|
|
43
|
+
let end = index + 1;
|
|
44
|
+
while (first > 0 && !isBlockNode(contents[first - 1]))
|
|
45
|
+
first--;
|
|
46
|
+
while (end < contents.length && !isBlockNode(contents[end]))
|
|
47
|
+
end++;
|
|
48
|
+
return [first, end];
|
|
49
|
+
}
|
|
50
|
+
function paragraphScope(editor, selection) {
|
|
51
|
+
const range = selection.getRangeAt(0);
|
|
52
|
+
const start = range.startContainer;
|
|
53
|
+
const target = start.childNodes[range.startOffset] ?? start.lastChild ?? start;
|
|
54
|
+
const element = elementOf(target);
|
|
55
|
+
if (!element || !editor.contains(element))
|
|
56
|
+
return null;
|
|
57
|
+
const heading = element.closest("h1,h2,h3,h4,h5,h6,p");
|
|
58
|
+
const current = heading && editor.contains(heading) ? heading : null;
|
|
59
|
+
const container = current ?? element.closest("div,blockquote,li") ?? editor;
|
|
60
|
+
let contents = Array.from(container.childNodes);
|
|
61
|
+
let first = 0;
|
|
62
|
+
if (!current && contents.length) {
|
|
63
|
+
// Imported fields may mix bare text with lists or other blocks. Style only this inline run.
|
|
64
|
+
const run = inlineRun(contents, target);
|
|
65
|
+
if (!run)
|
|
66
|
+
return null;
|
|
67
|
+
first = run[0];
|
|
68
|
+
contents = contents.slice(...run);
|
|
69
|
+
}
|
|
70
|
+
return { current, container, contents, first };
|
|
71
|
+
}
|
|
72
|
+
function reconnect({ container, current, replacement, parent, offset, first, count }) {
|
|
73
|
+
return (node, at) => {
|
|
74
|
+
if (node !== container)
|
|
75
|
+
return [node, Math.min(at, node.nodeType === Node.TEXT_NODE ? node.length : node.childNodes.length)];
|
|
76
|
+
if (current)
|
|
77
|
+
return [replacement ?? parent, at + offset];
|
|
78
|
+
if (at < first)
|
|
79
|
+
return [container, at];
|
|
80
|
+
if (at > first + count)
|
|
81
|
+
return [container, at - count + 1];
|
|
82
|
+
return [replacement, at - first];
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** The whole block becomes plain lines. */
|
|
86
|
+
function plainField(editor) {
|
|
87
|
+
// innerText keeps the visual line breaks; some DOM implementations only offer textContent
|
|
88
|
+
const text = editor.innerText ?? editor.textContent ?? "";
|
|
89
|
+
editor.innerHTML = "";
|
|
90
|
+
text.split("\n").forEach((line, index) => {
|
|
91
|
+
if (index > 0)
|
|
92
|
+
editor.appendChild(document.createElement("br"));
|
|
93
|
+
if (line)
|
|
94
|
+
editor.appendChild(document.createTextNode(line));
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** The whole list becomes plain lines, one per item. */
|
|
98
|
+
function plainList(editor, selection, list) {
|
|
99
|
+
const lines = Array.from(list.querySelectorAll("li"), (item) => item.textContent ?? "").filter((line) => line !== "");
|
|
100
|
+
const nodes = lines.flatMap((line, index) => [...(index > 0 ? [document.createElement("br")] : []), document.createTextNode(line)]);
|
|
101
|
+
list.replaceWith(...nodes);
|
|
102
|
+
const next = document.createRange();
|
|
103
|
+
const last = nodes.at(-1);
|
|
104
|
+
if (last)
|
|
105
|
+
next.setStartAfter(last);
|
|
106
|
+
else
|
|
107
|
+
next.setStart(editor, editor.childNodes.length);
|
|
108
|
+
next.collapse(true);
|
|
109
|
+
selection.removeAllRanges();
|
|
110
|
+
selection.addRange(next);
|
|
111
|
+
}
|
|
112
|
+
function plainSelection(editor, selection, range) {
|
|
113
|
+
const text = range.toString();
|
|
114
|
+
range.deleteContents();
|
|
115
|
+
const textNode = document.createTextNode(text);
|
|
116
|
+
range.insertNode(textNode);
|
|
117
|
+
let node = textNode.parentNode;
|
|
118
|
+
while (node && node !== editor) {
|
|
119
|
+
if (UNWRAP_TAGS.has(node.tagName)) {
|
|
120
|
+
unwrap(node);
|
|
121
|
+
node = textNode.parentNode;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
node = node.parentNode;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const next = document.createRange();
|
|
128
|
+
next.setStartAfter(textNode);
|
|
129
|
+
next.collapse(true);
|
|
130
|
+
selection.removeAllRanges();
|
|
131
|
+
selection.addRange(next);
|
|
132
|
+
}
|
|
133
|
+
function precedingBreak(range, editor) {
|
|
134
|
+
if (!range.collapsed)
|
|
135
|
+
return null;
|
|
136
|
+
const { startContainer, startOffset } = range;
|
|
137
|
+
if (startContainer.nodeType === Node.TEXT_NODE && startOffset > 0)
|
|
138
|
+
return null;
|
|
139
|
+
const scope = elementOf(startContainer)?.closest(BLOCK_CONTAINERS) ?? editor;
|
|
140
|
+
const walker = document.createTreeWalker(scope, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
|
|
141
|
+
acceptNode: (node) => (node.nodeName === "BR" && node.dataset.eleaCaret === undefined) || (node.nodeType === Node.TEXT_NODE && node.textContent)
|
|
142
|
+
? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP,
|
|
143
|
+
});
|
|
144
|
+
let left = startContainer.childNodes[startOffset - 1];
|
|
145
|
+
if (left) {
|
|
146
|
+
while (left.lastChild)
|
|
147
|
+
left = left.lastChild;
|
|
148
|
+
if (left.nodeName === "BR" && left.dataset.eleaCaret === undefined)
|
|
149
|
+
return left;
|
|
150
|
+
if (left.textContent)
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
walker.currentNode = left ?? startContainer;
|
|
154
|
+
const previous = walker.previousNode();
|
|
155
|
+
return previous?.nodeName === "BR" ? previous : null;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* The parts of a range that sit in one block each: a range spanning several list items or
|
|
159
|
+
* lines is split at their boundaries, so a wrapper never crosses a block.
|
|
160
|
+
*/
|
|
161
|
+
function rangesPerBlock(range, editor) {
|
|
162
|
+
const containerOf = (node) => {
|
|
163
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
164
|
+
const block = element?.closest(BLOCK_CONTAINERS);
|
|
165
|
+
return block && editor.contains(block) && block !== editor ? block : editor;
|
|
166
|
+
};
|
|
167
|
+
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
|
|
168
|
+
const groups = [];
|
|
169
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
170
|
+
if (!range.intersectsNode(node))
|
|
171
|
+
continue;
|
|
172
|
+
const block = containerOf(node);
|
|
173
|
+
const group = groups.at(-1);
|
|
174
|
+
if (group?.block === block)
|
|
175
|
+
group.nodes.push(node);
|
|
176
|
+
else
|
|
177
|
+
groups.push({ block, nodes: [node] });
|
|
178
|
+
}
|
|
179
|
+
if (groups.length <= 1)
|
|
180
|
+
return [range];
|
|
181
|
+
return groups.map(({ nodes }) => {
|
|
182
|
+
const first = nodes[0];
|
|
183
|
+
const last = nodes.at(-1);
|
|
184
|
+
const piece = document.createRange();
|
|
185
|
+
piece.setStart(first, first === range.startContainer ? range.startOffset : 0);
|
|
186
|
+
piece.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
|
|
187
|
+
return piece;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
function unwrap(element) {
|
|
191
|
+
const fragment = document.createDocumentFragment();
|
|
192
|
+
while (element.firstChild)
|
|
193
|
+
fragment.appendChild(element.firstChild);
|
|
194
|
+
element.replaceWith(fragment);
|
|
195
|
+
}
|
|
196
|
+
/** Lines of a fragment, delimited by `<br>` or block elements; trailing breaks and blank text dropped. */
|
|
197
|
+
function splitFragmentIntoLines(fragment) {
|
|
198
|
+
const lines = [];
|
|
199
|
+
let current = [];
|
|
200
|
+
const flush = () => {
|
|
201
|
+
while (current.length > 0) {
|
|
202
|
+
const last = current.at(-1);
|
|
203
|
+
if (last.nodeName === "BR" || (last.nodeType === Node.TEXT_NODE && !last.textContent?.trim()))
|
|
204
|
+
current.pop();
|
|
205
|
+
else
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
if (current.length > 0)
|
|
209
|
+
lines.push(current);
|
|
210
|
+
current = [];
|
|
211
|
+
};
|
|
212
|
+
for (const node of Array.from(fragment.childNodes)) {
|
|
213
|
+
if (node.nodeName === "BR") {
|
|
214
|
+
flush();
|
|
215
|
+
}
|
|
216
|
+
else if (BLOCK_TAGS.has(node.nodeName)) {
|
|
217
|
+
flush();
|
|
218
|
+
const children = Array.from(node.childNodes).filter((child) => !(child.nodeName === "BR" && !child.nextSibling));
|
|
219
|
+
if (children.length > 0)
|
|
220
|
+
lines.push(children);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
current.push(node);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
flush();
|
|
227
|
+
return lines;
|
|
228
|
+
}
|
|
229
|
+
/** Pasted lines join in a field of one line. */
|
|
230
|
+
const pastedLine = (html, single) => (single ? html.replaceAll(/<br\s*\/?>/gi, " ") : html);
|
|
231
|
+
/**
|
|
232
|
+
* Rich text on a contentEditable element. Formatting commands are exposed through the
|
|
233
|
+
* handle so a toolbar outside the DOM subtree can drive them; the last selection inside
|
|
234
|
+
* the editor is remembered so focus can be restored after a toolbar click.
|
|
235
|
+
*/
|
|
236
|
+
export const RichTextField = forwardRef(function RichText({ value, onChange, onFocus, onBlur, onEnter, onListItemReturn, onInsertBlocks, onNavigate, onMergeBackward, onMergeForward, onConvert, onSlash, onSelectionChange, singleLine, placeholder, className, style }, ref) {
|
|
237
|
+
const { sanitizer, messages, siteHostnames } = useContentServices();
|
|
238
|
+
const linkOptions = siteHostnames ? { siteHostnames } : {};
|
|
239
|
+
const effectivePlaceholder = placeholder ?? messages.editor.startWriting;
|
|
240
|
+
const editorRef = useRef(null);
|
|
241
|
+
const isComposingRef = useRef(false);
|
|
242
|
+
const lastValueRef = useRef(value);
|
|
243
|
+
const lastSelectionRef = useRef(null);
|
|
244
|
+
// Commands run from memoized callbacks and from the imperative handle: they read the
|
|
245
|
+
// props through this ref so a parent re-render never leaves them with stale callbacks
|
|
246
|
+
const latest = useRef({ onChange, onEnter, onListItemReturn, onInsertBlocks, onNavigate, onMergeBackward, onMergeForward, onConvert, onSlash, onSelectionChange, singleLine, sanitizer, linkOptions });
|
|
247
|
+
latest.current = { onChange, onEnter, onListItemReturn, onInsertBlocks, onNavigate, onMergeBackward, onMergeForward, onConvert, onSlash, onSelectionChange, singleLine, sanitizer, linkOptions };
|
|
248
|
+
// A value that arrives while the field is composing text is applied once the composition ends
|
|
249
|
+
const pendingValueRef = useRef(null);
|
|
250
|
+
const [showLinkInput, setShowLinkInput] = useState(false);
|
|
251
|
+
const [observeEditor, linkScope] = useSurfaceScope(showLinkInput);
|
|
252
|
+
const setEditorRef = useCallback((editor) => {
|
|
253
|
+
editorRef.current = editor;
|
|
254
|
+
observeEditor(editor);
|
|
255
|
+
}, [observeEditor]);
|
|
256
|
+
const [linkInputValue, setLinkInputValue] = useState("");
|
|
257
|
+
const [linkUrlError, setLinkUrlError] = useState(false);
|
|
258
|
+
const [linkPopoverPosition, setLinkPopoverPosition] = useState(null);
|
|
259
|
+
const savedSelectionForLinkRef = useRef(null);
|
|
260
|
+
const linkInputRef = useRef(null);
|
|
261
|
+
const writeContent = (editor, next) => {
|
|
262
|
+
editor.innerHTML = next ? sanitizer.sanitize(next) : "";
|
|
263
|
+
let end = editor.lastChild;
|
|
264
|
+
while (end?.lastChild)
|
|
265
|
+
end = end.lastChild;
|
|
266
|
+
return end?.nodeName === "BR" && !end.parentElement?.closest("li") ? addCaretPlaceholder(end) : null;
|
|
267
|
+
};
|
|
268
|
+
// DOM sync: the stored value is sanitized on the way in, never trusted as is
|
|
269
|
+
useEffect(() => {
|
|
270
|
+
if (editorRef.current && value && editorRef.current.innerHTML === "") {
|
|
271
|
+
writeContent(editorRef.current, value);
|
|
272
|
+
lastValueRef.current = value;
|
|
273
|
+
}
|
|
274
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
275
|
+
}, []);
|
|
276
|
+
/** Writes a value into the field; the caret goes to the end when the field has focus. */
|
|
277
|
+
const applyValue = (next) => {
|
|
278
|
+
const editor = editorRef.current;
|
|
279
|
+
if (!editor)
|
|
280
|
+
return;
|
|
281
|
+
const sentinel = writeContent(editor, next);
|
|
282
|
+
lastValueRef.current = next;
|
|
283
|
+
if (document.activeElement === editor) {
|
|
284
|
+
const selection = globalThis.getSelection();
|
|
285
|
+
const range = document.createRange();
|
|
286
|
+
range.selectNodeContents(editor);
|
|
287
|
+
if (sentinel)
|
|
288
|
+
range.setEndBefore(sentinel);
|
|
289
|
+
range.collapse(false);
|
|
290
|
+
selection?.removeAllRanges();
|
|
291
|
+
selection?.addRange(range);
|
|
292
|
+
lastSelectionRef.current = range.cloneRange();
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
// Controlled sync rule: `lastValueRef` holds the last value this field emitted or applied.
|
|
296
|
+
// A `value` equal to it is an echo of our own input and is ignored, whatever the focus.
|
|
297
|
+
// A different `value` is an external replacement and wins, focused or not, with the caret
|
|
298
|
+
// moved to the end; during a composition it waits for the composition to end.
|
|
299
|
+
useEffect(() => {
|
|
300
|
+
if (!editorRef.current || value === lastValueRef.current)
|
|
301
|
+
return;
|
|
302
|
+
if (isComposingRef.current) {
|
|
303
|
+
pendingValueRef.current = value;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
applyValue(value);
|
|
307
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
308
|
+
}, [value, sanitizer]);
|
|
309
|
+
const getActiveFormats = () => {
|
|
310
|
+
const selection = globalThis.getSelection();
|
|
311
|
+
if (!selection || selection.rangeCount === 0 || !editorRef.current)
|
|
312
|
+
return EMPTY_FORMATS;
|
|
313
|
+
const element = elementOf(selection.getRangeAt(0).startContainer);
|
|
314
|
+
if (!element || !editorRef.current.contains(element))
|
|
315
|
+
return EMPTY_FORMATS;
|
|
316
|
+
return {
|
|
317
|
+
bold: !!element.closest("strong, b"),
|
|
318
|
+
italic: !!element.closest("em"),
|
|
319
|
+
underline: !!element.closest("u"),
|
|
320
|
+
h1: !!element.closest("h1"), h2: !!element.closest("h2"), h3: !!element.closest("h3"),
|
|
321
|
+
h4: !!element.closest("h4"), h5: !!element.closest("h5"), h6: !!element.closest("h6"),
|
|
322
|
+
blockquote: !!element.closest("blockquote"),
|
|
323
|
+
ul: !!element.closest("ul"),
|
|
324
|
+
ol: !!element.closest("ol"),
|
|
325
|
+
};
|
|
326
|
+
};
|
|
327
|
+
useEffect(() => {
|
|
328
|
+
const saveSelection = () => {
|
|
329
|
+
const selection = globalThis.getSelection();
|
|
330
|
+
if (selection && selection.rangeCount > 0 && editorRef.current?.contains(selection.anchorNode)) {
|
|
331
|
+
const range = selection.getRangeAt(0);
|
|
332
|
+
lastSelectionRef.current = range.cloneRange();
|
|
333
|
+
const rect = typeof range.getBoundingClientRect === "function" ? range.getBoundingClientRect() : null;
|
|
334
|
+
latest.current.onSelectionChange?.(getActiveFormats(), { collapsed: selection.isCollapsed, rect: rect && (rect.width > 0 || rect.height > 0) ? rect : null });
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
document.addEventListener("selectionchange", saveSelection);
|
|
338
|
+
return () => document.removeEventListener("selectionchange", saveSelection);
|
|
339
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
340
|
+
}, []);
|
|
341
|
+
const INPUT_RULES = [
|
|
342
|
+
{ pattern: /^(#{1,6}) $/, convert: (match) => ({ type: "header", data: { text: "", level: match[1].length } }) },
|
|
343
|
+
{ pattern: /^[-*] $/, convert: () => ({ type: "list", data: { style: "unordered", items: [""] } }) },
|
|
344
|
+
{ pattern: /^1[.)] $/, convert: () => ({ type: "list", data: { style: "ordered", items: [""] } }) },
|
|
345
|
+
{ pattern: /^> $/, convert: () => ({ type: "quote", data: { text: "", caption: "" } }) },
|
|
346
|
+
];
|
|
347
|
+
/** Typing `# `, `- `, `1. ` or `> ` at the start of an empty block turns it into the matching block. */
|
|
348
|
+
const applyInputRule = (editor) => {
|
|
349
|
+
const convert = latest.current.onConvert;
|
|
350
|
+
if (!convert || editor.querySelector("*"))
|
|
351
|
+
return false;
|
|
352
|
+
const text = editor.textContent ?? "";
|
|
353
|
+
for (const rule of INPUT_RULES) {
|
|
354
|
+
const match = rule.pattern.exec(text.replaceAll("\u00a0", " "));
|
|
355
|
+
if (match) {
|
|
356
|
+
const target = rule.convert(match);
|
|
357
|
+
editor.innerHTML = "";
|
|
358
|
+
convert(target.type, target.data);
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return false;
|
|
363
|
+
};
|
|
364
|
+
/** `/` alone at the start of an empty block opens the block menu; what follows filters it. */
|
|
365
|
+
const reportSlash = (editor) => {
|
|
366
|
+
const slash = latest.current.onSlash;
|
|
367
|
+
if (!slash)
|
|
368
|
+
return;
|
|
369
|
+
const text = (editor.textContent ?? "").replaceAll("\u00a0", " ");
|
|
370
|
+
if (!editor.querySelector("*") && text.startsWith("/") && !text.includes(" ")) {
|
|
371
|
+
const range = editorRange();
|
|
372
|
+
const rect = range && typeof range.getBoundingClientRect === "function" ? range.getBoundingClientRect() : null;
|
|
373
|
+
slash(text.slice(1), rect ?? editor.getBoundingClientRect());
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
slash(null, null);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
const handleInput = () => {
|
|
380
|
+
const editor = editorRef.current;
|
|
381
|
+
if (!editor)
|
|
382
|
+
return;
|
|
383
|
+
if (applyInputRule(editor))
|
|
384
|
+
return;
|
|
385
|
+
const html = editableHtml(editor);
|
|
386
|
+
lastValueRef.current = html;
|
|
387
|
+
latest.current.onChange(html);
|
|
388
|
+
reportSlash(editor);
|
|
389
|
+
};
|
|
390
|
+
/** Focus the editor and bring back the last selection, unless a live one exists. */
|
|
391
|
+
const restoreSelection = () => {
|
|
392
|
+
const selection = globalThis.getSelection();
|
|
393
|
+
const live = selection && selection.rangeCount > 0 && editorRef.current?.contains(selection.anchorNode);
|
|
394
|
+
editorRef.current?.focus();
|
|
395
|
+
if (live || !lastSelectionRef.current)
|
|
396
|
+
return;
|
|
397
|
+
selection?.removeAllRanges();
|
|
398
|
+
selection?.addRange(lastSelectionRef.current);
|
|
399
|
+
};
|
|
400
|
+
/** Inserts sanitized inline HTML at the caret and leaves the caret after it. */
|
|
401
|
+
const insertInlineHtml = (html, range, selection) => {
|
|
402
|
+
range.deleteContents();
|
|
403
|
+
if (!html)
|
|
404
|
+
return;
|
|
405
|
+
const fragment = range.createContextualFragment(html);
|
|
406
|
+
const last = fragment.lastChild;
|
|
407
|
+
range.insertNode(fragment);
|
|
408
|
+
if (last) {
|
|
409
|
+
range.setStartAfter(last);
|
|
410
|
+
range.collapse(true);
|
|
411
|
+
selection.removeAllRanges();
|
|
412
|
+
selection.addRange(range);
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
const handlePaste = (event) => {
|
|
416
|
+
event.preventDefault();
|
|
417
|
+
const editor = editorRef.current;
|
|
418
|
+
const selection = globalThis.getSelection();
|
|
419
|
+
const range = editorRange();
|
|
420
|
+
if (!editor || !selection || !range)
|
|
421
|
+
return;
|
|
422
|
+
const { sanitizer: currentSanitizer, onInsertBlocks: insertBlocks } = latest.current;
|
|
423
|
+
const pasted = parseClipboard(event.clipboardData, currentSanitizer);
|
|
424
|
+
const [first, ...rest] = pasted.blocks;
|
|
425
|
+
const text = (block) => block?.type === "paragraph" ? block.data?.text : undefined;
|
|
426
|
+
const firstText = text(first);
|
|
427
|
+
let inline = pasted.inline;
|
|
428
|
+
if (first && !rest.length && typeof firstText === "string")
|
|
429
|
+
inline = firstText;
|
|
430
|
+
if (inline === null && first && !insertBlocks) {
|
|
431
|
+
// A list item or standalone rich field has no sibling block insertion callback.
|
|
432
|
+
inline = pasted.blocks.every(block => typeof text(block) === "string")
|
|
433
|
+
? pasted.blocks.map(text).join("<br>")
|
|
434
|
+
: documentToHtml({ blocks: pasted.blocks.map(copyBlock) }, { sanitize: html => currentSanitizer.sanitize(html) });
|
|
435
|
+
}
|
|
436
|
+
if (inline !== null) {
|
|
437
|
+
if (!inline)
|
|
438
|
+
return;
|
|
439
|
+
insertInlineHtml(currentSanitizer.sanitize(pastedLine(inline, latest.current.singleLine)), range, selection);
|
|
440
|
+
handleInput();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (!first || !insertBlocks)
|
|
444
|
+
return;
|
|
445
|
+
const after = extractContentAfterCaret(range, editor);
|
|
446
|
+
if (typeof firstText === "string")
|
|
447
|
+
insertInlineHtml(currentSanitizer.sanitize(firstText), range, selection);
|
|
448
|
+
else
|
|
449
|
+
range.deleteContents();
|
|
450
|
+
handleInput();
|
|
451
|
+
insertBlocks(typeof firstText === "string" ? rest : pasted.blocks, after);
|
|
452
|
+
};
|
|
453
|
+
const extractContentAfterCaret = (range, element) => {
|
|
454
|
+
const after = range.cloneRange();
|
|
455
|
+
after.selectNodeContents(element);
|
|
456
|
+
after.setStart(range.endContainer, range.endOffset);
|
|
457
|
+
const holder = document.createElement("div");
|
|
458
|
+
holder.appendChild(after.cloneContents());
|
|
459
|
+
after.deleteContents();
|
|
460
|
+
return paragraphHtml(holder);
|
|
461
|
+
};
|
|
462
|
+
const stripOuterBlockTag = (html) => {
|
|
463
|
+
const holder = document.createElement("div");
|
|
464
|
+
holder.innerHTML = html;
|
|
465
|
+
const only = holder.childNodes.length === 1 ? holder.firstElementChild : null;
|
|
466
|
+
return only && OUTER_BLOCK_TAGS.has(only.tagName.toLowerCase()) ? only.innerHTML : html;
|
|
467
|
+
};
|
|
468
|
+
/** The current range when it sits inside this editor; a stale selection elsewhere is ignored. */
|
|
469
|
+
const editorRange = () => {
|
|
470
|
+
const selection = globalThis.getSelection();
|
|
471
|
+
if (!selection || selection.rangeCount === 0 || !editorRef.current)
|
|
472
|
+
return null;
|
|
473
|
+
const range = selection.getRangeAt(0);
|
|
474
|
+
return editorRef.current.contains(range.commonAncestorContainer) ? range : null;
|
|
475
|
+
};
|
|
476
|
+
const splitParagraph = (range, separator) => {
|
|
477
|
+
const { onEnter: enter, onChange: change } = latest.current;
|
|
478
|
+
if (!enter || !editorRef.current)
|
|
479
|
+
return;
|
|
480
|
+
const after = extractContentAfterCaret(range, editorRef.current);
|
|
481
|
+
separator?.remove();
|
|
482
|
+
const before = paragraphHtml(editorRef.current);
|
|
483
|
+
lastValueRef.current = before;
|
|
484
|
+
change(before);
|
|
485
|
+
enter(before, stripOuterBlockTag(after));
|
|
486
|
+
};
|
|
487
|
+
const toggleInlineFormat = (tag) => {
|
|
488
|
+
const selection = globalThis.getSelection();
|
|
489
|
+
if (!selection || selection.rangeCount === 0 || selection.isCollapsed || !editorRef.current)
|
|
490
|
+
return;
|
|
491
|
+
const range = selection.getRangeAt(0);
|
|
492
|
+
const existing = elementOf(range.commonAncestorContainer)?.closest(tag);
|
|
493
|
+
if (existing) {
|
|
494
|
+
unwrap(existing);
|
|
495
|
+
handleInput();
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
// A selection across items or lines gets one wrapper per block, so the markup stays valid
|
|
499
|
+
const pieces = rangesPerBlock(range, editorRef.current);
|
|
500
|
+
const wrappers = pieces.map((piece) => {
|
|
501
|
+
const wrapper = document.createElement(tag);
|
|
502
|
+
wrapper.appendChild(piece.extractContents());
|
|
503
|
+
piece.insertNode(wrapper);
|
|
504
|
+
return wrapper;
|
|
505
|
+
});
|
|
506
|
+
const first = wrappers[0];
|
|
507
|
+
const last = wrappers.at(-1);
|
|
508
|
+
if (first && last) {
|
|
509
|
+
const next = document.createRange();
|
|
510
|
+
next.setStart(first, 0);
|
|
511
|
+
next.setEnd(last, last.childNodes.length);
|
|
512
|
+
selection.removeAllRanges();
|
|
513
|
+
selection.addRange(next);
|
|
514
|
+
}
|
|
515
|
+
handleInput();
|
|
516
|
+
};
|
|
517
|
+
const insertList = (tag) => {
|
|
518
|
+
const selection = globalThis.getSelection();
|
|
519
|
+
if (!selection || selection.rangeCount === 0 || !editorRef.current)
|
|
520
|
+
return;
|
|
521
|
+
const range = selection.getRangeAt(0);
|
|
522
|
+
const closest = elementOf(range.commonAncestorContainer)?.closest("ul, ol");
|
|
523
|
+
if (closest?.tagName.toLowerCase() === tag) {
|
|
524
|
+
// Toggle off: list items become lines
|
|
525
|
+
const fragment = document.createDocumentFragment();
|
|
526
|
+
Array.from(closest.querySelectorAll("li")).forEach((item, index) => {
|
|
527
|
+
if (index > 0)
|
|
528
|
+
fragment.appendChild(document.createElement("br"));
|
|
529
|
+
while (item.firstChild)
|
|
530
|
+
fragment.appendChild(item.firstChild);
|
|
531
|
+
});
|
|
532
|
+
closest.replaceWith(fragment);
|
|
533
|
+
handleInput();
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
const list = document.createElement(tag);
|
|
537
|
+
if (range.collapsed) {
|
|
538
|
+
const item = document.createElement("li");
|
|
539
|
+
list.appendChild(item);
|
|
540
|
+
range.insertNode(list);
|
|
541
|
+
const next = document.createRange();
|
|
542
|
+
next.setStart(item, 0);
|
|
543
|
+
next.collapse(true);
|
|
544
|
+
selection.removeAllRanges();
|
|
545
|
+
selection.addRange(next);
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const lines = splitFragmentIntoLines(range.extractContents());
|
|
549
|
+
if (lines.length === 0)
|
|
550
|
+
lines.push([]);
|
|
551
|
+
for (const line of lines) {
|
|
552
|
+
const item = document.createElement("li");
|
|
553
|
+
for (const node of line)
|
|
554
|
+
item.appendChild(node);
|
|
555
|
+
list.appendChild(item);
|
|
556
|
+
}
|
|
557
|
+
range.insertNode(list);
|
|
558
|
+
const next = document.createRange();
|
|
559
|
+
next.selectNodeContents(list);
|
|
560
|
+
selection.removeAllRanges();
|
|
561
|
+
selection.addRange(next);
|
|
562
|
+
}
|
|
563
|
+
handleInput();
|
|
564
|
+
};
|
|
565
|
+
// The style picker formats a whole paragraph, including inline markup around the caret.
|
|
566
|
+
const setParagraphHeading = (tag) => {
|
|
567
|
+
const editor = editorRef.current;
|
|
568
|
+
const selection = globalThis.getSelection();
|
|
569
|
+
if (!editor || !selection?.anchorNode || !selection.focusNode || !selection.rangeCount)
|
|
570
|
+
return;
|
|
571
|
+
const scope = paragraphScope(editor, selection);
|
|
572
|
+
if (!scope)
|
|
573
|
+
return;
|
|
574
|
+
const { current, container, contents, first } = scope;
|
|
575
|
+
const parent = current?.parentNode ?? container;
|
|
576
|
+
const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;
|
|
577
|
+
const replacement = current?.localName === tag ? null : document.createElement(tag);
|
|
578
|
+
const offset = current && !replacement ? Array.from(parent.childNodes).indexOf(current) : 0;
|
|
579
|
+
if (current)
|
|
580
|
+
current.replaceWith(...(replacement ? [replacement] : contents));
|
|
581
|
+
else
|
|
582
|
+
container.insertBefore(replacement, contents[0] ?? null);
|
|
583
|
+
replacement?.append(...contents);
|
|
584
|
+
// Moving children adjusts live DOM ranges. Reconnect both ends to the original nodes.
|
|
585
|
+
const boundary = reconnect({ container, current, replacement, parent, offset, first, count: contents.length });
|
|
586
|
+
selection.setBaseAndExtent(...boundary(anchorNode, anchorOffset), ...boundary(focusNode, focusOffset));
|
|
587
|
+
lastSelectionRef.current = selection.getRangeAt(0).cloneRange();
|
|
588
|
+
latest.current.onSelectionChange?.(getActiveFormats(), { collapsed: selection.isCollapsed, rect: null });
|
|
589
|
+
handleInput();
|
|
590
|
+
};
|
|
591
|
+
const toggleBlockFormat = (tag) => {
|
|
592
|
+
const editor = editorRef.current;
|
|
593
|
+
const selection = globalThis.getSelection();
|
|
594
|
+
if (!editor || !selection)
|
|
595
|
+
return;
|
|
596
|
+
if (!selection.isCollapsed && selection.rangeCount > 0) {
|
|
597
|
+
const range = selection.getRangeAt(0);
|
|
598
|
+
const existing = elementOf(range.commonAncestorContainer)?.closest(tag);
|
|
599
|
+
if (existing) {
|
|
600
|
+
unwrap(existing);
|
|
601
|
+
}
|
|
602
|
+
else {
|
|
603
|
+
const wrapper = document.createElement(tag);
|
|
604
|
+
wrapper.appendChild(range.extractContents());
|
|
605
|
+
range.insertNode(wrapper);
|
|
606
|
+
const next = document.createRange();
|
|
607
|
+
next.selectNodeContents(wrapper);
|
|
608
|
+
selection.removeAllRanges();
|
|
609
|
+
selection.addRange(next);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
// No selection: the whole block takes or loses the format
|
|
614
|
+
const only = editor.childNodes.length === 1 ? editor.firstChild : null;
|
|
615
|
+
if (only?.tagName?.toLowerCase() === tag) {
|
|
616
|
+
unwrap(only);
|
|
617
|
+
}
|
|
618
|
+
else {
|
|
619
|
+
const wrapper = document.createElement(tag);
|
|
620
|
+
while (editor.firstChild)
|
|
621
|
+
wrapper.appendChild(editor.firstChild);
|
|
622
|
+
editor.appendChild(wrapper);
|
|
623
|
+
const range = document.createRange();
|
|
624
|
+
range.selectNodeContents(wrapper);
|
|
625
|
+
range.collapse(false);
|
|
626
|
+
selection.removeAllRanges();
|
|
627
|
+
selection.addRange(range);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
handleInput();
|
|
631
|
+
};
|
|
632
|
+
const createLinkAtRange = (url, range) => {
|
|
633
|
+
const anchor = document.createElement("a");
|
|
634
|
+
anchor.href = url.replaceAll(/[<>"]/g, encodeURIComponent);
|
|
635
|
+
applyLinkTarget(anchor, latest.current.linkOptions);
|
|
636
|
+
if (range.collapsed)
|
|
637
|
+
anchor.textContent = url;
|
|
638
|
+
else
|
|
639
|
+
anchor.appendChild(range.extractContents());
|
|
640
|
+
range.insertNode(anchor);
|
|
641
|
+
const selection = globalThis.getSelection();
|
|
642
|
+
const next = document.createRange();
|
|
643
|
+
next.selectNodeContents(anchor);
|
|
644
|
+
selection?.removeAllRanges();
|
|
645
|
+
selection?.addRange(next);
|
|
646
|
+
handleInput();
|
|
647
|
+
};
|
|
648
|
+
const openLinkInput = () => {
|
|
649
|
+
const selection = globalThis.getSelection();
|
|
650
|
+
const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : lastSelectionRef.current;
|
|
651
|
+
// Inside an existing link: remove it instead of nesting one
|
|
652
|
+
const existingLink = elementOf(range?.startContainer)?.closest("a");
|
|
653
|
+
if (existingLink) {
|
|
654
|
+
unwrap(existingLink);
|
|
655
|
+
handleInput();
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
savedSelectionForLinkRef.current = range ? range.cloneRange() : null;
|
|
659
|
+
const selected = range ? range.toString().trim() : "";
|
|
660
|
+
const rangeRect = range?.getBoundingClientRect();
|
|
661
|
+
const editorRect = editorRef.current?.getBoundingClientRect();
|
|
662
|
+
const anchorRect = rangeRect && rangeRect.height > 0 ? rangeRect : editorRect;
|
|
663
|
+
if (anchorRect)
|
|
664
|
+
setLinkPopoverPosition({ top: anchorRect.bottom + 6, left: anchorRect.left });
|
|
665
|
+
setLinkInputValue(selected.startsWith("http") ? selected : "");
|
|
666
|
+
setLinkUrlError(false);
|
|
667
|
+
setShowLinkInput(true);
|
|
668
|
+
setTimeout(() => linkInputRef.current?.focus(), 0);
|
|
669
|
+
};
|
|
670
|
+
const closeLinkInput = () => {
|
|
671
|
+
setShowLinkInput(false);
|
|
672
|
+
setLinkInputValue("");
|
|
673
|
+
setLinkUrlError(false);
|
|
674
|
+
setLinkPopoverPosition(null);
|
|
675
|
+
editorRef.current?.focus();
|
|
676
|
+
};
|
|
677
|
+
const submitLink = () => {
|
|
678
|
+
const trimmed = linkInputValue.trim();
|
|
679
|
+
if (!trimmed) {
|
|
680
|
+
closeLinkInput();
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
const url = resolveLinkUrl(trimmed);
|
|
684
|
+
if (!url) {
|
|
685
|
+
setLinkUrlError(true);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const range = savedSelectionForLinkRef.current;
|
|
689
|
+
if (range)
|
|
690
|
+
createLinkAtRange(url, range);
|
|
691
|
+
editorRef.current?.focus();
|
|
692
|
+
setShowLinkInput(false);
|
|
693
|
+
setLinkInputValue("");
|
|
694
|
+
setLinkUrlError(false);
|
|
695
|
+
};
|
|
696
|
+
const clearFormat = () => {
|
|
697
|
+
const editor = editorRef.current;
|
|
698
|
+
if (!editor)
|
|
699
|
+
return;
|
|
700
|
+
restoreSelection();
|
|
701
|
+
const selection = globalThis.getSelection();
|
|
702
|
+
if (!selection || selection.rangeCount === 0)
|
|
703
|
+
return;
|
|
704
|
+
const range = selection.getRangeAt(0);
|
|
705
|
+
const listContainer = elementOf(range.commonAncestorContainer)?.closest("ul, ol");
|
|
706
|
+
if (range.collapsed)
|
|
707
|
+
plainField(editor);
|
|
708
|
+
else if (listContainer && editor.contains(listContainer))
|
|
709
|
+
plainList(editor, selection, listContainer);
|
|
710
|
+
else
|
|
711
|
+
plainSelection(editor, selection, range);
|
|
712
|
+
handleInput();
|
|
713
|
+
};
|
|
714
|
+
// Rebuilt on every render on purpose: each command closes over this render's handlers
|
|
715
|
+
useImperativeHandle(ref, () => ({
|
|
716
|
+
applyInlineFormat: (tag) => { restoreSelection(); toggleInlineFormat(tag); },
|
|
717
|
+
applyListFormat: (tag) => { restoreSelection(); insertList(tag); },
|
|
718
|
+
applyBlockFormat: (tag, wholeParagraph) => { restoreSelection(); if (wholeParagraph)
|
|
719
|
+
setParagraphHeading(tag);
|
|
720
|
+
else
|
|
721
|
+
toggleBlockFormat(tag); },
|
|
722
|
+
openLinkInput: () => { restoreSelection(); openLinkInput(); },
|
|
723
|
+
clearFormat: () => { clearFormat(); },
|
|
724
|
+
}));
|
|
725
|
+
const handleFormattingShortcut = (event) => {
|
|
726
|
+
if (!event.ctrlKey && !event.metaKey)
|
|
727
|
+
return false;
|
|
728
|
+
switch (event.key) {
|
|
729
|
+
case "b":
|
|
730
|
+
event.preventDefault();
|
|
731
|
+
toggleInlineFormat("strong");
|
|
732
|
+
return true;
|
|
733
|
+
case "i":
|
|
734
|
+
event.preventDefault();
|
|
735
|
+
toggleInlineFormat("em");
|
|
736
|
+
return true;
|
|
737
|
+
case "u":
|
|
738
|
+
event.preventDefault();
|
|
739
|
+
toggleInlineFormat("u");
|
|
740
|
+
return true;
|
|
741
|
+
case "k":
|
|
742
|
+
event.preventDefault();
|
|
743
|
+
openLinkInput();
|
|
744
|
+
return true;
|
|
745
|
+
default: return false;
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
const caretElement = () => {
|
|
749
|
+
const range = editorRange();
|
|
750
|
+
return range ? elementOf(range.startContainer) : null;
|
|
751
|
+
};
|
|
752
|
+
const isAtStartOf = (element) => {
|
|
753
|
+
const selection = globalThis.getSelection();
|
|
754
|
+
if (!selection || selection.rangeCount === 0 || !selection.isCollapsed)
|
|
755
|
+
return false;
|
|
756
|
+
const range = selection.getRangeAt(0);
|
|
757
|
+
if (range.startOffset !== 0)
|
|
758
|
+
return false;
|
|
759
|
+
let node = range.startContainer;
|
|
760
|
+
while (node && node !== element) {
|
|
761
|
+
if (node.previousSibling)
|
|
762
|
+
return false;
|
|
763
|
+
node = node.parentNode;
|
|
764
|
+
}
|
|
765
|
+
return true;
|
|
766
|
+
};
|
|
767
|
+
const isAtEndOf = (element) => {
|
|
768
|
+
const selection = globalThis.getSelection();
|
|
769
|
+
if (!selection || selection.rangeCount === 0 || !selection.isCollapsed)
|
|
770
|
+
return false;
|
|
771
|
+
const range = selection.getRangeAt(0);
|
|
772
|
+
const container = range.endContainer;
|
|
773
|
+
const length = container.nodeType === Node.TEXT_NODE ? (container.textContent?.length ?? 0) : container.childNodes.length;
|
|
774
|
+
if (range.endOffset !== length)
|
|
775
|
+
return false;
|
|
776
|
+
let node = container;
|
|
777
|
+
while (node && node !== element) {
|
|
778
|
+
// A trailing sentinel line break does not count as content after the caret
|
|
779
|
+
let next = node.nextSibling;
|
|
780
|
+
while (next?.nodeName === "BR" && !next.nextSibling)
|
|
781
|
+
next = next.nextSibling;
|
|
782
|
+
if (next)
|
|
783
|
+
return false;
|
|
784
|
+
node = node.parentNode;
|
|
785
|
+
}
|
|
786
|
+
return true;
|
|
787
|
+
};
|
|
788
|
+
const insertLineBreak = () => {
|
|
789
|
+
const selection = globalThis.getSelection();
|
|
790
|
+
const range = editorRange();
|
|
791
|
+
const editor = editorRef.current;
|
|
792
|
+
if (!selection || !range || !editor)
|
|
793
|
+
return;
|
|
794
|
+
range.deleteContents();
|
|
795
|
+
const br = document.createElement("br");
|
|
796
|
+
range.insertNode(br);
|
|
797
|
+
const tail = document.createRange();
|
|
798
|
+
tail.selectNodeContents(br.closest(BLOCK_CONTAINERS) ?? editor);
|
|
799
|
+
tail.setStartAfter(br);
|
|
800
|
+
const following = tail.cloneContents();
|
|
801
|
+
if (!following.textContent && !following.querySelector("br,img,hr")) {
|
|
802
|
+
addCaretPlaceholder(br);
|
|
803
|
+
}
|
|
804
|
+
// WebKit resolves the caret visually when the selection is applied. The
|
|
805
|
+
// trailing placeholder must already be in the DOM for that position to exist.
|
|
806
|
+
range.setStartAfter(br);
|
|
807
|
+
range.collapse(true);
|
|
808
|
+
selection.removeAllRanges();
|
|
809
|
+
selection.addRange(range);
|
|
810
|
+
handleInput();
|
|
811
|
+
};
|
|
812
|
+
const splitListItemAtCaret = (item) => {
|
|
813
|
+
const selection = globalThis.getSelection();
|
|
814
|
+
if (!selection || selection.rangeCount === 0)
|
|
815
|
+
return;
|
|
816
|
+
const range = selection.getRangeAt(0);
|
|
817
|
+
const after = range.cloneRange();
|
|
818
|
+
after.selectNodeContents(item);
|
|
819
|
+
after.setStart(range.endContainer, range.endOffset);
|
|
820
|
+
const next = document.createElement("li");
|
|
821
|
+
next.appendChild(after.extractContents());
|
|
822
|
+
item.parentNode?.insertBefore(next, item.nextSibling);
|
|
823
|
+
const caret = document.createRange();
|
|
824
|
+
caret.setStart(next, 0);
|
|
825
|
+
caret.collapse(true);
|
|
826
|
+
selection.removeAllRanges();
|
|
827
|
+
selection.addRange(caret);
|
|
828
|
+
handleInput();
|
|
829
|
+
};
|
|
830
|
+
/** Backspace at the start of an item: the item leaves the list as plain text, the list splits around it. */
|
|
831
|
+
const ejectListItem = (item) => {
|
|
832
|
+
const selection = globalThis.getSelection();
|
|
833
|
+
const list = item.parentElement;
|
|
834
|
+
if (!selection || !list)
|
|
835
|
+
return;
|
|
836
|
+
const fragment = document.createDocumentFragment();
|
|
837
|
+
while (item.firstChild)
|
|
838
|
+
fragment.appendChild(item.firstChild);
|
|
839
|
+
const siblings = Array.from(list.children);
|
|
840
|
+
const at = siblings.indexOf(item);
|
|
841
|
+
const tag = list.tagName.toLowerCase();
|
|
842
|
+
const sublist = (elements) => {
|
|
843
|
+
const part = document.createElement(tag);
|
|
844
|
+
part.append(...elements);
|
|
845
|
+
return elements.length > 0 ? [part] : [];
|
|
846
|
+
};
|
|
847
|
+
const nodes = Array.from(fragment.childNodes);
|
|
848
|
+
const br = document.createElement("br");
|
|
849
|
+
list.replaceWith(...sublist(siblings.slice(0, at)), ...nodes, br, ...sublist(siblings.slice(at + 1)));
|
|
850
|
+
const caret = document.createRange();
|
|
851
|
+
const first = nodes[0];
|
|
852
|
+
if (first)
|
|
853
|
+
caret.setStart(first, 0);
|
|
854
|
+
else
|
|
855
|
+
caret.setStartBefore(br);
|
|
856
|
+
caret.collapse(true);
|
|
857
|
+
selection.removeAllRanges();
|
|
858
|
+
selection.addRange(caret);
|
|
859
|
+
handleInput();
|
|
860
|
+
};
|
|
861
|
+
/** Enter inside a heading: the heading ends, the rest continues as plain text in the same block. */
|
|
862
|
+
const exitHeadingInline = (heading) => {
|
|
863
|
+
const selection = globalThis.getSelection();
|
|
864
|
+
if (!selection || selection.rangeCount === 0)
|
|
865
|
+
return;
|
|
866
|
+
const range = selection.getRangeAt(0);
|
|
867
|
+
const after = range.cloneRange();
|
|
868
|
+
after.selectNodeContents(heading);
|
|
869
|
+
after.setStart(range.endContainer, range.endOffset);
|
|
870
|
+
const fragment = after.extractContents();
|
|
871
|
+
const hasText = fragment.childNodes.length > 0 && fragment.textContent !== "";
|
|
872
|
+
const caretAnchor = hasText ? fragment.firstChild : document.createElement("br");
|
|
873
|
+
heading.after(hasText ? fragment : caretAnchor, document.createElement("br"));
|
|
874
|
+
const caret = document.createRange();
|
|
875
|
+
caret.setStartAfter(caretAnchor);
|
|
876
|
+
caret.collapse(true);
|
|
877
|
+
selection.removeAllRanges();
|
|
878
|
+
selection.addRange(caret);
|
|
879
|
+
handleInput();
|
|
880
|
+
};
|
|
881
|
+
const handleReturn = (soft) => {
|
|
882
|
+
const range = editorRange();
|
|
883
|
+
const editor = editorRef.current;
|
|
884
|
+
if (!editor || !range)
|
|
885
|
+
return;
|
|
886
|
+
if (latest.current.singleLine) {
|
|
887
|
+
if (!soft)
|
|
888
|
+
splitParagraph(range);
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
if (!soft) {
|
|
892
|
+
const element = elementOf(range.startContainer);
|
|
893
|
+
const item = element?.closest("li");
|
|
894
|
+
if (item) {
|
|
895
|
+
if (!latest.current.onListItemReturn?.(item))
|
|
896
|
+
splitListItemAtCaret(item);
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
const heading = element?.closest("h1,h2,h3,h4,h5,h6");
|
|
900
|
+
if (heading) {
|
|
901
|
+
exitHeadingInline(heading);
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
const separator = latest.current.onEnter && precedingBreak(range, editor);
|
|
905
|
+
if (separator) {
|
|
906
|
+
splitParagraph(range, separator);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
insertLineBreak();
|
|
911
|
+
};
|
|
912
|
+
// Mobile keyboards can send a beforeinput without a keydown. Use the native
|
|
913
|
+
// event to read inputType. Preventing the desktop keydown suppresses beforeinput.
|
|
914
|
+
useEffect(() => {
|
|
915
|
+
const editor = editorRef.current;
|
|
916
|
+
if (!editor)
|
|
917
|
+
return;
|
|
918
|
+
const onBeforeInput = (event) => {
|
|
919
|
+
if (!event.cancelable || event.defaultPrevented || event.isComposing || isComposingRef.current)
|
|
920
|
+
return;
|
|
921
|
+
if (event.inputType !== "insertParagraph" && event.inputType !== "insertLineBreak")
|
|
922
|
+
return;
|
|
923
|
+
event.preventDefault();
|
|
924
|
+
handleReturn(event.inputType === "insertLineBreak");
|
|
925
|
+
};
|
|
926
|
+
editor.addEventListener("beforeinput", onBeforeInput);
|
|
927
|
+
return () => editor.removeEventListener("beforeinput", onBeforeInput);
|
|
928
|
+
// handleReturn reads editor state and callbacks through refs.
|
|
929
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
930
|
+
}, []);
|
|
931
|
+
const backspaceAtStart = (event, editor) => {
|
|
932
|
+
const selection = globalThis.getSelection();
|
|
933
|
+
if (!selection || selection.rangeCount === 0 || !selection.isCollapsed)
|
|
934
|
+
return false;
|
|
935
|
+
const item = caretElement()?.closest("li");
|
|
936
|
+
if (item && isAtStartOf(item)) {
|
|
937
|
+
event.preventDefault();
|
|
938
|
+
ejectListItem(item);
|
|
939
|
+
return true;
|
|
940
|
+
}
|
|
941
|
+
if (!latest.current.onMergeBackward || !isAtStartOf(editor))
|
|
942
|
+
return false;
|
|
943
|
+
event.preventDefault();
|
|
944
|
+
latest.current.onMergeBackward(editableHtml(editor));
|
|
945
|
+
return true;
|
|
946
|
+
};
|
|
947
|
+
const handleKeyDown = (event) => {
|
|
948
|
+
const editor = editorRef.current;
|
|
949
|
+
if (!editor || event.nativeEvent.isComposing || isComposingRef.current || event.nativeEvent.keyCode === 229)
|
|
950
|
+
return;
|
|
951
|
+
if (event.key === "Enter") {
|
|
952
|
+
event.preventDefault();
|
|
953
|
+
handleReturn(event.shiftKey);
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
if (event.key === "Backspace" && !event.shiftKey && !event.ctrlKey && !event.metaKey && backspaceAtStart(event, editor))
|
|
957
|
+
return;
|
|
958
|
+
if (event.key === "Delete" && latest.current.onMergeForward && isAtEndOf(editor)) {
|
|
959
|
+
event.preventDefault();
|
|
960
|
+
latest.current.onMergeForward();
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
if (event.key === "ArrowUp" && !event.shiftKey && latest.current.onNavigate && isAtStartOf(editor)) {
|
|
964
|
+
event.preventDefault();
|
|
965
|
+
latest.current.onNavigate("up");
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
if (event.key === "ArrowDown" && !event.shiftKey && latest.current.onNavigate && isAtEndOf(editor)) {
|
|
969
|
+
event.preventDefault();
|
|
970
|
+
latest.current.onNavigate("down");
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
handleFormattingShortcut(event);
|
|
974
|
+
};
|
|
975
|
+
const handleCompositionStart = () => { isComposingRef.current = true; };
|
|
976
|
+
const handleCompositionEnd = (event) => {
|
|
977
|
+
isComposingRef.current = false;
|
|
978
|
+
if (event.data)
|
|
979
|
+
handleInput();
|
|
980
|
+
if (pendingValueRef.current !== null) {
|
|
981
|
+
const pending = pendingValueRef.current;
|
|
982
|
+
pendingValueRef.current = null;
|
|
983
|
+
if (pending !== lastValueRef.current)
|
|
984
|
+
applyValue(pending);
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
const isEmpty = !value || value === "<br>";
|
|
988
|
+
const editorRect = editorRef.current?.getBoundingClientRect();
|
|
989
|
+
const popoverTop = linkPopoverPosition?.top ?? (editorRect?.bottom ?? 100) + 6;
|
|
990
|
+
const popoverLeft = linkPopoverPosition?.left ?? editorRect?.left ?? 20;
|
|
991
|
+
const linkPopover = showLinkInput && typeof document !== "undefined"
|
|
992
|
+
? createPortal(_jsxs("div", { role: "dialog", "aria-label": messages.editor.linkUrlPrompt, className: "elea-link-popover", ...linkScope, style: { position: "fixed", top: popoverTop, left: popoverLeft }, children: [_jsx("input", { ref: linkInputRef, type: "url", value: linkInputValue, onChange: (event) => { setLinkInputValue(event.target.value); setLinkUrlError(false); }, onKeyDown: (event) => {
|
|
993
|
+
if (event.key === "Enter") {
|
|
994
|
+
event.preventDefault();
|
|
995
|
+
submitLink();
|
|
996
|
+
}
|
|
997
|
+
if (event.key === "Escape") {
|
|
998
|
+
event.preventDefault();
|
|
999
|
+
closeLinkInput();
|
|
1000
|
+
}
|
|
1001
|
+
}, placeholder: messages.editor.linkUrlPlaceholder, "aria-label": messages.editor.linkUrlPrompt, "aria-invalid": linkUrlError, className: `elea-link-popover__input${linkUrlError ? " elea-link-popover__input--invalid" : ""}` }), linkUrlError && _jsx("span", { className: "elea-link-popover__error", role: "alert", children: messages.editor.linkUrlInvalid }), _jsx("button", { type: "button", className: "elea-link-popover__button elea-link-popover__button--confirm", onMouseDown: (event) => { event.preventDefault(); submitLink(); }, "aria-label": messages.editor.linkConfirm, children: _jsx(CheckIcon, {}) }), _jsx("button", { type: "button", className: "elea-link-popover__button", onMouseDown: (event) => { event.preventDefault(); closeLinkInput(); }, "aria-label": messages.editor.linkCancel, children: _jsx(CloseIcon, {}) })] }), document.body)
|
|
1002
|
+
: null;
|
|
1003
|
+
return (_jsxs("div", { className: "elea-richtext", onBlur: (event) => {
|
|
1004
|
+
if (!event.currentTarget.contains(event.relatedTarget))
|
|
1005
|
+
onBlur?.(event);
|
|
1006
|
+
}, children: [linkPopover, _jsxs("div", { className: "elea-richtext__area", children: [isEmpty && _jsx("div", { className: "elea-richtext__placeholder", "aria-hidden": "true", children: effectivePlaceholder }), _jsx("div", { ref: setEditorRef, contentEditable: true, role: "textbox", "aria-multiline": "true", "aria-label": effectivePlaceholder, tabIndex: 0, onInput: handleInput, onFocus: onFocus, onPaste: handlePaste, onKeyDown: handleKeyDown, onCompositionStart: handleCompositionStart, onCompositionEnd: handleCompositionEnd, className: ["elea-richtext__editable", className].filter(Boolean).join(" "), style: style, suppressContentEditableWarning: true })] })] }));
|
|
1007
|
+
});
|
|
1008
|
+
//# sourceMappingURL=RichTextField.js.map
|