-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.ts
More file actions
330 lines (298 loc) · 12 KB
/
Copy patheditor.ts
File metadata and controls
330 lines (298 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
* editor.ts - Slate/DOM abstraction for Discord's chat textbox.
*
* We never mutate the DOM directly (Slate would desync). For Step 1 we only
* need to *read* text/caret and *move* the caret via the Selection API,
* which Slate tolerates and syncs from on its own selectionchange handling.
*/
export const EDITOR_SELECTOR = 'div[role="textbox"][data-slate-editor="true"]';
/** Returns the slate editor element if `el` is (inside) one, else null. */
export function getEditor(el: EventTarget | null): HTMLElement | null {
if (!(el instanceof HTMLElement)) return null;
return el.closest(EDITOR_SELECTOR);
}
/** Collect all DOM text nodes inside the editor, in document order. */
function textNodes(editor: HTMLElement): Text[] {
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
const nodes: Text[] = [];
let n: Node | null;
while ((n = walker.nextNode())) nodes.push(n as Text);
return nodes;
}
/*
* Slate renders zero-width placeholder characters (\uFEFF / \u200B) inside
* empty lines and some leaves. They are invisible and not part of the real
* content, but they DO appear in textContent - so all offset math must
* ignore them or every offset after an empty line is shifted.
*/
const ZERO_WIDTH = /[\uFEFF\u200B]/g;
function isZeroWidth(ch: string): boolean {
return ch === "\uFEFF" || ch === "\u200B";
}
/** Visible length of a string (zero-width placeholders stripped). */
function cleanLen(s: string): number {
return s.replace(ZERO_WIDTH, "").length;
}
function stripZeroWidth(s: string): string {
return s.replace(ZERO_WIDTH, "");
}
/** Raw string index corresponding to a clean (visible) offset. */
function rawIndex(s: string, cleanOffset: number): number {
let seen = 0;
for (let i = 0; i < s.length; i++) {
if (isZeroWidth(s[i])) continue;
if (seen === cleanOffset) return i;
seen++;
}
return s.length;
}
/**
* Slate renders each line as a block element. We map the DOM to a plain-text
* model where lines are joined with "\n". A line's text is the concatenation
* of the text nodes within its block.
*/
function lineBlocks(editor: HTMLElement): HTMLElement[] {
// Slate marks block elements with data-slate-node="element" at top level.
const blocks = Array.from(
editor.querySelectorAll<HTMLElement>(':scope > [data-slate-node="element"]')
);
return blocks.length ? blocks : [editor];
}
export interface Position {
/** absolute character offset into the joined ("\n"-separated) text */
offset: number;
line: number;
/** column within the line */
col: number;
}
/** Full plain text of the editor, lines joined with \n. */
export function getText(editor: HTMLElement): string {
return getLines(editor).join("\n");
}
export function getLines(editor: HTMLElement): string[] {
return lineBlocks(editor).map(b => stripZeroWidth(b.textContent ?? ""));
}
/** Absolute offset of (node, nodeOffset) within the editor's text model. */
function domToOffset(editor: HTMLElement, node: Node, nodeOffset: number): number {
const blocks = lineBlocks(editor);
let abs = 0;
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if (block.contains(node)) {
for (const t of textNodes(block)) {
if (t === node) return abs + cleanLen(t.data.slice(0, nodeOffset));
abs += cleanLen(t.data);
}
// node is an element within the block (e.g. empty line)
return abs;
}
abs += cleanLen(block.textContent ?? "") + 1; // +1 for "\n"
}
return abs;
}
/** Current caret position, or null if selection is outside the editor. */
export function getCaret(editor: HTMLElement): Position | null {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) return null;
const { focusNode, focusOffset } = sel;
if (!focusNode || !editor.contains(focusNode)) return null;
const offset = domToOffset(editor, focusNode, focusOffset);
const lines = getLines(editor);
let remaining = offset;
for (let line = 0; line < lines.length; line++) {
if (remaining <= lines[line].length)
return { offset, line, col: remaining };
remaining -= lines[line].length + 1;
}
const last = lines.length - 1;
return { offset, line: last, col: lines[last]?.length ?? 0 };
}
/** Map an absolute text offset to a (node, offset) DOM point. */
function offsetToDom(editor: HTMLElement, offset: number): { node: Node; offset: number; } | null {
const blocks = lineBlocks(editor);
let remaining = Math.max(0, offset);
for (const block of blocks) {
const len = cleanLen(block.textContent ?? "");
if (remaining <= len) {
// find the text node containing `remaining`
let node: Node = block;
let nodeOffset = 0;
for (const t of textNodes(block)) {
const tLen = cleanLen(t.data);
if (remaining <= tLen) {
node = t;
nodeOffset = rawIndex(t.data, remaining);
break;
}
remaining -= tLen;
}
return { node, offset: nodeOffset };
}
remaining -= len + 1;
}
return null;
}
/** Place the caret at absolute character offset `offset`. */
export function setCaret(editor: HTMLElement, offset: number): void {
const point = offsetToDom(editor, offset);
const sel = window.getSelection();
if (!point || !sel) return;
const range = document.createRange();
range.setStart(point.node, point.offset);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
/** Select the text range [start, end) (absolute offsets). */
export function selectRange(editor: HTMLElement, start: number, end: number): void {
const a = offsetToDom(editor, start);
const b = offsetToDom(editor, end);
const sel = window.getSelection();
if (!a || !b || !sel) return;
const range = document.createRange();
range.setStart(a.node, a.offset);
range.setEnd(b.node, b.offset);
sel.removeAllRanges();
sel.addRange(range);
}
/**
* Extend the selection from `base` to `extent` (absolute offsets), keeping
* the focus at `extent` so backwards (leftwards) visual selections work.
*/
export function extendSelection(editor: HTMLElement, base: number, extent: number): void {
const a = offsetToDom(editor, base);
const b = offsetToDom(editor, extent);
const sel = window.getSelection();
if (!a || !b || !sel) return;
sel.setBaseAndExtent(a.node, a.offset, b.node, b.offset);
}
/**
* Delete the currently selected DOM range by dispatching a synthetic
* beforeinput, which Slate handles (never mutate the DOM directly).
* The selection must already be synced into Slate - see afterSelectionSync.
*/
export function deleteSelection(editor: HTMLElement): void {
dispatchInput(editor, { inputType: "deleteContentBackward" });
}
/**
* Slate only syncs its internal selection from the DOM asynchronously
* (via selectionchange). After moving the caret / selecting a range we must
* wait before dispatching input events, or Slate acts at the *old* caret.
*/
export function afterSelectionSync(fn: () => void): void {
setTimeout(fn, 0);
}
/**
* Run `fn` after an input event's effects have actually been rendered into
* the editor's DOM (Slate applies to its model, then React re-renders
* asynchronously). Falls back to a timeout if no mutation arrives.
*/
export function afterRender(editor: HTMLElement, fn: () => void): void {
let done = false;
const finish = (): void => {
if (done) return;
done = true;
observer.disconnect();
setTimeout(fn, 0); // let the selection settle too
};
const observer = new MutationObserver(finish);
observer.observe(editor, { childList: true, subtree: true, characterData: true });
setTimeout(finish, 100);
}
/**
* Dispatch a synthetic beforeinput carrying the current DOM selection as
* its target range. Slate's onDOMBeforeInput prefers getTargetRanges()
* over its internal (async-synced) selection, so this makes edits land at
* the caret we just set even if Slate hasn't synced yet. Synthetic
* InputEvents can't set target ranges via the constructor, so we override
* the method on the instance.
*/
function dispatchInput(editor: HTMLElement, init: InputEventInit, at?: number | [number, number]): void {
const event = new InputEvent("beforeinput", {
bubbles: true,
cancelable: true,
...init,
});
let ranges: StaticRange[] | null = null;
if (at !== undefined) {
// explicit target at absolute offset(s), resolved against the
// *current* DOM (immune to stale/clobbered DOM selections)
const [s, e] = typeof at === "number" ? [at, at] : at;
const a = offsetToDom(editor, s);
const b = offsetToDom(editor, e);
if (a && b) {
ranges = [new StaticRange({
startContainer: a.node,
startOffset: a.offset,
endContainer: b.node,
endOffset: b.offset,
})];
}
}
if (!ranges) {
const sel = window.getSelection();
if (sel && sel.rangeCount > 0 && editor.contains(sel.anchorNode)) {
const r = sel.getRangeAt(0);
ranges = [new StaticRange({
startContainer: r.startContainer,
startOffset: r.startOffset,
endContainer: r.endContainer,
endOffset: r.endOffset,
})];
}
}
if (ranges) {
const value = ranges;
Object.defineProperty(event, "getTargetRanges", { value: () => value });
}
editor.dispatchEvent(event);
}
/**
* Insert plain text at the current caret via a synthetic beforeinput
* event, which Slate listens to (never mutate the DOM directly).
*/
export function insertText(editor: HTMLElement, text: string, at?: number): void {
dispatchInput(editor, { inputType: "insertText", data: text }, at);
}
/**
* Insert (possibly multi-line) text at absolute offset `at` as a single
* atomic operation, by dispatching a synthetic paste (insertFromPaste with
* a DataTransfer). This rides Discord's real paste path, which already
* handles multi-line text correctly - no chaining of events across
* re-renders, no selection races.
*/
export function insertPasteText(editor: HTMLElement, text: string, at?: number): void {
const dataTransfer = new DataTransfer();
dataTransfer.setData("text/plain", text);
dispatchInput(editor, { inputType: "insertFromPaste", dataTransfer }, at);
}
/**
* Replace the text range [start, end) with `text` in one atomic
* insertText targeted at an explicit range (used by r, ~, J).
*/
export function replaceRange(editor: HTMLElement, start: number, end: number, text: string): void {
dispatchInput(editor, { inputType: "insertText", data: text }, [start, end]);
}
/** Delete the text range [start, end) without touching the register. */
export function deleteRange(editor: HTMLElement, start: number, end: number): void {
dispatchInput(editor, { inputType: "deleteContentBackward" }, [start, end]);
}
/** Forward to Slate's history via a synthetic historyUndo beforeinput. */
export function undo(editor: HTMLElement): void {
dispatchInput(editor, { inputType: "historyUndo" });
}
/** Forward to Slate's history via a synthetic historyRedo beforeinput. */
export function redo(editor: HTMLElement): void {
dispatchInput(editor, { inputType: "historyRedo" });
}
/** Insert a soft line break (Shift+Enter semantics) at the caret. */
export function insertLineBreak(editor: HTMLElement, at?: number): void {
dispatchInput(editor, { inputType: "insertLineBreak" }, at);
}
/** Convert (line, col) to an absolute offset, clamping col to line length. */
export function lineColToOffset(lines: string[], line: number, col: number): number {
line = Math.max(0, Math.min(line, lines.length - 1));
let offset = 0;
for (let i = 0; i < line; i++) offset += lines[i].length + 1;
return offset + Math.min(col, lines[line].length);
}