@mwillbanks/tuil-editor 0.0.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +90 -29
- package/buffer.d.ts +25 -0
- package/buffer.d.ts.map +1 -0
- package/buffer.js +466 -0
- package/buffer.js.map +12 -0
- package/index.d.ts +133 -0
- package/index.d.ts.map +1 -0
- package/index.js +90 -0
- package/index.js.map +10 -0
- package/package.json +45 -6
- package/rich.d.ts +81 -0
- package/rich.d.ts.map +1 -0
- package/rich.js +1081 -0
- package/rich.js.map +13 -0
- package/session-commands.d.ts +6 -0
- package/session-commands.d.ts.map +1 -0
- package/testing.d.ts +8 -0
- package/testing.d.ts.map +1 -0
- package/testing.js +55 -0
- package/testing.js.map +10 -0
- package/vim.d.ts +31 -0
- package/vim.d.ts.map +1 -0
- package/vim.js +894 -0
- package/vim.js.map +13 -0
package/rich.js
ADDED
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/index.ts
|
|
3
|
+
function validateEditorProvider(providers, defaultId, provider, options) {
|
|
4
|
+
if (!provider.id.trim() || !provider.version.trim()) {
|
|
5
|
+
throw new Error("Editor providers require a stable id and version");
|
|
6
|
+
}
|
|
7
|
+
if (providers.has(provider.id) && !options.replace) {
|
|
8
|
+
throw new Error(`Editor provider "${provider.id}" is already registered`);
|
|
9
|
+
}
|
|
10
|
+
const replacesDefault = options.default && defaultId && defaultId !== provider.id;
|
|
11
|
+
if (replacesDefault && !options.replace) {
|
|
12
|
+
throw new Error(`Default editor "${defaultId}" cannot be replaced accidentally`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function supportsOptional(required, provided) {
|
|
16
|
+
return !required || !provided || provided.includes(required);
|
|
17
|
+
}
|
|
18
|
+
function supportsEditorRequirements(provider, requirements) {
|
|
19
|
+
if (requirements.documentType && provider.documentTypes && !provider.documentTypes.includes(requirements.documentType)) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
const capabilities = requirements.capabilities ?? [];
|
|
23
|
+
if (!capabilities.every((capability) => provider.capabilities.has(capability)))
|
|
24
|
+
return false;
|
|
25
|
+
return supportsOptional(requirements.renderer, provider.rendererCapabilities) && supportsOptional(requirements.input, provider.inputCapabilities) && supportsOptional(requirements.staticMode, provider.staticModes);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class EditorProviderRegistry {
|
|
29
|
+
#providers;
|
|
30
|
+
#defaultId;
|
|
31
|
+
constructor() {
|
|
32
|
+
this.#providers = new Map;
|
|
33
|
+
this.#defaultId = undefined;
|
|
34
|
+
}
|
|
35
|
+
register(provider, options = {}) {
|
|
36
|
+
validateEditorProvider(this.#providers, this.#defaultId, provider, options);
|
|
37
|
+
this.#providers.set(provider.id, provider);
|
|
38
|
+
if (options.default || !this.#defaultId)
|
|
39
|
+
this.#defaultId = provider.id;
|
|
40
|
+
return Object.freeze({
|
|
41
|
+
provider,
|
|
42
|
+
default: this.#defaultId === provider.id,
|
|
43
|
+
dispose: this.#providerDisposer(provider)
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
#providerDisposer(provider) {
|
|
47
|
+
let disposed = false;
|
|
48
|
+
return () => {
|
|
49
|
+
if (disposed || this.#providers.get(provider.id) !== provider)
|
|
50
|
+
return;
|
|
51
|
+
disposed = true;
|
|
52
|
+
this.#providers.delete(provider.id);
|
|
53
|
+
if (this.#defaultId === provider.id) {
|
|
54
|
+
this.#defaultId = this.#providers.keys().next().value;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
resolve(id, requirements = {}) {
|
|
59
|
+
const preferred = this.#defaultId ? this.#providers.get(this.#defaultId) : undefined;
|
|
60
|
+
const candidates = id ? [this.#providers.get(id)] : [preferred, ...this.#providers.values()];
|
|
61
|
+
const provider = candidates.find((candidate) => candidate !== undefined && supportsEditorRequirements(candidate, requirements));
|
|
62
|
+
if (!provider) {
|
|
63
|
+
throw new Error(`No compatible editor provider found${id ? ` for "${id}"` : ""}`);
|
|
64
|
+
}
|
|
65
|
+
return provider;
|
|
66
|
+
}
|
|
67
|
+
list() {
|
|
68
|
+
return Object.freeze([...this.#providers.values()]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function position(line, column) {
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
line: Math.max(0, Math.floor(line)),
|
|
74
|
+
column: Math.max(0, Math.floor(column))
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function selection(anchor, head = anchor, primary = true) {
|
|
78
|
+
return Object.freeze({
|
|
79
|
+
anchor: position(anchor.line, anchor.column),
|
|
80
|
+
head: position(head.line, head.column),
|
|
81
|
+
primary
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/buffer.ts
|
|
86
|
+
import { createGlobalSearchExpression } from "@mwillbanks/tuil-core";
|
|
87
|
+
|
|
88
|
+
// src/session-commands.ts
|
|
89
|
+
function executeClipboardCommand(session, command, argument) {
|
|
90
|
+
if (command === "copy")
|
|
91
|
+
return Promise.resolve(session.copy()).then(() => true);
|
|
92
|
+
if (command === "cut")
|
|
93
|
+
return Promise.resolve(session.cut()).then(() => true);
|
|
94
|
+
if (command === "paste") {
|
|
95
|
+
return session.paste(typeof argument === "string" ? argument : undefined);
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
function replaceSelections(session, content) {
|
|
100
|
+
const snapshot = session.snapshot();
|
|
101
|
+
if (content === undefined || snapshot.readOnly)
|
|
102
|
+
return false;
|
|
103
|
+
session.dispatch({
|
|
104
|
+
changes: snapshot.selections.map((range) => ({
|
|
105
|
+
range,
|
|
106
|
+
insert: content
|
|
107
|
+
}))
|
|
108
|
+
});
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
function cutSelections(session, copied) {
|
|
112
|
+
const remove = (value) => {
|
|
113
|
+
replaceSelections(session, "");
|
|
114
|
+
return value;
|
|
115
|
+
};
|
|
116
|
+
return copied instanceof Promise ? copied.then(remove) : remove(copied);
|
|
117
|
+
}
|
|
118
|
+
function pasteSelections(session, clipboard, value) {
|
|
119
|
+
if (value !== undefined)
|
|
120
|
+
return replaceSelections(session, value);
|
|
121
|
+
if (!clipboard)
|
|
122
|
+
return false;
|
|
123
|
+
return Promise.resolve(clipboard.read()).then((content) => replaceSelections(session, content));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/buffer.ts
|
|
127
|
+
var graphemeSegmenter = new Intl.Segmenter(undefined, {
|
|
128
|
+
granularity: "grapheme"
|
|
129
|
+
});
|
|
130
|
+
function graphemes(value) {
|
|
131
|
+
return Object.freeze([...graphemeSegmenter.segment(value)].map((segment) => segment.segment));
|
|
132
|
+
}
|
|
133
|
+
function maskText(value) {
|
|
134
|
+
return value.split(`
|
|
135
|
+
`).map((line) => "\u2022".repeat(graphemes(line).length)).join(`
|
|
136
|
+
`);
|
|
137
|
+
}
|
|
138
|
+
function starts(value) {
|
|
139
|
+
const result = [0];
|
|
140
|
+
for (let index = 0;index < value.length; index += 1) {
|
|
141
|
+
if (value[index] === `
|
|
142
|
+
`)
|
|
143
|
+
result.push(index + 1);
|
|
144
|
+
}
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
function clamp(value, target) {
|
|
148
|
+
const lines = value.split(`
|
|
149
|
+
`);
|
|
150
|
+
const line = Math.min(Math.max(0, target.line), Math.max(0, lines.length - 1));
|
|
151
|
+
return position(line, Math.min(Math.max(0, target.column), graphemes(lines[line] ?? "").length));
|
|
152
|
+
}
|
|
153
|
+
function offsetAt(value, target) {
|
|
154
|
+
const safe = clamp(value, target);
|
|
155
|
+
return (starts(value)[safe.line] ?? 0) + graphemes(value.split(`
|
|
156
|
+
`)[safe.line] ?? "").slice(0, safe.column).join("").length;
|
|
157
|
+
}
|
|
158
|
+
function positionAt(value, offset) {
|
|
159
|
+
const safe = Math.max(0, Math.min(value.length, offset));
|
|
160
|
+
const lineStarts = starts(value);
|
|
161
|
+
let line = 0;
|
|
162
|
+
for (let index = 0;index < lineStarts.length; index += 1) {
|
|
163
|
+
if ((lineStarts[index] ?? 0) <= safe)
|
|
164
|
+
line = index;
|
|
165
|
+
else
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
return position(line, graphemes(value.slice(lineStarts[line] ?? 0, safe)).length);
|
|
169
|
+
}
|
|
170
|
+
function offsets(value, range) {
|
|
171
|
+
const anchor = offsetAt(value, range.anchor);
|
|
172
|
+
const head = offsetAt(value, range.head);
|
|
173
|
+
return anchor <= head ? [anchor, head] : [head, anchor];
|
|
174
|
+
}
|
|
175
|
+
function freezeSelections(value, items) {
|
|
176
|
+
return Object.freeze(items.map((item, index) => selection(clamp(value, item.anchor), clamp(value, item.head), item.primary ?? index === 0)));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
class TextBufferSession {
|
|
180
|
+
#id;
|
|
181
|
+
#type;
|
|
182
|
+
#readOnly;
|
|
183
|
+
#masked;
|
|
184
|
+
#clipboard;
|
|
185
|
+
#onDocumentChange;
|
|
186
|
+
#observers = new Set;
|
|
187
|
+
#undo = [];
|
|
188
|
+
#redo = [];
|
|
189
|
+
#text;
|
|
190
|
+
#version = 0;
|
|
191
|
+
#selections;
|
|
192
|
+
#decorations = [];
|
|
193
|
+
#diagnostics = [];
|
|
194
|
+
#mode;
|
|
195
|
+
#viewportAnchor;
|
|
196
|
+
#disposed = false;
|
|
197
|
+
constructor(options = {}) {
|
|
198
|
+
this.#id = options.id ?? "document";
|
|
199
|
+
this.#type = options.documentType ?? "text/plain";
|
|
200
|
+
this.#text = options.value ?? "";
|
|
201
|
+
this.#readOnly = options.readOnly ?? false;
|
|
202
|
+
this.#masked = options.masked ?? false;
|
|
203
|
+
this.#clipboard = options.clipboard;
|
|
204
|
+
this.#onDocumentChange = options.onDocumentChange;
|
|
205
|
+
this.#mode = options.mode ?? "insert";
|
|
206
|
+
this.#viewportAnchor = options.viewportAnchor;
|
|
207
|
+
this.#selections = [selection(position(0, 0))];
|
|
208
|
+
}
|
|
209
|
+
snapshot() {
|
|
210
|
+
return Object.freeze({
|
|
211
|
+
document: Object.freeze({
|
|
212
|
+
id: this.#id,
|
|
213
|
+
type: this.#type,
|
|
214
|
+
version: this.#version,
|
|
215
|
+
text: this.#exportText()
|
|
216
|
+
}),
|
|
217
|
+
selections: this.#selections,
|
|
218
|
+
decorations: this.#decorations,
|
|
219
|
+
diagnostics: this.#diagnostics,
|
|
220
|
+
mode: this.#mode,
|
|
221
|
+
readOnly: this.#readOnly,
|
|
222
|
+
canUndo: this.#undo.length > 0,
|
|
223
|
+
canRedo: this.#redo.length > 0,
|
|
224
|
+
viewportAnchor: this.#viewportAnchor
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
dispatch(transaction) {
|
|
228
|
+
this.#assertActive();
|
|
229
|
+
const changes = [...transaction.changes ?? []];
|
|
230
|
+
if (changes.length > 0 && this.#readOnly) {
|
|
231
|
+
throw new Error("Editor session is read-only");
|
|
232
|
+
}
|
|
233
|
+
this.#recordTransactionHistory(changes, transaction.addToHistory);
|
|
234
|
+
const edits = prepareEdits(this.#text, changes);
|
|
235
|
+
this.#text = applyEdits(this.#text, edits);
|
|
236
|
+
this.#applyTransactionSelection(edits, transaction.selections);
|
|
237
|
+
if (changes.length > 0 || transaction.selections)
|
|
238
|
+
this.#version += 1;
|
|
239
|
+
if (changes.length > 0)
|
|
240
|
+
this.#onDocumentChange?.(this.#text);
|
|
241
|
+
this.#notify();
|
|
242
|
+
return this.snapshot();
|
|
243
|
+
}
|
|
244
|
+
#recordTransactionHistory(changes, addToHistory) {
|
|
245
|
+
if (changes.length === 0 || addToHistory === false)
|
|
246
|
+
return;
|
|
247
|
+
this.#undo.push({ text: this.#text, selections: this.#selections });
|
|
248
|
+
this.#redo.length = 0;
|
|
249
|
+
}
|
|
250
|
+
#applyTransactionSelection(edits, selections) {
|
|
251
|
+
if (selections) {
|
|
252
|
+
this.#selections = freezeSelections(this.#text, selections);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (edits.length === 0)
|
|
256
|
+
return;
|
|
257
|
+
this.#selections = edits.toSorted((left, right) => left.index - right.index).map((edit) => {
|
|
258
|
+
const precedingDelta = edits.filter((candidate) => candidate.offsets[0] < edit.offsets[0]).reduce((total, candidate) => total + candidate.change.insert.length - (candidate.offsets[1] - candidate.offsets[0]), 0);
|
|
259
|
+
return selection(positionAt(this.#text, edit.offsets[0] + edit.change.insert.length + precedingDelta));
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
execute(command, argument) {
|
|
263
|
+
this.#assertActive();
|
|
264
|
+
if (typeof command !== "string")
|
|
265
|
+
return command.execute(this, argument);
|
|
266
|
+
const clipboard = executeClipboardCommand(this, command, argument);
|
|
267
|
+
if (clipboard !== undefined)
|
|
268
|
+
return clipboard;
|
|
269
|
+
return this.#executeSelectionCommand(command);
|
|
270
|
+
}
|
|
271
|
+
#executeSelectionCommand(command) {
|
|
272
|
+
if (command === "select-all") {
|
|
273
|
+
this.#selections = [
|
|
274
|
+
selection(position(0, 0), positionAt(this.#text, this.#text.length))
|
|
275
|
+
];
|
|
276
|
+
} else if (command === "delete-selection") {
|
|
277
|
+
this.dispatch({
|
|
278
|
+
changes: this.#selections.map((range) => ({ range, insert: "" }))
|
|
279
|
+
});
|
|
280
|
+
return true;
|
|
281
|
+
} else if (command === "cursor-start") {
|
|
282
|
+
this.dispatch({
|
|
283
|
+
selections: [selection(position(0, 0))],
|
|
284
|
+
addToHistory: false
|
|
285
|
+
});
|
|
286
|
+
return true;
|
|
287
|
+
} else if (command === "cursor-end") {
|
|
288
|
+
this.dispatch({
|
|
289
|
+
selections: [selection(positionAt(this.#text, this.#text.length))],
|
|
290
|
+
addToHistory: false
|
|
291
|
+
});
|
|
292
|
+
return true;
|
|
293
|
+
} else {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
this.#notify();
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
copy() {
|
|
300
|
+
this.#assertActive();
|
|
301
|
+
const copied = this.#selections.map((range) => {
|
|
302
|
+
const [start, end] = offsets(this.#text, range);
|
|
303
|
+
const value = this.#text.slice(start, end);
|
|
304
|
+
return this.#masked ? maskText(value) : value;
|
|
305
|
+
}).join(`
|
|
306
|
+
`);
|
|
307
|
+
if (!this.#clipboard)
|
|
308
|
+
return copied;
|
|
309
|
+
return Promise.resolve(this.#clipboard.write(copied)).then(() => copied);
|
|
310
|
+
}
|
|
311
|
+
cut() {
|
|
312
|
+
return cutSelections(this, this.copy());
|
|
313
|
+
}
|
|
314
|
+
paste(value) {
|
|
315
|
+
return pasteSelections(this, this.#clipboard, value);
|
|
316
|
+
}
|
|
317
|
+
undo() {
|
|
318
|
+
return this.#restoreHistory(this.#undo, this.#redo);
|
|
319
|
+
}
|
|
320
|
+
redo() {
|
|
321
|
+
return this.#restoreHistory(this.#redo, this.#undo);
|
|
322
|
+
}
|
|
323
|
+
#restoreHistory(source, destination) {
|
|
324
|
+
this.#assertActive();
|
|
325
|
+
const entry = source.pop();
|
|
326
|
+
if (!entry)
|
|
327
|
+
return false;
|
|
328
|
+
destination.push({ text: this.#text, selections: this.#selections });
|
|
329
|
+
this.#text = entry.text;
|
|
330
|
+
this.#selections = entry.selections;
|
|
331
|
+
this.#version += 1;
|
|
332
|
+
this.#onDocumentChange?.(this.#text);
|
|
333
|
+
this.#notify();
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
search(query) {
|
|
337
|
+
this.#assertActive();
|
|
338
|
+
if (typeof query === "string" && query.length === 0)
|
|
339
|
+
return [];
|
|
340
|
+
const expression = createGlobalSearchExpression(query);
|
|
341
|
+
const ranges = [];
|
|
342
|
+
for (const match of this.#text.matchAll(expression)) {
|
|
343
|
+
ranges.push(Object.freeze({
|
|
344
|
+
anchor: positionAt(this.#text, match.index),
|
|
345
|
+
head: positionAt(this.#text, match.index + match[0].length)
|
|
346
|
+
}));
|
|
347
|
+
if (match[0].length === 0)
|
|
348
|
+
expression.lastIndex += 1;
|
|
349
|
+
}
|
|
350
|
+
return Object.freeze(ranges);
|
|
351
|
+
}
|
|
352
|
+
replace(query, replacement, all = true) {
|
|
353
|
+
const ranges = this.search(query);
|
|
354
|
+
const selected = all ? ranges : ranges.slice(0, 1);
|
|
355
|
+
if (selected.length === 0)
|
|
356
|
+
return 0;
|
|
357
|
+
this.dispatch({
|
|
358
|
+
changes: selected.map((range) => ({
|
|
359
|
+
range,
|
|
360
|
+
insert: replacement
|
|
361
|
+
}))
|
|
362
|
+
});
|
|
363
|
+
return selected.length;
|
|
364
|
+
}
|
|
365
|
+
serialize(format = "text") {
|
|
366
|
+
const text = this.#exportText();
|
|
367
|
+
return format === "json" ? JSON.stringify(this.#masked ? { type: this.#type, text, masked: true } : { type: this.#type, text }) : text;
|
|
368
|
+
}
|
|
369
|
+
#exportText() {
|
|
370
|
+
return this.#masked ? maskText(this.#text) : this.#text;
|
|
371
|
+
}
|
|
372
|
+
subscribe(observer) {
|
|
373
|
+
this.#assertActive();
|
|
374
|
+
this.#observers.add(observer);
|
|
375
|
+
return () => this.#observers.delete(observer);
|
|
376
|
+
}
|
|
377
|
+
setDecorations(decorations) {
|
|
378
|
+
this.#decorations = Object.freeze([...decorations]);
|
|
379
|
+
this.#notify();
|
|
380
|
+
}
|
|
381
|
+
setDiagnostics(diagnostics) {
|
|
382
|
+
this.#diagnostics = Object.freeze([...diagnostics]);
|
|
383
|
+
this.#notify();
|
|
384
|
+
}
|
|
385
|
+
setMode(mode) {
|
|
386
|
+
this.#mode = mode;
|
|
387
|
+
this.#notify();
|
|
388
|
+
}
|
|
389
|
+
setViewportAnchor(anchor) {
|
|
390
|
+
this.#viewportAnchor = clamp(this.#text, anchor);
|
|
391
|
+
this.#notify();
|
|
392
|
+
}
|
|
393
|
+
dispose() {
|
|
394
|
+
this.#disposed = true;
|
|
395
|
+
this.#observers.clear();
|
|
396
|
+
this.#undo.length = 0;
|
|
397
|
+
this.#redo.length = 0;
|
|
398
|
+
}
|
|
399
|
+
#notify() {
|
|
400
|
+
const snapshot = this.snapshot();
|
|
401
|
+
for (const observer of this.#observers)
|
|
402
|
+
observer(snapshot);
|
|
403
|
+
}
|
|
404
|
+
#assertActive() {
|
|
405
|
+
if (this.#disposed)
|
|
406
|
+
throw new Error("Editor session is disposed");
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function prepareEdits(text, changes) {
|
|
410
|
+
const edits = changes.map((change, index) => ({
|
|
411
|
+
index,
|
|
412
|
+
change,
|
|
413
|
+
offsets: offsets(text, change.range)
|
|
414
|
+
})).sort((left, right) => right.offsets[0] - left.offsets[0]);
|
|
415
|
+
for (let index = 1;index < edits.length; index += 1) {
|
|
416
|
+
const previous = edits[index - 1];
|
|
417
|
+
const current = edits[index];
|
|
418
|
+
if (previous && current && current.offsets[1] > previous.offsets[0]) {
|
|
419
|
+
throw new Error("Editor transaction changes cannot overlap");
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return edits;
|
|
423
|
+
}
|
|
424
|
+
function applyEdits(text, edits) {
|
|
425
|
+
let result = text;
|
|
426
|
+
for (const edit of edits) {
|
|
427
|
+
result = result.slice(0, edit.offsets[0]) + edit.change.insert + result.slice(edit.offsets[1]);
|
|
428
|
+
}
|
|
429
|
+
return result;
|
|
430
|
+
}
|
|
431
|
+
var textBufferProvider = Object.freeze({
|
|
432
|
+
id: "tuil-buffer",
|
|
433
|
+
version: "1",
|
|
434
|
+
capabilities: new Set([
|
|
435
|
+
"single-line",
|
|
436
|
+
"multiline",
|
|
437
|
+
"multiple-selections",
|
|
438
|
+
"history",
|
|
439
|
+
"search",
|
|
440
|
+
"replace",
|
|
441
|
+
"decorations",
|
|
442
|
+
"diagnostics",
|
|
443
|
+
"clipboard",
|
|
444
|
+
"masked",
|
|
445
|
+
"static"
|
|
446
|
+
]),
|
|
447
|
+
documentTypes: [
|
|
448
|
+
"text/plain",
|
|
449
|
+
"text/markdown",
|
|
450
|
+
"text/code",
|
|
451
|
+
"application/query"
|
|
452
|
+
],
|
|
453
|
+
staticModes: ["static", "json", "silent"],
|
|
454
|
+
create: (options) => new TextBufferSession(options)
|
|
455
|
+
});
|
|
456
|
+
function insertText(session, value) {
|
|
457
|
+
const changes = session.snapshot().selections.map((range) => ({ range, insert: value }));
|
|
458
|
+
return session.dispatch({ changes });
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// src/rich.ts
|
|
462
|
+
import { wrapTerminalText } from "@mwillbanks/tuil-core";
|
|
463
|
+
var graphemeSegmenter2 = new Intl.Segmenter(undefined, {
|
|
464
|
+
granularity: "grapheme"
|
|
465
|
+
});
|
|
466
|
+
var richNodeTypes = new Set([
|
|
467
|
+
"document",
|
|
468
|
+
"paragraph",
|
|
469
|
+
"heading",
|
|
470
|
+
"text",
|
|
471
|
+
"bullet-list",
|
|
472
|
+
"ordered-list",
|
|
473
|
+
"list-item",
|
|
474
|
+
"link",
|
|
475
|
+
"code-block",
|
|
476
|
+
"table",
|
|
477
|
+
"table-row",
|
|
478
|
+
"table-cell"
|
|
479
|
+
]);
|
|
480
|
+
function isRecord(value) {
|
|
481
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
482
|
+
}
|
|
483
|
+
function richNodeRecord(value) {
|
|
484
|
+
if (!isRecord(value) || typeof value["type"] !== "string" || value["type"].trim().length === 0) {
|
|
485
|
+
throw new Error("Rich editor changes must preserve non-empty node types");
|
|
486
|
+
}
|
|
487
|
+
return value;
|
|
488
|
+
}
|
|
489
|
+
function validateTextField(value) {
|
|
490
|
+
if (value["text"] !== undefined && typeof value["text"] !== "string") {
|
|
491
|
+
throw new Error("Rich editor text nodes must contain strings");
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function validateLevelField(value) {
|
|
495
|
+
if (value["level"] !== undefined && (!Number.isSafeInteger(value["level"]) || value["level"] < 1 || value["level"] > 6)) {
|
|
496
|
+
throw new Error("Rich editor heading levels must be between 1 and 6");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
function validateArrayField(value, field) {
|
|
500
|
+
if (value[field] !== undefined && !Array.isArray(value[field])) {
|
|
501
|
+
throw new Error(`Rich editor node ${field} must be an array`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function validateAttributesField(value) {
|
|
505
|
+
if (value["attributes"] !== undefined && !isRecord(value["attributes"])) {
|
|
506
|
+
throw new Error("Rich editor node attributes must be an object");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function validateRichNodeFields(value) {
|
|
510
|
+
validateTextField(value);
|
|
511
|
+
validateLevelField(value);
|
|
512
|
+
validateArrayField(value, "children");
|
|
513
|
+
validateArrayField(value, "marks");
|
|
514
|
+
validateAttributesField(value);
|
|
515
|
+
}
|
|
516
|
+
function validateRichMark(mark) {
|
|
517
|
+
if (!isRecord(mark) || typeof mark["type"] !== "string" || mark["type"].trim().length === 0) {
|
|
518
|
+
throw new Error("Rich editor changes must preserve non-empty marks");
|
|
519
|
+
}
|
|
520
|
+
if (mark["attributes"] !== undefined && !isRecord(mark["attributes"])) {
|
|
521
|
+
throw new Error("Rich editor mark attributes must be an object");
|
|
522
|
+
}
|
|
523
|
+
return mark;
|
|
524
|
+
}
|
|
525
|
+
function validateRichNode(value, providers) {
|
|
526
|
+
const record = richNodeRecord(value);
|
|
527
|
+
validateRichNodeFields(record);
|
|
528
|
+
const node = {
|
|
529
|
+
...record,
|
|
530
|
+
marks: record["marks"]?.map(validateRichMark),
|
|
531
|
+
children: record["children"]?.map((child) => validateRichNode(child, providers))
|
|
532
|
+
};
|
|
533
|
+
providers.get(node.type)?.validate?.(node);
|
|
534
|
+
return node;
|
|
535
|
+
}
|
|
536
|
+
function freezeNode(node) {
|
|
537
|
+
return Object.freeze({
|
|
538
|
+
...node,
|
|
539
|
+
attributes: node.attributes ? Object.freeze({ ...node.attributes }) : undefined,
|
|
540
|
+
marks: node.marks ? Object.freeze(node.marks.map((mark) => Object.freeze({ ...mark }))) : undefined,
|
|
541
|
+
children: node.children ? Object.freeze(node.children.map(freezeNode)) : undefined
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
function invalidRichPath(path) {
|
|
545
|
+
return new Error(`Rich document path ${path.join(".")} is invalid`);
|
|
546
|
+
}
|
|
547
|
+
function richNodeProviderMap(providers = []) {
|
|
548
|
+
const result = new Map;
|
|
549
|
+
for (const provider of providers) {
|
|
550
|
+
if (!provider.type.trim()) {
|
|
551
|
+
throw new Error("Rich node providers require a non-empty type");
|
|
552
|
+
}
|
|
553
|
+
if (richNodeTypes.has(provider.type)) {
|
|
554
|
+
throw new Error(`Rich node provider "${provider.type}" cannot replace a built-in node`);
|
|
555
|
+
}
|
|
556
|
+
if (result.has(provider.type)) {
|
|
557
|
+
throw new Error(`Rich node provider "${provider.type}" is duplicated`);
|
|
558
|
+
}
|
|
559
|
+
result.set(provider.type, Object.freeze({ ...provider }));
|
|
560
|
+
}
|
|
561
|
+
return result;
|
|
562
|
+
}
|
|
563
|
+
function editRichLeaf(children, index, transaction) {
|
|
564
|
+
if (transaction.remove) {
|
|
565
|
+
children.splice(index, 1);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
if (!children[index] || !transaction.node)
|
|
569
|
+
throw invalidRichPath(transaction.path);
|
|
570
|
+
children[index] = transaction.node;
|
|
571
|
+
}
|
|
572
|
+
function editRichNode(node, transaction, depth) {
|
|
573
|
+
const index = transaction.path[depth];
|
|
574
|
+
if (index === undefined)
|
|
575
|
+
return transaction.node ?? node;
|
|
576
|
+
const children = [...node.children ?? []];
|
|
577
|
+
const leaf = depth === transaction.path.length - 1;
|
|
578
|
+
if (leaf)
|
|
579
|
+
editRichLeaf(children, index, transaction);
|
|
580
|
+
else {
|
|
581
|
+
const child = children[index];
|
|
582
|
+
if (!child)
|
|
583
|
+
throw invalidRichPath(transaction.path);
|
|
584
|
+
children[index] = editRichNode(child, transaction, depth + 1);
|
|
585
|
+
}
|
|
586
|
+
return freezeNode({ ...node, children });
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
class RichDocumentSession {
|
|
590
|
+
#document;
|
|
591
|
+
#history = [];
|
|
592
|
+
#redo = [];
|
|
593
|
+
#providers;
|
|
594
|
+
constructor(root = { type: "document", children: [] }, options = {}) {
|
|
595
|
+
this.#providers = richNodeProviderMap(options.nodes);
|
|
596
|
+
const validated = validateRichNode(root, this.#providers);
|
|
597
|
+
if (validated.type !== "document") {
|
|
598
|
+
throw new Error("Rich documents require a document root");
|
|
599
|
+
}
|
|
600
|
+
this.#document = Object.freeze({ version: 0, root: freezeNode(validated) });
|
|
601
|
+
}
|
|
602
|
+
snapshot() {
|
|
603
|
+
return this.#document;
|
|
604
|
+
}
|
|
605
|
+
dispatch(transaction) {
|
|
606
|
+
const node = transaction.node ? freezeNode(validateRichNode(transaction.node, this.#providers)) : undefined;
|
|
607
|
+
const validated = { ...transaction, node };
|
|
608
|
+
if (transaction.path.length === 0 && transaction.node) {
|
|
609
|
+
if (node?.type !== "document") {
|
|
610
|
+
throw new Error("Rich documents require a document root");
|
|
611
|
+
}
|
|
612
|
+
this.#history.push(this.#document);
|
|
613
|
+
this.#redo.length = 0;
|
|
614
|
+
this.#document = Object.freeze({
|
|
615
|
+
version: this.#document.version + 1,
|
|
616
|
+
root: node
|
|
617
|
+
});
|
|
618
|
+
return this.#document;
|
|
619
|
+
}
|
|
620
|
+
this.#history.push(this.#document);
|
|
621
|
+
this.#redo.length = 0;
|
|
622
|
+
this.#document = Object.freeze({
|
|
623
|
+
version: this.#document.version + 1,
|
|
624
|
+
root: editRichNode(this.#document.root, validated, 0)
|
|
625
|
+
});
|
|
626
|
+
return this.#document;
|
|
627
|
+
}
|
|
628
|
+
undo() {
|
|
629
|
+
const previous = this.#history.pop();
|
|
630
|
+
if (!previous)
|
|
631
|
+
return false;
|
|
632
|
+
this.#redo.push(this.#document);
|
|
633
|
+
this.#document = previous;
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
redo() {
|
|
637
|
+
const next = this.#redo.pop();
|
|
638
|
+
if (!next)
|
|
639
|
+
return false;
|
|
640
|
+
this.#history.push(this.#document);
|
|
641
|
+
this.#document = next;
|
|
642
|
+
return true;
|
|
643
|
+
}
|
|
644
|
+
serialize(format = "json") {
|
|
645
|
+
return format === "json" ? JSON.stringify(this.#document) : richDocumentToMarkdown(this.#document.root, this.#providers);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
function parseRichDocument(value, providers) {
|
|
649
|
+
if (!value?.trim())
|
|
650
|
+
return { type: "document", children: [] };
|
|
651
|
+
let candidate;
|
|
652
|
+
try {
|
|
653
|
+
candidate = JSON.parse(value);
|
|
654
|
+
} catch {
|
|
655
|
+
candidate = undefined;
|
|
656
|
+
}
|
|
657
|
+
if (isRecord(candidate)) {
|
|
658
|
+
const root = validateRichNode(candidate["root"] ?? candidate, providers);
|
|
659
|
+
if (root.type === "document")
|
|
660
|
+
return root;
|
|
661
|
+
}
|
|
662
|
+
return {
|
|
663
|
+
type: "document",
|
|
664
|
+
children: [
|
|
665
|
+
{
|
|
666
|
+
type: "paragraph",
|
|
667
|
+
children: [{ type: "text", text: value }]
|
|
668
|
+
}
|
|
669
|
+
]
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
var richBlockNodeTypes = new Set([
|
|
673
|
+
"paragraph",
|
|
674
|
+
"heading",
|
|
675
|
+
"list-item",
|
|
676
|
+
"code-block",
|
|
677
|
+
"table-row"
|
|
678
|
+
]);
|
|
679
|
+
function projectRichText(root, providers) {
|
|
680
|
+
let text = "";
|
|
681
|
+
const spans = [];
|
|
682
|
+
const visit = (node, path) => {
|
|
683
|
+
const start = text.length;
|
|
684
|
+
const spanStart = spans.length;
|
|
685
|
+
if (node.text !== undefined) {
|
|
686
|
+
text += node.text;
|
|
687
|
+
spans.push(Object.freeze({ path, start, end: text.length }));
|
|
688
|
+
} else {
|
|
689
|
+
for (const [index, child] of (node.children ?? []).entries()) {
|
|
690
|
+
visit(child, [...path, index]);
|
|
691
|
+
}
|
|
692
|
+
const custom = providers.get(node.type)?.text?.(node, text.slice(start));
|
|
693
|
+
if (custom !== undefined) {
|
|
694
|
+
text = text.slice(0, start) + custom;
|
|
695
|
+
spans.splice(spanStart);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (richBlockNodeTypes.has(node.type) && !text.slice(start).endsWith(`
|
|
699
|
+
`)) {
|
|
700
|
+
text += `
|
|
701
|
+
`;
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
visit(root, []);
|
|
705
|
+
return Object.freeze({ text, spans: Object.freeze(spans) });
|
|
706
|
+
}
|
|
707
|
+
function richPositionOffset(text, target) {
|
|
708
|
+
const lines = text.split(`
|
|
709
|
+
`);
|
|
710
|
+
const line = Math.min(Math.max(0, target.line), lines.length - 1);
|
|
711
|
+
const lineText = lines[line] ?? "";
|
|
712
|
+
const column = Math.min(Math.max(0, target.column), [...graphemeSegmenter2.segment(lineText)].length);
|
|
713
|
+
const lineStart = lines.slice(0, line).reduce((total, value2) => total + value2.length + 1, 0);
|
|
714
|
+
const value = [...graphemeSegmenter2.segment(lineText)].slice(0, column).map((segment) => segment.segment).join("");
|
|
715
|
+
return lineStart + value.length;
|
|
716
|
+
}
|
|
717
|
+
function richChangeOffsets(text, change) {
|
|
718
|
+
const anchor = richPositionOffset(text, change.range.anchor);
|
|
719
|
+
const head = richPositionOffset(text, change.range.head);
|
|
720
|
+
return anchor <= head ? [anchor, head] : [head, anchor];
|
|
721
|
+
}
|
|
722
|
+
function replaceRichNodeAtPath(node, path, replacement, depth = 0) {
|
|
723
|
+
if (depth === path.length)
|
|
724
|
+
return replacement;
|
|
725
|
+
const index = path[depth];
|
|
726
|
+
const children = [...node.children ?? []];
|
|
727
|
+
if (index === undefined || !children[index])
|
|
728
|
+
throw invalidRichPath(path);
|
|
729
|
+
children[index] = replaceRichNodeAtPath(children[index], path, replacement, depth + 1);
|
|
730
|
+
return freezeNode({ ...node, children });
|
|
731
|
+
}
|
|
732
|
+
function applyRichTextChange(root, projection, change) {
|
|
733
|
+
const [start, end] = richChangeOffsets(projection.text, change);
|
|
734
|
+
const touched = richTextSpansForRange(projection.spans, start, end);
|
|
735
|
+
if (touched.length === 0) {
|
|
736
|
+
return applyRichTextOutsideLeaf(root, projection, change, start, end);
|
|
737
|
+
}
|
|
738
|
+
assertRichTextRangeIsEditable(projection.text, touched, start, end);
|
|
739
|
+
return replaceRichTextSpans(root, touched, start, end, change.insert);
|
|
740
|
+
}
|
|
741
|
+
function richTextSpansForRange(spans, start, end) {
|
|
742
|
+
return spans.filter((span) => start === end && span.start <= start && span.end >= start || span.start < end && span.end > start);
|
|
743
|
+
}
|
|
744
|
+
function applyRichTextOutsideLeaf(root, projection, change, start, end) {
|
|
745
|
+
if (projection.spans.length === 0 && start === 0 && end === 0) {
|
|
746
|
+
return freezeNode({
|
|
747
|
+
...root,
|
|
748
|
+
children: [
|
|
749
|
+
...root.children ?? [],
|
|
750
|
+
{
|
|
751
|
+
type: "paragraph",
|
|
752
|
+
children: [{ type: "text", text: change.insert }]
|
|
753
|
+
}
|
|
754
|
+
]
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
throw new Error("Rich text edits require an editable text node");
|
|
758
|
+
}
|
|
759
|
+
function assertRichTextRangeIsEditable(text, touched, start, end) {
|
|
760
|
+
const first = touched[0];
|
|
761
|
+
const last = touched.at(-1);
|
|
762
|
+
if (!first || !last)
|
|
763
|
+
throw new Error("Rich text range is empty");
|
|
764
|
+
const editableStart = Math.max(start, first.start);
|
|
765
|
+
const editableEnd = Math.min(end, last.end);
|
|
766
|
+
const structuralText = text.slice(start, editableStart) + text.slice(editableEnd, end);
|
|
767
|
+
const spanGaps = touched.slice(0, -1).map((span, index) => text.slice(span.end, touched[index + 1]?.start ?? span.end)).join("");
|
|
768
|
+
if (structuralText || spanGaps) {
|
|
769
|
+
throw new Error("Rich text edits cannot replace structural separators; use a rich transaction");
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
function replaceRichTextSpans(root, touched, start, end, insert) {
|
|
773
|
+
let next = root;
|
|
774
|
+
for (const [index, span] of touched.entries()) {
|
|
775
|
+
const current = nodeAtRichPath(next, span.path);
|
|
776
|
+
const prefix = index === 0 ? (current.text ?? "").slice(0, Math.max(0, start - span.start)) : "";
|
|
777
|
+
const suffix = index === touched.length - 1 ? (current.text ?? "").slice(Math.max(0, end - span.start)) : "";
|
|
778
|
+
next = replaceRichNodeAtPath(next, span.path, {
|
|
779
|
+
...current,
|
|
780
|
+
text: `${prefix}${index === 0 ? insert : ""}${suffix}`
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
return next;
|
|
784
|
+
}
|
|
785
|
+
function nodeAtRichPath(root, path) {
|
|
786
|
+
let node = root;
|
|
787
|
+
for (const index of path) {
|
|
788
|
+
const child = node.children?.[index];
|
|
789
|
+
if (!child)
|
|
790
|
+
throw invalidRichPath(path);
|
|
791
|
+
node = child;
|
|
792
|
+
}
|
|
793
|
+
return node;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
class RichEditorSession {
|
|
797
|
+
rich;
|
|
798
|
+
#view;
|
|
799
|
+
#clipboard;
|
|
800
|
+
#providers;
|
|
801
|
+
#readOnly;
|
|
802
|
+
#history = [];
|
|
803
|
+
#redo = [];
|
|
804
|
+
#document;
|
|
805
|
+
constructor(options, richOptions = {}) {
|
|
806
|
+
this.#providers = richNodeProviderMap(richOptions.nodes);
|
|
807
|
+
const root = validateRichNode(parseRichDocument(options.value, this.#providers), this.#providers);
|
|
808
|
+
this.#document = Object.freeze({ version: 0, root: freezeNode(root) });
|
|
809
|
+
this.#readOnly = options.readOnly ?? false;
|
|
810
|
+
this.#view = new TextBufferSession({
|
|
811
|
+
...options,
|
|
812
|
+
readOnly: false,
|
|
813
|
+
documentType: options.documentType ?? "application/tuil-rich+json",
|
|
814
|
+
value: projectRichText(root, this.#providers).text
|
|
815
|
+
});
|
|
816
|
+
this.#clipboard = options.clipboard;
|
|
817
|
+
this.rich = Object.freeze({
|
|
818
|
+
snapshot: () => this.richSnapshot(),
|
|
819
|
+
dispatch: (transaction) => this.transact(transaction),
|
|
820
|
+
undo: () => this.undo(),
|
|
821
|
+
redo: () => this.redo(),
|
|
822
|
+
serialize: (format = "json") => this.serialize(format)
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
richSnapshot() {
|
|
826
|
+
return this.#document;
|
|
827
|
+
}
|
|
828
|
+
transact(transaction) {
|
|
829
|
+
this.#assertWritable();
|
|
830
|
+
const editor = new RichDocumentSession(this.#document.root, {
|
|
831
|
+
nodes: [...this.#providers.values()]
|
|
832
|
+
});
|
|
833
|
+
const next = editor.dispatch(transaction);
|
|
834
|
+
this.#recordHistory();
|
|
835
|
+
this.#setDocument(next.root);
|
|
836
|
+
return this.#document;
|
|
837
|
+
}
|
|
838
|
+
snapshot() {
|
|
839
|
+
const snapshot = this.#view.snapshot();
|
|
840
|
+
return Object.freeze({
|
|
841
|
+
...snapshot,
|
|
842
|
+
readOnly: this.#readOnly,
|
|
843
|
+
canUndo: this.#history.length > 0,
|
|
844
|
+
canRedo: this.#redo.length > 0
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
dispatch(transaction) {
|
|
848
|
+
const changes = [...transaction.changes ?? []];
|
|
849
|
+
if (changes.length > 0)
|
|
850
|
+
this.#assertWritable();
|
|
851
|
+
if (changes.length === 0) {
|
|
852
|
+
this.#view.dispatch({ ...transaction, addToHistory: false });
|
|
853
|
+
return this.snapshot();
|
|
854
|
+
}
|
|
855
|
+
const before = projectRichText(this.#document.root, this.#providers);
|
|
856
|
+
const trial = new TextBufferSession({ value: before.text });
|
|
857
|
+
const candidate = trial.dispatch(transaction);
|
|
858
|
+
trial.dispose();
|
|
859
|
+
let root = this.#document.root;
|
|
860
|
+
const sorted = changes.map((change) => ({
|
|
861
|
+
change,
|
|
862
|
+
offset: richChangeOffsets(before.text, change)[0]
|
|
863
|
+
})).sort((left, right) => right.offset - left.offset);
|
|
864
|
+
for (const { change } of sorted) {
|
|
865
|
+
const current = projectRichText(root, this.#providers);
|
|
866
|
+
root = applyRichTextChange(root, current, change);
|
|
867
|
+
}
|
|
868
|
+
const projected = projectRichText(root, this.#providers).text;
|
|
869
|
+
if (projected !== candidate.document.text) {
|
|
870
|
+
throw new Error("Rich text edit changed document structure");
|
|
871
|
+
}
|
|
872
|
+
if (transaction.addToHistory !== false)
|
|
873
|
+
this.#recordHistory();
|
|
874
|
+
this.#document = Object.freeze({
|
|
875
|
+
version: this.#document.version + 1,
|
|
876
|
+
root: freezeNode(root)
|
|
877
|
+
});
|
|
878
|
+
this.#replaceView(projected, candidate.selections);
|
|
879
|
+
return this.snapshot();
|
|
880
|
+
}
|
|
881
|
+
execute(command, argument) {
|
|
882
|
+
if (typeof command !== "string")
|
|
883
|
+
return command.execute(this, argument);
|
|
884
|
+
const clipboard = executeClipboardCommand(this, command, argument);
|
|
885
|
+
if (clipboard !== undefined)
|
|
886
|
+
return clipboard;
|
|
887
|
+
if (command === "delete-selection") {
|
|
888
|
+
this.dispatch({
|
|
889
|
+
changes: this.snapshot().selections.map((range) => ({
|
|
890
|
+
range,
|
|
891
|
+
insert: ""
|
|
892
|
+
}))
|
|
893
|
+
});
|
|
894
|
+
return true;
|
|
895
|
+
}
|
|
896
|
+
return this.#view.execute(command, argument);
|
|
897
|
+
}
|
|
898
|
+
undo() {
|
|
899
|
+
return this.#restoreHistory(this.#history, this.#redo);
|
|
900
|
+
}
|
|
901
|
+
redo() {
|
|
902
|
+
return this.#restoreHistory(this.#redo, this.#history);
|
|
903
|
+
}
|
|
904
|
+
search(query) {
|
|
905
|
+
return this.#view.search(query);
|
|
906
|
+
}
|
|
907
|
+
replace(query, replacement, all) {
|
|
908
|
+
const ranges = this.search(query);
|
|
909
|
+
const selected = all === false ? ranges.slice(0, 1) : ranges;
|
|
910
|
+
if (selected.length === 0)
|
|
911
|
+
return 0;
|
|
912
|
+
this.dispatch({
|
|
913
|
+
changes: selected.map((range) => ({ range, insert: replacement }))
|
|
914
|
+
});
|
|
915
|
+
return selected.length;
|
|
916
|
+
}
|
|
917
|
+
copy() {
|
|
918
|
+
return this.#view.copy();
|
|
919
|
+
}
|
|
920
|
+
cut() {
|
|
921
|
+
return cutSelections(this, this.copy());
|
|
922
|
+
}
|
|
923
|
+
paste(value) {
|
|
924
|
+
return pasteSelections(this, this.#clipboard, value);
|
|
925
|
+
}
|
|
926
|
+
serialize(format = "text") {
|
|
927
|
+
const snapshot = this.#document;
|
|
928
|
+
return format === "markdown" ? richDocumentToMarkdown(snapshot.root, this.#providers) : format === "json" ? JSON.stringify(snapshot) : this.#view.serialize("text");
|
|
929
|
+
}
|
|
930
|
+
subscribe(observer) {
|
|
931
|
+
return this.#view.subscribe(() => observer(this.snapshot()));
|
|
932
|
+
}
|
|
933
|
+
dispose() {
|
|
934
|
+
this.#view.dispose();
|
|
935
|
+
this.#history.length = 0;
|
|
936
|
+
this.#redo.length = 0;
|
|
937
|
+
}
|
|
938
|
+
#recordHistory() {
|
|
939
|
+
this.#history.push({
|
|
940
|
+
document: this.#document,
|
|
941
|
+
selections: this.#view.snapshot().selections
|
|
942
|
+
});
|
|
943
|
+
this.#redo.length = 0;
|
|
944
|
+
}
|
|
945
|
+
#assertWritable() {
|
|
946
|
+
if (this.#readOnly)
|
|
947
|
+
throw new Error("Editor session is read-only");
|
|
948
|
+
}
|
|
949
|
+
#restoreHistory(source, destination) {
|
|
950
|
+
const entry = source.pop();
|
|
951
|
+
if (!entry)
|
|
952
|
+
return false;
|
|
953
|
+
destination.push({
|
|
954
|
+
document: this.#document,
|
|
955
|
+
selections: this.#view.snapshot().selections
|
|
956
|
+
});
|
|
957
|
+
this.#document = entry.document;
|
|
958
|
+
this.#replaceView(projectRichText(this.#document.root, this.#providers).text, entry.selections);
|
|
959
|
+
return true;
|
|
960
|
+
}
|
|
961
|
+
#setDocument(root) {
|
|
962
|
+
this.#document = Object.freeze({
|
|
963
|
+
version: this.#document.version + 1,
|
|
964
|
+
root: freezeNode(root)
|
|
965
|
+
});
|
|
966
|
+
this.#replaceView(projectRichText(root, this.#providers).text);
|
|
967
|
+
}
|
|
968
|
+
#replaceView(value, selections = this.#view.snapshot().selections) {
|
|
969
|
+
const current = this.#view.serialize("text");
|
|
970
|
+
const lines = current.split(`
|
|
971
|
+
`);
|
|
972
|
+
this.#view.dispatch({
|
|
973
|
+
changes: [
|
|
974
|
+
{
|
|
975
|
+
range: {
|
|
976
|
+
anchor: { line: 0, column: 0 },
|
|
977
|
+
head: {
|
|
978
|
+
line: lines.length - 1,
|
|
979
|
+
column: lines.at(-1)?.length ?? 0
|
|
980
|
+
}
|
|
981
|
+
},
|
|
982
|
+
insert: value
|
|
983
|
+
}
|
|
984
|
+
],
|
|
985
|
+
selections,
|
|
986
|
+
addToHistory: false
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
function createRichEditorProvider(options = {}) {
|
|
991
|
+
const nodes = Object.freeze([...richNodeProviderMap(options.nodes).values()]);
|
|
992
|
+
return Object.freeze({
|
|
993
|
+
id: "tuil-rich-document",
|
|
994
|
+
version: "1",
|
|
995
|
+
capabilities: new Set([
|
|
996
|
+
"multiline",
|
|
997
|
+
"history",
|
|
998
|
+
"search",
|
|
999
|
+
"replace",
|
|
1000
|
+
"decorations",
|
|
1001
|
+
"diagnostics",
|
|
1002
|
+
"clipboard",
|
|
1003
|
+
"rich-document",
|
|
1004
|
+
"static"
|
|
1005
|
+
]),
|
|
1006
|
+
documentTypes: [
|
|
1007
|
+
"application/tuil-rich+json",
|
|
1008
|
+
"application/json",
|
|
1009
|
+
"text/markdown"
|
|
1010
|
+
],
|
|
1011
|
+
staticModes: ["static", "json", "silent"],
|
|
1012
|
+
create(editorOptions) {
|
|
1013
|
+
return new RichEditorSession(editorOptions, { nodes });
|
|
1014
|
+
}
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
var richEditorProvider = createRichEditorProvider();
|
|
1018
|
+
function applyMarkdownMark(value, mark) {
|
|
1019
|
+
if (!value)
|
|
1020
|
+
return value;
|
|
1021
|
+
const wrappers = {
|
|
1022
|
+
bold: ["**", "**"],
|
|
1023
|
+
italic: ["_", "_"],
|
|
1024
|
+
code: ["`", "`"],
|
|
1025
|
+
strike: ["~~", "~~"]
|
|
1026
|
+
};
|
|
1027
|
+
const wrapper = wrappers[mark.type];
|
|
1028
|
+
if (wrapper)
|
|
1029
|
+
return `${wrapper[0]}${value}${wrapper[1]}`;
|
|
1030
|
+
return mark.type === "link" ? `[${value}](${mark.attributes?.["href"] ?? ""})` : value;
|
|
1031
|
+
}
|
|
1032
|
+
function richDocumentToMarkdown(node, providers = new Map) {
|
|
1033
|
+
const children = (node.children ?? []).map((child) => richDocumentToMarkdown(child, providers)).join("");
|
|
1034
|
+
const formatters = {
|
|
1035
|
+
document: (_current, content) => content,
|
|
1036
|
+
paragraph: (_current, content) => `${content}
|
|
1037
|
+
|
|
1038
|
+
`,
|
|
1039
|
+
heading: (current, content) => `${"#".repeat(current.level ?? 1)} ${content}
|
|
1040
|
+
|
|
1041
|
+
`,
|
|
1042
|
+
text: (current) => (current.marks ?? []).reduce(applyMarkdownMark, current.text ?? ""),
|
|
1043
|
+
"list-item": (_current, content) => `- ${content.trim()}
|
|
1044
|
+
`,
|
|
1045
|
+
"code-block": (current, content) => `\`\`\`${current.attributes?.["language"] ?? ""}
|
|
1046
|
+
${current.text ?? content}
|
|
1047
|
+
\`\`\`
|
|
1048
|
+
|
|
1049
|
+
`,
|
|
1050
|
+
table: (_current, content) => `${content}
|
|
1051
|
+
`,
|
|
1052
|
+
"table-row": (_current, content) => `|${content}|
|
|
1053
|
+
`,
|
|
1054
|
+
"table-cell": (_current, content) => ` ${content.trim()} |`
|
|
1055
|
+
};
|
|
1056
|
+
const builtIn = formatters[node.type];
|
|
1057
|
+
if (builtIn)
|
|
1058
|
+
return builtIn(node, children);
|
|
1059
|
+
return providers.get(node.type)?.markdown?.(node, children) ?? children;
|
|
1060
|
+
}
|
|
1061
|
+
function projectRichDocument(node, width = 80) {
|
|
1062
|
+
if (!Number.isSafeInteger(width) || width < 1) {
|
|
1063
|
+
throw new TypeError("Rich document width must be a positive integer");
|
|
1064
|
+
}
|
|
1065
|
+
const lines = [];
|
|
1066
|
+
for (const source of richDocumentToMarkdown(node).split(`
|
|
1067
|
+
`)) {
|
|
1068
|
+
lines.push(...wrapTerminalText(source, width));
|
|
1069
|
+
}
|
|
1070
|
+
return Object.freeze(lines);
|
|
1071
|
+
}
|
|
1072
|
+
export {
|
|
1073
|
+
richEditorProvider,
|
|
1074
|
+
richDocumentToMarkdown,
|
|
1075
|
+
projectRichDocument,
|
|
1076
|
+
createRichEditorProvider,
|
|
1077
|
+
RichEditorSession,
|
|
1078
|
+
RichDocumentSession
|
|
1079
|
+
};
|
|
1080
|
+
|
|
1081
|
+
//# debugId=4FE75DD295C7BB5064756E2164756E21
|