@ngstarter-ui/components 22.0.6 → 22.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/ai/component-registry.json +249 -167
- package/fesm2022/ngstarter-ui-components-comment-editor.mjs +781 -749
- package/fesm2022/ngstarter-ui-components-comment-editor.mjs.map +1 -1
- package/fesm2022/ngstarter-ui-components-headless-editor.mjs +3689 -0
- package/fesm2022/ngstarter-ui-components-headless-editor.mjs.map +1 -0
- package/package.json +5 -19
- package/styles/_tokens.scss +17 -2
- package/styles/themes/chalk.scss +1 -0
- package/types/ngstarter-ui-components-comment-editor.d.ts +150 -99
- package/types/ngstarter-ui-components-headless-editor.d.ts +795 -0
- package/fesm2022/ngstarter-ui-components-text-editor.mjs +0 -1038
- package/fesm2022/ngstarter-ui-components-text-editor.mjs.map +0 -1
- package/types/ngstarter-ui-components-text-editor.d.ts +0 -192
|
@@ -0,0 +1,3689 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { signal, computed, Injectable, InjectionToken, inject, DestroyRef, ElementRef, DOCUMENT, Renderer2, NgZone, Injector, EnvironmentInjector, ApplicationRef, input, booleanAttribute, effect, untracked, afterNextRender, createComponent, Directive, reflectComponentType, viewChild, ChangeDetectionStrategy, Component, ViewContainerRef, output } from '@angular/core';
|
|
3
|
+
import { NgTemplateOutlet, NgComponentOutlet } from '@angular/common';
|
|
4
|
+
import { Overlay } from '@angular/cdk/overlay';
|
|
5
|
+
import { TemplatePortal } from '@angular/cdk/portal';
|
|
6
|
+
import { Menu, MenuItem } from '@ngstarter-ui/components/menu';
|
|
7
|
+
|
|
8
|
+
let nextEditorId = 0;
|
|
9
|
+
function createNgsHeadlessEditorId(prefix = 'block') {
|
|
10
|
+
const randomUuid = globalThis.crypto?.randomUUID?.();
|
|
11
|
+
if (randomUuid) {
|
|
12
|
+
return `${prefix}-${randomUuid}`;
|
|
13
|
+
}
|
|
14
|
+
nextEditorId += 1;
|
|
15
|
+
return `${prefix}-${Date.now().toString(36)}-${nextEditorId.toString(36)}`;
|
|
16
|
+
}
|
|
17
|
+
function createNgsHeadlessEditorText(text = '', marks = []) {
|
|
18
|
+
return {
|
|
19
|
+
type: 'text',
|
|
20
|
+
text,
|
|
21
|
+
marks: normalizeNgsHeadlessEditorMarks(marks)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function createNgsHeadlessEditorParagraph(text = '', marks = []) {
|
|
25
|
+
return {
|
|
26
|
+
id: createNgsHeadlessEditorId('paragraph'),
|
|
27
|
+
type: 'paragraph',
|
|
28
|
+
content: [createNgsHeadlessEditorText(text, marks)]
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function createNgsHeadlessEditorDocument(text = '') {
|
|
32
|
+
return normalizeNgsHeadlessEditorDocument({
|
|
33
|
+
version: 1,
|
|
34
|
+
blocks: [createNgsHeadlessEditorParagraph(text)]
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function cloneNgsHeadlessEditorDocument(document) {
|
|
38
|
+
return {
|
|
39
|
+
version: 1,
|
|
40
|
+
blocks: document.blocks.map(block => ({
|
|
41
|
+
...block,
|
|
42
|
+
attrs: block.attrs ? { ...block.attrs } : undefined,
|
|
43
|
+
content: isNgsHeadlessEditorTextContent(block.content)
|
|
44
|
+
? block.content.map(run => ({
|
|
45
|
+
type: 'text',
|
|
46
|
+
text: run.text,
|
|
47
|
+
marks: run.marks.map(mark => ({
|
|
48
|
+
type: mark.type,
|
|
49
|
+
attrs: mark.attrs ? { ...mark.attrs } : undefined
|
|
50
|
+
}))
|
|
51
|
+
}))
|
|
52
|
+
: block.content
|
|
53
|
+
}))
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Normalizes a document. The model is immutable, so unchanged blocks keep their
|
|
58
|
+
* object identity; the surface relies on it to re-render only changed blocks.
|
|
59
|
+
* When nothing needs fixing the input document itself is returned.
|
|
60
|
+
*/
|
|
61
|
+
function normalizeNgsHeadlessEditorDocument(document) {
|
|
62
|
+
const usedIds = new Set();
|
|
63
|
+
let changed = document.version !== 1;
|
|
64
|
+
const blocks = document.blocks.map(block => {
|
|
65
|
+
let id = block.id || createNgsHeadlessEditorId(block.type || 'block');
|
|
66
|
+
while (usedIds.has(id)) {
|
|
67
|
+
id = createNgsHeadlessEditorId(block.type || 'block');
|
|
68
|
+
}
|
|
69
|
+
usedIds.add(id);
|
|
70
|
+
const content = isNgsHeadlessEditorTextContent(block.content)
|
|
71
|
+
? normalizeNgsHeadlessEditorTextContent(block.content)
|
|
72
|
+
: block.content;
|
|
73
|
+
if (id === block.id && content === block.content) {
|
|
74
|
+
return block;
|
|
75
|
+
}
|
|
76
|
+
changed = true;
|
|
77
|
+
return { ...block, id, content };
|
|
78
|
+
});
|
|
79
|
+
if (blocks.length === 0) {
|
|
80
|
+
return { version: 1, blocks: [createNgsHeadlessEditorParagraph()] };
|
|
81
|
+
}
|
|
82
|
+
return changed ? { version: 1, blocks } : document;
|
|
83
|
+
}
|
|
84
|
+
function normalizeNgsHeadlessEditorTextContent(content) {
|
|
85
|
+
if (isNormalizedTextContent(content)) {
|
|
86
|
+
return content;
|
|
87
|
+
}
|
|
88
|
+
const normalized = [];
|
|
89
|
+
for (const run of content) {
|
|
90
|
+
if (run.type !== 'text' || run.text.length === 0) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const next = createNgsHeadlessEditorText(run.text, run.marks);
|
|
94
|
+
const previous = normalized.at(-1);
|
|
95
|
+
if (previous && ngsHeadlessEditorMarksEqual(previous.marks, next.marks)) {
|
|
96
|
+
normalized[normalized.length - 1] = {
|
|
97
|
+
...previous,
|
|
98
|
+
text: previous.text + next.text
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
normalized.push(next);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return normalized.length > 0 ? normalized : [createNgsHeadlessEditorText()];
|
|
106
|
+
}
|
|
107
|
+
function normalizeNgsHeadlessEditorMarks(marks) {
|
|
108
|
+
if (isNormalizedMarks(marks)) {
|
|
109
|
+
return marks;
|
|
110
|
+
}
|
|
111
|
+
const byType = new Map();
|
|
112
|
+
for (const mark of marks) {
|
|
113
|
+
if (mark.type) {
|
|
114
|
+
byType.set(mark.type, {
|
|
115
|
+
type: mark.type,
|
|
116
|
+
attrs: mark.attrs ? { ...mark.attrs } : undefined
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return [...byType.values()].sort((a, b) => a.type.localeCompare(b.type));
|
|
121
|
+
}
|
|
122
|
+
function ngsHeadlessEditorMarksEqual(left, right) {
|
|
123
|
+
if (left === right) {
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
const normalizedLeft = normalizeNgsHeadlessEditorMarks(left);
|
|
127
|
+
const normalizedRight = normalizeNgsHeadlessEditorMarks(right);
|
|
128
|
+
return normalizedLeft.length === normalizedRight.length &&
|
|
129
|
+
normalizedLeft.every((mark, index) => (mark.type === normalizedRight[index].type &&
|
|
130
|
+
ngsHeadlessEditorValuesEqual(mark.attrs, normalizedRight[index].attrs)));
|
|
131
|
+
}
|
|
132
|
+
/** Structural equality of two blocks (id, type, attrs and content). */
|
|
133
|
+
function ngsHeadlessEditorBlocksEqual(left, right) {
|
|
134
|
+
if (left === right) {
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
if (left.id !== right.id ||
|
|
138
|
+
left.type !== right.type ||
|
|
139
|
+
!ngsHeadlessEditorValuesEqual(left.attrs, right.attrs)) {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
if (isNgsHeadlessEditorTextContent(left.content) && isNgsHeadlessEditorTextContent(right.content)) {
|
|
143
|
+
const rightContent = right.content;
|
|
144
|
+
return left.content.length === rightContent.length &&
|
|
145
|
+
left.content.every((run, index) => (run.text === rightContent[index].text &&
|
|
146
|
+
ngsHeadlessEditorMarksEqual(run.marks, rightContent[index].marks)));
|
|
147
|
+
}
|
|
148
|
+
return ngsHeadlessEditorValuesEqual(left.content, right.content);
|
|
149
|
+
}
|
|
150
|
+
/** Structural document equality; short-circuits on shared (unchanged) blocks. */
|
|
151
|
+
function ngsHeadlessEditorDocumentsEqual(left, right) {
|
|
152
|
+
if (left === right) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
return left.version === right.version &&
|
|
156
|
+
left.blocks.length === right.blocks.length &&
|
|
157
|
+
left.blocks.every((block, index) => ngsHeadlessEditorBlocksEqual(block, right.blocks[index]));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Deep equality for JSON-like values. Object key order is ignored and keys with
|
|
161
|
+
* `undefined` values are treated as absent, matching JSON serialization.
|
|
162
|
+
*/
|
|
163
|
+
function ngsHeadlessEditorValuesEqual(left, right) {
|
|
164
|
+
if (Object.is(left, right)) {
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
171
|
+
return Array.isArray(left) && Array.isArray(right) &&
|
|
172
|
+
left.length === right.length &&
|
|
173
|
+
left.every((value, index) => ngsHeadlessEditorValuesEqual(value, right[index]));
|
|
174
|
+
}
|
|
175
|
+
const leftRecord = left;
|
|
176
|
+
const rightRecord = right;
|
|
177
|
+
const leftKeys = Object.keys(leftRecord).filter(key => leftRecord[key] !== undefined);
|
|
178
|
+
const rightKeys = Object.keys(rightRecord).filter(key => rightRecord[key] !== undefined);
|
|
179
|
+
return leftKeys.length === rightKeys.length &&
|
|
180
|
+
leftKeys.every(key => ngsHeadlessEditorValuesEqual(leftRecord[key], rightRecord[key]));
|
|
181
|
+
}
|
|
182
|
+
function isNormalizedMarks(marks) {
|
|
183
|
+
for (let index = 0; index < marks.length; index += 1) {
|
|
184
|
+
if (!marks[index].type) {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
if (index > 0 && marks[index - 1].type.localeCompare(marks[index].type) >= 0) {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
function isNormalizedTextContent(content) {
|
|
194
|
+
if (content.length === 0) {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
if (content.length === 1 && content[0].type === 'text' && content[0].text.length === 0) {
|
|
198
|
+
return content[0].marks.length === 0;
|
|
199
|
+
}
|
|
200
|
+
for (let index = 0; index < content.length; index += 1) {
|
|
201
|
+
const run = content[index];
|
|
202
|
+
if (run.type !== 'text' || run.text.length === 0 || !isNormalizedMarks(run.marks)) {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
if (index > 0 && ngsHeadlessEditorMarksEqual(content[index - 1].marks, run.marks)) {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
function isNgsHeadlessEditorTextContent(content) {
|
|
212
|
+
return Array.isArray(content) && content.every(run => (typeof run === 'object' && run !== null && run.type === 'text'));
|
|
213
|
+
}
|
|
214
|
+
function getNgsHeadlessEditorBlockText(block) {
|
|
215
|
+
return isNgsHeadlessEditorTextContent(block.content)
|
|
216
|
+
? block.content.map(run => run.text).join('')
|
|
217
|
+
: '';
|
|
218
|
+
}
|
|
219
|
+
function getNgsHeadlessEditorDocumentText(document) {
|
|
220
|
+
return document.blocks.map(getNgsHeadlessEditorBlockText).join('\n');
|
|
221
|
+
}
|
|
222
|
+
function isNgsHeadlessEditorDocumentEmpty(document) {
|
|
223
|
+
return getNgsHeadlessEditorDocumentText(document).trim().length === 0;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function defineNgsHeadlessEditorPlugin(plugin) {
|
|
227
|
+
return plugin;
|
|
228
|
+
}
|
|
229
|
+
function withHeadlessEditorPlugin(plugin) {
|
|
230
|
+
return { plugin };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Maximum number of undo steps kept in memory. */
|
|
234
|
+
const NGS_HEADLESS_EDITOR_HISTORY_LIMIT = 200;
|
|
235
|
+
/** Consecutive changes of the same group within this window form one undo step. */
|
|
236
|
+
const NGS_HEADLESS_EDITOR_HISTORY_GROUP_DELAY = 1000;
|
|
237
|
+
class NgsHeadlessEditorHistory {
|
|
238
|
+
_past = signal([], /* @ts-ignore */
|
|
239
|
+
...(ngDevMode ? [{ debugName: "_past" }] : /* istanbul ignore next */ []));
|
|
240
|
+
_future = signal([], /* @ts-ignore */
|
|
241
|
+
...(ngDevMode ? [{ debugName: "_future" }] : /* istanbul ignore next */ []));
|
|
242
|
+
lastGroup = null;
|
|
243
|
+
lastRecordedAt = 0;
|
|
244
|
+
canUndo = computed(() => this._past().length > 0, /* @ts-ignore */
|
|
245
|
+
...(ngDevMode ? [{ debugName: "canUndo" }] : /* istanbul ignore next */ []));
|
|
246
|
+
canRedo = computed(() => this._future().length > 0, /* @ts-ignore */
|
|
247
|
+
...(ngDevMode ? [{ debugName: "canRedo" }] : /* istanbul ignore next */ []));
|
|
248
|
+
/**
|
|
249
|
+
* Records the state before a change. Changes that share a non-null `group`
|
|
250
|
+
* (for example consecutive typed characters) and follow each other quickly
|
|
251
|
+
* are merged into a single undo step.
|
|
252
|
+
*/
|
|
253
|
+
record(snapshot, group = null, now = Date.now()) {
|
|
254
|
+
const merge = group !== null &&
|
|
255
|
+
group === this.lastGroup &&
|
|
256
|
+
now - this.lastRecordedAt < NGS_HEADLESS_EDITOR_HISTORY_GROUP_DELAY &&
|
|
257
|
+
this._past().length > 0;
|
|
258
|
+
this.lastGroup = group;
|
|
259
|
+
this.lastRecordedAt = now;
|
|
260
|
+
this._future.set([]);
|
|
261
|
+
if (merge) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this._past.update(past => {
|
|
265
|
+
const next = [...past, snapshot];
|
|
266
|
+
return next.length > NGS_HEADLESS_EDITOR_HISTORY_LIMIT
|
|
267
|
+
? next.slice(next.length - NGS_HEADLESS_EDITOR_HISTORY_LIMIT)
|
|
268
|
+
: next;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/** Starts a new undo step for the next recorded change. */
|
|
272
|
+
breakGroup() {
|
|
273
|
+
this.lastGroup = null;
|
|
274
|
+
}
|
|
275
|
+
undo(current) {
|
|
276
|
+
const past = this._past();
|
|
277
|
+
const previous = past.at(-1);
|
|
278
|
+
if (!previous) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
this.breakGroup();
|
|
282
|
+
this._past.set(past.slice(0, -1));
|
|
283
|
+
this._future.update(future => [...future, current]);
|
|
284
|
+
return previous;
|
|
285
|
+
}
|
|
286
|
+
redo(current) {
|
|
287
|
+
const future = this._future();
|
|
288
|
+
const next = future.at(-1);
|
|
289
|
+
if (!next) {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
this.breakGroup();
|
|
293
|
+
this._future.set(future.slice(0, -1));
|
|
294
|
+
this._past.update(past => [...past, current]);
|
|
295
|
+
return next;
|
|
296
|
+
}
|
|
297
|
+
clear() {
|
|
298
|
+
this.breakGroup();
|
|
299
|
+
this._past.set([]);
|
|
300
|
+
this._future.set([]);
|
|
301
|
+
}
|
|
302
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorHistory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
303
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorHistory });
|
|
304
|
+
}
|
|
305
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorHistory, decorators: [{
|
|
306
|
+
type: Injectable
|
|
307
|
+
}] });
|
|
308
|
+
|
|
309
|
+
const NGS_HEADLESS_EDITOR_PLUGINS = new InjectionToken('NGS_HEADLESS_EDITOR_PLUGINS');
|
|
310
|
+
function provideNgsHeadlessEditor(...features) {
|
|
311
|
+
const plugins = features.map(feature => feature.plugin);
|
|
312
|
+
return [
|
|
313
|
+
NgsHeadlessEditorHistory,
|
|
314
|
+
NgsHeadlessEditor,
|
|
315
|
+
...plugins.flatMap(plugin => plugin.providers ?? []),
|
|
316
|
+
{
|
|
317
|
+
provide: NGS_HEADLESS_EDITOR_PLUGINS,
|
|
318
|
+
useValue: plugins
|
|
319
|
+
}
|
|
320
|
+
];
|
|
321
|
+
}
|
|
322
|
+
class NgsHeadlessEditor {
|
|
323
|
+
history = inject(NgsHeadlessEditorHistory);
|
|
324
|
+
destroyRef = inject(DestroyRef);
|
|
325
|
+
injectedPlugins = inject(NGS_HEADLESS_EDITOR_PLUGINS, { optional: true }) ?? [];
|
|
326
|
+
_document = signal(createNgsHeadlessEditorDocument(), /* @ts-ignore */
|
|
327
|
+
...(ngDevMode ? [{ debugName: "_document" }] : /* istanbul ignore next */ []));
|
|
328
|
+
_selection = signal(null, /* @ts-ignore */
|
|
329
|
+
...(ngDevMode ? [{ debugName: "_selection" }] : /* istanbul ignore next */ []));
|
|
330
|
+
/** Marks for the next insertion at a collapsed caret; `null` means "inherit from the text". */
|
|
331
|
+
_storedMarks = signal(null, /* @ts-ignore */
|
|
332
|
+
...(ngDevMode ? [{ debugName: "_storedMarks" }] : /* istanbul ignore next */ []));
|
|
333
|
+
_focused = signal(false, /* @ts-ignore */
|
|
334
|
+
...(ngDevMode ? [{ debugName: "_focused" }] : /* istanbul ignore next */ []));
|
|
335
|
+
_composing = signal(false, /* @ts-ignore */
|
|
336
|
+
...(ngDevMode ? [{ debugName: "_composing" }] : /* istanbul ignore next */ []));
|
|
337
|
+
_readOnly = signal(false, /* @ts-ignore */
|
|
338
|
+
...(ngDevMode ? [{ debugName: "_readOnly" }] : /* istanbul ignore next */ []));
|
|
339
|
+
_revision = signal(0, /* @ts-ignore */
|
|
340
|
+
...(ngDevMode ? [{ debugName: "_revision" }] : /* istanbul ignore next */ []));
|
|
341
|
+
_origin = signal('external', /* @ts-ignore */
|
|
342
|
+
...(ngDevMode ? [{ debugName: "_origin" }] : /* istanbul ignore next */ []));
|
|
343
|
+
_plugins = signal([], /* @ts-ignore */
|
|
344
|
+
...(ngDevMode ? [{ debugName: "_plugins" }] : /* istanbul ignore next */ []));
|
|
345
|
+
_inlineTarget = signal(null, /* @ts-ignore */
|
|
346
|
+
...(ngDevMode ? [{ debugName: "_inlineTarget" }] : /* istanbul ignore next */ []));
|
|
347
|
+
commands = new Map();
|
|
348
|
+
marks = new Map();
|
|
349
|
+
blocks = new Map();
|
|
350
|
+
keymap = [];
|
|
351
|
+
pluginCleanups = [];
|
|
352
|
+
document = this._document.asReadonly();
|
|
353
|
+
/**
|
|
354
|
+
* Nested editor that currently receives formatting, for example the editor of
|
|
355
|
+
* the focused table cell. See setInlineTarget().
|
|
356
|
+
*/
|
|
357
|
+
inlineTarget = this._inlineTarget.asReadonly();
|
|
358
|
+
/** Selection of the inline target while one is active, otherwise of this editor. */
|
|
359
|
+
selection = computed(() => {
|
|
360
|
+
const target = this._inlineTarget();
|
|
361
|
+
return target ? target.selection() : this._selection();
|
|
362
|
+
}, /* @ts-ignore */
|
|
363
|
+
...(ngDevMode ? [{ debugName: "selection" }] : /* istanbul ignore next */ []));
|
|
364
|
+
storedMarks = computed(() => {
|
|
365
|
+
const target = this._inlineTarget();
|
|
366
|
+
return target ? target.storedMarks() : this._storedMarks() ?? [];
|
|
367
|
+
}, /* @ts-ignore */
|
|
368
|
+
...(ngDevMode ? [{ debugName: "storedMarks" }] : /* istanbul ignore next */ []));
|
|
369
|
+
focused = this._focused.asReadonly();
|
|
370
|
+
composing = this._composing.asReadonly();
|
|
371
|
+
readOnly = this._readOnly.asReadonly();
|
|
372
|
+
revision = this._revision.asReadonly();
|
|
373
|
+
origin = this._origin.asReadonly();
|
|
374
|
+
plugins = this._plugins.asReadonly();
|
|
375
|
+
empty = computed(() => {
|
|
376
|
+
this._plugins();
|
|
377
|
+
return this._document().blocks.every(block => {
|
|
378
|
+
const definition = this.blocks.get(block.type);
|
|
379
|
+
return definition?.isEmpty
|
|
380
|
+
? definition.isEmpty(block)
|
|
381
|
+
: getNgsHeadlessEditorBlockText(block).trim().length === 0;
|
|
382
|
+
});
|
|
383
|
+
}, /* @ts-ignore */
|
|
384
|
+
...(ngDevMode ? [{ debugName: "empty" }] : /* istanbul ignore next */ []));
|
|
385
|
+
canUndo = this.history.canUndo;
|
|
386
|
+
canRedo = this.history.canRedo;
|
|
387
|
+
constructor() {
|
|
388
|
+
this.setPlugins(this.injectedPlugins);
|
|
389
|
+
this.destroyRef.onDestroy(() => this.destroyPlugins());
|
|
390
|
+
}
|
|
391
|
+
setPlugins(plugins) {
|
|
392
|
+
if (samePluginSet(this._plugins(), plugins)) {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const pluginIds = new Set();
|
|
396
|
+
const commands = new Map();
|
|
397
|
+
const marks = new Map();
|
|
398
|
+
const blocks = new Map();
|
|
399
|
+
const keymap = [];
|
|
400
|
+
for (const plugin of plugins) {
|
|
401
|
+
assertUnique(pluginIds, plugin.id, 'plugin');
|
|
402
|
+
for (const command of plugin.commands ?? []) {
|
|
403
|
+
assertUnique(commands, command.id, 'command');
|
|
404
|
+
commands.set(command.id, command);
|
|
405
|
+
}
|
|
406
|
+
for (const mark of plugin.marks ?? []) {
|
|
407
|
+
assertUnique(marks, mark.type, 'mark');
|
|
408
|
+
marks.set(mark.type, mark);
|
|
409
|
+
}
|
|
410
|
+
for (const block of plugin.blocks ?? []) {
|
|
411
|
+
assertUnique(blocks, block.type, 'block');
|
|
412
|
+
blocks.set(block.type, block);
|
|
413
|
+
}
|
|
414
|
+
keymap.push(...(plugin.keymap ?? []));
|
|
415
|
+
}
|
|
416
|
+
this.destroyPlugins();
|
|
417
|
+
this.commands.clear();
|
|
418
|
+
this.marks.clear();
|
|
419
|
+
this.blocks.clear();
|
|
420
|
+
commands.forEach((command, id) => this.commands.set(id, command));
|
|
421
|
+
marks.forEach((mark, type) => this.marks.set(type, mark));
|
|
422
|
+
blocks.forEach((block, type) => this.blocks.set(type, block));
|
|
423
|
+
this.keymap = keymap;
|
|
424
|
+
this._plugins.set([...plugins]);
|
|
425
|
+
for (const plugin of plugins) {
|
|
426
|
+
const cleanup = plugin.setup?.(this);
|
|
427
|
+
if (cleanup) {
|
|
428
|
+
this.pluginCleanups.push(cleanup);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
getMarkDefinition(type) {
|
|
433
|
+
return this.marks.get(type);
|
|
434
|
+
}
|
|
435
|
+
getMarkDefinitions() {
|
|
436
|
+
return [...this.marks.values()];
|
|
437
|
+
}
|
|
438
|
+
getBlockDefinition(type) {
|
|
439
|
+
return this.blocks.get(type);
|
|
440
|
+
}
|
|
441
|
+
getBlockDefinitions() {
|
|
442
|
+
return [...this.blocks.values()];
|
|
443
|
+
}
|
|
444
|
+
setDocument(document, resetHistory = true) {
|
|
445
|
+
// Copy once at the boundary: the caller may keep mutating its object, while
|
|
446
|
+
// everything inside the editor treats documents as immutable.
|
|
447
|
+
const normalized = normalizeNgsHeadlessEditorDocument(cloneNgsHeadlessEditorDocument(document));
|
|
448
|
+
if (ngsHeadlessEditorDocumentsEqual(this._document(), normalized)) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
this._document.set(normalized);
|
|
452
|
+
this._selection.set(firstSelection(normalized));
|
|
453
|
+
this._storedMarks.set(null);
|
|
454
|
+
this._origin.set('external');
|
|
455
|
+
this._revision.update(revision => revision + 1);
|
|
456
|
+
if (resetHistory) {
|
|
457
|
+
this.history.clear();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
setReadOnly(readOnly) {
|
|
461
|
+
this._readOnly.set(readOnly);
|
|
462
|
+
}
|
|
463
|
+
setFocused(focused) {
|
|
464
|
+
this._focused.set(focused);
|
|
465
|
+
}
|
|
466
|
+
setComposing(composing) {
|
|
467
|
+
this._composing.set(composing);
|
|
468
|
+
}
|
|
469
|
+
setSelection(selection) {
|
|
470
|
+
const next = selection ? clampSelection(this._document(), selection, this.marks) : null;
|
|
471
|
+
if (!selectionsEqual(this._selection(), next)) {
|
|
472
|
+
// Moving the caret discards pending marks and starts a new undo step.
|
|
473
|
+
this._storedMarks.set(null);
|
|
474
|
+
this.history.breakGroup();
|
|
475
|
+
}
|
|
476
|
+
this._selection.set(next);
|
|
477
|
+
}
|
|
478
|
+
execute(command, payload) {
|
|
479
|
+
const resolved = typeof command === 'string'
|
|
480
|
+
? this.commands.get(command)
|
|
481
|
+
: command;
|
|
482
|
+
if (!resolved || this._readOnly() || resolved.enabled?.(this, payload) === false) {
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
return resolved.execute(this, payload);
|
|
486
|
+
}
|
|
487
|
+
isCommandEnabled(command, payload) {
|
|
488
|
+
return !this._readOnly() && (command.enabled?.(this, payload) ?? true);
|
|
489
|
+
}
|
|
490
|
+
isCommandActive(command, payload) {
|
|
491
|
+
return command.active?.(this, payload) ?? false;
|
|
492
|
+
}
|
|
493
|
+
handleKeydown(event) {
|
|
494
|
+
const candidates = eventToKeyBindings(event);
|
|
495
|
+
for (const candidate of candidates) {
|
|
496
|
+
const binding = this.keymap.find(item => item.key.toLowerCase() === candidate);
|
|
497
|
+
if (binding) {
|
|
498
|
+
return this.execute(binding.command, binding.payload);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
// Edits are applied to the model, so the browser has no native undo stack
|
|
502
|
+
// and never emits historyUndo/historyRedo for these shortcuts.
|
|
503
|
+
if (candidates.includes('mod-z')) {
|
|
504
|
+
return !this._readOnly() && this.undo();
|
|
505
|
+
}
|
|
506
|
+
if (candidates.includes('mod-shift-z') || candidates.includes('mod-y')) {
|
|
507
|
+
return !this._readOnly() && this.redo();
|
|
508
|
+
}
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
handlePaste(event) {
|
|
512
|
+
for (const plugin of this._plugins()) {
|
|
513
|
+
if (plugin.handlePaste?.(event, this)) {
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return false;
|
|
518
|
+
}
|
|
519
|
+
insertText(text, origin = 'keyboard') {
|
|
520
|
+
const target = this._inlineTarget();
|
|
521
|
+
if (target) {
|
|
522
|
+
return target.insertText(text, origin);
|
|
523
|
+
}
|
|
524
|
+
if (this._readOnly() || text.length === 0) {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
const initialSelection = this.ensureSelection();
|
|
528
|
+
const base = deleteSelectedRange(this._document(), initialSelection);
|
|
529
|
+
const selection = base.selection;
|
|
530
|
+
const point = selection.focus;
|
|
531
|
+
const blockIndex = base.document.blocks.findIndex(block => block.id === point.blockId);
|
|
532
|
+
if (blockIndex < 0) {
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
const block = base.document.blocks[blockIndex];
|
|
536
|
+
if (!isNgsHeadlessEditorTextContent(block.content)) {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
|
540
|
+
const marks = (this._storedMarks() ?? marksAtOffset(block.content, point.offset))
|
|
541
|
+
.filter(mark => !this.marks.get(mark.type)?.atomic);
|
|
542
|
+
const before = sliceTextContent(block.content, 0, point.offset);
|
|
543
|
+
const after = sliceTextContent(block.content, point.offset, textContentLength(block.content));
|
|
544
|
+
const blocks = [...base.document.blocks];
|
|
545
|
+
if (lines.length === 1) {
|
|
546
|
+
blocks[blockIndex] = {
|
|
547
|
+
...block,
|
|
548
|
+
content: normalizeNgsHeadlessEditorTextContent([
|
|
549
|
+
...before,
|
|
550
|
+
createNgsHeadlessEditorText(lines[0], marks),
|
|
551
|
+
...after
|
|
552
|
+
])
|
|
553
|
+
};
|
|
554
|
+
const offset = point.offset + lines[0].length;
|
|
555
|
+
const group = origin === 'keyboard' &&
|
|
556
|
+
isCollapsed(initialSelection) &&
|
|
557
|
+
graphemeCount(lines[0]) === 1 &&
|
|
558
|
+
!/\s/.test(lines[0])
|
|
559
|
+
? 'insert-text'
|
|
560
|
+
: null;
|
|
561
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(block.id, offset), origin, group);
|
|
562
|
+
}
|
|
563
|
+
const insertedBlocks = lines.map((line, index) => {
|
|
564
|
+
if (index === 0) {
|
|
565
|
+
return {
|
|
566
|
+
...block,
|
|
567
|
+
content: normalizeNgsHeadlessEditorTextContent([...before, createNgsHeadlessEditorText(line, marks)])
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
if (index === lines.length - 1) {
|
|
571
|
+
return {
|
|
572
|
+
...createNgsHeadlessEditorParagraph(),
|
|
573
|
+
content: normalizeNgsHeadlessEditorTextContent([createNgsHeadlessEditorText(line, marks), ...after])
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
return createNgsHeadlessEditorParagraph(line, marks);
|
|
577
|
+
});
|
|
578
|
+
blocks.splice(blockIndex, 1, ...insertedBlocks);
|
|
579
|
+
const last = insertedBlocks[insertedBlocks.length - 1];
|
|
580
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(last.id, lines.at(-1)?.length ?? 0), origin);
|
|
581
|
+
}
|
|
582
|
+
deleteBackward() {
|
|
583
|
+
if (this._readOnly()) {
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
const selection = this.ensureSelection();
|
|
587
|
+
if (!isCollapsed(selection)) {
|
|
588
|
+
return this.deleteRange(selection, 'keyboard');
|
|
589
|
+
}
|
|
590
|
+
const point = selection.focus;
|
|
591
|
+
const blockIndex = this._document().blocks.findIndex(block => block.id === point.blockId);
|
|
592
|
+
const block = this._document().blocks[blockIndex];
|
|
593
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content)) {
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
if (point.offset > 0) {
|
|
597
|
+
const start = previousGraphemeBoundary(getNgsHeadlessEditorBlockText(block), point.offset);
|
|
598
|
+
return this.deleteRange({
|
|
599
|
+
anchor: { blockId: block.id, offset: start },
|
|
600
|
+
focus: point
|
|
601
|
+
}, 'keyboard', 'delete-backward');
|
|
602
|
+
}
|
|
603
|
+
if (blockIndex === 0) {
|
|
604
|
+
return false;
|
|
605
|
+
}
|
|
606
|
+
const previous = this._document().blocks[blockIndex - 1];
|
|
607
|
+
if (!isNgsHeadlessEditorTextContent(previous.content)) {
|
|
608
|
+
const blocks = [...this._document().blocks];
|
|
609
|
+
blocks.splice(blockIndex - 1, 1);
|
|
610
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(block.id, 0), 'keyboard');
|
|
611
|
+
}
|
|
612
|
+
const previousLength = textContentLength(previous.content);
|
|
613
|
+
const blocks = [...this._document().blocks];
|
|
614
|
+
blocks.splice(blockIndex - 1, 2, {
|
|
615
|
+
...previous,
|
|
616
|
+
content: normalizeNgsHeadlessEditorTextContent([...previous.content, ...block.content])
|
|
617
|
+
});
|
|
618
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(previous.id, previousLength), 'keyboard');
|
|
619
|
+
}
|
|
620
|
+
deleteForward() {
|
|
621
|
+
if (this._readOnly()) {
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
const selection = this.ensureSelection();
|
|
625
|
+
if (!isCollapsed(selection)) {
|
|
626
|
+
return this.deleteRange(selection, 'keyboard');
|
|
627
|
+
}
|
|
628
|
+
const point = selection.focus;
|
|
629
|
+
const blockIndex = this._document().blocks.findIndex(block => block.id === point.blockId);
|
|
630
|
+
const block = this._document().blocks[blockIndex];
|
|
631
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content)) {
|
|
632
|
+
return false;
|
|
633
|
+
}
|
|
634
|
+
const text = getNgsHeadlessEditorBlockText(block);
|
|
635
|
+
if (point.offset < text.length) {
|
|
636
|
+
return this.deleteRange({
|
|
637
|
+
anchor: point,
|
|
638
|
+
focus: { blockId: block.id, offset: nextGraphemeBoundary(text, point.offset) }
|
|
639
|
+
}, 'keyboard', 'delete-forward');
|
|
640
|
+
}
|
|
641
|
+
const next = this._document().blocks[blockIndex + 1];
|
|
642
|
+
if (!next) {
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
if (!isNgsHeadlessEditorTextContent(next.content)) {
|
|
646
|
+
const blocks = [...this._document().blocks];
|
|
647
|
+
blocks.splice(blockIndex + 1, 1);
|
|
648
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(block.id, point.offset), 'keyboard');
|
|
649
|
+
}
|
|
650
|
+
const blocks = [...this._document().blocks];
|
|
651
|
+
blocks.splice(blockIndex, 2, {
|
|
652
|
+
...block,
|
|
653
|
+
content: normalizeNgsHeadlessEditorTextContent([...block.content, ...next.content])
|
|
654
|
+
});
|
|
655
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(block.id, point.offset), 'keyboard');
|
|
656
|
+
}
|
|
657
|
+
deleteRange(selection, origin, historyGroup = null) {
|
|
658
|
+
if (this._readOnly()) {
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
const deleted = deleteSelectedRange(this._document(), clampSelection(this._document(), selection, this.marks));
|
|
662
|
+
if (ngsHeadlessEditorDocumentsEqual(deleted.document, this._document())) {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
return this.commit(deleted.document, deleted.selection, origin, historyGroup);
|
|
666
|
+
}
|
|
667
|
+
splitBlock() {
|
|
668
|
+
if (this._readOnly()) {
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
const deleted = deleteSelectedRange(this._document(), this.ensureSelection());
|
|
672
|
+
const point = deleted.selection.focus;
|
|
673
|
+
const blockIndex = deleted.document.blocks.findIndex(block => block.id === point.blockId);
|
|
674
|
+
const block = deleted.document.blocks[blockIndex];
|
|
675
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content)) {
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
const definition = this.blocks.get(block.type);
|
|
679
|
+
const exitType = definition?.exitType ?? 'paragraph';
|
|
680
|
+
if (getNgsHeadlessEditorBlockText(block).length === 0 &&
|
|
681
|
+
block.type !== exitType &&
|
|
682
|
+
definition?.exitOnEmptyEnter !== false &&
|
|
683
|
+
this.blocks.has(exitType)) {
|
|
684
|
+
// Second Enter in a quote, list or code block: drop the empty line and
|
|
685
|
+
// continue below the block with a paragraph.
|
|
686
|
+
const exit = this.blocks.get(exitType)?.create() ?? createNgsHeadlessEditorParagraph();
|
|
687
|
+
const blocks = [...deleted.document.blocks];
|
|
688
|
+
blocks.splice(blockIndex, 1, {
|
|
689
|
+
...exit,
|
|
690
|
+
type: exitType,
|
|
691
|
+
content: normalizeNgsHeadlessEditorTextContent([])
|
|
692
|
+
});
|
|
693
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(exit.id, 0), 'keyboard');
|
|
694
|
+
}
|
|
695
|
+
const left = sliceTextContent(block.content, 0, point.offset);
|
|
696
|
+
const right = sliceTextContent(block.content, point.offset, textContentLength(block.content));
|
|
697
|
+
const next = definition?.create() ?? createNgsHeadlessEditorParagraph();
|
|
698
|
+
const blocks = [...deleted.document.blocks];
|
|
699
|
+
blocks.splice(blockIndex, 1, { ...block, content: normalizeNgsHeadlessEditorTextContent(left) }, { ...next, content: normalizeNgsHeadlessEditorTextContent(right) });
|
|
700
|
+
return this.commit({ version: 1, blocks }, collapsedSelection(next.id, 0), 'keyboard');
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Routes formatting (marks, stored marks, the selection used by mark commands
|
|
704
|
+
* and insertText()) to a nested editor, such as the editor of a focused table
|
|
705
|
+
* cell. Toolbar commands keep working unchanged: they run against this editor
|
|
706
|
+
* and act on the nested one. Pass null to restore normal behavior. Block-level
|
|
707
|
+
* operations are disabled while a target is active.
|
|
708
|
+
*/
|
|
709
|
+
setInlineTarget(target) {
|
|
710
|
+
this._inlineTarget.set(target === this ? null : target);
|
|
711
|
+
}
|
|
712
|
+
/** Whether a mark can be applied at the current selection (registered, writable). */
|
|
713
|
+
canApplyMark(type) {
|
|
714
|
+
const target = this._inlineTarget();
|
|
715
|
+
if (target) {
|
|
716
|
+
return target.canApplyMark(type);
|
|
717
|
+
}
|
|
718
|
+
this._plugins();
|
|
719
|
+
return !this._readOnly() && this.marks.has(type);
|
|
720
|
+
}
|
|
721
|
+
/** Whether block operations such as toggleBlock() are possible right now. */
|
|
722
|
+
canEditBlocks() {
|
|
723
|
+
return !this._readOnly() && this._inlineTarget() === null;
|
|
724
|
+
}
|
|
725
|
+
toggleMark(type, attrs) {
|
|
726
|
+
const target = this._inlineTarget();
|
|
727
|
+
if (target) {
|
|
728
|
+
return target.toggleMark(type, attrs);
|
|
729
|
+
}
|
|
730
|
+
if (this._readOnly() || !this.marks.has(type)) {
|
|
731
|
+
return false;
|
|
732
|
+
}
|
|
733
|
+
const mark = { type, attrs };
|
|
734
|
+
const selection = this.ensureSelection();
|
|
735
|
+
if (isCollapsed(selection)) {
|
|
736
|
+
const current = this._storedMarks() ?? this.getMarksAtSelection();
|
|
737
|
+
const active = current.some(item => item.type === type);
|
|
738
|
+
this._storedMarks.set(active
|
|
739
|
+
? current.filter(item => item.type !== type)
|
|
740
|
+
: normalizeNgsHeadlessEditorMarks([...current, mark]));
|
|
741
|
+
return true;
|
|
742
|
+
}
|
|
743
|
+
const ordered = orderSelection(this._document(), selection);
|
|
744
|
+
const blocks = this._document().blocks.map((block, blockIndex) => {
|
|
745
|
+
if (blockIndex < ordered.startBlockIndex ||
|
|
746
|
+
blockIndex > ordered.endBlockIndex ||
|
|
747
|
+
!isNgsHeadlessEditorTextContent(block.content)) {
|
|
748
|
+
return block;
|
|
749
|
+
}
|
|
750
|
+
const from = blockIndex === ordered.startBlockIndex ? ordered.start.offset : 0;
|
|
751
|
+
const to = blockIndex === ordered.endBlockIndex
|
|
752
|
+
? ordered.end.offset
|
|
753
|
+
: textContentLength(block.content);
|
|
754
|
+
return {
|
|
755
|
+
...block,
|
|
756
|
+
content: toggleMarkInContent(block.content, from, to, mark)
|
|
757
|
+
};
|
|
758
|
+
});
|
|
759
|
+
return this.commit({ version: 1, blocks }, selection, 'command');
|
|
760
|
+
}
|
|
761
|
+
isMarkActive(type) {
|
|
762
|
+
const target = this._inlineTarget();
|
|
763
|
+
if (target) {
|
|
764
|
+
return target.isMarkActive(type);
|
|
765
|
+
}
|
|
766
|
+
const selection = this._selection();
|
|
767
|
+
if (!selection) {
|
|
768
|
+
return false;
|
|
769
|
+
}
|
|
770
|
+
if (isCollapsed(selection)) {
|
|
771
|
+
return this.getCollapsedMarks().some(mark => mark.type === type);
|
|
772
|
+
}
|
|
773
|
+
const ordered = orderSelection(this._document(), selection);
|
|
774
|
+
for (let index = ordered.startBlockIndex; index <= ordered.endBlockIndex; index += 1) {
|
|
775
|
+
const block = this._document().blocks[index];
|
|
776
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content)) {
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
const from = index === ordered.startBlockIndex ? ordered.start.offset : 0;
|
|
780
|
+
const to = index === ordered.endBlockIndex ? ordered.end.offset : textContentLength(block.content);
|
|
781
|
+
if (!contentRangeHasMark(block.content, from, to, type)) {
|
|
782
|
+
return false;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return true;
|
|
786
|
+
}
|
|
787
|
+
getActiveMark(type) {
|
|
788
|
+
const target = this._inlineTarget();
|
|
789
|
+
if (target) {
|
|
790
|
+
return target.getActiveMark(type);
|
|
791
|
+
}
|
|
792
|
+
const selection = this._selection();
|
|
793
|
+
const marks = selection && isCollapsed(selection)
|
|
794
|
+
? this.getCollapsedMarks()
|
|
795
|
+
: this.getMarksAtSelection();
|
|
796
|
+
return marks.find(mark => mark.type === type);
|
|
797
|
+
}
|
|
798
|
+
setMark(type, attrs) {
|
|
799
|
+
const target = this._inlineTarget();
|
|
800
|
+
if (target) {
|
|
801
|
+
return target.setMark(type, attrs);
|
|
802
|
+
}
|
|
803
|
+
if (this._readOnly() || !this.marks.has(type)) {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
const selection = this.ensureSelection();
|
|
807
|
+
const mark = { type, attrs };
|
|
808
|
+
if (isCollapsed(selection)) {
|
|
809
|
+
const current = this.getCollapsedMarks();
|
|
810
|
+
this._storedMarks.set(normalizeNgsHeadlessEditorMarks([
|
|
811
|
+
...current.filter(item => item.type !== type),
|
|
812
|
+
mark
|
|
813
|
+
]));
|
|
814
|
+
return true;
|
|
815
|
+
}
|
|
816
|
+
return this.applyMarkToSelection(selection, mark);
|
|
817
|
+
}
|
|
818
|
+
unsetMark(type) {
|
|
819
|
+
const target = this._inlineTarget();
|
|
820
|
+
if (target) {
|
|
821
|
+
return target.unsetMark(type);
|
|
822
|
+
}
|
|
823
|
+
if (this._readOnly() || !this.marks.has(type)) {
|
|
824
|
+
return false;
|
|
825
|
+
}
|
|
826
|
+
const selection = this.ensureSelection();
|
|
827
|
+
if (isCollapsed(selection)) {
|
|
828
|
+
const current = this.getCollapsedMarks();
|
|
829
|
+
const next = current.filter(mark => mark.type !== type);
|
|
830
|
+
if (next.length === current.length) {
|
|
831
|
+
return false;
|
|
832
|
+
}
|
|
833
|
+
this._storedMarks.set(next);
|
|
834
|
+
return true;
|
|
835
|
+
}
|
|
836
|
+
const ordered = orderSelection(this._document(), selection);
|
|
837
|
+
const blocks = this._document().blocks.map((block, blockIndex) => {
|
|
838
|
+
if (blockIndex < ordered.startBlockIndex ||
|
|
839
|
+
blockIndex > ordered.endBlockIndex ||
|
|
840
|
+
!isNgsHeadlessEditorTextContent(block.content)) {
|
|
841
|
+
return block;
|
|
842
|
+
}
|
|
843
|
+
const from = blockIndex === ordered.startBlockIndex ? ordered.start.offset : 0;
|
|
844
|
+
const to = blockIndex === ordered.endBlockIndex
|
|
845
|
+
? ordered.end.offset
|
|
846
|
+
: textContentLength(block.content);
|
|
847
|
+
return {
|
|
848
|
+
...block,
|
|
849
|
+
content: setMarkInContent(block.content, from, to, type)
|
|
850
|
+
};
|
|
851
|
+
});
|
|
852
|
+
return this.commit({ version: 1, blocks }, selection, 'command');
|
|
853
|
+
}
|
|
854
|
+
toggleBlock(type, fallbackType = 'paragraph') {
|
|
855
|
+
if (!this.canEditBlocks() || !this.blocks.has(type)) {
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
const selection = this.ensureSelection();
|
|
859
|
+
const ordered = orderSelection(this._document(), selection);
|
|
860
|
+
const selected = this._document().blocks.slice(ordered.startBlockIndex, ordered.endBlockIndex + 1);
|
|
861
|
+
const nextType = selected.every(block => block.type === type) ? fallbackType : type;
|
|
862
|
+
if (!this.blocks.has(nextType)) {
|
|
863
|
+
return false;
|
|
864
|
+
}
|
|
865
|
+
const blocks = this._document().blocks.map((block, blockIndex) => (blockIndex >= ordered.startBlockIndex && blockIndex <= ordered.endBlockIndex
|
|
866
|
+
? { ...block, type: nextType }
|
|
867
|
+
: block));
|
|
868
|
+
return this.commit({ version: 1, blocks }, selection, 'command');
|
|
869
|
+
}
|
|
870
|
+
isBlockActive(type) {
|
|
871
|
+
const selection = this._selection();
|
|
872
|
+
if (!selection || this._inlineTarget()) {
|
|
873
|
+
return false;
|
|
874
|
+
}
|
|
875
|
+
const ordered = orderSelection(this._document(), selection);
|
|
876
|
+
return this._document().blocks
|
|
877
|
+
.slice(ordered.startBlockIndex, ordered.endBlockIndex + 1)
|
|
878
|
+
.every(block => block.type === type);
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Inserts one or more blocks after the block that holds the caret, as one
|
|
882
|
+
* undo step. With `selectInserted` the caret moves to the end of the last
|
|
883
|
+
* inserted block.
|
|
884
|
+
*/
|
|
885
|
+
insertBlock(block, selectInserted = false) {
|
|
886
|
+
if (this._readOnly()) {
|
|
887
|
+
return false;
|
|
888
|
+
}
|
|
889
|
+
const inserted = Array.isArray(block) ? block : [block];
|
|
890
|
+
if (inserted.length === 0) {
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
const selection = this.ensureSelection();
|
|
894
|
+
const focusIndex = this._document().blocks.findIndex(item => item.id === selection.focus.blockId);
|
|
895
|
+
const blocks = [...this._document().blocks];
|
|
896
|
+
blocks.splice(Math.max(0, focusIndex + 1), 0, ...inserted);
|
|
897
|
+
const last = inserted[inserted.length - 1];
|
|
898
|
+
const nextSelection = selectInserted
|
|
899
|
+
? collapsedSelection(last.id, getNgsHeadlessEditorBlockText(last).length)
|
|
900
|
+
: selection;
|
|
901
|
+
return this.commit({ version: 1, blocks }, nextSelection, 'command');
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Replaces a block with zero or more blocks as one undo step, for example to
|
|
905
|
+
* turn an empty line into a table. The caret moves to `selection` when given.
|
|
906
|
+
*/
|
|
907
|
+
replaceBlock(blockId, replacement, selection) {
|
|
908
|
+
if (this._readOnly()) {
|
|
909
|
+
return false;
|
|
910
|
+
}
|
|
911
|
+
const index = this._document().blocks.findIndex(block => block.id === blockId);
|
|
912
|
+
if (index < 0) {
|
|
913
|
+
return false;
|
|
914
|
+
}
|
|
915
|
+
const blocks = [...this._document().blocks];
|
|
916
|
+
blocks.splice(index, 1, ...replacement);
|
|
917
|
+
const document = normalizeNgsHeadlessEditorDocument({ version: 1, blocks });
|
|
918
|
+
const fallback = document.blocks[Math.min(index, document.blocks.length - 1)];
|
|
919
|
+
return this.commit(document, selection ?? collapsedSelection(fallback.id, 0), 'command');
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Replaces type, content or attrs of a block. Updates that share a non-null
|
|
923
|
+
* `historyGroup` in quick succession (for example typing in one table cell)
|
|
924
|
+
* form a single undo step.
|
|
925
|
+
*/
|
|
926
|
+
updateBlock(blockId, update, origin = 'command', historyGroup = null) {
|
|
927
|
+
if (this._readOnly()) {
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
let found = false;
|
|
931
|
+
const blocks = this._document().blocks.map(block => {
|
|
932
|
+
if (block.id !== blockId) {
|
|
933
|
+
return block;
|
|
934
|
+
}
|
|
935
|
+
found = true;
|
|
936
|
+
return { ...block, ...update };
|
|
937
|
+
});
|
|
938
|
+
return found && this.commit({ version: 1, blocks }, this._selection(), origin, historyGroup);
|
|
939
|
+
}
|
|
940
|
+
removeBlock(blockId) {
|
|
941
|
+
if (this._readOnly()) {
|
|
942
|
+
return false;
|
|
943
|
+
}
|
|
944
|
+
const index = this._document().blocks.findIndex(block => block.id === blockId);
|
|
945
|
+
if (index < 0) {
|
|
946
|
+
return false;
|
|
947
|
+
}
|
|
948
|
+
const blocks = this._document().blocks.filter(block => block.id !== blockId);
|
|
949
|
+
const document = normalizeNgsHeadlessEditorDocument({ version: 1, blocks });
|
|
950
|
+
const target = document.blocks[Math.min(index, document.blocks.length - 1)];
|
|
951
|
+
return this.commit(document, collapsedSelection(target.id, 0), 'command');
|
|
952
|
+
}
|
|
953
|
+
commitDomDocument(document, selection) {
|
|
954
|
+
return this.commit(document, selection ?? firstSelection(document), 'composition');
|
|
955
|
+
}
|
|
956
|
+
undo() {
|
|
957
|
+
const snapshot = this.history.undo({
|
|
958
|
+
document: this._document(),
|
|
959
|
+
selection: this._selection()
|
|
960
|
+
});
|
|
961
|
+
if (!snapshot) {
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
this.restoreSnapshot(snapshot.document, snapshot.selection);
|
|
965
|
+
return true;
|
|
966
|
+
}
|
|
967
|
+
redo() {
|
|
968
|
+
const snapshot = this.history.redo({
|
|
969
|
+
document: this._document(),
|
|
970
|
+
selection: this._selection()
|
|
971
|
+
});
|
|
972
|
+
if (!snapshot) {
|
|
973
|
+
return false;
|
|
974
|
+
}
|
|
975
|
+
this.restoreSnapshot(snapshot.document, snapshot.selection);
|
|
976
|
+
return true;
|
|
977
|
+
}
|
|
978
|
+
clear() {
|
|
979
|
+
this.commit(createNgsHeadlessEditorDocument(), null, 'api');
|
|
980
|
+
this.history.clear();
|
|
981
|
+
}
|
|
982
|
+
/** Marks that apply at a collapsed caret, including pending stored marks. */
|
|
983
|
+
getCollapsedMarks() {
|
|
984
|
+
return this._storedMarks() ?? this.getMarksAtSelection();
|
|
985
|
+
}
|
|
986
|
+
getMarksAtSelection() {
|
|
987
|
+
const selection = this.ensureSelection();
|
|
988
|
+
const block = this._document().blocks.find(item => item.id === selection.focus.blockId);
|
|
989
|
+
return block && isNgsHeadlessEditorTextContent(block.content)
|
|
990
|
+
? marksAtOffset(block.content, selection.focus.offset).filter(mark => !this.marks.get(mark.type)?.atomic)
|
|
991
|
+
: [];
|
|
992
|
+
}
|
|
993
|
+
applyMarkToSelection(selection, mark) {
|
|
994
|
+
const ordered = orderSelection(this._document(), selection);
|
|
995
|
+
const blocks = this._document().blocks.map((block, blockIndex) => {
|
|
996
|
+
if (blockIndex < ordered.startBlockIndex ||
|
|
997
|
+
blockIndex > ordered.endBlockIndex ||
|
|
998
|
+
!isNgsHeadlessEditorTextContent(block.content)) {
|
|
999
|
+
return block;
|
|
1000
|
+
}
|
|
1001
|
+
const from = blockIndex === ordered.startBlockIndex ? ordered.start.offset : 0;
|
|
1002
|
+
const to = blockIndex === ordered.endBlockIndex
|
|
1003
|
+
? ordered.end.offset
|
|
1004
|
+
: textContentLength(block.content);
|
|
1005
|
+
return {
|
|
1006
|
+
...block,
|
|
1007
|
+
content: setMarkInContent(block.content, from, to, mark.type, mark)
|
|
1008
|
+
};
|
|
1009
|
+
});
|
|
1010
|
+
return this.commit({ version: 1, blocks }, selection, 'command');
|
|
1011
|
+
}
|
|
1012
|
+
ensureSelection() {
|
|
1013
|
+
return clampSelection(this._document(), this._selection() ?? firstSelection(this._document()), this.marks);
|
|
1014
|
+
}
|
|
1015
|
+
commit(document, selection, origin, historyGroup = null) {
|
|
1016
|
+
const normalized = normalizeNgsHeadlessEditorDocument(document);
|
|
1017
|
+
if (ngsHeadlessEditorDocumentsEqual(normalized, this._document())) {
|
|
1018
|
+
if (selection) {
|
|
1019
|
+
this.setSelection(selection);
|
|
1020
|
+
}
|
|
1021
|
+
return false;
|
|
1022
|
+
}
|
|
1023
|
+
this.history.record({
|
|
1024
|
+
document: this._document(),
|
|
1025
|
+
selection: this._selection()
|
|
1026
|
+
}, historyGroup);
|
|
1027
|
+
this._document.set(normalized);
|
|
1028
|
+
this._selection.set(selection ? clampSelection(normalized, selection, this.marks) : firstSelection(normalized));
|
|
1029
|
+
this._storedMarks.set(null);
|
|
1030
|
+
this._origin.set(origin);
|
|
1031
|
+
this._revision.update(revision => revision + 1);
|
|
1032
|
+
return true;
|
|
1033
|
+
}
|
|
1034
|
+
restoreSnapshot(document, selection) {
|
|
1035
|
+
this._document.set(document);
|
|
1036
|
+
this._selection.set(selection ? clampSelection(document, selection, this.marks) : firstSelection(document));
|
|
1037
|
+
this._storedMarks.set(null);
|
|
1038
|
+
this._origin.set('history');
|
|
1039
|
+
this._revision.update(revision => revision + 1);
|
|
1040
|
+
}
|
|
1041
|
+
destroyPlugins() {
|
|
1042
|
+
for (const cleanup of this.pluginCleanups.splice(0)) {
|
|
1043
|
+
cleanup();
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1047
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditor });
|
|
1048
|
+
}
|
|
1049
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditor, decorators: [{
|
|
1050
|
+
type: Injectable
|
|
1051
|
+
}], ctorParameters: () => [] });
|
|
1052
|
+
function samePluginSet(left, right) {
|
|
1053
|
+
return left.length === right.length && left.every((plugin, index) => plugin === right[index]);
|
|
1054
|
+
}
|
|
1055
|
+
function assertUnique(collection, id, kind) {
|
|
1056
|
+
if (collection.has(id)) {
|
|
1057
|
+
throw new Error(`[NgsHeadlessEditor] Duplicate ${kind} id "${id}".`);
|
|
1058
|
+
}
|
|
1059
|
+
if (collection instanceof Set) {
|
|
1060
|
+
collection.add(id);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Returns lower-cased binding candidates for a keyboard event, most specific first.
|
|
1065
|
+
* `event.key` is layout dependent: Shift+7 produces "&", Option+C on macOS produces
|
|
1066
|
+
* "ç" and a Cyrillic layout produces "и" for the B key. The physical `event.code`
|
|
1067
|
+
* is used as a fallback so bindings like `Mod-Shift-7` and `Mod-b` still resolve.
|
|
1068
|
+
*/
|
|
1069
|
+
function eventToKeyBindings(event) {
|
|
1070
|
+
const modifiers = [];
|
|
1071
|
+
if (event.ctrlKey || event.metaKey)
|
|
1072
|
+
modifiers.push('mod');
|
|
1073
|
+
if (event.altKey)
|
|
1074
|
+
modifiers.push('alt');
|
|
1075
|
+
if (event.shiftKey)
|
|
1076
|
+
modifiers.push('shift');
|
|
1077
|
+
const keys = [];
|
|
1078
|
+
const add = (key) => {
|
|
1079
|
+
const normalized = key?.toLowerCase();
|
|
1080
|
+
if (normalized && !keys.includes(normalized)) {
|
|
1081
|
+
keys.push(normalized);
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
add(event.key);
|
|
1085
|
+
const code = event.code ?? '';
|
|
1086
|
+
if (/^Key[A-Z]$/.test(code)) {
|
|
1087
|
+
add(code.slice(3));
|
|
1088
|
+
}
|
|
1089
|
+
else if (/^Digit\d$/.test(code)) {
|
|
1090
|
+
add(code.slice(5));
|
|
1091
|
+
}
|
|
1092
|
+
return keys.map(key => [...modifiers, key].join('-'));
|
|
1093
|
+
}
|
|
1094
|
+
function selectionsEqual(left, right) {
|
|
1095
|
+
if (left === right) {
|
|
1096
|
+
return true;
|
|
1097
|
+
}
|
|
1098
|
+
if (!left || !right) {
|
|
1099
|
+
return false;
|
|
1100
|
+
}
|
|
1101
|
+
return left.anchor.blockId === right.anchor.blockId &&
|
|
1102
|
+
left.anchor.offset === right.anchor.offset &&
|
|
1103
|
+
left.focus.blockId === right.focus.blockId &&
|
|
1104
|
+
left.focus.offset === right.focus.offset;
|
|
1105
|
+
}
|
|
1106
|
+
const graphemeSegmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl
|
|
1107
|
+
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
|
1108
|
+
: null;
|
|
1109
|
+
/** Start offset of the user-perceived character before `offset` (emoji sequences, flags, combining marks). */
|
|
1110
|
+
function previousGraphemeBoundary(text, offset) {
|
|
1111
|
+
if (offset <= 0) {
|
|
1112
|
+
return 0;
|
|
1113
|
+
}
|
|
1114
|
+
if (graphemeSegmenter) {
|
|
1115
|
+
let start = 0;
|
|
1116
|
+
for (const segment of graphemeSegmenter.segment(text)) {
|
|
1117
|
+
if (segment.index >= offset) {
|
|
1118
|
+
break;
|
|
1119
|
+
}
|
|
1120
|
+
start = segment.index;
|
|
1121
|
+
}
|
|
1122
|
+
return start;
|
|
1123
|
+
}
|
|
1124
|
+
const previous = Array.from(text.slice(0, offset)).at(-1) ?? '';
|
|
1125
|
+
return offset - previous.length;
|
|
1126
|
+
}
|
|
1127
|
+
/** End offset of the user-perceived character after `offset`. */
|
|
1128
|
+
function nextGraphemeBoundary(text, offset) {
|
|
1129
|
+
if (offset >= text.length) {
|
|
1130
|
+
return text.length;
|
|
1131
|
+
}
|
|
1132
|
+
if (graphemeSegmenter) {
|
|
1133
|
+
for (const segment of graphemeSegmenter.segment(text)) {
|
|
1134
|
+
const end = segment.index + segment.segment.length;
|
|
1135
|
+
if (end > offset) {
|
|
1136
|
+
return end;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return text.length;
|
|
1140
|
+
}
|
|
1141
|
+
const next = Array.from(text.slice(offset))[0] ?? '';
|
|
1142
|
+
return offset + next.length;
|
|
1143
|
+
}
|
|
1144
|
+
function graphemeCount(text) {
|
|
1145
|
+
if (graphemeSegmenter) {
|
|
1146
|
+
let count = 0;
|
|
1147
|
+
for (const _segment of graphemeSegmenter.segment(text)) {
|
|
1148
|
+
count += 1;
|
|
1149
|
+
}
|
|
1150
|
+
return count;
|
|
1151
|
+
}
|
|
1152
|
+
return Array.from(text).length;
|
|
1153
|
+
}
|
|
1154
|
+
function firstSelection(document) {
|
|
1155
|
+
const block = document.blocks[0];
|
|
1156
|
+
return collapsedSelection(block.id, 0);
|
|
1157
|
+
}
|
|
1158
|
+
function collapsedSelection(blockId, offset) {
|
|
1159
|
+
const point = { blockId, offset };
|
|
1160
|
+
return { anchor: point, focus: point };
|
|
1161
|
+
}
|
|
1162
|
+
function isCollapsed(selection) {
|
|
1163
|
+
return selection.anchor.blockId === selection.focus.blockId && selection.anchor.offset === selection.focus.offset;
|
|
1164
|
+
}
|
|
1165
|
+
function clampSelection(document, selection, marks) {
|
|
1166
|
+
const clamped = {
|
|
1167
|
+
anchor: clampPoint(document, selection.anchor),
|
|
1168
|
+
focus: clampPoint(document, selection.focus)
|
|
1169
|
+
};
|
|
1170
|
+
if (isCollapsed(clamped)) {
|
|
1171
|
+
const point = snapAtomicPoint(document, clamped.focus, marks, 'nearest');
|
|
1172
|
+
return { anchor: point, focus: point };
|
|
1173
|
+
}
|
|
1174
|
+
const ordered = orderSelection(document, clamped);
|
|
1175
|
+
const start = snapAtomicPoint(document, ordered.start, marks, 'start');
|
|
1176
|
+
const end = snapAtomicPoint(document, ordered.end, marks, 'end');
|
|
1177
|
+
return ordered.start === clamped.anchor ? { anchor: start, focus: end } : { anchor: end, focus: start };
|
|
1178
|
+
}
|
|
1179
|
+
/** Adjacent runs may share one token while having different surrounding formatting. */
|
|
1180
|
+
function snapAtomicPoint(document, point, definitions, bias) {
|
|
1181
|
+
const block = document.blocks.find(item => item.id === point.blockId);
|
|
1182
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content))
|
|
1183
|
+
return point;
|
|
1184
|
+
const tokens = [];
|
|
1185
|
+
let offset = 0;
|
|
1186
|
+
for (const run of block.content) {
|
|
1187
|
+
const mark = run.marks.find(item => definitions.get(item.type)?.atomic);
|
|
1188
|
+
if (mark) {
|
|
1189
|
+
const previous = tokens.at(-1);
|
|
1190
|
+
if (previous?.to === offset && ngsHeadlessEditorMarksEqual([previous.mark], [mark])) {
|
|
1191
|
+
previous.to += run.text.length;
|
|
1192
|
+
}
|
|
1193
|
+
else {
|
|
1194
|
+
tokens.push({ from: offset, to: offset + run.text.length, mark });
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
offset += run.text.length;
|
|
1198
|
+
}
|
|
1199
|
+
const token = tokens.find(item => item.from < point.offset && point.offset < item.to);
|
|
1200
|
+
if (!token)
|
|
1201
|
+
return point;
|
|
1202
|
+
const toStart = bias === 'start' || (bias === 'nearest' && point.offset - token.from < token.to - point.offset);
|
|
1203
|
+
return { ...point, offset: toStart ? token.from : token.to };
|
|
1204
|
+
}
|
|
1205
|
+
function clampPoint(document, point) {
|
|
1206
|
+
const block = document.blocks.find(item => item.id === point.blockId) ?? document.blocks[0];
|
|
1207
|
+
return {
|
|
1208
|
+
blockId: block.id,
|
|
1209
|
+
offset: Math.max(0, Math.min(point.offset, getNgsHeadlessEditorBlockText(block).length))
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
function orderSelection(document, selection) {
|
|
1213
|
+
const anchorIndex = document.blocks.findIndex(block => block.id === selection.anchor.blockId);
|
|
1214
|
+
const focusIndex = document.blocks.findIndex(block => block.id === selection.focus.blockId);
|
|
1215
|
+
const anchorFirst = anchorIndex < focusIndex || (anchorIndex === focusIndex && selection.anchor.offset <= selection.focus.offset);
|
|
1216
|
+
return {
|
|
1217
|
+
start: anchorFirst ? selection.anchor : selection.focus,
|
|
1218
|
+
end: anchorFirst ? selection.focus : selection.anchor,
|
|
1219
|
+
startBlockIndex: anchorFirst ? anchorIndex : focusIndex,
|
|
1220
|
+
endBlockIndex: anchorFirst ? focusIndex : anchorIndex
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Removes the content between the selection points and returns the collapsed
|
|
1225
|
+
* caret. Blocks fully inside the range are removed. A non-text (atomic) block at
|
|
1226
|
+
* the start of the range is removed; one at the end is kept, because a point at
|
|
1227
|
+
* offset 0 of an atomic block sits before it.
|
|
1228
|
+
*/
|
|
1229
|
+
function deleteSelectedRange(document, selection) {
|
|
1230
|
+
if (isCollapsed(selection)) {
|
|
1231
|
+
return { document, selection };
|
|
1232
|
+
}
|
|
1233
|
+
const ordered = orderSelection(document, selection);
|
|
1234
|
+
const startBlock = document.blocks[ordered.startBlockIndex];
|
|
1235
|
+
const endBlock = document.blocks[ordered.endBlockIndex];
|
|
1236
|
+
if (!startBlock || !endBlock) {
|
|
1237
|
+
return { document, selection };
|
|
1238
|
+
}
|
|
1239
|
+
const endIsText = isNgsHeadlessEditorTextContent(endBlock.content);
|
|
1240
|
+
const after = isNgsHeadlessEditorTextContent(endBlock.content)
|
|
1241
|
+
? sliceTextContent(endBlock.content, ordered.end.offset, textContentLength(endBlock.content))
|
|
1242
|
+
: [];
|
|
1243
|
+
const blocks = [...document.blocks];
|
|
1244
|
+
if (isNgsHeadlessEditorTextContent(startBlock.content)) {
|
|
1245
|
+
const before = sliceTextContent(startBlock.content, 0, ordered.start.offset);
|
|
1246
|
+
const removeCount = (endIsText ? ordered.endBlockIndex : ordered.endBlockIndex - 1) -
|
|
1247
|
+
ordered.startBlockIndex + 1;
|
|
1248
|
+
blocks.splice(ordered.startBlockIndex, removeCount, {
|
|
1249
|
+
...startBlock,
|
|
1250
|
+
content: normalizeNgsHeadlessEditorTextContent([...before, ...after])
|
|
1251
|
+
});
|
|
1252
|
+
return {
|
|
1253
|
+
document: { version: 1, blocks },
|
|
1254
|
+
selection: collapsedSelection(startBlock.id, ordered.start.offset)
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
if (endIsText) {
|
|
1258
|
+
blocks.splice(ordered.startBlockIndex, ordered.endBlockIndex - ordered.startBlockIndex + 1, { ...endBlock, content: normalizeNgsHeadlessEditorTextContent(after) });
|
|
1259
|
+
return {
|
|
1260
|
+
document: { version: 1, blocks },
|
|
1261
|
+
selection: collapsedSelection(endBlock.id, 0)
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
// Both ends are atomic blocks: drop everything before the end block and leave
|
|
1265
|
+
// an empty paragraph for the caret.
|
|
1266
|
+
const paragraph = createNgsHeadlessEditorParagraph();
|
|
1267
|
+
blocks.splice(ordered.startBlockIndex, ordered.endBlockIndex - ordered.startBlockIndex, paragraph);
|
|
1268
|
+
return {
|
|
1269
|
+
document: { version: 1, blocks },
|
|
1270
|
+
selection: collapsedSelection(paragraph.id, 0)
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
function textContentLength(content) {
|
|
1274
|
+
return content.reduce((length, run) => length + run.text.length, 0);
|
|
1275
|
+
}
|
|
1276
|
+
function sliceTextContent(content, from, to) {
|
|
1277
|
+
const result = [];
|
|
1278
|
+
let offset = 0;
|
|
1279
|
+
for (const run of content) {
|
|
1280
|
+
const runStart = offset;
|
|
1281
|
+
const runEnd = offset + run.text.length;
|
|
1282
|
+
const start = Math.max(from, runStart);
|
|
1283
|
+
const end = Math.min(to, runEnd);
|
|
1284
|
+
if (start < end) {
|
|
1285
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(start - runStart, end - runStart), run.marks));
|
|
1286
|
+
}
|
|
1287
|
+
offset = runEnd;
|
|
1288
|
+
}
|
|
1289
|
+
return result;
|
|
1290
|
+
}
|
|
1291
|
+
function marksAtOffset(content, offset) {
|
|
1292
|
+
let currentOffset = 0;
|
|
1293
|
+
for (const run of content) {
|
|
1294
|
+
const end = currentOffset + run.text.length;
|
|
1295
|
+
if (offset > currentOffset && offset <= end) {
|
|
1296
|
+
return run.marks;
|
|
1297
|
+
}
|
|
1298
|
+
if (offset === currentOffset && currentOffset === 0) {
|
|
1299
|
+
return run.marks;
|
|
1300
|
+
}
|
|
1301
|
+
currentOffset = end;
|
|
1302
|
+
}
|
|
1303
|
+
return content.at(-1)?.marks ?? [];
|
|
1304
|
+
}
|
|
1305
|
+
function toggleMarkInContent(content, from, to, mark) {
|
|
1306
|
+
const remove = contentRangeHasMark(content, from, to, mark.type);
|
|
1307
|
+
const result = [];
|
|
1308
|
+
let offset = 0;
|
|
1309
|
+
for (const run of content) {
|
|
1310
|
+
const runStart = offset;
|
|
1311
|
+
const runEnd = offset + run.text.length;
|
|
1312
|
+
const overlapStart = Math.max(from, runStart);
|
|
1313
|
+
const overlapEnd = Math.min(to, runEnd);
|
|
1314
|
+
if (overlapStart >= overlapEnd) {
|
|
1315
|
+
result.push(run);
|
|
1316
|
+
offset = runEnd;
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
if (runStart < overlapStart) {
|
|
1320
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(0, overlapStart - runStart), run.marks));
|
|
1321
|
+
}
|
|
1322
|
+
const marks = remove
|
|
1323
|
+
? run.marks.filter(item => item.type !== mark.type)
|
|
1324
|
+
: normalizeNgsHeadlessEditorMarks([...run.marks.filter(item => item.type !== mark.type), mark]);
|
|
1325
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(overlapStart - runStart, overlapEnd - runStart), marks));
|
|
1326
|
+
if (overlapEnd < runEnd) {
|
|
1327
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(overlapEnd - runStart), run.marks));
|
|
1328
|
+
}
|
|
1329
|
+
offset = runEnd;
|
|
1330
|
+
}
|
|
1331
|
+
return normalizeNgsHeadlessEditorTextContent(result);
|
|
1332
|
+
}
|
|
1333
|
+
function setMarkInContent(content, from, to, type, mark) {
|
|
1334
|
+
const result = [];
|
|
1335
|
+
let offset = 0;
|
|
1336
|
+
for (const run of content) {
|
|
1337
|
+
const runStart = offset;
|
|
1338
|
+
const runEnd = offset + run.text.length;
|
|
1339
|
+
const overlapStart = Math.max(from, runStart);
|
|
1340
|
+
const overlapEnd = Math.min(to, runEnd);
|
|
1341
|
+
if (overlapStart >= overlapEnd) {
|
|
1342
|
+
result.push(run);
|
|
1343
|
+
offset = runEnd;
|
|
1344
|
+
continue;
|
|
1345
|
+
}
|
|
1346
|
+
if (runStart < overlapStart) {
|
|
1347
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(0, overlapStart - runStart), run.marks));
|
|
1348
|
+
}
|
|
1349
|
+
const marks = mark
|
|
1350
|
+
? normalizeNgsHeadlessEditorMarks([...run.marks.filter(item => item.type !== type), mark])
|
|
1351
|
+
: run.marks.filter(item => item.type !== type);
|
|
1352
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(overlapStart - runStart, overlapEnd - runStart), marks));
|
|
1353
|
+
if (overlapEnd < runEnd) {
|
|
1354
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(overlapEnd - runStart), run.marks));
|
|
1355
|
+
}
|
|
1356
|
+
offset = runEnd;
|
|
1357
|
+
}
|
|
1358
|
+
return normalizeNgsHeadlessEditorTextContent(result);
|
|
1359
|
+
}
|
|
1360
|
+
function contentRangeHasMark(content, from, to, type) {
|
|
1361
|
+
if (from === to) {
|
|
1362
|
+
return marksAtOffset(content, from).some(mark => mark.type === type);
|
|
1363
|
+
}
|
|
1364
|
+
let offset = 0;
|
|
1365
|
+
let foundText = false;
|
|
1366
|
+
for (const run of content) {
|
|
1367
|
+
const runStart = offset;
|
|
1368
|
+
const runEnd = offset + run.text.length;
|
|
1369
|
+
if (Math.max(from, runStart) < Math.min(to, runEnd)) {
|
|
1370
|
+
foundText = true;
|
|
1371
|
+
if (!run.marks.some(mark => mark.type === type)) {
|
|
1372
|
+
return false;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
offset = runEnd;
|
|
1376
|
+
}
|
|
1377
|
+
return foundText;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
const NGS_HEADLESS_EDITOR_TOGGLE_BOLD = toggleMarkCommand('bold');
|
|
1381
|
+
const NGS_HEADLESS_EDITOR_TOGGLE_ITALIC = toggleMarkCommand('italic');
|
|
1382
|
+
const NGS_HEADLESS_EDITOR_TOGGLE_STRIKE = toggleMarkCommand('strike');
|
|
1383
|
+
const NGS_HEADLESS_EDITOR_TOGGLE_CODE = toggleMarkCommand('code');
|
|
1384
|
+
function basicTextEditorPlugin() {
|
|
1385
|
+
return defineNgsHeadlessEditorPlugin({
|
|
1386
|
+
id: 'basic-text',
|
|
1387
|
+
blocks: [
|
|
1388
|
+
{
|
|
1389
|
+
type: 'paragraph',
|
|
1390
|
+
tagName: 'p',
|
|
1391
|
+
create: () => createNgsHeadlessEditorParagraph()
|
|
1392
|
+
}
|
|
1393
|
+
],
|
|
1394
|
+
marks: [
|
|
1395
|
+
{ type: 'bold', tagName: 'strong', parseTags: ['strong', 'b'] },
|
|
1396
|
+
{ type: 'italic', tagName: 'em', parseTags: ['em', 'i'] },
|
|
1397
|
+
{ type: 'strike', tagName: 's', parseTags: ['s', 'strike'] },
|
|
1398
|
+
{ type: 'code', tagName: 'code', parseTags: ['code'] }
|
|
1399
|
+
],
|
|
1400
|
+
commands: [
|
|
1401
|
+
NGS_HEADLESS_EDITOR_TOGGLE_BOLD,
|
|
1402
|
+
NGS_HEADLESS_EDITOR_TOGGLE_ITALIC,
|
|
1403
|
+
NGS_HEADLESS_EDITOR_TOGGLE_STRIKE,
|
|
1404
|
+
NGS_HEADLESS_EDITOR_TOGGLE_CODE
|
|
1405
|
+
],
|
|
1406
|
+
keymap: [
|
|
1407
|
+
{ key: 'Mod-b', command: NGS_HEADLESS_EDITOR_TOGGLE_BOLD },
|
|
1408
|
+
{ key: 'Mod-i', command: NGS_HEADLESS_EDITOR_TOGGLE_ITALIC },
|
|
1409
|
+
{ key: 'Mod-Shift-x', command: NGS_HEADLESS_EDITOR_TOGGLE_STRIKE },
|
|
1410
|
+
{ key: 'Mod-e', command: NGS_HEADLESS_EDITOR_TOGGLE_CODE }
|
|
1411
|
+
]
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
function toggleMarkCommand(type) {
|
|
1415
|
+
return {
|
|
1416
|
+
id: `toggle-${type}`,
|
|
1417
|
+
execute: editor => editor.toggleMark(type),
|
|
1418
|
+
enabled: editor => editor.canApplyMark(type),
|
|
1419
|
+
active: editor => editor.isMarkActive(type)
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
const NGS_HEADLESS_EDITOR_TEXT_COLOR_MARK = 'textColor';
|
|
1424
|
+
const NGS_HEADLESS_EDITOR_BACKGROUND_COLOR_MARK = 'backgroundColor';
|
|
1425
|
+
const NGS_HEADLESS_EDITOR_SET_TEXT_COLOR = setColorCommand('set-text-color', NGS_HEADLESS_EDITOR_TEXT_COLOR_MARK);
|
|
1426
|
+
const NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR = unsetColorCommand('unset-text-color', NGS_HEADLESS_EDITOR_TEXT_COLOR_MARK);
|
|
1427
|
+
const NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR = setColorCommand('set-background-color', NGS_HEADLESS_EDITOR_BACKGROUND_COLOR_MARK);
|
|
1428
|
+
const NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR = unsetColorCommand('unset-background-color', NGS_HEADLESS_EDITOR_BACKGROUND_COLOR_MARK);
|
|
1429
|
+
function colorEditorPlugin() {
|
|
1430
|
+
return defineNgsHeadlessEditorPlugin({
|
|
1431
|
+
id: 'color',
|
|
1432
|
+
marks: [
|
|
1433
|
+
colorMark(NGS_HEADLESS_EDITOR_TEXT_COLOR_MARK, 'color'),
|
|
1434
|
+
colorMark(NGS_HEADLESS_EDITOR_BACKGROUND_COLOR_MARK, 'backgroundColor')
|
|
1435
|
+
],
|
|
1436
|
+
commands: [
|
|
1437
|
+
NGS_HEADLESS_EDITOR_SET_TEXT_COLOR,
|
|
1438
|
+
NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR,
|
|
1439
|
+
NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR,
|
|
1440
|
+
NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR
|
|
1441
|
+
]
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Keeps color values serializable and safe to write to an inline style attribute.
|
|
1446
|
+
* The editor accepts common CSS colors and design-token variables, but rejects
|
|
1447
|
+
* declarations, URLs, and other values that could escape the color property.
|
|
1448
|
+
*/
|
|
1449
|
+
function normalizeNgsHeadlessEditorColor(value) {
|
|
1450
|
+
const color = value?.trim() ?? '';
|
|
1451
|
+
if (!color ||
|
|
1452
|
+
color.length > 128 ||
|
|
1453
|
+
/[;{}<>"'\\\u0000-\u001f\u007f]/.test(color) ||
|
|
1454
|
+
/(?:url|expression)\s*\(/i.test(color)) {
|
|
1455
|
+
return null;
|
|
1456
|
+
}
|
|
1457
|
+
if (/^#[\da-f]{3,8}$/i.test(color) ||
|
|
1458
|
+
/^[a-z]+$/i.test(color) ||
|
|
1459
|
+
/^var\(--[\w-]+(?:\s*,\s*(?:#[\da-f]{3,8}|[a-z]+))?\)$/i.test(color) ||
|
|
1460
|
+
/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch)\([\w\s.,%+\-/]+\)$/i.test(color) ||
|
|
1461
|
+
/^color\([\w\s.,%+\-/]+\)$/i.test(color)) {
|
|
1462
|
+
return color;
|
|
1463
|
+
}
|
|
1464
|
+
return null;
|
|
1465
|
+
}
|
|
1466
|
+
function colorMark(type, styleProperty) {
|
|
1467
|
+
return {
|
|
1468
|
+
type,
|
|
1469
|
+
tagName: 'span',
|
|
1470
|
+
applyAttributes: (element, mark) => {
|
|
1471
|
+
const color = normalizeNgsHeadlessEditorColor(String(mark.attrs?.['color'] ?? ''));
|
|
1472
|
+
if (color) {
|
|
1473
|
+
element.style[styleProperty] = color;
|
|
1474
|
+
}
|
|
1475
|
+
},
|
|
1476
|
+
readAttributes: element => {
|
|
1477
|
+
const color = normalizeNgsHeadlessEditorColor(element.style[styleProperty]);
|
|
1478
|
+
return color ? { color } : undefined;
|
|
1479
|
+
}
|
|
1480
|
+
};
|
|
1481
|
+
}
|
|
1482
|
+
function setColorCommand(id, type) {
|
|
1483
|
+
return {
|
|
1484
|
+
id,
|
|
1485
|
+
execute: (editor, value) => {
|
|
1486
|
+
const color = normalizeNgsHeadlessEditorColor(value);
|
|
1487
|
+
return color ? editor.setMark(type, { color }) : false;
|
|
1488
|
+
},
|
|
1489
|
+
enabled: (editor, value) => normalizeNgsHeadlessEditorColor(value) !== null && editor.canApplyMark(type),
|
|
1490
|
+
active: (editor, value) => {
|
|
1491
|
+
const color = normalizeNgsHeadlessEditorColor(value);
|
|
1492
|
+
return !!color &&
|
|
1493
|
+
editor.isMarkActive(type) &&
|
|
1494
|
+
editor.getActiveMark(type)?.attrs?.['color'] === color;
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
function unsetColorCommand(id, type) {
|
|
1499
|
+
return {
|
|
1500
|
+
id,
|
|
1501
|
+
execute: editor => editor.unsetMark(type),
|
|
1502
|
+
enabled: editor => editor.canApplyMark(type),
|
|
1503
|
+
active: editor => editor.isMarkActive(type)
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/** Attribute written on every mark wrapper element. */
|
|
1508
|
+
const NGS_HEADLESS_EDITOR_MARK_ATTRIBUTE = 'data-ngs-headless-editor-mark';
|
|
1509
|
+
/**
|
|
1510
|
+
* Renders one text run: a text node wrapped in one element per mark, in mark
|
|
1511
|
+
* order. Unknown marks are wrapped in a span that only carries the mark type.
|
|
1512
|
+
*/
|
|
1513
|
+
function renderNgsHeadlessEditorTextRun(document, text, marks, registry) {
|
|
1514
|
+
let node = document.createTextNode(text);
|
|
1515
|
+
for (const mark of marks) {
|
|
1516
|
+
const definition = registry.getMarkDefinition(mark.type);
|
|
1517
|
+
const wrapper = document.createElement(definition?.tagName ?? 'span');
|
|
1518
|
+
wrapper.setAttribute(NGS_HEADLESS_EDITOR_MARK_ATTRIBUTE, mark.type);
|
|
1519
|
+
definition?.applyAttributes?.(wrapper, mark);
|
|
1520
|
+
if (definition?.atomic) {
|
|
1521
|
+
wrapper.contentEditable = 'false';
|
|
1522
|
+
wrapper.setAttribute('data-ngs-headless-editor-atomic', '');
|
|
1523
|
+
}
|
|
1524
|
+
wrapper.append(node);
|
|
1525
|
+
node = wrapper;
|
|
1526
|
+
}
|
|
1527
|
+
return node;
|
|
1528
|
+
}
|
|
1529
|
+
/** Replaces the children of `target` with rendered runs, or a <br> when empty. */
|
|
1530
|
+
function renderNgsHeadlessEditorRuns(target, runs, registry) {
|
|
1531
|
+
const document = target.ownerDocument;
|
|
1532
|
+
const fragment = document.createDocumentFragment();
|
|
1533
|
+
if (runs.some(run => run.text.length > 0)) {
|
|
1534
|
+
for (const run of runs) {
|
|
1535
|
+
fragment.append(renderNgsHeadlessEditorTextRun(document, run.text, run.marks, registry));
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
else {
|
|
1539
|
+
fragment.append(document.createElement('br'));
|
|
1540
|
+
}
|
|
1541
|
+
target.replaceChildren(fragment);
|
|
1542
|
+
}
|
|
1543
|
+
/** Finds the mark definition that produced (or matches) an element. */
|
|
1544
|
+
function findNgsHeadlessEditorMarkDefinition(element, registry) {
|
|
1545
|
+
const explicitType = element.getAttribute(NGS_HEADLESS_EDITOR_MARK_ATTRIBUTE);
|
|
1546
|
+
if (explicitType) {
|
|
1547
|
+
return registry.getMarkDefinition(explicitType);
|
|
1548
|
+
}
|
|
1549
|
+
const tag = element.tagName.toLowerCase();
|
|
1550
|
+
return registry.getMarkDefinitions().find(definition => (definition.tagName.toLowerCase() === tag ||
|
|
1551
|
+
definition.parseTags?.some(parseTag => parseTag.toLowerCase() === tag)));
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Reads text runs from DOM, turning elements into marks through the registry.
|
|
1555
|
+
* With `lineBreaks`, <br> and the boundaries of block-level elements become "\n".
|
|
1556
|
+
* Elements without a matching mark definition keep their text but add no mark.
|
|
1557
|
+
*/
|
|
1558
|
+
function readNgsHeadlessEditorInlineContent(element, registry, options = {}) {
|
|
1559
|
+
const runs = [];
|
|
1560
|
+
const blockTags = new Set(['p', 'div', 'li', 'tr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre']);
|
|
1561
|
+
const newline = () => {
|
|
1562
|
+
if (options.lineBreaks && runs.length > 0 && !runs[runs.length - 1].text.endsWith('\n')) {
|
|
1563
|
+
runs.push(createNgsHeadlessEditorText('\n'));
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
const visit = (node, marks) => {
|
|
1567
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
1568
|
+
if (node.textContent) {
|
|
1569
|
+
runs.push(createNgsHeadlessEditorText(node.textContent, marks));
|
|
1570
|
+
}
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
if (!(node instanceof Element)) {
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
const tag = node.tagName.toLowerCase();
|
|
1577
|
+
if (tag === 'br') {
|
|
1578
|
+
if (options.lineBreaks) {
|
|
1579
|
+
runs.push(createNgsHeadlessEditorText('\n', marks));
|
|
1580
|
+
}
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
const isBlock = options.lineBreaks && blockTags.has(tag);
|
|
1584
|
+
if (isBlock) {
|
|
1585
|
+
newline();
|
|
1586
|
+
}
|
|
1587
|
+
const definition = node instanceof HTMLElement ? findNgsHeadlessEditorMarkDefinition(node, registry) : undefined;
|
|
1588
|
+
const nextMarks = definition
|
|
1589
|
+
? [...marks, { type: definition.type, attrs: definition.readAttributes?.(node) }]
|
|
1590
|
+
: marks;
|
|
1591
|
+
for (const child of node.childNodes) {
|
|
1592
|
+
visit(child, nextMarks);
|
|
1593
|
+
}
|
|
1594
|
+
if (isBlock) {
|
|
1595
|
+
newline();
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
for (const child of element.childNodes) {
|
|
1599
|
+
visit(child, []);
|
|
1600
|
+
}
|
|
1601
|
+
if (options.lineBreaks) {
|
|
1602
|
+
while (runs.length > 0 && runs[runs.length - 1].text === '\n') {
|
|
1603
|
+
runs.pop();
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
return runs.length > 0 ? runs : [createNgsHeadlessEditorText()];
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
const BLOCK_ID_ATTRIBUTE = 'data-ngs-headless-editor-block-id';
|
|
1610
|
+
const BLOCK_TYPE_ATTRIBUTE = 'data-ngs-headless-editor-block-type';
|
|
1611
|
+
const BLOCK_PLACEHOLDER_ATTRIBUTE = 'data-ngs-headless-editor-placeholder';
|
|
1612
|
+
/** Browser formatting and structure commands the model does not map; they are blocked. */
|
|
1613
|
+
const BLOCKED_INPUT_TYPES = /^(format|insertOrderedList$|insertUnorderedList$|insertHorizontalRule$|insertLink$)/;
|
|
1614
|
+
const componentAcceptsBlock = new WeakMap();
|
|
1615
|
+
/**
|
|
1616
|
+
* Binds an `NgsHeadlessEditor` to a contenteditable element.
|
|
1617
|
+
*
|
|
1618
|
+
* Rendering is keyed by block id. Because the model is immutable, a block whose
|
|
1619
|
+
* object did not change keeps its DOM element untouched; only changed, added and
|
|
1620
|
+
* removed blocks are patched. Browser-owned DOM changes (IME composition, drag and
|
|
1621
|
+
* drop, unmapped input types) are tracked with a MutationObserver, read back only
|
|
1622
|
+
* for the blocks that were touched, and then re-rendered canonically.
|
|
1623
|
+
*/
|
|
1624
|
+
class NgsHeadlessEditorSurface {
|
|
1625
|
+
editor = inject(NgsHeadlessEditor);
|
|
1626
|
+
elementRef = inject(ElementRef);
|
|
1627
|
+
documentRef = inject(DOCUMENT);
|
|
1628
|
+
renderer = inject(Renderer2);
|
|
1629
|
+
zone = inject(NgZone);
|
|
1630
|
+
destroyRef = inject(DestroyRef);
|
|
1631
|
+
injector = inject(Injector);
|
|
1632
|
+
environmentInjector = inject(EnvironmentInjector);
|
|
1633
|
+
appRef = inject(ApplicationRef);
|
|
1634
|
+
placeholder = input('Write something…', /* @ts-ignore */
|
|
1635
|
+
...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
|
|
1636
|
+
ariaLabel = input('Rich text editor', /* @ts-ignore */
|
|
1637
|
+
...(ngDevMode ? [{ debugName: "ariaLabel" }] : /* istanbul ignore next */ []));
|
|
1638
|
+
disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
1639
|
+
spellcheck = input(true, { ...(ngDevMode ? { debugName: "spellcheck" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
|
|
1640
|
+
rendering = false;
|
|
1641
|
+
initialized = false;
|
|
1642
|
+
programmaticFocus = false;
|
|
1643
|
+
removeSelectionListener;
|
|
1644
|
+
rendered = new Map();
|
|
1645
|
+
renderedPlugins = null;
|
|
1646
|
+
mutationObserver = null;
|
|
1647
|
+
pendingMutations = [];
|
|
1648
|
+
constructor() {
|
|
1649
|
+
effect(() => {
|
|
1650
|
+
this.editor.revision();
|
|
1651
|
+
this.editor.plugins();
|
|
1652
|
+
this.editor.readOnly();
|
|
1653
|
+
this.disabled();
|
|
1654
|
+
this.placeholder();
|
|
1655
|
+
const composing = this.editor.composing();
|
|
1656
|
+
if (!this.initialized || composing) {
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
untracked(() => this.renderDocument());
|
|
1660
|
+
});
|
|
1661
|
+
afterNextRender(() => {
|
|
1662
|
+
this.initialized = true;
|
|
1663
|
+
this.renderDocument();
|
|
1664
|
+
this.zone.runOutsideAngular(() => {
|
|
1665
|
+
this.removeSelectionListener = this.renderer.listen(this.documentRef, 'selectionchange', () => this.syncSelectionFromDom());
|
|
1666
|
+
const MutationObserverRef = this.documentRef.defaultView?.MutationObserver;
|
|
1667
|
+
if (MutationObserverRef) {
|
|
1668
|
+
this.mutationObserver = new MutationObserverRef(records => {
|
|
1669
|
+
this.pendingMutations.push(...records);
|
|
1670
|
+
});
|
|
1671
|
+
this.mutationObserver.observe(this.elementRef.nativeElement, {
|
|
1672
|
+
childList: true,
|
|
1673
|
+
characterData: true,
|
|
1674
|
+
subtree: true
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
});
|
|
1678
|
+
});
|
|
1679
|
+
this.destroyRef.onDestroy(() => {
|
|
1680
|
+
this.removeSelectionListener?.();
|
|
1681
|
+
this.mutationObserver?.disconnect();
|
|
1682
|
+
for (const entry of this.rendered.values()) {
|
|
1683
|
+
entry.componentRef?.destroy();
|
|
1684
|
+
}
|
|
1685
|
+
this.rendered.clear();
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1688
|
+
onBeforeInput(event) {
|
|
1689
|
+
if (this.isForeignEvent(event)) {
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
if (this.disabled() || this.editor.readOnly()) {
|
|
1693
|
+
event.preventDefault();
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
if (event.isComposing || this.editor.composing()) {
|
|
1697
|
+
return;
|
|
1698
|
+
}
|
|
1699
|
+
this.syncSelectionFromDom();
|
|
1700
|
+
let handled = true;
|
|
1701
|
+
switch (event.inputType) {
|
|
1702
|
+
case 'insertText':
|
|
1703
|
+
this.editor.insertText(event.data ?? '', 'keyboard');
|
|
1704
|
+
break;
|
|
1705
|
+
case 'insertReplacementText': {
|
|
1706
|
+
// Spellcheck and autocorrect replace the target range, not the caret.
|
|
1707
|
+
const target = this.readTargetRange(event);
|
|
1708
|
+
if (target) {
|
|
1709
|
+
this.editor.setSelection(target);
|
|
1710
|
+
}
|
|
1711
|
+
const text = event.dataTransfer?.getData('text/plain') || event.data || '';
|
|
1712
|
+
if (text) {
|
|
1713
|
+
this.editor.insertText(text, 'keyboard');
|
|
1714
|
+
}
|
|
1715
|
+
else if (target) {
|
|
1716
|
+
this.editor.deleteRange(target, 'keyboard');
|
|
1717
|
+
}
|
|
1718
|
+
break;
|
|
1719
|
+
}
|
|
1720
|
+
case 'insertParagraph':
|
|
1721
|
+
case 'insertLineBreak':
|
|
1722
|
+
this.editor.splitBlock();
|
|
1723
|
+
break;
|
|
1724
|
+
case 'deleteContentBackward':
|
|
1725
|
+
this.editor.deleteBackward();
|
|
1726
|
+
break;
|
|
1727
|
+
case 'deleteContentForward':
|
|
1728
|
+
this.editor.deleteForward();
|
|
1729
|
+
break;
|
|
1730
|
+
case 'deleteByCut': {
|
|
1731
|
+
const selection = this.editor.selection();
|
|
1732
|
+
if (selection) {
|
|
1733
|
+
this.editor.deleteRange(selection, 'keyboard');
|
|
1734
|
+
}
|
|
1735
|
+
break;
|
|
1736
|
+
}
|
|
1737
|
+
case 'historyUndo':
|
|
1738
|
+
this.editor.undo();
|
|
1739
|
+
break;
|
|
1740
|
+
case 'historyRedo':
|
|
1741
|
+
this.editor.redo();
|
|
1742
|
+
break;
|
|
1743
|
+
case 'formatBold':
|
|
1744
|
+
this.editor.toggleMark('bold');
|
|
1745
|
+
break;
|
|
1746
|
+
case 'formatItalic':
|
|
1747
|
+
this.editor.toggleMark('italic');
|
|
1748
|
+
break;
|
|
1749
|
+
case 'formatStrikeThrough':
|
|
1750
|
+
this.editor.toggleMark('strike');
|
|
1751
|
+
break;
|
|
1752
|
+
case 'insertFromPaste':
|
|
1753
|
+
case 'insertFromDrop':
|
|
1754
|
+
case 'insertCompositionText':
|
|
1755
|
+
case 'deleteByDrag':
|
|
1756
|
+
handled = false;
|
|
1757
|
+
break;
|
|
1758
|
+
default:
|
|
1759
|
+
if (event.inputType.startsWith('delete')) {
|
|
1760
|
+
// deleteWordBackward, deleteSoftLineBackward, deleteHardLineForward, ...
|
|
1761
|
+
this.deleteTargetRange(event);
|
|
1762
|
+
}
|
|
1763
|
+
else if (!BLOCKED_INPUT_TYPES.test(event.inputType)) {
|
|
1764
|
+
// Unknown insertions (transpose, yank, ...) mutate the DOM and are read
|
|
1765
|
+
// back into the model by the input handler.
|
|
1766
|
+
handled = false;
|
|
1767
|
+
}
|
|
1768
|
+
break;
|
|
1769
|
+
}
|
|
1770
|
+
if (handled) {
|
|
1771
|
+
event.preventDefault();
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
onKeydown(event) {
|
|
1775
|
+
if (this.isForeignEvent(event) || this.disabled() || this.editor.readOnly() || event.isComposing) {
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
this.syncSelectionFromDom();
|
|
1779
|
+
if (this.editor.handleKeydown(event)) {
|
|
1780
|
+
event.preventDefault();
|
|
1781
|
+
event.stopPropagation();
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
onPaste(event) {
|
|
1785
|
+
if (this.isForeignEvent(event)) {
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
if (this.disabled() || this.editor.readOnly()) {
|
|
1789
|
+
event.preventDefault();
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
this.syncSelectionFromDom();
|
|
1793
|
+
if (this.editor.handlePaste(event)) {
|
|
1794
|
+
event.preventDefault();
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
const text = event.clipboardData?.getData('text/plain');
|
|
1798
|
+
if (typeof text === 'string') {
|
|
1799
|
+
event.preventDefault();
|
|
1800
|
+
this.editor.insertText(text, 'paste');
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
onInput(event) {
|
|
1804
|
+
if (event && this.isForeignEvent(event)) {
|
|
1805
|
+
return;
|
|
1806
|
+
}
|
|
1807
|
+
if (!this.editor.composing() && !this.rendering) {
|
|
1808
|
+
this.commitDomState();
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
onCompositionStart(event) {
|
|
1812
|
+
if (event && this.isForeignEvent(event)) {
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
this.syncSelectionFromDom();
|
|
1816
|
+
this.editor.setComposing(true);
|
|
1817
|
+
}
|
|
1818
|
+
onCompositionEnd(event) {
|
|
1819
|
+
if (event && this.isForeignEvent(event)) {
|
|
1820
|
+
return;
|
|
1821
|
+
}
|
|
1822
|
+
this.editor.setComposing(false);
|
|
1823
|
+
this.commitDomState();
|
|
1824
|
+
}
|
|
1825
|
+
onFocus() {
|
|
1826
|
+
this.editor.setFocused(true);
|
|
1827
|
+
if (!this.programmaticFocus) {
|
|
1828
|
+
this.syncSelectionFromDom();
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
onBlur() {
|
|
1832
|
+
this.editor.setFocused(false);
|
|
1833
|
+
}
|
|
1834
|
+
onClick(event) {
|
|
1835
|
+
if (this.disabled() || this.editor.readOnly()) {
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
const target = event.target;
|
|
1839
|
+
if (target instanceof Element && target.closest('a[data-ngs-headless-editor-mark="link"]')) {
|
|
1840
|
+
event.preventDefault();
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
onPointerDown(event) {
|
|
1844
|
+
if (this.isForeignEvent(event) ||
|
|
1845
|
+
this.disabled() ||
|
|
1846
|
+
this.editor.readOnly() ||
|
|
1847
|
+
!this.editor.empty()) {
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
const block = this.editor.document().blocks.find(item => isNgsHeadlessEditorTextContent(item.content));
|
|
1851
|
+
if (!block) {
|
|
1852
|
+
return;
|
|
1853
|
+
}
|
|
1854
|
+
event.preventDefault();
|
|
1855
|
+
this.elementRef.nativeElement.focus();
|
|
1856
|
+
this.editor.setSelection({
|
|
1857
|
+
anchor: { blockId: block.id, offset: 0 },
|
|
1858
|
+
focus: { blockId: block.id, offset: 0 }
|
|
1859
|
+
});
|
|
1860
|
+
this.restoreSelectionToDom();
|
|
1861
|
+
}
|
|
1862
|
+
focus() {
|
|
1863
|
+
this.programmaticFocus = true;
|
|
1864
|
+
try {
|
|
1865
|
+
this.elementRef.nativeElement.focus();
|
|
1866
|
+
this.restoreSelectionToDom();
|
|
1867
|
+
}
|
|
1868
|
+
finally {
|
|
1869
|
+
this.programmaticFocus = false;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
getSelectionRect() {
|
|
1873
|
+
const root = this.elementRef.nativeElement;
|
|
1874
|
+
const selection = this.documentRef.getSelection();
|
|
1875
|
+
if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
|
|
1876
|
+
return null;
|
|
1877
|
+
}
|
|
1878
|
+
const range = selection.getRangeAt(0);
|
|
1879
|
+
const ancestor = range.commonAncestorContainer;
|
|
1880
|
+
if (ancestor !== root && !root.contains(ancestor)) {
|
|
1881
|
+
return null;
|
|
1882
|
+
}
|
|
1883
|
+
const rect = range.getBoundingClientRect();
|
|
1884
|
+
return rect.width > 0 || rect.height > 0 ? rect : null;
|
|
1885
|
+
}
|
|
1886
|
+
/** Returns the element that currently renders a block, if any. */
|
|
1887
|
+
getBlockElement(blockId) {
|
|
1888
|
+
return this.rendered.get(blockId)?.element ?? null;
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* Events that originate inside a non-editable block (for example an input or a
|
|
1892
|
+
* textarea rendered by a component block) belong to that widget, not to the
|
|
1893
|
+
* editor, even though they bubble through the surface.
|
|
1894
|
+
*/
|
|
1895
|
+
isForeignEvent(event) {
|
|
1896
|
+
const target = event.target;
|
|
1897
|
+
if (!(target instanceof Node) || target === this.elementRef.nativeElement) {
|
|
1898
|
+
return false;
|
|
1899
|
+
}
|
|
1900
|
+
const block = this.closestBlock(target);
|
|
1901
|
+
const entry = block ? this.rendered.get(block.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '') : undefined;
|
|
1902
|
+
return !!entry && entry.element === block && !entry.editable;
|
|
1903
|
+
}
|
|
1904
|
+
// ---------------------------------------------------------------------------
|
|
1905
|
+
// Rendering
|
|
1906
|
+
// ---------------------------------------------------------------------------
|
|
1907
|
+
/**
|
|
1908
|
+
* Brings the DOM in line with the model. Blocks whose object, definition,
|
|
1909
|
+
* placeholder and component did not change are reused as-is; `dirty` forces
|
|
1910
|
+
* a re-render of block elements the browser modified.
|
|
1911
|
+
*/
|
|
1912
|
+
renderDocument(dirty = new Set()) {
|
|
1913
|
+
const root = this.elementRef.nativeElement;
|
|
1914
|
+
const plugins = this.editor.plugins();
|
|
1915
|
+
if (plugins !== this.renderedPlugins) {
|
|
1916
|
+
// Block and mark definitions may have changed: rebuild everything.
|
|
1917
|
+
this.destroyRendered(this.rendered.values());
|
|
1918
|
+
this.rendered = new Map();
|
|
1919
|
+
this.renderedPlugins = plugins;
|
|
1920
|
+
}
|
|
1921
|
+
const interactive = !(this.disabled() || this.editor.readOnly());
|
|
1922
|
+
const documentEmpty = this.editor.empty();
|
|
1923
|
+
const next = new Map();
|
|
1924
|
+
const ordered = [];
|
|
1925
|
+
let placeholderAssigned = false;
|
|
1926
|
+
for (const block of this.editor.document().blocks) {
|
|
1927
|
+
const definition = this.editor.getBlockDefinition(block.type);
|
|
1928
|
+
const component = blockComponent(definition, interactive);
|
|
1929
|
+
let placeholder = null;
|
|
1930
|
+
if (!component &&
|
|
1931
|
+
!definition?.render &&
|
|
1932
|
+
documentEmpty &&
|
|
1933
|
+
!placeholderAssigned &&
|
|
1934
|
+
isNgsHeadlessEditorTextContent(block.content) &&
|
|
1935
|
+
block.content.every(run => run.text.trim().length === 0)) {
|
|
1936
|
+
placeholder = this.placeholder();
|
|
1937
|
+
placeholderAssigned = true;
|
|
1938
|
+
}
|
|
1939
|
+
const previous = this.rendered.get(block.id);
|
|
1940
|
+
let entry;
|
|
1941
|
+
if (previous &&
|
|
1942
|
+
!dirty.has(previous.element) &&
|
|
1943
|
+
previous.definition === definition &&
|
|
1944
|
+
previous.component === component &&
|
|
1945
|
+
(component !== null || (previous.block === block && previous.placeholder === placeholder))) {
|
|
1946
|
+
entry = previous;
|
|
1947
|
+
if (previous.componentRef && previous.block !== block) {
|
|
1948
|
+
// Keep component instances (and their DOM, e.g. a playing video) alive.
|
|
1949
|
+
setComponentBlock(previous.componentRef, component, block);
|
|
1950
|
+
entry = { ...previous, block };
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
else {
|
|
1954
|
+
entry = this.createRenderedBlock(block, definition, component, placeholder);
|
|
1955
|
+
}
|
|
1956
|
+
next.set(block.id, entry);
|
|
1957
|
+
ordered.push(entry.element);
|
|
1958
|
+
}
|
|
1959
|
+
const reusedElements = new Set(ordered);
|
|
1960
|
+
this.destroyRendered([...this.rendered.values()].filter(entry => !reusedElements.has(entry.element)));
|
|
1961
|
+
this.rendered = next;
|
|
1962
|
+
this.rendering = true;
|
|
1963
|
+
try {
|
|
1964
|
+
// Keyed reconciliation: move/insert expected elements, drop anything else
|
|
1965
|
+
// (including stray nodes the browser may have created).
|
|
1966
|
+
let cursor = root.firstChild;
|
|
1967
|
+
for (const element of ordered) {
|
|
1968
|
+
if (cursor === element) {
|
|
1969
|
+
cursor = cursor.nextSibling;
|
|
1970
|
+
continue;
|
|
1971
|
+
}
|
|
1972
|
+
root.insertBefore(element, cursor);
|
|
1973
|
+
}
|
|
1974
|
+
while (cursor) {
|
|
1975
|
+
const nextNode = cursor.nextSibling;
|
|
1976
|
+
root.removeChild(cursor);
|
|
1977
|
+
cursor = nextNode;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
finally {
|
|
1981
|
+
this.rendering = false;
|
|
1982
|
+
}
|
|
1983
|
+
this.discardMutations();
|
|
1984
|
+
if (this.editor.focused()) {
|
|
1985
|
+
this.restoreSelectionToDom();
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
createRenderedBlock(block, definition, component, placeholder) {
|
|
1989
|
+
const element = this.documentRef.createElement(definition?.tagName ?? 'div');
|
|
1990
|
+
element.setAttribute(BLOCK_ID_ATTRIBUTE, block.id);
|
|
1991
|
+
element.setAttribute(BLOCK_TYPE_ATTRIBUTE, block.type);
|
|
1992
|
+
if (component) {
|
|
1993
|
+
element.setAttribute('contenteditable', 'false');
|
|
1994
|
+
const componentRef = createComponent(component, {
|
|
1995
|
+
environmentInjector: this.environmentInjector,
|
|
1996
|
+
elementInjector: this.injector,
|
|
1997
|
+
hostElement: element
|
|
1998
|
+
});
|
|
1999
|
+
setComponentBlock(componentRef, component, block);
|
|
2000
|
+
this.appRef.attachView(componentRef.hostView);
|
|
2001
|
+
componentRef.changeDetectorRef.detectChanges();
|
|
2002
|
+
return { block, element, definition, placeholder, component, componentRef, editable: false };
|
|
2003
|
+
}
|
|
2004
|
+
if (definition?.editable === false) {
|
|
2005
|
+
element.setAttribute('contenteditable', 'false');
|
|
2006
|
+
}
|
|
2007
|
+
if (definition?.render) {
|
|
2008
|
+
definition.render(element, block);
|
|
2009
|
+
}
|
|
2010
|
+
else if (isNgsHeadlessEditorTextContent(block.content)) {
|
|
2011
|
+
const contentRoot = definition?.contentTagName
|
|
2012
|
+
? this.documentRef.createElement(definition.contentTagName)
|
|
2013
|
+
: element;
|
|
2014
|
+
if (placeholder !== null) {
|
|
2015
|
+
contentRoot.setAttribute(BLOCK_PLACEHOLDER_ATTRIBUTE, placeholder);
|
|
2016
|
+
}
|
|
2017
|
+
if (block.content.some(run => run.text.length > 0)) {
|
|
2018
|
+
for (const run of block.content) {
|
|
2019
|
+
contentRoot.append(renderNgsHeadlessEditorTextRun(this.documentRef, run.text, run.marks, this.editor));
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
else {
|
|
2023
|
+
contentRoot.append(this.documentRef.createElement('br'));
|
|
2024
|
+
}
|
|
2025
|
+
if (contentRoot !== element) {
|
|
2026
|
+
element.append(contentRoot);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
return {
|
|
2030
|
+
block,
|
|
2031
|
+
element,
|
|
2032
|
+
definition,
|
|
2033
|
+
placeholder,
|
|
2034
|
+
component: null,
|
|
2035
|
+
componentRef: null,
|
|
2036
|
+
editable: definition?.editable !== false
|
|
2037
|
+
};
|
|
2038
|
+
}
|
|
2039
|
+
destroyRendered(entries) {
|
|
2040
|
+
for (const entry of entries) {
|
|
2041
|
+
entry.componentRef?.destroy();
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
// ---------------------------------------------------------------------------
|
|
2045
|
+
// Reading browser-owned DOM changes back into the model
|
|
2046
|
+
// ---------------------------------------------------------------------------
|
|
2047
|
+
commitDomState() {
|
|
2048
|
+
const dirty = this.collectDirtyBlocks();
|
|
2049
|
+
const selection = this.readSelectionFromDom();
|
|
2050
|
+
const document = this.readDocumentFromDom(dirty);
|
|
2051
|
+
this.editor.commitDomDocument(document, selection);
|
|
2052
|
+
// Replace whatever markup the browser produced with the canonical rendering,
|
|
2053
|
+
// even when the model did not change (e.g. a stray <font> or <div>).
|
|
2054
|
+
this.renderDocument(dirty);
|
|
2055
|
+
}
|
|
2056
|
+
/** Editable block elements touched by the browser since the last render. */
|
|
2057
|
+
collectDirtyBlocks() {
|
|
2058
|
+
const records = [...this.pendingMutations, ...(this.mutationObserver?.takeRecords() ?? [])];
|
|
2059
|
+
this.pendingMutations = [];
|
|
2060
|
+
const root = this.elementRef.nativeElement;
|
|
2061
|
+
const dirty = new Set();
|
|
2062
|
+
const editableElements = new Set([...this.rendered.values()].filter(entry => entry.editable).map(entry => entry.element));
|
|
2063
|
+
const mark = (node) => {
|
|
2064
|
+
const block = node ? this.closestBlock(node) : null;
|
|
2065
|
+
if (block && editableElements.has(block)) {
|
|
2066
|
+
dirty.add(block);
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
for (const record of records) {
|
|
2070
|
+
if (record.target === root) {
|
|
2071
|
+
record.addedNodes.forEach(node => mark(node));
|
|
2072
|
+
continue;
|
|
2073
|
+
}
|
|
2074
|
+
mark(record.target);
|
|
2075
|
+
}
|
|
2076
|
+
// Without MutationObserver support every editable block is treated as dirty.
|
|
2077
|
+
return this.mutationObserver ? dirty : editableElements;
|
|
2078
|
+
}
|
|
2079
|
+
discardMutations() {
|
|
2080
|
+
this.mutationObserver?.takeRecords();
|
|
2081
|
+
this.pendingMutations = [];
|
|
2082
|
+
}
|
|
2083
|
+
readDocumentFromDom(dirty) {
|
|
2084
|
+
const root = this.elementRef.nativeElement;
|
|
2085
|
+
const previousBlocks = new Map(this.editor.document().blocks.map(block => [block.id, block]));
|
|
2086
|
+
const blocks = [];
|
|
2087
|
+
for (const element of root.querySelectorAll(`[${BLOCK_ID_ATTRIBUTE}]`)) {
|
|
2088
|
+
if (element.parentElement?.closest(`[${BLOCK_ID_ATTRIBUTE}]`)) {
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
const id = element.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '';
|
|
2092
|
+
const type = element.getAttribute(BLOCK_TYPE_ATTRIBUTE) ?? 'paragraph';
|
|
2093
|
+
const entry = this.rendered.get(id);
|
|
2094
|
+
const previous = previousBlocks.get(id);
|
|
2095
|
+
if (entry && entry.element === element && !dirty.has(element)) {
|
|
2096
|
+
blocks.push(entry.block);
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
const definition = this.editor.getBlockDefinition(type);
|
|
2100
|
+
if (previous && (entry?.componentRef || definition?.editable === false)) {
|
|
2101
|
+
blocks.push(previous);
|
|
2102
|
+
}
|
|
2103
|
+
else if (definition?.read && previous) {
|
|
2104
|
+
blocks.push(definition.read(element, previous));
|
|
2105
|
+
}
|
|
2106
|
+
else {
|
|
2107
|
+
const read = {
|
|
2108
|
+
id,
|
|
2109
|
+
type,
|
|
2110
|
+
content: normalizeNgsHeadlessEditorTextContent(readNgsHeadlessEditorInlineContent(element, this.editor))
|
|
2111
|
+
};
|
|
2112
|
+
blocks.push(previous && ngsHeadlessEditorBlocksEqual(previous, read) ? previous : read);
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
if (blocks.length === 0) {
|
|
2116
|
+
return createNgsHeadlessEditorDocument(root.textContent ?? '');
|
|
2117
|
+
}
|
|
2118
|
+
return normalizeNgsHeadlessEditorDocument({ version: 1, blocks });
|
|
2119
|
+
}
|
|
2120
|
+
// ---------------------------------------------------------------------------
|
|
2121
|
+
// Selection mapping
|
|
2122
|
+
// ---------------------------------------------------------------------------
|
|
2123
|
+
/** Deletes the range the browser reports for a word/line deletion. */
|
|
2124
|
+
deleteTargetRange(event) {
|
|
2125
|
+
const target = this.readTargetRange(event);
|
|
2126
|
+
if (target) {
|
|
2127
|
+
const collapsed = target.anchor.blockId === target.focus.blockId &&
|
|
2128
|
+
target.anchor.offset === target.focus.offset;
|
|
2129
|
+
if (!collapsed) {
|
|
2130
|
+
this.editor.deleteRange(target, 'keyboard');
|
|
2131
|
+
}
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
if (event.inputType.endsWith('Forward')) {
|
|
2135
|
+
this.editor.deleteForward();
|
|
2136
|
+
}
|
|
2137
|
+
else {
|
|
2138
|
+
this.editor.deleteBackward();
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
readTargetRange(event) {
|
|
2142
|
+
const range = typeof event.getTargetRanges === 'function'
|
|
2143
|
+
? event.getTargetRanges()[0]
|
|
2144
|
+
: undefined;
|
|
2145
|
+
if (!range) {
|
|
2146
|
+
return null;
|
|
2147
|
+
}
|
|
2148
|
+
const anchor = this.domPositionToPoint(range.startContainer, range.startOffset);
|
|
2149
|
+
const focus = this.domPositionToPoint(range.endContainer, range.endOffset);
|
|
2150
|
+
return anchor && focus ? { anchor, focus } : null;
|
|
2151
|
+
}
|
|
2152
|
+
syncSelectionFromDom() {
|
|
2153
|
+
if (this.rendering) {
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
const selection = this.readSelectionFromDom();
|
|
2157
|
+
if (selection) {
|
|
2158
|
+
this.editor.setSelection(selection);
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
readSelectionFromDom() {
|
|
2162
|
+
const nativeSelection = this.documentRef.getSelection();
|
|
2163
|
+
const root = this.elementRef.nativeElement;
|
|
2164
|
+
if (!nativeSelection?.anchorNode || !nativeSelection.focusNode) {
|
|
2165
|
+
return null;
|
|
2166
|
+
}
|
|
2167
|
+
if (!root.contains(nativeSelection.anchorNode) || !root.contains(nativeSelection.focusNode)) {
|
|
2168
|
+
return null;
|
|
2169
|
+
}
|
|
2170
|
+
// Selections inside component blocks belong to their own controls or nested editors.
|
|
2171
|
+
if (this.isInsideComponentBlock(nativeSelection.anchorNode) ||
|
|
2172
|
+
this.isInsideComponentBlock(nativeSelection.focusNode)) {
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
const anchor = this.domPositionToPoint(nativeSelection.anchorNode, nativeSelection.anchorOffset);
|
|
2176
|
+
const focus = this.domPositionToPoint(nativeSelection.focusNode, nativeSelection.focusOffset);
|
|
2177
|
+
return anchor && focus ? { anchor, focus } : null;
|
|
2178
|
+
}
|
|
2179
|
+
domPositionToPoint(node, offset) {
|
|
2180
|
+
const root = this.elementRef.nativeElement;
|
|
2181
|
+
if (node === root) {
|
|
2182
|
+
// Boundary points between blocks are expressed as a child index of the surface.
|
|
2183
|
+
const children = [...root.childNodes];
|
|
2184
|
+
const next = children.slice(offset).find(isBlockElement);
|
|
2185
|
+
if (next) {
|
|
2186
|
+
return { blockId: next.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '', offset: 0 };
|
|
2187
|
+
}
|
|
2188
|
+
const last = children.filter(isBlockElement).at(-1);
|
|
2189
|
+
return last
|
|
2190
|
+
? { blockId: last.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '', offset: last.textContent?.length ?? 0 }
|
|
2191
|
+
: null;
|
|
2192
|
+
}
|
|
2193
|
+
const block = this.closestBlock(node);
|
|
2194
|
+
if (!block) {
|
|
2195
|
+
return null;
|
|
2196
|
+
}
|
|
2197
|
+
const range = this.documentRef.createRange();
|
|
2198
|
+
range.selectNodeContents(block);
|
|
2199
|
+
try {
|
|
2200
|
+
range.setEnd(node, offset);
|
|
2201
|
+
}
|
|
2202
|
+
catch {
|
|
2203
|
+
return null;
|
|
2204
|
+
}
|
|
2205
|
+
return {
|
|
2206
|
+
blockId: block.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '',
|
|
2207
|
+
offset: range.toString().length
|
|
2208
|
+
};
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* The top-level block element that contains a node. Only direct children of
|
|
2212
|
+
* the surface are blocks of this editor; elements with block attributes deeper
|
|
2213
|
+
* down belong to nested editors (for example inside a table cell).
|
|
2214
|
+
*/
|
|
2215
|
+
closestBlock(node) {
|
|
2216
|
+
const root = this.elementRef.nativeElement;
|
|
2217
|
+
let current = node;
|
|
2218
|
+
while (current && current.parentNode !== root) {
|
|
2219
|
+
current = current.parentNode;
|
|
2220
|
+
}
|
|
2221
|
+
return current instanceof HTMLElement && current.hasAttribute(BLOCK_ID_ATTRIBUTE) ? current : null;
|
|
2222
|
+
}
|
|
2223
|
+
/** True when a node is inside a block rendered by an Angular component. */
|
|
2224
|
+
isInsideComponentBlock(node) {
|
|
2225
|
+
const block = this.closestBlock(node);
|
|
2226
|
+
const entry = block ? this.rendered.get(block.getAttribute(BLOCK_ID_ATTRIBUTE) ?? '') : undefined;
|
|
2227
|
+
return !!entry && entry.element === block && entry.componentRef !== null;
|
|
2228
|
+
}
|
|
2229
|
+
restoreSelectionToDom() {
|
|
2230
|
+
const selection = this.editor.selection();
|
|
2231
|
+
if (!selection) {
|
|
2232
|
+
return;
|
|
2233
|
+
}
|
|
2234
|
+
const anchor = this.pointToDomPosition(selection.anchor);
|
|
2235
|
+
const focus = this.pointToDomPosition(selection.focus);
|
|
2236
|
+
if (!anchor || !focus) {
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
const nativeSelection = this.documentRef.getSelection();
|
|
2240
|
+
if (!nativeSelection) {
|
|
2241
|
+
return;
|
|
2242
|
+
}
|
|
2243
|
+
if (nativeSelection.anchorNode === anchor.node &&
|
|
2244
|
+
nativeSelection.anchorOffset === anchor.offset &&
|
|
2245
|
+
nativeSelection.focusNode === focus.node &&
|
|
2246
|
+
nativeSelection.focusOffset === focus.offset) {
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
try {
|
|
2250
|
+
nativeSelection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
|
|
2251
|
+
}
|
|
2252
|
+
catch {
|
|
2253
|
+
const range = this.documentRef.createRange();
|
|
2254
|
+
range.setStart(anchor.node, anchor.offset);
|
|
2255
|
+
range.setEnd(focus.node, focus.offset);
|
|
2256
|
+
nativeSelection.removeAllRanges();
|
|
2257
|
+
nativeSelection.addRange(range);
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
pointToDomPosition(point) {
|
|
2261
|
+
const block = this.rendered.get(point.blockId)?.element;
|
|
2262
|
+
if (!block?.isConnected) {
|
|
2263
|
+
return null;
|
|
2264
|
+
}
|
|
2265
|
+
const walker = this.documentRef.createTreeWalker(block, NodeFilter.SHOW_TEXT);
|
|
2266
|
+
let remaining = point.offset;
|
|
2267
|
+
let textNode = walker.nextNode();
|
|
2268
|
+
while (textNode) {
|
|
2269
|
+
const length = textNode.textContent?.length ?? 0;
|
|
2270
|
+
if (remaining <= length) {
|
|
2271
|
+
const atomic = textNode.parentElement?.closest('[data-ngs-headless-editor-atomic]');
|
|
2272
|
+
if (atomic?.parentNode) {
|
|
2273
|
+
return {
|
|
2274
|
+
node: atomic.parentNode,
|
|
2275
|
+
offset: [...atomic.parentNode.childNodes].indexOf(atomic) + (remaining === 0 ? 0 : 1)
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
return { node: textNode, offset: remaining };
|
|
2279
|
+
}
|
|
2280
|
+
remaining -= length;
|
|
2281
|
+
textNode = walker.nextNode();
|
|
2282
|
+
}
|
|
2283
|
+
return { node: block, offset: 0 };
|
|
2284
|
+
}
|
|
2285
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorSurface, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
2286
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: NgsHeadlessEditorSurface, isStandalone: true, selector: "[ngsHeadlessEditorSurface]", inputs: { placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, ariaLabel: { classPropertyName: "ariaLabel", publicName: "ariaLabel", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, spellcheck: { classPropertyName: "spellcheck", publicName: "spellcheck", isSignal: true, isRequired: false, transformFunction: null } }, host: { attributes: { "role": "textbox" }, listeners: { "beforeinput": "onBeforeInput($event)", "keydown": "onKeydown($event)", "paste": "onPaste($event)", "input": "onInput($event)", "compositionstart": "onCompositionStart($event)", "compositionend": "onCompositionEnd($event)", "focus": "onFocus()", "blur": "onBlur()", "click": "onClick($event)", "pointerdown": "onPointerDown($event)" }, properties: { "attr.contenteditable": "(disabled() || editor.readOnly()) ? \"false\" : \"true\"", "attr.aria-disabled": "(disabled() || editor.readOnly()).toString()", "attr.aria-label": "ariaLabel()", "attr.aria-multiline": "true", "attr.data-placeholder": "placeholder()", "attr.data-empty": "editor.empty() ? \"\" : null", "attr.spellcheck": "spellcheck().toString()" }, classAttribute: "ngs-headless-editor-surface" }, exportAs: ["ngsHeadlessEditorSurface"], ngImport: i0 });
|
|
2287
|
+
}
|
|
2288
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorSurface, decorators: [{
|
|
2289
|
+
type: Directive,
|
|
2290
|
+
args: [{
|
|
2291
|
+
selector: '[ngsHeadlessEditorSurface]',
|
|
2292
|
+
exportAs: 'ngsHeadlessEditorSurface',
|
|
2293
|
+
host: {
|
|
2294
|
+
'class': 'ngs-headless-editor-surface',
|
|
2295
|
+
'role': 'textbox',
|
|
2296
|
+
'[attr.contenteditable]': '(disabled() || editor.readOnly()) ? "false" : "true"',
|
|
2297
|
+
'[attr.aria-disabled]': '(disabled() || editor.readOnly()).toString()',
|
|
2298
|
+
'[attr.aria-label]': 'ariaLabel()',
|
|
2299
|
+
'[attr.aria-multiline]': 'true',
|
|
2300
|
+
'[attr.data-placeholder]': 'placeholder()',
|
|
2301
|
+
'[attr.data-empty]': 'editor.empty() ? "" : null',
|
|
2302
|
+
'[attr.spellcheck]': 'spellcheck().toString()',
|
|
2303
|
+
'(beforeinput)': 'onBeforeInput($event)',
|
|
2304
|
+
'(keydown)': 'onKeydown($event)',
|
|
2305
|
+
'(paste)': 'onPaste($event)',
|
|
2306
|
+
'(input)': 'onInput($event)',
|
|
2307
|
+
'(compositionstart)': 'onCompositionStart($event)',
|
|
2308
|
+
'(compositionend)': 'onCompositionEnd($event)',
|
|
2309
|
+
'(focus)': 'onFocus()',
|
|
2310
|
+
'(blur)': 'onBlur()',
|
|
2311
|
+
'(click)': 'onClick($event)',
|
|
2312
|
+
'(pointerdown)': 'onPointerDown($event)'
|
|
2313
|
+
}
|
|
2314
|
+
}]
|
|
2315
|
+
}], ctorParameters: () => [], propDecorators: { placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], ariaLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "ariaLabel", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], spellcheck: [{ type: i0.Input, args: [{ isSignal: true, alias: "spellcheck", required: false }] }] } });
|
|
2316
|
+
function isBlockElement(node) {
|
|
2317
|
+
return node instanceof HTMLElement && node.hasAttribute(BLOCK_ID_ATTRIBUTE);
|
|
2318
|
+
}
|
|
2319
|
+
function blockComponent(definition, interactive) {
|
|
2320
|
+
const component = interactive
|
|
2321
|
+
? definition?.editorComponent ?? definition?.rendererComponent
|
|
2322
|
+
: definition?.rendererComponent ?? definition?.editorComponent;
|
|
2323
|
+
return component ?? null;
|
|
2324
|
+
}
|
|
2325
|
+
function setComponentBlock(componentRef, component, block) {
|
|
2326
|
+
if (!component) {
|
|
2327
|
+
return;
|
|
2328
|
+
}
|
|
2329
|
+
let accepts = componentAcceptsBlock.get(component);
|
|
2330
|
+
if (accepts === undefined) {
|
|
2331
|
+
accepts = reflectComponentType(component)?.inputs.some(item => item.templateName === 'block') ?? false;
|
|
2332
|
+
componentAcceptsBlock.set(component, accepts);
|
|
2333
|
+
}
|
|
2334
|
+
if (accepts) {
|
|
2335
|
+
componentRef.setInput('block', block);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
class NgsHeadlessEditorCommandDirective {
|
|
2340
|
+
editor = inject(NgsHeadlessEditor);
|
|
2341
|
+
command = input.required({ ...(ngDevMode ? { debugName: "command" } : /* istanbul ignore next */ {}), alias: 'ngsHeadlessEditorCommand' });
|
|
2342
|
+
commandData = input(/* @ts-ignore */
|
|
2343
|
+
...(ngDevMode ? [undefined, { debugName: "commandData" }] : /* istanbul ignore next */ []));
|
|
2344
|
+
active = computed(() => this.editor.isCommandActive(this.command(), this.commandData()), /* @ts-ignore */
|
|
2345
|
+
...(ngDevMode ? [{ debugName: "active" }] : /* istanbul ignore next */ []));
|
|
2346
|
+
disabled = computed(() => !this.editor.isCommandEnabled(this.command(), this.commandData()), /* @ts-ignore */
|
|
2347
|
+
...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
|
|
2348
|
+
preserveSelection(event) {
|
|
2349
|
+
event.preventDefault();
|
|
2350
|
+
}
|
|
2351
|
+
execute(event) {
|
|
2352
|
+
event.preventDefault();
|
|
2353
|
+
if (!this.disabled()) {
|
|
2354
|
+
this.editor.execute(this.command(), this.commandData());
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorCommandDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
2358
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: NgsHeadlessEditorCommandDirective, isStandalone: true, selector: "[ngsHeadlessEditorCommand]", inputs: { command: { classPropertyName: "command", publicName: "ngsHeadlessEditorCommand", isSignal: true, isRequired: true, transformFunction: null }, commandData: { classPropertyName: "commandData", publicName: "commandData", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "mousedown": "preserveSelection($event)", "click": "execute($event)" }, properties: { "class.active": "active()", "attr.disabled": "disabled() ? \"\" : null", "attr.aria-pressed": "active().toString()" } }, exportAs: ["ngsHeadlessEditorCommand"], ngImport: i0 });
|
|
2359
|
+
}
|
|
2360
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorCommandDirective, decorators: [{
|
|
2361
|
+
type: Directive,
|
|
2362
|
+
args: [{
|
|
2363
|
+
selector: '[ngsHeadlessEditorCommand]',
|
|
2364
|
+
exportAs: 'ngsHeadlessEditorCommand',
|
|
2365
|
+
host: {
|
|
2366
|
+
'(mousedown)': 'preserveSelection($event)',
|
|
2367
|
+
'(click)': 'execute($event)',
|
|
2368
|
+
'[class.active]': 'active()',
|
|
2369
|
+
'[attr.disabled]': 'disabled() ? "" : null',
|
|
2370
|
+
'[attr.aria-pressed]': 'active().toString()'
|
|
2371
|
+
}
|
|
2372
|
+
}]
|
|
2373
|
+
}], propDecorators: { command: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsHeadlessEditorCommand", required: true }] }], commandData: [{ type: i0.Input, args: [{ isSignal: true, alias: "commandData", required: false }] }] } });
|
|
2374
|
+
|
|
2375
|
+
/** Block type used by the table plugin. */
|
|
2376
|
+
const NGS_HEADLESS_EDITOR_TABLE_TYPE = 'table';
|
|
2377
|
+
const MAX_ROWS = 500;
|
|
2378
|
+
const MAX_COLUMNS = 50;
|
|
2379
|
+
function clampCount(value, max) {
|
|
2380
|
+
return Math.max(1, Math.min(max, Math.floor(Number.isFinite(value) ? value : 1)));
|
|
2381
|
+
}
|
|
2382
|
+
function emptyCell() {
|
|
2383
|
+
return [createNgsHeadlessEditorText()];
|
|
2384
|
+
}
|
|
2385
|
+
/** Normalizes one cell from plain text, text runs or untrusted JSON. */
|
|
2386
|
+
function normalizeNgsHeadlessEditorTableCell(cell) {
|
|
2387
|
+
if (typeof cell === 'string') {
|
|
2388
|
+
return [createNgsHeadlessEditorText(cell)];
|
|
2389
|
+
}
|
|
2390
|
+
if (Array.isArray(cell)) {
|
|
2391
|
+
const runs = cell
|
|
2392
|
+
.filter((run) => (typeof run === 'object' && run !== null && typeof run.text === 'string'))
|
|
2393
|
+
.map(run => createNgsHeadlessEditorText(run.text, Array.isArray(run.marks) ? run.marks : []));
|
|
2394
|
+
return isNgsHeadlessEditorTextContent(runs) && runs.length > 0
|
|
2395
|
+
? normalizeNgsHeadlessEditorTextContent(runs)
|
|
2396
|
+
: emptyCell();
|
|
2397
|
+
}
|
|
2398
|
+
return cell === null || cell === undefined ? emptyCell() : [createNgsHeadlessEditorText(String(cell))];
|
|
2399
|
+
}
|
|
2400
|
+
/** Makes the rows rectangular, normalizes every cell and keeps at least one cell. */
|
|
2401
|
+
function normalizeNgsHeadlessEditorTableRows(rows) {
|
|
2402
|
+
const source = Array.isArray(rows) ? rows : [];
|
|
2403
|
+
const normalized = source
|
|
2404
|
+
.slice(0, MAX_ROWS)
|
|
2405
|
+
.map(row => (Array.isArray(row) ? row : []).slice(0, MAX_COLUMNS).map(normalizeNgsHeadlessEditorTableCell));
|
|
2406
|
+
const columns = Math.max(1, ...normalized.map(row => row.length));
|
|
2407
|
+
const result = normalized.map(row => [...row, ...Array.from({ length: columns - row.length }, emptyCell)]);
|
|
2408
|
+
return result.length > 0 ? result : [Array.from({ length: columns }, emptyCell)];
|
|
2409
|
+
}
|
|
2410
|
+
/** Plain text of a cell. */
|
|
2411
|
+
function getNgsHeadlessEditorTableCellText(cell) {
|
|
2412
|
+
return cell.map(run => run.text).join('');
|
|
2413
|
+
}
|
|
2414
|
+
/** Reads and normalizes the table data of a block. */
|
|
2415
|
+
function getNgsHeadlessEditorTableData(block) {
|
|
2416
|
+
return {
|
|
2417
|
+
rows: normalizeNgsHeadlessEditorTableRows(block.attrs?.['rows']),
|
|
2418
|
+
header: block.attrs?.['header'] === true
|
|
2419
|
+
};
|
|
2420
|
+
}
|
|
2421
|
+
/** Creates a table block from cell text or from a size. */
|
|
2422
|
+
function createNgsHeadlessEditorTable(source, header = true) {
|
|
2423
|
+
const rows = Array.isArray(source)
|
|
2424
|
+
? normalizeNgsHeadlessEditorTableRows(source)
|
|
2425
|
+
: Array.from({ length: clampCount(source.rows, MAX_ROWS) }, () => Array.from({ length: clampCount(source.columns, MAX_COLUMNS) }, emptyCell));
|
|
2426
|
+
const withHeader = Array.isArray(source) ? header : source.header ?? header;
|
|
2427
|
+
return {
|
|
2428
|
+
id: createNgsHeadlessEditorId(NGS_HEADLESS_EDITOR_TABLE_TYPE),
|
|
2429
|
+
type: NGS_HEADLESS_EDITOR_TABLE_TYPE,
|
|
2430
|
+
content: null,
|
|
2431
|
+
attrs: { rows, header: withHeader }
|
|
2432
|
+
};
|
|
2433
|
+
}
|
|
2434
|
+
function isNgsHeadlessEditorTable(block) {
|
|
2435
|
+
return block?.type === NGS_HEADLESS_EDITOR_TABLE_TYPE;
|
|
2436
|
+
}
|
|
2437
|
+
// ---------------------------------------------------------------------------
|
|
2438
|
+
// Pure table operations. Each returns new data and never mutates the input.
|
|
2439
|
+
// ---------------------------------------------------------------------------
|
|
2440
|
+
function setNgsHeadlessEditorTableCell(data, row, column, content) {
|
|
2441
|
+
const next = normalizeNgsHeadlessEditorTableCell(content);
|
|
2442
|
+
return {
|
|
2443
|
+
...data,
|
|
2444
|
+
rows: data.rows.map((cells, rowIndex) => rowIndex !== row
|
|
2445
|
+
? cells
|
|
2446
|
+
: cells.map((cell, columnIndex) => columnIndex === column ? next : cell))
|
|
2447
|
+
};
|
|
2448
|
+
}
|
|
2449
|
+
function insertNgsHeadlessEditorTableRow(data, index) {
|
|
2450
|
+
const columns = data.rows[0]?.length ?? 1;
|
|
2451
|
+
const rows = [...data.rows];
|
|
2452
|
+
rows.splice(Math.max(0, Math.min(index, rows.length)), 0, Array.from({ length: columns }, emptyCell));
|
|
2453
|
+
return { ...data, rows };
|
|
2454
|
+
}
|
|
2455
|
+
function removeNgsHeadlessEditorTableRow(data, index) {
|
|
2456
|
+
if (data.rows.length <= 1) {
|
|
2457
|
+
return data;
|
|
2458
|
+
}
|
|
2459
|
+
return { ...data, rows: data.rows.filter((_, rowIndex) => rowIndex !== index) };
|
|
2460
|
+
}
|
|
2461
|
+
function insertNgsHeadlessEditorTableColumn(data, index) {
|
|
2462
|
+
return {
|
|
2463
|
+
...data,
|
|
2464
|
+
rows: data.rows.map(cells => {
|
|
2465
|
+
const next = [...cells];
|
|
2466
|
+
next.splice(Math.max(0, Math.min(index, next.length)), 0, emptyCell());
|
|
2467
|
+
return next;
|
|
2468
|
+
})
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
2471
|
+
function removeNgsHeadlessEditorTableColumn(data, index) {
|
|
2472
|
+
if ((data.rows[0]?.length ?? 0) <= 1) {
|
|
2473
|
+
return data;
|
|
2474
|
+
}
|
|
2475
|
+
return { ...data, rows: data.rows.map(cells => cells.filter((_, columnIndex) => columnIndex !== index)) };
|
|
2476
|
+
}
|
|
2477
|
+
// ---------------------------------------------------------------------------
|
|
2478
|
+
// Clipboard parsing
|
|
2479
|
+
// ---------------------------------------------------------------------------
|
|
2480
|
+
/**
|
|
2481
|
+
* Parses tab-separated text as copied from Excel, Google Sheets or Numbers.
|
|
2482
|
+
* Returns null unless the text has at least two cells. Quoted cells with tabs,
|
|
2483
|
+
* newlines and doubled quotes are supported.
|
|
2484
|
+
*/
|
|
2485
|
+
function parseNgsHeadlessEditorTableText(text) {
|
|
2486
|
+
const source = (text ?? '').replace(/\r\n?/g, '\n').replace(/\n$/, '');
|
|
2487
|
+
if (!source.includes('\t')) {
|
|
2488
|
+
return null;
|
|
2489
|
+
}
|
|
2490
|
+
const rows = [];
|
|
2491
|
+
let row = [];
|
|
2492
|
+
let cell = '';
|
|
2493
|
+
let quoted = false;
|
|
2494
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
2495
|
+
const char = source[index];
|
|
2496
|
+
if (quoted) {
|
|
2497
|
+
if (char === '"' && source[index + 1] === '"') {
|
|
2498
|
+
cell += '"';
|
|
2499
|
+
index += 1;
|
|
2500
|
+
}
|
|
2501
|
+
else if (char === '"') {
|
|
2502
|
+
quoted = false;
|
|
2503
|
+
}
|
|
2504
|
+
else {
|
|
2505
|
+
cell += char;
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
else if (char === '"' && cell.length === 0) {
|
|
2509
|
+
quoted = true;
|
|
2510
|
+
}
|
|
2511
|
+
else if (char === '\t') {
|
|
2512
|
+
row.push(cell);
|
|
2513
|
+
cell = '';
|
|
2514
|
+
}
|
|
2515
|
+
else if (char === '\n') {
|
|
2516
|
+
row.push(cell);
|
|
2517
|
+
rows.push(row);
|
|
2518
|
+
row = [];
|
|
2519
|
+
cell = '';
|
|
2520
|
+
}
|
|
2521
|
+
else {
|
|
2522
|
+
cell += char;
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
row.push(cell);
|
|
2526
|
+
rows.push(row);
|
|
2527
|
+
// Only a real grid counts: the same number of cells (at least two) in every
|
|
2528
|
+
// row and some row with two filled cells. This keeps tab-indented code and
|
|
2529
|
+
// prose with a stray tab from turning into tables.
|
|
2530
|
+
const columns = rows[0].length;
|
|
2531
|
+
const isGrid = columns >= 2 &&
|
|
2532
|
+
rows.every(cells => cells.length === columns) &&
|
|
2533
|
+
rows.some(cells => cells.filter(value => value.trim().length > 0).length >= 2);
|
|
2534
|
+
return isGrid ? normalizeNgsHeadlessEditorTableRows(rows) : null;
|
|
2535
|
+
}
|
|
2536
|
+
/**
|
|
2537
|
+
* Extracts the table from clipboard HTML (text content only; markup and
|
|
2538
|
+
* attributes are discarded). Returns null when the clipboard also contains text
|
|
2539
|
+
* outside the table, so copying an article that happens to include a table is
|
|
2540
|
+
* pasted as text, and on the server where there is no DOMParser.
|
|
2541
|
+
*/
|
|
2542
|
+
function parseNgsHeadlessEditorTableHtml(html, marks) {
|
|
2543
|
+
if (!html || !/<table[\s>]/i.test(html) || typeof DOMParser === 'undefined') {
|
|
2544
|
+
return null;
|
|
2545
|
+
}
|
|
2546
|
+
const parsed = new DOMParser().parseFromString(html, 'text/html');
|
|
2547
|
+
const table = parsed.querySelector('table');
|
|
2548
|
+
if (!table) {
|
|
2549
|
+
return null;
|
|
2550
|
+
}
|
|
2551
|
+
const outside = (parsed.body.textContent ?? '').replace(table.textContent ?? '', '').trim();
|
|
2552
|
+
if (outside.length > 0) {
|
|
2553
|
+
return null;
|
|
2554
|
+
}
|
|
2555
|
+
const registry = marks ?? { getMarkDefinition: () => undefined, getMarkDefinitions: () => [] };
|
|
2556
|
+
const rows = [...table.querySelectorAll('tr')].map(row => [...row.querySelectorAll('th, td')].map(cell => (trimRuns(readNgsHeadlessEditorInlineContent(cell, registry, { lineBreaks: true })
|
|
2557
|
+
.map(run => createNgsHeadlessEditorText(run.text.replace(/\u00a0/g, ' '), run.marks))))));
|
|
2558
|
+
const filtered = rows.filter(row => row.length > 0);
|
|
2559
|
+
return filtered.length > 0 ? normalizeNgsHeadlessEditorTableRows(filtered) : null;
|
|
2560
|
+
}
|
|
2561
|
+
/** Trims whitespace at both ends of a cell while keeping marks. */
|
|
2562
|
+
function trimRuns(runs) {
|
|
2563
|
+
const result = runs.map(run => ({ ...run }));
|
|
2564
|
+
while (result.length > 0 && result[0].text.trim() === '') {
|
|
2565
|
+
result.shift();
|
|
2566
|
+
}
|
|
2567
|
+
while (result.length > 0 && result[result.length - 1].text.trim() === '') {
|
|
2568
|
+
result.pop();
|
|
2569
|
+
}
|
|
2570
|
+
if (result.length === 0) {
|
|
2571
|
+
return emptyCell();
|
|
2572
|
+
}
|
|
2573
|
+
result[0] = { ...result[0], text: result[0].text.replace(/^\s+/, '') };
|
|
2574
|
+
const last = result.length - 1;
|
|
2575
|
+
result[last] = { ...result[last], text: result[last].text.replace(/\s+$/, '') };
|
|
2576
|
+
return normalizeNgsHeadlessEditorTextContent(result);
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
const states = new WeakMap();
|
|
2580
|
+
function state(editor) {
|
|
2581
|
+
let current = states.get(editor);
|
|
2582
|
+
if (!current) {
|
|
2583
|
+
current = { cell: signal(null), pendingFocus: signal(null) };
|
|
2584
|
+
states.set(editor, current);
|
|
2585
|
+
}
|
|
2586
|
+
return current;
|
|
2587
|
+
}
|
|
2588
|
+
/**
|
|
2589
|
+
* The table cell that currently has focus, or the last focused one while focus
|
|
2590
|
+
* is on a toolbar control. Table commands operate on this cell.
|
|
2591
|
+
*/
|
|
2592
|
+
function ngsHeadlessEditorActiveTableCell(editor) {
|
|
2593
|
+
return state(editor).cell.asReadonly();
|
|
2594
|
+
}
|
|
2595
|
+
/** @internal Used by the table component. */
|
|
2596
|
+
function setNgsHeadlessEditorActiveTableCell(editor, cell) {
|
|
2597
|
+
state(editor).cell.set(cell);
|
|
2598
|
+
}
|
|
2599
|
+
/** Moves focus to a table cell once its table is rendered. */
|
|
2600
|
+
function focusNgsHeadlessEditorTableCell(editor, cell) {
|
|
2601
|
+
state(editor).cell.set(cell);
|
|
2602
|
+
state(editor).pendingFocus.set(cell);
|
|
2603
|
+
}
|
|
2604
|
+
/** @internal Used by the table component. */
|
|
2605
|
+
function pendingNgsHeadlessEditorTableFocus(editor) {
|
|
2606
|
+
return state(editor).pendingFocus;
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
/**
|
|
2610
|
+
* Provides a nested editor for rich text inside a component block, for example a
|
|
2611
|
+
* table cell or a caption. Add it to the component's providers; the component
|
|
2612
|
+
* then injects NgsHeadlessEditorInlineRegion and renders an
|
|
2613
|
+
* ngsHeadlessEditorSurface, which binds to the nested editor.
|
|
2614
|
+
*/
|
|
2615
|
+
function provideNgsHeadlessEditorInlineRegion() {
|
|
2616
|
+
return [...provideNgsHeadlessEditor(), NgsHeadlessEditorInlineRegion];
|
|
2617
|
+
}
|
|
2618
|
+
/**
|
|
2619
|
+
* A small editor for inline rich text that lives inside a block of a parent
|
|
2620
|
+
* editor. It reuses the parent's marks, mark commands and key bindings, sends
|
|
2621
|
+
* undo and redo to the parent history, and, while active, becomes the parent's
|
|
2622
|
+
* inline target so toolbar formatting commands apply to it.
|
|
2623
|
+
*
|
|
2624
|
+
* Content is exchanged as text runs; line breaks are "\n" characters.
|
|
2625
|
+
*/
|
|
2626
|
+
class NgsHeadlessEditorInlineRegion {
|
|
2627
|
+
/** Editor of the document that contains the region. */
|
|
2628
|
+
parent = inject(NgsHeadlessEditor, { skipSelf: true });
|
|
2629
|
+
/** Nested editor that edits the region. */
|
|
2630
|
+
editor = inject(NgsHeadlessEditor);
|
|
2631
|
+
options = signal({ marks: true }, /* @ts-ignore */
|
|
2632
|
+
...(ngDevMode ? [{ debugName: "options" }] : /* istanbul ignore next */ []));
|
|
2633
|
+
/** True while formatting commands of the parent act on this region. */
|
|
2634
|
+
active = computed(() => this.parent.inlineTarget() === this.editor, /* @ts-ignore */
|
|
2635
|
+
...(ngDevMode ? [{ debugName: "active" }] : /* istanbul ignore next */ []));
|
|
2636
|
+
/** Region content as text runs. */
|
|
2637
|
+
content = computed(() => documentToRuns(this.editor.document()), /* @ts-ignore */
|
|
2638
|
+
...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
|
|
2639
|
+
constructor() {
|
|
2640
|
+
effect(() => {
|
|
2641
|
+
const plugins = this.parent.plugins();
|
|
2642
|
+
const options = this.options();
|
|
2643
|
+
untracked(() => this.editor.setPlugins([createInlinePlugin(this.parent, plugins, options)]));
|
|
2644
|
+
});
|
|
2645
|
+
effect(() => {
|
|
2646
|
+
const readOnly = this.parent.readOnly();
|
|
2647
|
+
untracked(() => this.editor.setReadOnly(readOnly));
|
|
2648
|
+
});
|
|
2649
|
+
inject(DestroyRef).onDestroy(() => this.deactivate());
|
|
2650
|
+
}
|
|
2651
|
+
configure(options) {
|
|
2652
|
+
this.options.set({ marks: true, ...options });
|
|
2653
|
+
}
|
|
2654
|
+
/** Makes the region the parent's inline target. */
|
|
2655
|
+
activate() {
|
|
2656
|
+
this.parent.setInlineTarget(this.editor);
|
|
2657
|
+
}
|
|
2658
|
+
deactivate() {
|
|
2659
|
+
if (this.parent.inlineTarget() === this.editor) {
|
|
2660
|
+
this.parent.setInlineTarget(null);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
/**
|
|
2664
|
+
* Loads content into the nested editor unless it already shows it. The caret
|
|
2665
|
+
* position is kept when possible.
|
|
2666
|
+
*/
|
|
2667
|
+
load(content) {
|
|
2668
|
+
const next = normalizeNgsHeadlessEditorTextContent(content);
|
|
2669
|
+
if (ngsHeadlessEditorValuesEqual(next, this.content())) {
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
const selection = this.editor.selection();
|
|
2673
|
+
this.editor.setDocument(runsToDocument(next));
|
|
2674
|
+
if (selection) {
|
|
2675
|
+
this.editor.setSelection(selection);
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorInlineRegion, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
2679
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorInlineRegion });
|
|
2680
|
+
}
|
|
2681
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorInlineRegion, decorators: [{
|
|
2682
|
+
type: Injectable
|
|
2683
|
+
}], ctorParameters: () => [] });
|
|
2684
|
+
function createInlinePlugin(parent, plugins, options) {
|
|
2685
|
+
const allowed = (mark) => {
|
|
2686
|
+
if (mark.nested === false || options.marks === false) {
|
|
2687
|
+
return false;
|
|
2688
|
+
}
|
|
2689
|
+
return Array.isArray(options.marks) ? options.marks.includes(mark.type) : true;
|
|
2690
|
+
};
|
|
2691
|
+
const undo = { id: 'inline-region-undo', execute: () => parent.undo() };
|
|
2692
|
+
const redo = { id: 'inline-region-redo', execute: () => parent.redo() };
|
|
2693
|
+
const keymap = [
|
|
2694
|
+
// Region edits are recorded in the parent history.
|
|
2695
|
+
{ key: 'Mod-z', command: undo },
|
|
2696
|
+
{ key: 'Mod-Shift-z', command: redo },
|
|
2697
|
+
{ key: 'Mod-y', command: redo },
|
|
2698
|
+
...plugins.flatMap(plugin => plugin.keymap ?? [])
|
|
2699
|
+
];
|
|
2700
|
+
return defineNgsHeadlessEditorPlugin({
|
|
2701
|
+
id: 'inline-region',
|
|
2702
|
+
blocks: [
|
|
2703
|
+
plugins.flatMap(plugin => plugin.blocks ?? []).find(block => block.type === 'paragraph') ?? {
|
|
2704
|
+
type: 'paragraph',
|
|
2705
|
+
tagName: 'p',
|
|
2706
|
+
create: () => ({ id: 'line-0', type: 'paragraph', content: [createNgsHeadlessEditorText()] })
|
|
2707
|
+
}
|
|
2708
|
+
],
|
|
2709
|
+
marks: plugins.flatMap(plugin => plugin.marks ?? []).filter(allowed),
|
|
2710
|
+
commands: [undo, redo, ...plugins.flatMap(plugin => plugin.commands ?? [])],
|
|
2711
|
+
keymap
|
|
2712
|
+
});
|
|
2713
|
+
}
|
|
2714
|
+
/** Splits runs on "\n" into paragraphs with stable ids, so the caret survives reloads. */
|
|
2715
|
+
function runsToDocument(runs) {
|
|
2716
|
+
const lines = [[]];
|
|
2717
|
+
for (const run of runs) {
|
|
2718
|
+
run.text.split('\n').forEach((part, index) => {
|
|
2719
|
+
if (index > 0) {
|
|
2720
|
+
lines.push([]);
|
|
2721
|
+
}
|
|
2722
|
+
if (part) {
|
|
2723
|
+
lines[lines.length - 1].push(createNgsHeadlessEditorText(part, run.marks));
|
|
2724
|
+
}
|
|
2725
|
+
});
|
|
2726
|
+
}
|
|
2727
|
+
return {
|
|
2728
|
+
version: 1,
|
|
2729
|
+
blocks: lines.map((line, index) => ({
|
|
2730
|
+
id: `line-${index}`,
|
|
2731
|
+
type: 'paragraph',
|
|
2732
|
+
content: normalizeNgsHeadlessEditorTextContent(line)
|
|
2733
|
+
}))
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
function documentToRuns(document) {
|
|
2737
|
+
const runs = [];
|
|
2738
|
+
document.blocks.forEach((block, index) => {
|
|
2739
|
+
if (index > 0) {
|
|
2740
|
+
runs.push(createNgsHeadlessEditorText('\n'));
|
|
2741
|
+
}
|
|
2742
|
+
if (isNgsHeadlessEditorTextContent(block.content)) {
|
|
2743
|
+
runs.push(...block.content);
|
|
2744
|
+
}
|
|
2745
|
+
});
|
|
2746
|
+
return normalizeNgsHeadlessEditorTextContent(runs);
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
/**
|
|
2750
|
+
* Renders text runs with the mark definitions of the nearest editor, exactly as
|
|
2751
|
+
* the surface renders them. Use it for read-only previews of rich text such as
|
|
2752
|
+
* table cells that are not being edited. Line breaks ("\n") are preserved.
|
|
2753
|
+
*/
|
|
2754
|
+
class NgsHeadlessEditorRuns {
|
|
2755
|
+
editor = inject(NgsHeadlessEditor);
|
|
2756
|
+
element = inject(ElementRef).nativeElement;
|
|
2757
|
+
runs = input.required({ ...(ngDevMode ? { debugName: "runs" } : /* istanbul ignore next */ {}), alias: 'ngsHeadlessEditorRuns' });
|
|
2758
|
+
constructor() {
|
|
2759
|
+
effect(() => {
|
|
2760
|
+
const runs = this.runs();
|
|
2761
|
+
this.editor.plugins();
|
|
2762
|
+
renderNgsHeadlessEditorRuns(this.element, runs, this.editor);
|
|
2763
|
+
});
|
|
2764
|
+
}
|
|
2765
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorRuns, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
2766
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: NgsHeadlessEditorRuns, isStandalone: true, selector: "[ngsHeadlessEditorRuns]", inputs: { runs: { classPropertyName: "runs", publicName: "ngsHeadlessEditorRuns", isSignal: true, isRequired: true, transformFunction: null } }, host: { styleAttribute: "white-space: pre-wrap" }, ngImport: i0 });
|
|
2767
|
+
}
|
|
2768
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorRuns, decorators: [{
|
|
2769
|
+
type: Directive,
|
|
2770
|
+
args: [{
|
|
2771
|
+
selector: '[ngsHeadlessEditorRuns]',
|
|
2772
|
+
host: {
|
|
2773
|
+
'style': 'white-space: pre-wrap'
|
|
2774
|
+
}
|
|
2775
|
+
}]
|
|
2776
|
+
}], ctorParameters: () => [], propDecorators: { runs: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsHeadlessEditorRuns", required: true }] }] } });
|
|
2777
|
+
|
|
2778
|
+
/** Options of the table plugin, provided by withHeadlessEditorPlugin(tableEditorPlugin(...)). */
|
|
2779
|
+
const NGS_HEADLESS_EDITOR_TABLE_OPTIONS = new InjectionToken('NGS_HEADLESS_EDITOR_TABLE_OPTIONS', { factory: () => ({}) });
|
|
2780
|
+
/** Marks allowed in cells for the given formatting option. */
|
|
2781
|
+
function ngsHeadlessEditorTableCellMarks(registry, formatting = true) {
|
|
2782
|
+
const allowed = (mark) => !!mark &&
|
|
2783
|
+
formatting !== false &&
|
|
2784
|
+
mark.nested !== false &&
|
|
2785
|
+
(Array.isArray(formatting) ? formatting.includes(mark.type) : true);
|
|
2786
|
+
return {
|
|
2787
|
+
getMarkDefinition: type => {
|
|
2788
|
+
const mark = registry.getMarkDefinition(type);
|
|
2789
|
+
return allowed(mark) ? mark : undefined;
|
|
2790
|
+
},
|
|
2791
|
+
getMarkDefinitions: () => registry.getMarkDefinitions().filter(allowed)
|
|
2792
|
+
};
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
/**
|
|
2796
|
+
* Editing component for table blocks.
|
|
2797
|
+
*
|
|
2798
|
+
* Cells are rendered as static rich text. The focused cell is edited by one
|
|
2799
|
+
* nested editor (NgsHeadlessEditorInlineRegion) that reuses the marks, commands
|
|
2800
|
+
* and shortcuts of the document editor and becomes its inline target, so the
|
|
2801
|
+
* regular toolbar formats the cell. Changes are written back with updateBlock()
|
|
2802
|
+
* and recorded in the document history, grouped per cell.
|
|
2803
|
+
*
|
|
2804
|
+
* Styling hooks: `ngs-headless-editor-table`, `ngs-headless-editor-table-cell`
|
|
2805
|
+
* (th for header cells), `active` on the focused cell,
|
|
2806
|
+
* `ngs-headless-editor-table-cell-content` and `ngs-headless-editor-table-cell-editor`.
|
|
2807
|
+
*/
|
|
2808
|
+
class NgsHeadlessEditorTableBlockEditor {
|
|
2809
|
+
region = inject(NgsHeadlessEditorInlineRegion);
|
|
2810
|
+
editor = this.region.parent;
|
|
2811
|
+
host = inject(ElementRef).nativeElement;
|
|
2812
|
+
documentRef = inject(DOCUMENT);
|
|
2813
|
+
injector = inject(Injector);
|
|
2814
|
+
options = inject(NGS_HEADLESS_EDITOR_TABLE_OPTIONS);
|
|
2815
|
+
activeCell = ngsHeadlessEditorActiveTableCell(this.editor);
|
|
2816
|
+
pendingFocus = pendingNgsHeadlessEditorTableFocus(this.editor);
|
|
2817
|
+
surface = viewChild(NgsHeadlessEditorSurface, /* @ts-ignore */
|
|
2818
|
+
...(ngDevMode ? [{ debugName: "surface" }] : /* istanbul ignore next */ []));
|
|
2819
|
+
block = input.required(/* @ts-ignore */
|
|
2820
|
+
...(ngDevMode ? [{ debugName: "block" }] : /* istanbul ignore next */ []));
|
|
2821
|
+
data = computed(() => getNgsHeadlessEditorTableData(this.block()), /* @ts-ignore */
|
|
2822
|
+
...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
|
|
2823
|
+
/** Cell edited by the nested editor, if any. */
|
|
2824
|
+
editing = signal(null, /* @ts-ignore */
|
|
2825
|
+
...(ngDevMode ? [{ debugName: "editing" }] : /* istanbul ignore next */ []));
|
|
2826
|
+
/** Set while focus returns to a static cell after Escape, so it is not edited again. */
|
|
2827
|
+
skipFocusEdit = false;
|
|
2828
|
+
constructor() {
|
|
2829
|
+
this.region.configure({ marks: this.options.formatting ?? true });
|
|
2830
|
+
// Nested editor -> table block.
|
|
2831
|
+
effect(() => {
|
|
2832
|
+
this.region.editor.document();
|
|
2833
|
+
const origin = this.region.editor.origin();
|
|
2834
|
+
untracked(() => {
|
|
2835
|
+
const editing = this.editing();
|
|
2836
|
+
if (!editing || origin === 'external') {
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
const typing = origin === 'keyboard' || origin === 'composition';
|
|
2840
|
+
this.writeCell(editing.row, editing.column, this.region.content(), typing);
|
|
2841
|
+
});
|
|
2842
|
+
});
|
|
2843
|
+
// Table block (undo, redo, commands) -> nested editor.
|
|
2844
|
+
effect(() => {
|
|
2845
|
+
const data = this.data();
|
|
2846
|
+
const editing = this.editing();
|
|
2847
|
+
if (!editing) {
|
|
2848
|
+
return;
|
|
2849
|
+
}
|
|
2850
|
+
const cell = data.rows[editing.row]?.[editing.column];
|
|
2851
|
+
untracked(() => cell ? this.region.load(cell) : this.stopEditing());
|
|
2852
|
+
});
|
|
2853
|
+
// Leave the cell when the document text gets focus or another nested editor
|
|
2854
|
+
// takes over. Only a change to "focused" counts: a cell can be opened with a
|
|
2855
|
+
// click while the document text still has focus.
|
|
2856
|
+
let documentWasFocused = this.editor.focused();
|
|
2857
|
+
effect(() => {
|
|
2858
|
+
const documentFocused = this.editor.focused();
|
|
2859
|
+
const target = this.editor.inlineTarget();
|
|
2860
|
+
untracked(() => {
|
|
2861
|
+
const focusMovedToDocument = documentFocused && !documentWasFocused;
|
|
2862
|
+
documentWasFocused = documentFocused;
|
|
2863
|
+
if (this.editing() && (focusMovedToDocument || target !== this.region.editor)) {
|
|
2864
|
+
this.stopEditing();
|
|
2865
|
+
}
|
|
2866
|
+
});
|
|
2867
|
+
});
|
|
2868
|
+
// Focus requests from commands (insert table, add row, ...).
|
|
2869
|
+
effect(() => {
|
|
2870
|
+
const pending = this.pendingFocus();
|
|
2871
|
+
if (pending && pending.blockId === this.block().id) {
|
|
2872
|
+
afterNextRender(() => {
|
|
2873
|
+
if (this.pendingFocus() === pending) {
|
|
2874
|
+
this.pendingFocus.set(null);
|
|
2875
|
+
this.edit(pending.row, pending.column);
|
|
2876
|
+
}
|
|
2877
|
+
}, { injector: this.injector });
|
|
2878
|
+
}
|
|
2879
|
+
});
|
|
2880
|
+
}
|
|
2881
|
+
isActive(row, column) {
|
|
2882
|
+
const cell = this.activeCell();
|
|
2883
|
+
return !!cell && cell.blockId === this.block().id && cell.row === row && cell.column === column;
|
|
2884
|
+
}
|
|
2885
|
+
isEditing(row, column) {
|
|
2886
|
+
const editing = this.editing();
|
|
2887
|
+
return !!editing && editing.row === row && editing.column === column;
|
|
2888
|
+
}
|
|
2889
|
+
onContentPointerDown(event, row, column) {
|
|
2890
|
+
if (event.button !== 0) {
|
|
2891
|
+
return;
|
|
2892
|
+
}
|
|
2893
|
+
event.preventDefault();
|
|
2894
|
+
this.edit(row, column, { x: event.clientX, y: event.clientY });
|
|
2895
|
+
}
|
|
2896
|
+
onContentFocus(row, column) {
|
|
2897
|
+
if (this.skipFocusEdit) {
|
|
2898
|
+
this.skipFocusEdit = false;
|
|
2899
|
+
return;
|
|
2900
|
+
}
|
|
2901
|
+
if (!this.isEditing(row, column)) {
|
|
2902
|
+
this.edit(row, column);
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
onKeydown(event, row, column) {
|
|
2906
|
+
if (event.key === 'Escape' && this.isEditing(row, column)) {
|
|
2907
|
+
event.preventDefault();
|
|
2908
|
+
this.stopEditing();
|
|
2909
|
+
afterNextRender(() => {
|
|
2910
|
+
this.skipFocusEdit = true;
|
|
2911
|
+
this.cellContent(row, column)?.focus();
|
|
2912
|
+
this.skipFocusEdit = false;
|
|
2913
|
+
}, { injector: this.injector });
|
|
2914
|
+
return;
|
|
2915
|
+
}
|
|
2916
|
+
if (event.key !== 'Tab' || event.ctrlKey || event.metaKey || event.altKey) {
|
|
2917
|
+
return;
|
|
2918
|
+
}
|
|
2919
|
+
event.preventDefault();
|
|
2920
|
+
const { rows } = this.data();
|
|
2921
|
+
const columns = rows[0]?.length ?? 1;
|
|
2922
|
+
const index = row * columns + column + (event.shiftKey ? -1 : 1);
|
|
2923
|
+
if (index < 0) {
|
|
2924
|
+
return;
|
|
2925
|
+
}
|
|
2926
|
+
if (index >= rows.length * columns) {
|
|
2927
|
+
// Tab in the last cell appends a row, like spreadsheets and word processors.
|
|
2928
|
+
if (this.writeData(insertNgsHeadlessEditorTableRow(this.data(), rows.length))) {
|
|
2929
|
+
focusNgsHeadlessEditorTableCell(this.editor, { blockId: this.block().id, row: rows.length, column: 0 });
|
|
2930
|
+
}
|
|
2931
|
+
return;
|
|
2932
|
+
}
|
|
2933
|
+
this.edit(Math.floor(index / columns), index % columns);
|
|
2934
|
+
}
|
|
2935
|
+
/** Starts editing a cell, with the caret at a point or at the end of the cell. */
|
|
2936
|
+
edit(row, column, point) {
|
|
2937
|
+
const cell = this.data().rows[row]?.[column];
|
|
2938
|
+
if (!cell || this.editor.readOnly()) {
|
|
2939
|
+
return;
|
|
2940
|
+
}
|
|
2941
|
+
this.editing.set({ row, column });
|
|
2942
|
+
this.region.load(cell);
|
|
2943
|
+
this.region.activate();
|
|
2944
|
+
setNgsHeadlessEditorActiveTableCell(this.editor, { blockId: this.block().id, row, column });
|
|
2945
|
+
afterNextRender(() => this.focusEditor(point), { injector: this.injector });
|
|
2946
|
+
}
|
|
2947
|
+
stopEditing() {
|
|
2948
|
+
const editing = this.editing();
|
|
2949
|
+
this.editing.set(null);
|
|
2950
|
+
this.region.deactivate();
|
|
2951
|
+
const active = this.activeCell();
|
|
2952
|
+
if (editing && active?.blockId === this.block().id) {
|
|
2953
|
+
setNgsHeadlessEditorActiveTableCell(this.editor, null);
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
focusEditor(point) {
|
|
2957
|
+
const surface = this.surface();
|
|
2958
|
+
const element = this.host.querySelector('.ngs-headless-editor-table-cell-editor');
|
|
2959
|
+
if (!surface || !element) {
|
|
2960
|
+
return;
|
|
2961
|
+
}
|
|
2962
|
+
if (point) {
|
|
2963
|
+
surface.focus();
|
|
2964
|
+
const range = this.rangeFromPoint(point.x, point.y);
|
|
2965
|
+
if (range && element.contains(range.startContainer)) {
|
|
2966
|
+
const selection = this.documentRef.getSelection();
|
|
2967
|
+
selection?.removeAllRanges();
|
|
2968
|
+
selection?.addRange(range);
|
|
2969
|
+
return;
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
const blocks = this.region.editor.document().blocks;
|
|
2973
|
+
const last = blocks[blocks.length - 1];
|
|
2974
|
+
const offset = getNgsHeadlessEditorBlockText(last).length;
|
|
2975
|
+
this.region.editor.setSelection({
|
|
2976
|
+
anchor: { blockId: last.id, offset },
|
|
2977
|
+
focus: { blockId: last.id, offset }
|
|
2978
|
+
});
|
|
2979
|
+
surface.focus();
|
|
2980
|
+
}
|
|
2981
|
+
rangeFromPoint(x, y) {
|
|
2982
|
+
const document = this.documentRef;
|
|
2983
|
+
if (typeof document.caretPositionFromPoint === 'function') {
|
|
2984
|
+
const position = document.caretPositionFromPoint(x, y);
|
|
2985
|
+
if (!position) {
|
|
2986
|
+
return null;
|
|
2987
|
+
}
|
|
2988
|
+
const range = document.createRange();
|
|
2989
|
+
range.setStart(position.offsetNode, position.offset);
|
|
2990
|
+
range.collapse(true);
|
|
2991
|
+
return range;
|
|
2992
|
+
}
|
|
2993
|
+
return typeof document.caretRangeFromPoint === 'function' ? document.caretRangeFromPoint(x, y) : null;
|
|
2994
|
+
}
|
|
2995
|
+
cellContent(row, column) {
|
|
2996
|
+
return this.host.querySelector(`[data-row="${row}"][data-column="${column}"] .ngs-headless-editor-table-cell-content`);
|
|
2997
|
+
}
|
|
2998
|
+
writeCell(row, column, content, typing) {
|
|
2999
|
+
const data = this.data();
|
|
3000
|
+
const current = data.rows[row]?.[column];
|
|
3001
|
+
if (!current || ngsHeadlessEditorValuesEqual(current, normalizeNgsHeadlessEditorTableCell(content))) {
|
|
3002
|
+
return;
|
|
3003
|
+
}
|
|
3004
|
+
this.writeData(setNgsHeadlessEditorTableCell(data, row, column, content), typing ? `table-cell:${this.block().id}:${row}:${column}` : null);
|
|
3005
|
+
}
|
|
3006
|
+
writeData(data, historyGroup = null) {
|
|
3007
|
+
return this.editor.updateBlock(this.block().id, { attrs: { ...this.block().attrs, rows: data.rows, header: data.header } }, 'keyboard', historyGroup);
|
|
3008
|
+
}
|
|
3009
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorTableBlockEditor, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
3010
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: NgsHeadlessEditorTableBlockEditor, isStandalone: true, selector: "ngs-headless-editor-table-editor", inputs: { block: { classPropertyName: "block", publicName: "block", isSignal: true, isRequired: true, transformFunction: null } }, providers: [provideNgsHeadlessEditorInlineRegion()], viewQueries: [{ propertyName: "surface", first: true, predicate: NgsHeadlessEditorSurface, descendants: true, isSignal: true }], ngImport: i0, template: "<table class=\"ngs-headless-editor-table\" [class.has-header]=\"data().header\">\n <tbody>\n @for (row of data().rows; track $index; let rowIndex = $index) {\n <tr>\n @for (cell of row; track $index; let columnIndex = $index) {\n @if (data().header && rowIndex === 0) {\n <th\n scope=\"col\"\n class=\"ngs-headless-editor-table-cell\"\n [attr.data-row]=\"rowIndex\"\n [attr.data-column]=\"columnIndex\"\n [class.active]=\"isActive(rowIndex, columnIndex)\"\n (keydown)=\"onKeydown($event, rowIndex, columnIndex)\">\n <ng-container\n [ngTemplateOutlet]=\"cellTemplate\"\n [ngTemplateOutletContext]=\"{ $implicit: cell, row: rowIndex, column: columnIndex }\"/>\n </th>\n } @else {\n <td\n class=\"ngs-headless-editor-table-cell\"\n [attr.data-row]=\"rowIndex\"\n [attr.data-column]=\"columnIndex\"\n [class.active]=\"isActive(rowIndex, columnIndex)\"\n (keydown)=\"onKeydown($event, rowIndex, columnIndex)\">\n <ng-container\n [ngTemplateOutlet]=\"cellTemplate\"\n [ngTemplateOutletContext]=\"{ $implicit: cell, row: rowIndex, column: columnIndex }\"/>\n </td>\n }\n }\n </tr>\n }\n </tbody>\n</table>\n\n<ng-template #cellTemplate let-cell let-row=\"row\" let-column=\"column\">\n @if (isEditing(row, column)) {\n <div\n class=\"ngs-headless-editor-table-cell-editor\"\n ngsHeadlessEditorSurface\n placeholder=\"\"\n [ariaLabel]=\"'Row ' + (row + 1) + ', column ' + (column + 1)\">\n </div>\n } @else {\n <div\n class=\"ngs-headless-editor-table-cell-content\"\n tabindex=\"0\"\n [ngsHeadlessEditorRuns]=\"cell\"\n (pointerdown)=\"onContentPointerDown($event, row, column)\"\n (focus)=\"onContentFocus(row, column)\">\n </div>\n }\n</ng-template>\n", styles: [":host{display:block;overflow-x:auto}.ngs-headless-editor-table{border-collapse:collapse}.ngs-headless-editor-table-cell{min-width:3rem;vertical-align:top}.ngs-headless-editor-table-cell-content,.ngs-headless-editor-table-cell-editor{display:block;min-height:1.5em;outline:none;cursor:text}:host ::ng-deep .ngs-headless-editor-table-cell-editor>*{margin:0}\n"], dependencies: [{ kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: NgsHeadlessEditorRuns, selector: "[ngsHeadlessEditorRuns]", inputs: ["ngsHeadlessEditorRuns"] }, { kind: "directive", type: NgsHeadlessEditorSurface, selector: "[ngsHeadlessEditorSurface]", inputs: ["placeholder", "ariaLabel", "disabled", "spellcheck"], exportAs: ["ngsHeadlessEditorSurface"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
3011
|
+
}
|
|
3012
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorTableBlockEditor, decorators: [{
|
|
3013
|
+
type: Component,
|
|
3014
|
+
args: [{ selector: 'ngs-headless-editor-table-editor', imports: [NgTemplateOutlet, NgsHeadlessEditorRuns, NgsHeadlessEditorSurface], providers: [provideNgsHeadlessEditorInlineRegion()], changeDetection: ChangeDetectionStrategy.OnPush, template: "<table class=\"ngs-headless-editor-table\" [class.has-header]=\"data().header\">\n <tbody>\n @for (row of data().rows; track $index; let rowIndex = $index) {\n <tr>\n @for (cell of row; track $index; let columnIndex = $index) {\n @if (data().header && rowIndex === 0) {\n <th\n scope=\"col\"\n class=\"ngs-headless-editor-table-cell\"\n [attr.data-row]=\"rowIndex\"\n [attr.data-column]=\"columnIndex\"\n [class.active]=\"isActive(rowIndex, columnIndex)\"\n (keydown)=\"onKeydown($event, rowIndex, columnIndex)\">\n <ng-container\n [ngTemplateOutlet]=\"cellTemplate\"\n [ngTemplateOutletContext]=\"{ $implicit: cell, row: rowIndex, column: columnIndex }\"/>\n </th>\n } @else {\n <td\n class=\"ngs-headless-editor-table-cell\"\n [attr.data-row]=\"rowIndex\"\n [attr.data-column]=\"columnIndex\"\n [class.active]=\"isActive(rowIndex, columnIndex)\"\n (keydown)=\"onKeydown($event, rowIndex, columnIndex)\">\n <ng-container\n [ngTemplateOutlet]=\"cellTemplate\"\n [ngTemplateOutletContext]=\"{ $implicit: cell, row: rowIndex, column: columnIndex }\"/>\n </td>\n }\n }\n </tr>\n }\n </tbody>\n</table>\n\n<ng-template #cellTemplate let-cell let-row=\"row\" let-column=\"column\">\n @if (isEditing(row, column)) {\n <div\n class=\"ngs-headless-editor-table-cell-editor\"\n ngsHeadlessEditorSurface\n placeholder=\"\"\n [ariaLabel]=\"'Row ' + (row + 1) + ', column ' + (column + 1)\">\n </div>\n } @else {\n <div\n class=\"ngs-headless-editor-table-cell-content\"\n tabindex=\"0\"\n [ngsHeadlessEditorRuns]=\"cell\"\n (pointerdown)=\"onContentPointerDown($event, row, column)\"\n (focus)=\"onContentFocus(row, column)\">\n </div>\n }\n</ng-template>\n", styles: [":host{display:block;overflow-x:auto}.ngs-headless-editor-table{border-collapse:collapse}.ngs-headless-editor-table-cell{min-width:3rem;vertical-align:top}.ngs-headless-editor-table-cell-content,.ngs-headless-editor-table-cell-editor{display:block;min-height:1.5em;outline:none;cursor:text}:host ::ng-deep .ngs-headless-editor-table-cell-editor>*{margin:0}\n"] }]
|
|
3015
|
+
}], ctorParameters: () => [], propDecorators: { surface: [{ type: i0.ViewChild, args: [i0.forwardRef(() => NgsHeadlessEditorSurface), { isSignal: true }] }], block: [{ type: i0.Input, args: [{ isSignal: true, alias: "block", required: true }] }] } });
|
|
3016
|
+
|
|
3017
|
+
/** Read-only rendering of table blocks, used while the surface is disabled or read-only. */
|
|
3018
|
+
class NgsHeadlessEditorTableView {
|
|
3019
|
+
block = input.required(/* @ts-ignore */
|
|
3020
|
+
...(ngDevMode ? [{ debugName: "block" }] : /* istanbul ignore next */ []));
|
|
3021
|
+
data = computed(() => getNgsHeadlessEditorTableData(this.block()), /* @ts-ignore */
|
|
3022
|
+
...(ngDevMode ? [{ debugName: "data" }] : /* istanbul ignore next */ []));
|
|
3023
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorTableView, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
3024
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: NgsHeadlessEditorTableView, isStandalone: true, selector: "ngs-headless-editor-table-view", inputs: { block: { classPropertyName: "block", publicName: "block", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: "<table class=\"ngs-headless-editor-table\" [class.has-header]=\"data().header\">\n @if (data().header) {\n <thead>\n <tr>\n @for (cell of data().rows[0]; track $index) {\n <th scope=\"col\" class=\"ngs-headless-editor-table-cell\" [ngsHeadlessEditorRuns]=\"cell\"></th>\n }\n </tr>\n </thead>\n }\n <tbody>\n @for (row of data().rows; track $index; let rowIndex = $index) {\n @if (!data().header || rowIndex > 0) {\n <tr>\n @for (cell of row; track $index) {\n <td class=\"ngs-headless-editor-table-cell\" [ngsHeadlessEditorRuns]=\"cell\"></td>\n }\n </tr>\n }\n }\n </tbody>\n</table>\n", styles: [":host{display:block;overflow-x:auto}.ngs-headless-editor-table{border-collapse:collapse}.ngs-headless-editor-table-cell{min-width:3rem;vertical-align:top;white-space:pre-wrap}\n"], dependencies: [{ kind: "directive", type: NgsHeadlessEditorRuns, selector: "[ngsHeadlessEditorRuns]", inputs: ["ngsHeadlessEditorRuns"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
3025
|
+
}
|
|
3026
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorTableView, decorators: [{
|
|
3027
|
+
type: Component,
|
|
3028
|
+
args: [{ selector: 'ngs-headless-editor-table-view', imports: [NgsHeadlessEditorRuns], changeDetection: ChangeDetectionStrategy.OnPush, template: "<table class=\"ngs-headless-editor-table\" [class.has-header]=\"data().header\">\n @if (data().header) {\n <thead>\n <tr>\n @for (cell of data().rows[0]; track $index) {\n <th scope=\"col\" class=\"ngs-headless-editor-table-cell\" [ngsHeadlessEditorRuns]=\"cell\"></th>\n }\n </tr>\n </thead>\n }\n <tbody>\n @for (row of data().rows; track $index; let rowIndex = $index) {\n @if (!data().header || rowIndex > 0) {\n <tr>\n @for (cell of row; track $index) {\n <td class=\"ngs-headless-editor-table-cell\" [ngsHeadlessEditorRuns]=\"cell\"></td>\n }\n </tr>\n }\n }\n </tbody>\n</table>\n", styles: [":host{display:block;overflow-x:auto}.ngs-headless-editor-table{border-collapse:collapse}.ngs-headless-editor-table-cell{min-width:3rem;vertical-align:top;white-space:pre-wrap}\n"] }]
|
|
3029
|
+
}], propDecorators: { block: [{ type: i0.Input, args: [{ isSignal: true, alias: "block", required: true }] }] } });
|
|
3030
|
+
|
|
3031
|
+
const DEFAULT_SIZE = { rows: 3, columns: 3, header: true };
|
|
3032
|
+
function activeTable(editor) {
|
|
3033
|
+
const cell = ngsHeadlessEditorActiveTableCell(editor)();
|
|
3034
|
+
if (!cell) {
|
|
3035
|
+
return null;
|
|
3036
|
+
}
|
|
3037
|
+
const block = editor.document().blocks.find(item => item.id === cell.blockId);
|
|
3038
|
+
if (!block || !isNgsHeadlessEditorTable(block)) {
|
|
3039
|
+
return null;
|
|
3040
|
+
}
|
|
3041
|
+
const data = getNgsHeadlessEditorTableData(block);
|
|
3042
|
+
const row = Math.min(cell.row, data.rows.length - 1);
|
|
3043
|
+
const column = Math.min(cell.column, (data.rows[0]?.length ?? 1) - 1);
|
|
3044
|
+
return { block, data, cell: { blockId: block.id, row, column } };
|
|
3045
|
+
}
|
|
3046
|
+
/**
|
|
3047
|
+
* Inserts a table block. An empty paragraph at the caret is replaced; otherwise
|
|
3048
|
+
* the table goes after the current block. A paragraph is added after the table
|
|
3049
|
+
* when it would be the last block, so the caret can always continue below it.
|
|
3050
|
+
* Focus moves to the first cell.
|
|
3051
|
+
*/
|
|
3052
|
+
function insertNgsHeadlessEditorTable(editor, table) {
|
|
3053
|
+
const blocks = editor.document().blocks;
|
|
3054
|
+
const focusId = editor.selection()?.focus.blockId ?? blocks[blocks.length - 1]?.id;
|
|
3055
|
+
const focusIndex = Math.max(0, blocks.findIndex(block => block.id === focusId));
|
|
3056
|
+
const focus = blocks[focusIndex];
|
|
3057
|
+
const replaceFocus = !!focus &&
|
|
3058
|
+
focus.type === 'paragraph' &&
|
|
3059
|
+
isNgsHeadlessEditorTextContent(focus.content) &&
|
|
3060
|
+
getNgsHeadlessEditorBlockText(focus).length === 0;
|
|
3061
|
+
const isLast = focusIndex === blocks.length - 1;
|
|
3062
|
+
const trailing = isLast ? [createNgsHeadlessEditorParagraph()] : [];
|
|
3063
|
+
const inserted = replaceFocus
|
|
3064
|
+
? editor.replaceBlock(focus.id, [table, ...trailing])
|
|
3065
|
+
: editor.insertBlock([table, ...trailing]);
|
|
3066
|
+
if (inserted) {
|
|
3067
|
+
focusNgsHeadlessEditorTableCell(editor, { blockId: table.id, row: 0, column: 0 });
|
|
3068
|
+
}
|
|
3069
|
+
return inserted;
|
|
3070
|
+
}
|
|
3071
|
+
function tableCommand(id, change, enabled = () => true) {
|
|
3072
|
+
return {
|
|
3073
|
+
id,
|
|
3074
|
+
enabled: editor => {
|
|
3075
|
+
const table = activeTable(editor);
|
|
3076
|
+
return !!table && enabled(table);
|
|
3077
|
+
},
|
|
3078
|
+
execute: editor => {
|
|
3079
|
+
const table = activeTable(editor);
|
|
3080
|
+
const result = table ? change(table) : null;
|
|
3081
|
+
if (!table || !result) {
|
|
3082
|
+
return false;
|
|
3083
|
+
}
|
|
3084
|
+
const updated = editor.updateBlock(table.block.id, {
|
|
3085
|
+
attrs: { ...table.block.attrs, rows: result.data.rows, header: result.data.header }
|
|
3086
|
+
});
|
|
3087
|
+
if (updated) {
|
|
3088
|
+
focusNgsHeadlessEditorTableCell(editor, { blockId: table.block.id, row: result.row, column: result.column });
|
|
3089
|
+
}
|
|
3090
|
+
return updated;
|
|
3091
|
+
}
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
/** Inserts a table. Payload: size and header row, default 3 × 3 with a header. */
|
|
3095
|
+
const NGS_HEADLESS_EDITOR_INSERT_TABLE = {
|
|
3096
|
+
id: 'insert-table',
|
|
3097
|
+
execute: (editor, size) => insertNgsHeadlessEditorTable(editor, createNgsHeadlessEditorTable(size ?? DEFAULT_SIZE))
|
|
3098
|
+
};
|
|
3099
|
+
const NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_BEFORE = tableCommand('table-add-row-before', ({ data, cell }) => ({
|
|
3100
|
+
data: insertNgsHeadlessEditorTableRow(data, cell.row),
|
|
3101
|
+
row: cell.row,
|
|
3102
|
+
column: cell.column
|
|
3103
|
+
}));
|
|
3104
|
+
const NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_AFTER = tableCommand('table-add-row-after', ({ data, cell }) => ({
|
|
3105
|
+
data: insertNgsHeadlessEditorTableRow(data, cell.row + 1),
|
|
3106
|
+
row: cell.row + 1,
|
|
3107
|
+
column: cell.column
|
|
3108
|
+
}));
|
|
3109
|
+
const NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_BEFORE = tableCommand('table-add-column-before', ({ data, cell }) => ({
|
|
3110
|
+
data: insertNgsHeadlessEditorTableColumn(data, cell.column),
|
|
3111
|
+
row: cell.row,
|
|
3112
|
+
column: cell.column
|
|
3113
|
+
}));
|
|
3114
|
+
const NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_AFTER = tableCommand('table-add-column-after', ({ data, cell }) => ({
|
|
3115
|
+
data: insertNgsHeadlessEditorTableColumn(data, cell.column + 1),
|
|
3116
|
+
row: cell.row,
|
|
3117
|
+
column: cell.column + 1
|
|
3118
|
+
}));
|
|
3119
|
+
const NGS_HEADLESS_EDITOR_TABLE_DELETE_ROW = tableCommand('table-delete-row', ({ data, cell }) => ({
|
|
3120
|
+
data: removeNgsHeadlessEditorTableRow(data, cell.row),
|
|
3121
|
+
row: Math.min(cell.row, data.rows.length - 2),
|
|
3122
|
+
column: cell.column
|
|
3123
|
+
}), ({ data }) => data.rows.length > 1);
|
|
3124
|
+
const NGS_HEADLESS_EDITOR_TABLE_DELETE_COLUMN = tableCommand('table-delete-column', ({ data, cell }) => ({
|
|
3125
|
+
data: removeNgsHeadlessEditorTableColumn(data, cell.column),
|
|
3126
|
+
row: cell.row,
|
|
3127
|
+
column: Math.min(cell.column, (data.rows[0]?.length ?? 1) - 2)
|
|
3128
|
+
}), ({ data }) => (data.rows[0]?.length ?? 0) > 1);
|
|
3129
|
+
const NGS_HEADLESS_EDITOR_TABLE_TOGGLE_HEADER = {
|
|
3130
|
+
...tableCommand('table-toggle-header', ({ data, cell }) => ({
|
|
3131
|
+
data: { ...data, header: !data.header },
|
|
3132
|
+
row: cell.row,
|
|
3133
|
+
column: cell.column
|
|
3134
|
+
})),
|
|
3135
|
+
active: editor => activeTable(editor)?.data.header ?? false
|
|
3136
|
+
};
|
|
3137
|
+
const NGS_HEADLESS_EDITOR_TABLE_DELETE = {
|
|
3138
|
+
id: 'table-delete',
|
|
3139
|
+
enabled: editor => activeTable(editor) !== null,
|
|
3140
|
+
execute: editor => {
|
|
3141
|
+
const table = activeTable(editor);
|
|
3142
|
+
if (!table) {
|
|
3143
|
+
return false;
|
|
3144
|
+
}
|
|
3145
|
+
setNgsHeadlessEditorActiveTableCell(editor, null);
|
|
3146
|
+
return editor.removeBlock(table.block.id);
|
|
3147
|
+
}
|
|
3148
|
+
};
|
|
3149
|
+
/**
|
|
3150
|
+
* Adds a `table` block edited through an Angular component, commands for rows,
|
|
3151
|
+
* columns and the header row, and (optionally) pasting spreadsheet ranges and
|
|
3152
|
+
* HTML tables as tables. Cells hold rich text: every formatting command of the
|
|
3153
|
+
* editor works inside a focused cell unless `formatting` restricts it.
|
|
3154
|
+
*/
|
|
3155
|
+
function tableEditorPlugin(options = {}) {
|
|
3156
|
+
return defineNgsHeadlessEditorPlugin({
|
|
3157
|
+
id: 'table',
|
|
3158
|
+
blocks: [
|
|
3159
|
+
{
|
|
3160
|
+
type: NGS_HEADLESS_EDITOR_TABLE_TYPE,
|
|
3161
|
+
tagName: 'div',
|
|
3162
|
+
create: () => createNgsHeadlessEditorTable(DEFAULT_SIZE),
|
|
3163
|
+
isEmpty: () => false,
|
|
3164
|
+
editorComponent: NgsHeadlessEditorTableBlockEditor,
|
|
3165
|
+
rendererComponent: NgsHeadlessEditorTableView
|
|
3166
|
+
}
|
|
3167
|
+
],
|
|
3168
|
+
commands: [
|
|
3169
|
+
NGS_HEADLESS_EDITOR_INSERT_TABLE,
|
|
3170
|
+
NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_BEFORE,
|
|
3171
|
+
NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_AFTER,
|
|
3172
|
+
NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_BEFORE,
|
|
3173
|
+
NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_AFTER,
|
|
3174
|
+
NGS_HEADLESS_EDITOR_TABLE_DELETE_ROW,
|
|
3175
|
+
NGS_HEADLESS_EDITOR_TABLE_DELETE_COLUMN,
|
|
3176
|
+
NGS_HEADLESS_EDITOR_TABLE_TOGGLE_HEADER,
|
|
3177
|
+
NGS_HEADLESS_EDITOR_TABLE_DELETE
|
|
3178
|
+
],
|
|
3179
|
+
providers: [{ provide: NGS_HEADLESS_EDITOR_TABLE_OPTIONS, useValue: options }],
|
|
3180
|
+
handlePaste: options.paste === false
|
|
3181
|
+
? undefined
|
|
3182
|
+
: (event, editor) => {
|
|
3183
|
+
// Cell formatting from the clipboard (bold, links, ...) is kept for the
|
|
3184
|
+
// marks that are allowed in cells.
|
|
3185
|
+
const marks = ngsHeadlessEditorTableCellMarks(editor, options.formatting);
|
|
3186
|
+
const rows = parseNgsHeadlessEditorTableHtml(event.clipboardData?.getData('text/html'), marks) ??
|
|
3187
|
+
parseNgsHeadlessEditorTableText(event.clipboardData?.getData('text/plain'));
|
|
3188
|
+
return rows ? insertNgsHeadlessEditorTable(editor, createNgsHeadlessEditorTable(rows, false)) : false;
|
|
3189
|
+
}
|
|
3190
|
+
});
|
|
3191
|
+
}
|
|
3192
|
+
|
|
3193
|
+
/** Editor-scoped configurations installed together by mentionEditorPlugin(). */
|
|
3194
|
+
const NGS_HEADLESS_EDITOR_MENTION_OPTIONS = new InjectionToken('NGS_HEADLESS_EDITOR_MENTION_OPTIONS', { factory: () => [] });
|
|
3195
|
+
|
|
3196
|
+
const NGS_HEADLESS_EDITOR_MENTION_MARK = 'mention';
|
|
3197
|
+
// All registrations share one mark definition, while searches and option renderers
|
|
3198
|
+
// belong to their individual trigger. Existing documents without a trigger remain valid.
|
|
3199
|
+
const mentionMark = {
|
|
3200
|
+
type: NGS_HEADLESS_EDITOR_MENTION_MARK,
|
|
3201
|
+
tagName: 'span',
|
|
3202
|
+
atomic: true,
|
|
3203
|
+
applyAttributes: (element, mark) => {
|
|
3204
|
+
element.classList.add('ngs-headless-editor-mention');
|
|
3205
|
+
element.dataset['mentionId'] = String(mark.attrs?.['id'] ?? '');
|
|
3206
|
+
element.dataset['mentionLabel'] = String(mark.attrs?.['label'] ?? '');
|
|
3207
|
+
const trigger = mark.attrs?.['trigger'];
|
|
3208
|
+
if (typeof trigger === 'string')
|
|
3209
|
+
element.dataset['mentionTrigger'] = trigger;
|
|
3210
|
+
else
|
|
3211
|
+
delete element.dataset['mentionTrigger'];
|
|
3212
|
+
const tokenId = mark.attrs?.['tokenId'];
|
|
3213
|
+
if (typeof tokenId === 'string')
|
|
3214
|
+
element.dataset['mentionTokenId'] = tokenId;
|
|
3215
|
+
else
|
|
3216
|
+
delete element.dataset['mentionTokenId'];
|
|
3217
|
+
},
|
|
3218
|
+
readAttributes: element => ({
|
|
3219
|
+
id: element.dataset['mentionId'] ?? '',
|
|
3220
|
+
label: element.dataset['mentionLabel'] ?? '',
|
|
3221
|
+
...(element.dataset['mentionTrigger'] !== undefined ? { trigger: element.dataset['mentionTrigger'] } : {}),
|
|
3222
|
+
...(element.dataset['mentionTokenId'] !== undefined ? { tokenId: element.dataset['mentionTokenId'] } : {})
|
|
3223
|
+
})
|
|
3224
|
+
};
|
|
3225
|
+
function mentionEditorPlugin(options = {}) {
|
|
3226
|
+
const configurations = Array.isArray(options)
|
|
3227
|
+
? options : [options];
|
|
3228
|
+
const triggers = new Set();
|
|
3229
|
+
const registrations = configurations.map(config => {
|
|
3230
|
+
const trigger = config.trigger ?? '@';
|
|
3231
|
+
if (!trigger || /\s/.test(trigger)) {
|
|
3232
|
+
throw new Error('[NgsHeadlessEditor] Mention trigger must be non-empty and contain no whitespace.');
|
|
3233
|
+
}
|
|
3234
|
+
if (triggers.has(trigger)) {
|
|
3235
|
+
throw new Error(`[NgsHeadlessEditor] Duplicate mention trigger "${trigger}".`);
|
|
3236
|
+
}
|
|
3237
|
+
triggers.add(trigger);
|
|
3238
|
+
return { ...config, trigger };
|
|
3239
|
+
});
|
|
3240
|
+
return defineNgsHeadlessEditorPlugin({
|
|
3241
|
+
id: 'mention',
|
|
3242
|
+
providers: [{ provide: NGS_HEADLESS_EDITOR_MENTION_OPTIONS, useValue: registrations }],
|
|
3243
|
+
marks: [mentionMark]
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3246
|
+
/** Finds trigger/query at a collapsed caret, excluding e-mail addresses and existing mentions. */
|
|
3247
|
+
function findNgsHeadlessEditorMentionQuery(editor, trigger = '@') {
|
|
3248
|
+
const selection = editor.selection();
|
|
3249
|
+
if (!trigger || /\s/.test(trigger) || editor.readOnly() || editor.composing() ||
|
|
3250
|
+
!editor.canApplyMark(NGS_HEADLESS_EDITOR_MENTION_MARK) || !selection ||
|
|
3251
|
+
selection.anchor.blockId !== selection.focus.blockId ||
|
|
3252
|
+
selection.anchor.offset !== selection.focus.offset) {
|
|
3253
|
+
return null;
|
|
3254
|
+
}
|
|
3255
|
+
const block = editor.document().blocks.find(item => item.id === selection.focus.blockId);
|
|
3256
|
+
if (!block || !isNgsHeadlessEditorTextContent(block.content)) {
|
|
3257
|
+
return null;
|
|
3258
|
+
}
|
|
3259
|
+
const escaped = trigger.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
3260
|
+
const before = getNgsHeadlessEditorBlockText(block).slice(0, selection.focus.offset);
|
|
3261
|
+
const match = new RegExp(`(?:^|[\\s([{])(${escaped}([\\p{L}\\p{N}_.-]{0,64}))$`, 'u').exec(before);
|
|
3262
|
+
if (!match) {
|
|
3263
|
+
return null;
|
|
3264
|
+
}
|
|
3265
|
+
const from = before.length - match[1].length;
|
|
3266
|
+
const to = before.length;
|
|
3267
|
+
if (sliceRuns(block.content, from, to).some(run => run.marks.some(mark => mark.type === NGS_HEADLESS_EDITOR_MENTION_MARK))) {
|
|
3268
|
+
return null;
|
|
3269
|
+
}
|
|
3270
|
+
return { blockId: block.id, from, to, query: match[2], trigger };
|
|
3271
|
+
}
|
|
3272
|
+
/** Replaces the current trigger/query with a mention and a plain space in one undo step. */
|
|
3273
|
+
function insertNgsHeadlessEditorMention(editor, option, query) {
|
|
3274
|
+
const current = findNgsHeadlessEditorMentionQuery(editor, query.trigger);
|
|
3275
|
+
if (!option.id || !option.label || !current ||
|
|
3276
|
+
current.blockId !== query.blockId || current.from !== query.from ||
|
|
3277
|
+
current.to !== query.to || current.query !== query.query) {
|
|
3278
|
+
return false;
|
|
3279
|
+
}
|
|
3280
|
+
const block = editor.document().blocks.find(item => item.id === query.blockId);
|
|
3281
|
+
if (!isNgsHeadlessEditorTextContent(block.content)) {
|
|
3282
|
+
return false;
|
|
3283
|
+
}
|
|
3284
|
+
const marks = sliceRuns(block.content, query.from, query.to)[0]?.marks ?? [];
|
|
3285
|
+
const label = option.text ?? query.trigger + option.label;
|
|
3286
|
+
if (!label || /[\r\n]/.test(label))
|
|
3287
|
+
return false;
|
|
3288
|
+
const after = sliceRuns(block.content, query.to, getNgsHeadlessEditorBlockText(block).length);
|
|
3289
|
+
const space = after[0]?.text.startsWith(' ') ? [] : [createNgsHeadlessEditorText(' ', marks)];
|
|
3290
|
+
const content = normalizeNgsHeadlessEditorTextContent([
|
|
3291
|
+
...sliceRuns(block.content, 0, query.from),
|
|
3292
|
+
createNgsHeadlessEditorText(label, [
|
|
3293
|
+
...marks,
|
|
3294
|
+
{
|
|
3295
|
+
type: NGS_HEADLESS_EDITOR_MENTION_MARK,
|
|
3296
|
+
attrs: { id: option.id, label: option.label, trigger: query.trigger, tokenId: createNgsHeadlessEditorId('mention') }
|
|
3297
|
+
}
|
|
3298
|
+
]),
|
|
3299
|
+
...space,
|
|
3300
|
+
...after
|
|
3301
|
+
]);
|
|
3302
|
+
const point = { blockId: block.id, offset: query.from + label.length + 1 };
|
|
3303
|
+
return editor.replaceBlock(block.id, [{ ...block, content }], { anchor: point, focus: point });
|
|
3304
|
+
}
|
|
3305
|
+
function sliceRuns(runs, from, to) {
|
|
3306
|
+
const result = [];
|
|
3307
|
+
let offset = 0;
|
|
3308
|
+
for (const run of runs) {
|
|
3309
|
+
const start = Math.max(from, offset);
|
|
3310
|
+
const end = Math.min(to, offset + run.text.length);
|
|
3311
|
+
if (start < end) {
|
|
3312
|
+
result.push(createNgsHeadlessEditorText(run.text.slice(start - offset, end - offset), run.marks));
|
|
3313
|
+
}
|
|
3314
|
+
offset += run.text.length;
|
|
3315
|
+
}
|
|
3316
|
+
return result;
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
/** Default menu; the active plugin registration supplies the option component. */
|
|
3320
|
+
class NgsHeadlessEditorMentionMenu {
|
|
3321
|
+
mentions = input.required(/* @ts-ignore */
|
|
3322
|
+
...(ngDevMode ? [{ debugName: "mentions" }] : /* istanbul ignore next */ []));
|
|
3323
|
+
menu = viewChild.required(Menu, /* @ts-ignore */
|
|
3324
|
+
...(ngDevMode ? [{ debugName: "menu" }] : /* istanbul ignore next */ []));
|
|
3325
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorMentionMenu, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
3326
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.7", type: NgsHeadlessEditorMentionMenu, isStandalone: true, selector: "ngs-headless-editor-mention-menu", inputs: { mentions: { classPropertyName: "mentions", publicName: "mentions", isSignal: true, isRequired: true, transformFunction: null } }, viewQueries: [{ propertyName: "menu", first: true, predicate: Menu, descendants: true, isSignal: true }], ngImport: i0, template: "<ngs-menu classList=\"max-h-72 min-w-64 overflow-y-auto\" >\n @for (option of mentions().suggestions(); track option.id; let index = $index) {\n <ngs-menu-item\n [attr.id]=\"mentions().optionId(index)\"\n [selected]=\"mentions().activeIndex() === index\"\n (click)=\"mentions().select(option)\">\n @if (mentions().optionComponent(); as optionComponent) {\n <ng-container\n [ngComponentOutlet]=\"optionComponent\"\n [ngComponentOutletInputs]=\"{ option: option, active: mentions().activeIndex() === index }\"/>\n } @else {\n {{ option.label }}\n }\n </ngs-menu-item>\n }\n</ngs-menu>\n", dependencies: [{ kind: "component", type: Menu, selector: "ngs-menu", inputs: ["role", "classList", "xPosition", "yPosition"], outputs: ["closed"], exportAs: ["ngsMenu"] }, { kind: "component", type: MenuItem, selector: "ngs-menu-item, [ngs-menu-item]", inputs: ["disabled", "role", "selected"], outputs: ["_triggered"], exportAs: ["ngsMenuItem"] }, { kind: "directive", type: NgComponentOutlet, selector: "[ngComponentOutlet]", inputs: ["ngComponentOutlet", "ngComponentOutletInputs", "ngComponentOutletInjector", "ngComponentOutletEnvironmentInjector", "ngComponentOutletContent", "ngComponentOutletNgModule"], exportAs: ["ngComponentOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
3327
|
+
}
|
|
3328
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorMentionMenu, decorators: [{
|
|
3329
|
+
type: Component,
|
|
3330
|
+
args: [{ selector: 'ngs-headless-editor-mention-menu', imports: [Menu, MenuItem, NgComponentOutlet], changeDetection: ChangeDetectionStrategy.OnPush, template: "<ngs-menu classList=\"max-h-72 min-w-64 overflow-y-auto\" >\n @for (option of mentions().suggestions(); track option.id; let index = $index) {\n <ngs-menu-item\n [attr.id]=\"mentions().optionId(index)\"\n [selected]=\"mentions().activeIndex() === index\"\n (click)=\"mentions().select(option)\">\n @if (mentions().optionComponent(); as optionComponent) {\n <ng-container\n [ngComponentOutlet]=\"optionComponent\"\n [ngComponentOutletInputs]=\"{ option: option, active: mentions().activeIndex() === index }\"/>\n } @else {\n {{ option.label }}\n }\n </ngs-menu-item>\n }\n</ngs-menu>\n" }]
|
|
3331
|
+
}], propDecorators: { mentions: [{ type: i0.Input, args: [{ isSignal: true, alias: "mentions", required: true }] }], menu: [{ type: i0.ViewChild, args: [i0.forwardRef(() => Menu), { isSignal: true }] }] } });
|
|
3332
|
+
|
|
3333
|
+
/**
|
|
3334
|
+
* Routes trigger/query to the matching mention plugin registration. Focus stays in the editor;
|
|
3335
|
+
* ArrowUp/Down, Enter/Tab and Escape control the suggestions. Works in nested
|
|
3336
|
+
* inline editors too. The menu owns its option templates; call select(option)
|
|
3337
|
+
* on click and use optionId(index) / activeIndex() for accessible highlighting.
|
|
3338
|
+
*/
|
|
3339
|
+
class NgsHeadlessEditorMentions {
|
|
3340
|
+
editor = inject(NgsHeadlessEditor);
|
|
3341
|
+
surface = inject(NgsHeadlessEditorSurface);
|
|
3342
|
+
host = inject(ElementRef).nativeElement;
|
|
3343
|
+
document = inject(DOCUMENT);
|
|
3344
|
+
overlay = inject(Overlay);
|
|
3345
|
+
viewContainer = inject(ViewContainerRef);
|
|
3346
|
+
config = inject(NGS_HEADLESS_EDITOR_MENTION_OPTIONS);
|
|
3347
|
+
initialized = signal(false, /* @ts-ignore */
|
|
3348
|
+
...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
|
|
3349
|
+
dismissed = signal(null, /* @ts-ignore */
|
|
3350
|
+
...(ngDevMode ? [{ debugName: "dismissed" }] : /* istanbul ignore next */ []));
|
|
3351
|
+
menuId = createNgsHeadlessEditorId('mentions');
|
|
3352
|
+
overlayRef = null;
|
|
3353
|
+
shownMenu = null;
|
|
3354
|
+
ariaHost = null;
|
|
3355
|
+
previousAria = new Map();
|
|
3356
|
+
frame = null;
|
|
3357
|
+
previousEditor = null;
|
|
3358
|
+
previousQuery = '';
|
|
3359
|
+
defaultMenu = null;
|
|
3360
|
+
menuClosed = null;
|
|
3361
|
+
menu = input(null, { ...(ngDevMode ? { debugName: "menu" } : /* istanbul ignore next */ {}), alias: 'ngsHeadlessEditorMentions' });
|
|
3362
|
+
/** Single-configuration compatibility override. Configure multiple triggers in the plugin's array. */
|
|
3363
|
+
options = input(null, { ...(ngDevMode ? { debugName: "options" } : /* istanbul ignore next */ {}), alias: 'mentionOptions' });
|
|
3364
|
+
/** Single-configuration compatibility override. */
|
|
3365
|
+
trigger = input(null, { ...(ngDevMode ? { debugName: "trigger" } : /* istanbul ignore next */ {}), alias: 'mentionTrigger' });
|
|
3366
|
+
selected = output({ alias: 'mentionSelected' });
|
|
3367
|
+
queryChange = output({ alias: 'mentionQueryChange' });
|
|
3368
|
+
target = computed(() => this.editor.inlineTarget() ?? this.editor, /* @ts-ignore */
|
|
3369
|
+
...(ngDevMode ? [{ debugName: "target" }] : /* istanbul ignore next */ []));
|
|
3370
|
+
registrations = computed(() => {
|
|
3371
|
+
const options = this.options();
|
|
3372
|
+
const trigger = this.trigger();
|
|
3373
|
+
if (this.config.length > 1 && (options !== null || trigger !== null)) {
|
|
3374
|
+
throw new Error('[NgsHeadlessEditor] Configure mention options and triggers in the plugin configurations when using multiple triggers.');
|
|
3375
|
+
}
|
|
3376
|
+
return this.config.map(config => ({
|
|
3377
|
+
...config,
|
|
3378
|
+
options: options ?? config.options,
|
|
3379
|
+
trigger: trigger ?? config.trigger
|
|
3380
|
+
})).sort((left, right) => right.trigger.length - left.trigger.length);
|
|
3381
|
+
}, /* @ts-ignore */
|
|
3382
|
+
...(ngDevMode ? [{ debugName: "registrations" }] : /* istanbul ignore next */ []));
|
|
3383
|
+
session = computed(() => {
|
|
3384
|
+
const target = this.target();
|
|
3385
|
+
if (!this.initialized() || this.surface.disabled() || this.editor.readOnly() || !target.focused())
|
|
3386
|
+
return null;
|
|
3387
|
+
for (const registration of this.registrations()) {
|
|
3388
|
+
const match = findNgsHeadlessEditorMentionQuery(target, registration.trigger);
|
|
3389
|
+
if (match)
|
|
3390
|
+
return { registration, match };
|
|
3391
|
+
}
|
|
3392
|
+
return null;
|
|
3393
|
+
}, /* @ts-ignore */
|
|
3394
|
+
...(ngDevMode ? [{ debugName: "session" }] : /* istanbul ignore next */ []));
|
|
3395
|
+
match = computed(() => this.session()?.match ?? null, /* @ts-ignore */
|
|
3396
|
+
...(ngDevMode ? [{ debugName: "match" }] : /* istanbul ignore next */ []));
|
|
3397
|
+
/** Settings of the plugin handling the current query, or null outside a query. */
|
|
3398
|
+
registration = computed(() => this.session()?.registration ?? null, /* @ts-ignore */
|
|
3399
|
+
...(ngDevMode ? [{ debugName: "registration" }] : /* istanbul ignore next */ []));
|
|
3400
|
+
activeTrigger = computed(() => this.match()?.trigger ?? null, /* @ts-ignore */
|
|
3401
|
+
...(ngDevMode ? [{ debugName: "activeTrigger" }] : /* istanbul ignore next */ []));
|
|
3402
|
+
optionComponent = computed(() => this.registration()?.optionComponent, /* @ts-ignore */
|
|
3403
|
+
...(ngDevMode ? [{ debugName: "optionComponent" }] : /* istanbul ignore next */ []));
|
|
3404
|
+
query = computed(() => this.match()?.query ?? null, /* @ts-ignore */
|
|
3405
|
+
...(ngDevMode ? [{ debugName: "query" }] : /* istanbul ignore next */ []));
|
|
3406
|
+
results = signal([], /* @ts-ignore */
|
|
3407
|
+
...(ngDevMode ? [{ debugName: "results" }] : /* istanbul ignore next */ []));
|
|
3408
|
+
searching = signal(false, /* @ts-ignore */
|
|
3409
|
+
...(ngDevMode ? [{ debugName: "searching" }] : /* istanbul ignore next */ []));
|
|
3410
|
+
searchError = signal(null, /* @ts-ignore */
|
|
3411
|
+
...(ngDevMode ? [{ debugName: "searchError" }] : /* istanbul ignore next */ []));
|
|
3412
|
+
suggestions = this.results.asReadonly();
|
|
3413
|
+
loading = this.searching.asReadonly();
|
|
3414
|
+
error = this.searchError.asReadonly();
|
|
3415
|
+
activeIndex = signal(0, /* @ts-ignore */
|
|
3416
|
+
...(ngDevMode ? [{ debugName: "activeIndex" }] : /* istanbul ignore next */ []));
|
|
3417
|
+
open = computed(() => {
|
|
3418
|
+
const match = this.match();
|
|
3419
|
+
return match !== null && !sameQuery(match, this.dismissed()) && this.suggestions().length > 0;
|
|
3420
|
+
}, /* @ts-ignore */
|
|
3421
|
+
...(ngDevMode ? [{ debugName: "open" }] : /* istanbul ignore next */ []));
|
|
3422
|
+
constructor() {
|
|
3423
|
+
effect(onCleanup => {
|
|
3424
|
+
const query = this.query();
|
|
3425
|
+
const search = this.registration()?.options;
|
|
3426
|
+
// Changing the nested editor invalidates a request even for the same query.
|
|
3427
|
+
this.target();
|
|
3428
|
+
let cancelled = false;
|
|
3429
|
+
onCleanup(() => { cancelled = true; });
|
|
3430
|
+
untracked(() => {
|
|
3431
|
+
this.results.set([]);
|
|
3432
|
+
this.searchError.set(null);
|
|
3433
|
+
this.searching.set(query !== null);
|
|
3434
|
+
if (query === null || !search) {
|
|
3435
|
+
this.searching.set(false);
|
|
3436
|
+
return;
|
|
3437
|
+
}
|
|
3438
|
+
void (async () => {
|
|
3439
|
+
try {
|
|
3440
|
+
const options = await search(query);
|
|
3441
|
+
if (!cancelled)
|
|
3442
|
+
this.results.set(options);
|
|
3443
|
+
}
|
|
3444
|
+
catch (error) {
|
|
3445
|
+
if (!cancelled)
|
|
3446
|
+
this.searchError.set(error);
|
|
3447
|
+
}
|
|
3448
|
+
finally {
|
|
3449
|
+
if (!cancelled)
|
|
3450
|
+
this.searching.set(false);
|
|
3451
|
+
}
|
|
3452
|
+
})();
|
|
3453
|
+
});
|
|
3454
|
+
});
|
|
3455
|
+
effect(() => {
|
|
3456
|
+
const query = this.query();
|
|
3457
|
+
untracked(() => this.queryChange.emit(query));
|
|
3458
|
+
});
|
|
3459
|
+
effect(() => {
|
|
3460
|
+
const target = this.target();
|
|
3461
|
+
const match = this.match();
|
|
3462
|
+
const count = this.suggestions().length;
|
|
3463
|
+
const key = match ? `${match.trigger}:${match.blockId}:${match.from}:${match.to}:${match.query}` : '';
|
|
3464
|
+
untracked(() => {
|
|
3465
|
+
if (target !== this.previousEditor || key !== this.previousQuery) {
|
|
3466
|
+
this.activeIndex.set(0);
|
|
3467
|
+
this.dismissed.set(null);
|
|
3468
|
+
}
|
|
3469
|
+
else if (this.activeIndex() >= count) {
|
|
3470
|
+
this.activeIndex.set(Math.max(0, count - 1));
|
|
3471
|
+
}
|
|
3472
|
+
this.previousEditor = target;
|
|
3473
|
+
this.previousQuery = key;
|
|
3474
|
+
});
|
|
3475
|
+
});
|
|
3476
|
+
effect(() => {
|
|
3477
|
+
this.open();
|
|
3478
|
+
this.menu();
|
|
3479
|
+
this.activeIndex();
|
|
3480
|
+
this.match();
|
|
3481
|
+
untracked(() => this.schedulePosition());
|
|
3482
|
+
});
|
|
3483
|
+
const destroyRef = inject(DestroyRef);
|
|
3484
|
+
afterNextRender(() => {
|
|
3485
|
+
this.initialized.set(true);
|
|
3486
|
+
// Capture before the surface processes Enter or a table handles Tab.
|
|
3487
|
+
this.host.addEventListener('keydown', this.onKeydown, true);
|
|
3488
|
+
this.document.addEventListener('scroll', this.onViewportChange, true);
|
|
3489
|
+
this.document.defaultView?.addEventListener('resize', this.onViewportChange);
|
|
3490
|
+
});
|
|
3491
|
+
destroyRef.onDestroy(() => {
|
|
3492
|
+
this.host.removeEventListener('keydown', this.onKeydown, true);
|
|
3493
|
+
this.document.removeEventListener('scroll', this.onViewportChange, true);
|
|
3494
|
+
this.document.defaultView?.removeEventListener('resize', this.onViewportChange);
|
|
3495
|
+
if (this.frame !== null)
|
|
3496
|
+
this.document.defaultView?.cancelAnimationFrame(this.frame);
|
|
3497
|
+
this.clearAria();
|
|
3498
|
+
this.menuClosed?.unsubscribe();
|
|
3499
|
+
this.overlayRef?.dispose();
|
|
3500
|
+
this.defaultMenu?.destroy();
|
|
3501
|
+
});
|
|
3502
|
+
}
|
|
3503
|
+
optionId(index) {
|
|
3504
|
+
return `${this.menuId}-option-${index}`;
|
|
3505
|
+
}
|
|
3506
|
+
select(option) {
|
|
3507
|
+
const match = this.match();
|
|
3508
|
+
if (!match || !this.open() || !this.suggestions().includes(option))
|
|
3509
|
+
return false;
|
|
3510
|
+
const inserted = insertNgsHeadlessEditorMention(this.target(), option, match);
|
|
3511
|
+
if (inserted) {
|
|
3512
|
+
this.closeOverlay();
|
|
3513
|
+
this.selected.emit(option);
|
|
3514
|
+
}
|
|
3515
|
+
return inserted;
|
|
3516
|
+
}
|
|
3517
|
+
dismiss() {
|
|
3518
|
+
this.dismissed.set(this.match());
|
|
3519
|
+
this.closeOverlay();
|
|
3520
|
+
}
|
|
3521
|
+
onKeydown = (event) => {
|
|
3522
|
+
const match = this.match();
|
|
3523
|
+
if (!match || sameQuery(match, this.dismissed()) || event.isComposing || event.ctrlKey || event.metaKey || event.altKey)
|
|
3524
|
+
return;
|
|
3525
|
+
const selection = this.document.getSelection();
|
|
3526
|
+
if (!selection?.anchorNode || !this.host.contains(selection.anchorNode))
|
|
3527
|
+
return;
|
|
3528
|
+
// Escape also dismisses a pending search, so its response cannot reopen the menu.
|
|
3529
|
+
if (event.key !== 'Escape' && !this.open())
|
|
3530
|
+
return;
|
|
3531
|
+
switch (event.key) {
|
|
3532
|
+
case 'ArrowDown':
|
|
3533
|
+
case 'ArrowUp': {
|
|
3534
|
+
const count = this.suggestions().length;
|
|
3535
|
+
this.activeIndex.update(index => (index + (event.key === 'ArrowDown' ? 1 : count - 1)) % count);
|
|
3536
|
+
break;
|
|
3537
|
+
}
|
|
3538
|
+
case 'Enter':
|
|
3539
|
+
case 'Tab':
|
|
3540
|
+
if (event.shiftKey)
|
|
3541
|
+
return;
|
|
3542
|
+
this.select(this.suggestions()[this.activeIndex()]);
|
|
3543
|
+
break;
|
|
3544
|
+
case 'Escape':
|
|
3545
|
+
this.dismiss();
|
|
3546
|
+
break;
|
|
3547
|
+
default: return;
|
|
3548
|
+
}
|
|
3549
|
+
event.preventDefault();
|
|
3550
|
+
event.stopImmediatePropagation();
|
|
3551
|
+
};
|
|
3552
|
+
onViewportChange = () => this.schedulePosition();
|
|
3553
|
+
schedulePosition() {
|
|
3554
|
+
const window = this.document.defaultView;
|
|
3555
|
+
if (!this.initialized() || !window)
|
|
3556
|
+
return;
|
|
3557
|
+
if (this.frame !== null)
|
|
3558
|
+
window.cancelAnimationFrame(this.frame);
|
|
3559
|
+
this.frame = window.requestAnimationFrame(() => {
|
|
3560
|
+
this.frame = null;
|
|
3561
|
+
this.positionMenu();
|
|
3562
|
+
});
|
|
3563
|
+
}
|
|
3564
|
+
positionMenu() {
|
|
3565
|
+
const selection = this.document.getSelection();
|
|
3566
|
+
if (!this.open() || !selection?.anchorNode || !selection.isCollapsed ||
|
|
3567
|
+
!this.host.contains(selection.anchorNode) || selection.rangeCount === 0) {
|
|
3568
|
+
this.closeOverlay();
|
|
3569
|
+
return;
|
|
3570
|
+
}
|
|
3571
|
+
const range = selection.getRangeAt(0).cloneRange();
|
|
3572
|
+
let rect = range.getBoundingClientRect();
|
|
3573
|
+
if (rect.height === 0 && range.startContainer.nodeType === 3 && range.startOffset > 0) {
|
|
3574
|
+
range.setStart(range.startContainer, range.startOffset - 1);
|
|
3575
|
+
rect = range.getBoundingClientRect();
|
|
3576
|
+
rect = new DOMRect(rect.right, rect.top, 0, rect.height);
|
|
3577
|
+
}
|
|
3578
|
+
if (rect.height === 0) {
|
|
3579
|
+
this.closeOverlay();
|
|
3580
|
+
return;
|
|
3581
|
+
}
|
|
3582
|
+
const menu = this.resolveMenu();
|
|
3583
|
+
if (this.shownMenu !== menu)
|
|
3584
|
+
this.closeOverlay();
|
|
3585
|
+
const strategy = this.overlay.position().flexibleConnectedTo({ x: rect.left, y: rect.bottom })
|
|
3586
|
+
.withPositions([
|
|
3587
|
+
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top', offsetY: 4 },
|
|
3588
|
+
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -rect.height - 4 }
|
|
3589
|
+
]).withPush(true).withViewportMargin(8);
|
|
3590
|
+
if (!this.overlayRef) {
|
|
3591
|
+
this.overlayRef = this.overlay.create({
|
|
3592
|
+
positionStrategy: strategy,
|
|
3593
|
+
scrollStrategy: this.overlay.scrollStrategies.reposition(),
|
|
3594
|
+
hasBackdrop: false
|
|
3595
|
+
});
|
|
3596
|
+
this.overlayRef.outsidePointerEvents().subscribe(event => {
|
|
3597
|
+
if (!(event.target instanceof Node) || !this.host.contains(event.target))
|
|
3598
|
+
this.dismiss();
|
|
3599
|
+
});
|
|
3600
|
+
this.overlayRef.overlayElement.addEventListener('mousedown', event => event.preventDefault());
|
|
3601
|
+
}
|
|
3602
|
+
else {
|
|
3603
|
+
this.overlayRef.updatePositionStrategy(strategy);
|
|
3604
|
+
}
|
|
3605
|
+
if (!this.overlayRef.hasAttached()) {
|
|
3606
|
+
this.overlayRef.overlayElement.id = this.menuId;
|
|
3607
|
+
this.overlayRef.attach(new TemplatePortal(menu.templateRef(), this.viewContainer));
|
|
3608
|
+
this.shownMenu = menu;
|
|
3609
|
+
this.menuClosed = menu.closed.subscribe(reason => {
|
|
3610
|
+
// MenuItem emits its host click before the consumer's (click) handler.
|
|
3611
|
+
// Let select(option) run before dismissing a click-closed menu.
|
|
3612
|
+
if (reason === 'click') {
|
|
3613
|
+
queueMicrotask(() => {
|
|
3614
|
+
if (this.shownMenu === menu)
|
|
3615
|
+
this.dismiss();
|
|
3616
|
+
});
|
|
3617
|
+
}
|
|
3618
|
+
else {
|
|
3619
|
+
this.dismiss();
|
|
3620
|
+
}
|
|
3621
|
+
});
|
|
3622
|
+
}
|
|
3623
|
+
const anchor = selection.anchorNode.nodeType === 1
|
|
3624
|
+
? selection.anchorNode : selection.anchorNode.parentElement;
|
|
3625
|
+
const surface = anchor?.closest('[ngsHeadlessEditorSurface]') ?? this.host;
|
|
3626
|
+
if (this.ariaHost !== surface) {
|
|
3627
|
+
this.clearAria();
|
|
3628
|
+
this.ariaHost = surface;
|
|
3629
|
+
for (const name of ['aria-autocomplete', 'aria-expanded', 'aria-controls', 'aria-activedescendant']) {
|
|
3630
|
+
this.previousAria.set(name, surface.getAttribute(name));
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
surface.setAttribute('aria-autocomplete', 'list');
|
|
3634
|
+
surface.setAttribute('aria-expanded', 'true');
|
|
3635
|
+
surface.setAttribute('aria-controls', this.menuId);
|
|
3636
|
+
const activeId = this.optionId(this.activeIndex());
|
|
3637
|
+
if (this.document.getElementById(activeId))
|
|
3638
|
+
surface.setAttribute('aria-activedescendant', activeId);
|
|
3639
|
+
this.document.getElementById(activeId)?.scrollIntoView({ block: 'nearest' });
|
|
3640
|
+
}
|
|
3641
|
+
closeOverlay() {
|
|
3642
|
+
this.clearAria();
|
|
3643
|
+
this.menuClosed?.unsubscribe();
|
|
3644
|
+
this.menuClosed = null;
|
|
3645
|
+
this.overlayRef?.detach();
|
|
3646
|
+
this.shownMenu = null;
|
|
3647
|
+
}
|
|
3648
|
+
resolveMenu() {
|
|
3649
|
+
const menu = this.menu();
|
|
3650
|
+
if (menu)
|
|
3651
|
+
return menu;
|
|
3652
|
+
if (!this.defaultMenu) {
|
|
3653
|
+
this.defaultMenu = this.viewContainer.createComponent(NgsHeadlessEditorMentionMenu);
|
|
3654
|
+
this.defaultMenu.setInput('mentions', this);
|
|
3655
|
+
this.defaultMenu.changeDetectorRef.detectChanges();
|
|
3656
|
+
}
|
|
3657
|
+
return this.defaultMenu.instance.menu();
|
|
3658
|
+
}
|
|
3659
|
+
clearAria() {
|
|
3660
|
+
for (const [name, value] of this.previousAria) {
|
|
3661
|
+
if (value === null)
|
|
3662
|
+
this.ariaHost?.removeAttribute(name);
|
|
3663
|
+
else
|
|
3664
|
+
this.ariaHost?.setAttribute(name, value);
|
|
3665
|
+
}
|
|
3666
|
+
this.previousAria.clear();
|
|
3667
|
+
this.ariaHost = null;
|
|
3668
|
+
}
|
|
3669
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorMentions, deps: [], target: i0.ɵɵFactoryTarget.Directive });
|
|
3670
|
+
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.7", type: NgsHeadlessEditorMentions, isStandalone: true, selector: "[ngsHeadlessEditorSurface][ngsHeadlessEditorMentions]", inputs: { menu: { classPropertyName: "menu", publicName: "ngsHeadlessEditorMentions", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "mentionOptions", isSignal: true, isRequired: false, transformFunction: null }, trigger: { classPropertyName: "trigger", publicName: "mentionTrigger", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { selected: "mentionSelected", queryChange: "mentionQueryChange" }, exportAs: ["ngsHeadlessEditorMentions"], ngImport: i0 });
|
|
3671
|
+
}
|
|
3672
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: NgsHeadlessEditorMentions, decorators: [{
|
|
3673
|
+
type: Directive,
|
|
3674
|
+
args: [{
|
|
3675
|
+
selector: '[ngsHeadlessEditorSurface][ngsHeadlessEditorMentions]',
|
|
3676
|
+
exportAs: 'ngsHeadlessEditorMentions'
|
|
3677
|
+
}]
|
|
3678
|
+
}], ctorParameters: () => [], propDecorators: { menu: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsHeadlessEditorMentions", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "mentionOptions", required: false }] }], trigger: [{ type: i0.Input, args: [{ isSignal: true, alias: "mentionTrigger", required: false }] }], selected: [{ type: i0.Output, args: ["mentionSelected"] }], queryChange: [{ type: i0.Output, args: ["mentionQueryChange"] }] } });
|
|
3679
|
+
function sameQuery(left, right) {
|
|
3680
|
+
return right !== null && left.blockId === right.blockId && left.from === right.from &&
|
|
3681
|
+
left.to === right.to && left.query === right.query && left.trigger === right.trigger;
|
|
3682
|
+
}
|
|
3683
|
+
|
|
3684
|
+
/**
|
|
3685
|
+
* Generated bundle index. Do not edit.
|
|
3686
|
+
*/
|
|
3687
|
+
|
|
3688
|
+
export { NGS_HEADLESS_EDITOR_BACKGROUND_COLOR_MARK, NGS_HEADLESS_EDITOR_HISTORY_GROUP_DELAY, NGS_HEADLESS_EDITOR_HISTORY_LIMIT, NGS_HEADLESS_EDITOR_INSERT_TABLE, NGS_HEADLESS_EDITOR_MARK_ATTRIBUTE, NGS_HEADLESS_EDITOR_MENTION_MARK, NGS_HEADLESS_EDITOR_MENTION_OPTIONS, NGS_HEADLESS_EDITOR_PLUGINS, NGS_HEADLESS_EDITOR_SET_BACKGROUND_COLOR, NGS_HEADLESS_EDITOR_SET_TEXT_COLOR, NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_AFTER, NGS_HEADLESS_EDITOR_TABLE_ADD_COLUMN_BEFORE, NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_AFTER, NGS_HEADLESS_EDITOR_TABLE_ADD_ROW_BEFORE, NGS_HEADLESS_EDITOR_TABLE_DELETE, NGS_HEADLESS_EDITOR_TABLE_DELETE_COLUMN, NGS_HEADLESS_EDITOR_TABLE_DELETE_ROW, NGS_HEADLESS_EDITOR_TABLE_OPTIONS, NGS_HEADLESS_EDITOR_TABLE_TOGGLE_HEADER, NGS_HEADLESS_EDITOR_TABLE_TYPE, NGS_HEADLESS_EDITOR_TEXT_COLOR_MARK, NGS_HEADLESS_EDITOR_TOGGLE_BOLD, NGS_HEADLESS_EDITOR_TOGGLE_CODE, NGS_HEADLESS_EDITOR_TOGGLE_ITALIC, NGS_HEADLESS_EDITOR_TOGGLE_STRIKE, NGS_HEADLESS_EDITOR_UNSET_BACKGROUND_COLOR, NGS_HEADLESS_EDITOR_UNSET_TEXT_COLOR, NgsHeadlessEditor, NgsHeadlessEditorCommandDirective, NgsHeadlessEditorHistory, NgsHeadlessEditorInlineRegion, NgsHeadlessEditorMentionMenu, NgsHeadlessEditorMentions, NgsHeadlessEditorRuns, NgsHeadlessEditorSurface, NgsHeadlessEditorTableBlockEditor, NgsHeadlessEditorTableView, basicTextEditorPlugin, cloneNgsHeadlessEditorDocument, colorEditorPlugin, createNgsHeadlessEditorDocument, createNgsHeadlessEditorId, createNgsHeadlessEditorParagraph, createNgsHeadlessEditorTable, createNgsHeadlessEditorText, defineNgsHeadlessEditorPlugin, findNgsHeadlessEditorMarkDefinition, findNgsHeadlessEditorMentionQuery, focusNgsHeadlessEditorTableCell, getNgsHeadlessEditorBlockText, getNgsHeadlessEditorDocumentText, getNgsHeadlessEditorTableCellText, getNgsHeadlessEditorTableData, insertNgsHeadlessEditorMention, insertNgsHeadlessEditorTable, insertNgsHeadlessEditorTableColumn, insertNgsHeadlessEditorTableRow, isNgsHeadlessEditorDocumentEmpty, isNgsHeadlessEditorTable, isNgsHeadlessEditorTextContent, mentionEditorPlugin, ngsHeadlessEditorActiveTableCell, ngsHeadlessEditorBlocksEqual, ngsHeadlessEditorDocumentsEqual, ngsHeadlessEditorMarksEqual, ngsHeadlessEditorTableCellMarks, ngsHeadlessEditorValuesEqual, normalizeNgsHeadlessEditorColor, normalizeNgsHeadlessEditorDocument, normalizeNgsHeadlessEditorMarks, normalizeNgsHeadlessEditorTableCell, normalizeNgsHeadlessEditorTableRows, normalizeNgsHeadlessEditorTextContent, parseNgsHeadlessEditorTableHtml, parseNgsHeadlessEditorTableText, pendingNgsHeadlessEditorTableFocus, provideNgsHeadlessEditor, provideNgsHeadlessEditorInlineRegion, readNgsHeadlessEditorInlineContent, removeNgsHeadlessEditorTableColumn, removeNgsHeadlessEditorTableRow, renderNgsHeadlessEditorRuns, renderNgsHeadlessEditorTextRun, setNgsHeadlessEditorActiveTableCell, setNgsHeadlessEditorTableCell, tableEditorPlugin, withHeadlessEditorPlugin };
|
|
3689
|
+
//# sourceMappingURL=ngstarter-ui-components-headless-editor.mjs.map
|