-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
536 lines (443 loc) · 15.1 KB
/
index.ts
File metadata and controls
536 lines (443 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import { isNativeInput } from '@editorjs/dom';
import {
type EditorJSModel,
type DataKey,
createDataKey,
EventAction,
EventType,
IndexBuilder,
type ModelEvents,
TextAddedEvent,
TextRemovedEvent
} from '@editorjs/model';
import type { CaretAdapter } from '../CaretAdapter/index.js';
import {
findNextHardLineBoundary,
findNextWordBoundary, findPreviousHardLineBoundary,
findPreviousWordBoundary,
getAbsoluteRangeOffset,
getBoundaryPointByAbsoluteOffset,
isNonTextInput
} from '../utils/index.js';
import { InputType } from './types/InputType.js';
import type { BlockToolAdapter as BlockToolAdapterInterface, CoreConfig } from '@editorjs/sdk';
import type { FormattingAdapter } from '../FormattingAdapter/index.js';
import type { EventBus } from '@editorjs/sdk';
/**
* BlockToolAdapter is using inside Block tools to connect browser DOM elements to the model
* It can handle beforeinput events and update model data
* It can handle model's change events and update DOM
*/
export class BlockToolAdapter implements BlockToolAdapterInterface {
/**
* Model instance
*/
#model: EditorJSModel;
/**
* Index of the block that this adapter is connected to
*/
#blockIndex: number;
/**
* Caret adapter instance
*/
#caretAdapter: CaretAdapter;
/**
* Formatting adapter instance
*/
#formattingAdapter: FormattingAdapter;
/**
* Name of the tool that this adapter is connected to
*/
#toolName: string;
/**
* Editor's config
*/
#config: CoreConfig;
/**
* BlockToolAdapter constructor
*
* @param config - Editor's config
* @param model - EditorJSModel instance
* @param eventBus - Editor EventBus instance
* @param caretAdapter - CaretAdapter instance
* @param blockIndex - index of the block that this adapter is connected to
* @param formattingAdapter - needed to render formatted text
* @param toolName - tool name of the block
*/
constructor(config: CoreConfig, model: EditorJSModel, eventBus: EventBus, caretAdapter: CaretAdapter, blockIndex: number, formattingAdapter: FormattingAdapter, toolName: string) {
this.#config = config;
this.#model = model;
this.#blockIndex = blockIndex;
this.#caretAdapter = caretAdapter;
this.#formattingAdapter = formattingAdapter;
this.#toolName = toolName;
}
/**
* Attaches input to the model using key
* It handles beforeinput events and updates model data
*
* @param keyRaw - tools data key to attach input to
* @param input - input element
*/
public attachInput(keyRaw: string, input: HTMLElement): void {
if (input instanceof HTMLInputElement && isNonTextInput(input)) {
throw new Error('Cannot attach non-text input');
}
const key = createDataKey(keyRaw);
input.addEventListener('beforeinput', event => this.#handleBeforeInputEvent(event, input, key));
this.#model.addEventListener(EventType.Changed, (event: ModelEvents) => this.#handleModelUpdate(event, input, key));
const builder = new IndexBuilder();
builder.addBlockIndex(this.#blockIndex).addDataKey(key);
this.#caretAdapter.attachInput(input, builder.build());
try {
const value = this.#model.getText(this.#blockIndex, key);
const fragments = this.#model.getFragments(this.#blockIndex, key);
input.textContent = value;
fragments.forEach(fragment => {
this.#formattingAdapter.formatElementContent(input, fragment);
});
} catch (_) {
// do nothing — TextNode is not created yet as there is no initial data in the model
}
}
/**
* Handles delete events in native input
*
* @param event - beforeinput event
* @param input - input element
* @param key - data key input is attached to
* @private
*/
#handleDeleteInNativeInput(event: InputEvent, input: HTMLInputElement | HTMLTextAreaElement, key: DataKey): void {
const inputType = event.inputType as InputType;
/**
* Check that selection exists in current input
*/
if (input.selectionStart === null || input.selectionEnd === null) {
return;
}
let start = input.selectionStart;
let end = input.selectionEnd;
/**
* If selection is not collapsed, just remove selected text
*/
if (start !== end) {
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, end);
return;
}
switch (inputType) {
case InputType.DeleteContentForward: {
/**
* If selection end is already after the last element, then there is nothing to delete
*/
end = end !== input.value.length ? end + 1 : end;
break;
}
case InputType.DeleteContentBackward: {
/**
* If start is already 0, then there is nothing to delete
*/
start = start !== 0 ? start - 1 : start;
break;
}
case InputType.DeleteWordBackward: {
start = findPreviousWordBoundary(input.value, start);
break;
}
case InputType.DeleteWordForward: {
end = findNextWordBoundary(input.value, start);
break;
}
case InputType.DeleteHardLineBackward: {
start = findPreviousHardLineBoundary(input.value, start);
break;
}
case InputType.DeleteHardLineForward: {
end = findNextHardLineBoundary(input.value, start);
break;
}
case InputType.DeleteSoftLineBackward:
case InputType.DeleteSoftLineForward:
case InputType.DeleteEntireSoftLine:
/**
* @todo Think of how to find soft line boundaries
*/
case InputType.DeleteByDrag:
case InputType.DeleteByCut:
case InputType.DeleteContent:
default:
/**
* do nothing, use start and end from user selection
*/
}
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, end);
};
/**
* Handles delete events in contenteditable element
*
* @param event - beforeinput event
* @param input - input element
* @param key - data key input is attached to
*/
#handleDeleteInContentEditable(event: InputEvent, input: HTMLElement, key: DataKey): void {
const targetRanges = event.getTargetRanges();
const range = targetRanges[0];
const start: number = getAbsoluteRangeOffset(input, range.startContainer, range.startOffset);
const end: number = getAbsoluteRangeOffset(input, range.endContainer, range.endOffset);
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, end);
};
/**
* Handles beforeinput event from user input and updates model data
*
* We prevent beforeinput event of any type to handle it manually via model update
*
* @param event - beforeinput event
* @param input - input element
* @param key - data key input is attached to
*/
#handleBeforeInputEvent(event: InputEvent, input: HTMLElement, key: DataKey): void {
/**
* We prevent all events to handle them manually via model update
*/
event.preventDefault();
const isInputNative = isNativeInput(input);
const inputType = event.inputType as InputType;
let start: number;
let end: number;
if (isInputNative === false) {
const targetRanges = event.getTargetRanges();
const range = targetRanges[0];
start = getAbsoluteRangeOffset(input, range.startContainer, range.startOffset);
end = getAbsoluteRangeOffset(input, range.endContainer, range.endOffset);
} else {
const currentElement = input as HTMLInputElement | HTMLTextAreaElement;
start = currentElement.selectionStart as number;
end = currentElement.selectionEnd as number;
}
switch (inputType) {
case InputType.InsertReplacementText:
case InputType.InsertFromDrop:
case InputType.InsertFromPaste: {
if (start !== end) {
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, end);
}
let data: string;
/**
* For native inputs data for those events comes from event.data property
* while for contenteditable elements it's stored in event.dataTransfer
*
* @see https://www.w3.org/TR/input-events-2/#overview
*/
if (isInputNative) {
data = event.data ?? '';
} else {
data = event.dataTransfer!.getData('text/plain');
}
this.#model.insertText(this.#config.userId, this.#blockIndex, key, data, start);
break;
}
case InputType.InsertText:
/**
* @todo Handle composition events
*/
case InputType.InsertCompositionText: {
/**
* If start and end aren't equal,
* it means that user selected some text and replaced it with new one
*/
if (start !== end) {
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, end);
}
const data = event.data as string;
this.#model.insertText(this.#config.userId, this.#blockIndex, key, data, start);
break;
}
case InputType.DeleteContent:
case InputType.DeleteContentBackward:
case InputType.DeleteContentForward:
case InputType.DeleteByCut:
case InputType.DeleteByDrag:
case InputType.DeleteHardLineBackward:
case InputType.DeleteHardLineForward:
case InputType.DeleteSoftLineBackward:
case InputType.DeleteSoftLineForward:
case InputType.DeleteEntireSoftLine:
case InputType.DeleteWordBackward:
case InputType.DeleteWordForward: {
if (isInputNative === true) {
this.#handleDeleteInNativeInput(event, input as HTMLInputElement | HTMLTextAreaElement, key);
} else {
this.#handleDeleteInContentEditable(event, input, key);
}
break;
}
case InputType.InsertParagraph:
this.#handleSplit(key, start, end);
break;
case InputType.InsertLineBreak:
/**
* @todo Think if we need to keep that or not
*/
if (isInputNative === true) {
this.#model.insertText(this.#config.userId, this.#blockIndex, key, '\n', start);
}
break;
default:
}
};
/**
* Splits the current block's data field at the specified index
* Removes selected range if it's not collapsed
* Sets caret to the beginning of the next block
*
* @param key - data key to split
* @param start - start index of the split
* @param end - end index of the selected range
*/
#handleSplit(key: DataKey, start: number, end: number): void {
const currentValue = this.#model.getText(this.#blockIndex, key);
const newValueAfter = currentValue.slice(end);
this.#model.removeText(this.#config.userId, this.#blockIndex, key, start, currentValue.length);
this.#model.addBlock(
this.#config.userId,
{
name: this.#toolName,
data : {
[key]: {
$t: 't',
value: newValueAfter,
fragments: [],
},
},
},
this.#blockIndex + 1
);
/**
* Raf is needed to ensure that the new block is added so caret can be moved to it
*/
requestAnimationFrame(() => {
this.#caretAdapter.updateIndex(
new IndexBuilder()
.addBlockIndex(this.#blockIndex + 1)
.addDataKey(key)
.addTextRange([0, 0])
.build()
);
});
}
/**
* Handles model update events for native inputs and updates DOM
*
* @param event - model update event
* @param input - input element
* @param key - data key input is attached to
*/
#handleModelUpdateForNativeInput(event: ModelEvents, input: HTMLInputElement | HTMLTextAreaElement, key: DataKey): void {
if (!(event instanceof TextAddedEvent) && !(event instanceof TextRemovedEvent)) {
return;
}
const { textRange, dataKey, blockIndex } = event.detail.index;
if (textRange === undefined) {
return;
}
/**
* Event is not related to the attached block
*/
if (blockIndex !== this.#blockIndex) {
return;
}
/**
* Event is not related to the attached data key
*/
if (dataKey !== key) {
return;
}
const currentElement = input;
const [start, end] = textRange;
const action = event.detail.action;
const caretIndexBuilder = new IndexBuilder();
caretIndexBuilder.from(event.detail.index);
switch (action) {
case EventAction.Added: {
const text = event.detail.data as string;
const prevValue = currentElement.value;
currentElement.value = prevValue.slice(0, start) + text + prevValue.slice(start);
caretIndexBuilder.addTextRange([start + text.length, start + text.length]);
break;
}
case EventAction.Removed: {
currentElement.value = currentElement.value.slice(0, start) +
currentElement.value.slice(end);
caretIndexBuilder.addTextRange([start, start]);
break;
}
}
this.#caretAdapter.updateIndex(caretIndexBuilder.build());
};
/**
* Handles model update events for contenteditable elements and updates DOM
*
* @param event - model update event
* @param input - input element
* @param key - data key input is attached to
*/
#handleModelUpdateForContentEditableElement(event: ModelEvents, input: HTMLElement, key: DataKey): void {
if (!(event instanceof TextAddedEvent) && !(event instanceof TextRemovedEvent)) {
return;
}
const { textRange, dataKey, blockIndex } = event.detail.index;
if (blockIndex !== this.#blockIndex) {
return;
}
/**
* Event is not related to the attached data key
*/
if (dataKey !== key) {
return;
}
if (textRange === undefined) {
return;
}
const action = event.detail.action;
const start = textRange[0];
const end = textRange[1];
const [startNode, startOffset] = getBoundaryPointByAbsoluteOffset(input, start);
const [endNode, endOffset] = getBoundaryPointByAbsoluteOffset(input, end);
const range = new Range();
range.setStart(startNode, startOffset);
const builder = new IndexBuilder();
builder.addDataKey(key).addBlockIndex(this.#blockIndex);
switch (action) {
case EventAction.Added: {
const text = event.detail.data as string;
const textNode = document.createTextNode(text);
range.insertNode(textNode);
builder.addTextRange([start + text.length, start + text.length]);
break;
}
case EventAction.Removed: {
range.setEnd(endNode, endOffset);
range.deleteContents();
builder.addTextRange([start, start]);
break;
}
}
input.normalize();
this.#caretAdapter.updateIndex(builder.build());
};
/**
* Handles model update events and updates DOM
*
* @param event - model update event
* @param input - attched input element
* @param key - data key input is attached to
*/
#handleModelUpdate(event: ModelEvents, input: HTMLElement, key: DataKey): void {
const isInputNative = isNativeInput(input);
if (isInputNative === true) {
this.#handleModelUpdateForNativeInput(event, input as HTMLInputElement | HTMLTextAreaElement, key);
} else {
this.#handleModelUpdateForContentEditableElement(event, input, key);
}
};
}