@ckeditor/ckeditor5-typing 0.0.0-internal-20241017.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/LICENSE.md +21 -0
  3. package/README.md +22 -0
  4. package/ckeditor5-metadata.json +11 -0
  5. package/dist/augmentation.d.ts +31 -0
  6. package/dist/delete.d.ts +40 -0
  7. package/dist/deletecommand.d.ts +87 -0
  8. package/dist/deleteobserver.d.ts +59 -0
  9. package/dist/index-content.css +4 -0
  10. package/dist/index-editor.css +4 -0
  11. package/dist/index.css +4 -0
  12. package/dist/index.d.ts +29 -0
  13. package/dist/index.js +2490 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/input.d.ts +37 -0
  16. package/dist/inserttextcommand.d.ts +80 -0
  17. package/dist/inserttextobserver.d.ts +59 -0
  18. package/dist/texttransformation.d.ts +41 -0
  19. package/dist/textwatcher.d.ts +142 -0
  20. package/dist/twostepcaretmovement.d.ts +240 -0
  21. package/dist/typing.d.ts +31 -0
  22. package/dist/typingconfig.d.ts +208 -0
  23. package/dist/utils/changebuffer.d.ts +107 -0
  24. package/dist/utils/findattributerange.d.ts +37 -0
  25. package/dist/utils/getlasttextline.d.ts +53 -0
  26. package/dist/utils/inlinehighlight.d.ts +37 -0
  27. package/package.json +40 -0
  28. package/src/augmentation.d.ts +27 -0
  29. package/src/augmentation.js +5 -0
  30. package/src/delete.d.ts +36 -0
  31. package/src/delete.js +88 -0
  32. package/src/deletecommand.d.ts +83 -0
  33. package/src/deletecommand.js +201 -0
  34. package/src/deleteobserver.d.ts +55 -0
  35. package/src/deleteobserver.js +260 -0
  36. package/src/index.d.ts +25 -0
  37. package/src/index.js +18 -0
  38. package/src/input.d.ts +33 -0
  39. package/src/input.js +422 -0
  40. package/src/inserttextcommand.d.ts +76 -0
  41. package/src/inserttextcommand.js +83 -0
  42. package/src/inserttextobserver.d.ts +55 -0
  43. package/src/inserttextobserver.js +102 -0
  44. package/src/texttransformation.d.ts +37 -0
  45. package/src/texttransformation.js +234 -0
  46. package/src/textwatcher.d.ts +138 -0
  47. package/src/textwatcher.js +105 -0
  48. package/src/twostepcaretmovement.d.ts +236 -0
  49. package/src/twostepcaretmovement.js +628 -0
  50. package/src/typing.d.ts +27 -0
  51. package/src/typing.js +33 -0
  52. package/src/typingconfig.d.ts +204 -0
  53. package/src/typingconfig.js +5 -0
  54. package/src/utils/changebuffer.d.ts +103 -0
  55. package/src/utils/changebuffer.js +123 -0
  56. package/src/utils/findattributerange.d.ts +33 -0
  57. package/src/utils/findattributerange.js +41 -0
  58. package/src/utils/getlasttextline.d.ts +49 -0
  59. package/src/utils/getlasttextline.js +43 -0
  60. package/src/utils/inlinehighlight.d.ts +33 -0
  61. package/src/utils/inlinehighlight.js +74 -0
package/dist/index.js ADDED
@@ -0,0 +1,2490 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ import { Command, Plugin } from '@ckeditor/ckeditor5-core/dist/index.js';
6
+ import { env, EventInfo, count, keyCodes, isInsideSurrogatePair, isInsideCombinedSymbol, isInsideEmojiSequence, ObservableMixin } from '@ckeditor/ckeditor5-utils/dist/index.js';
7
+ import { Observer, FocusObserver, DomEventData, LiveRange, BubblingEventInfo, MouseObserver } from '@ckeditor/ckeditor5-engine/dist/index.js';
8
+ import { debounce, escapeRegExp } from 'lodash-es';
9
+
10
+ /**
11
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
12
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
13
+ */ /**
14
+ * @module typing/utils/changebuffer
15
+ */ /**
16
+ * Change buffer allows to group atomic changes (like characters that have been typed) into
17
+ * {@link module:engine/model/batch~Batch batches}.
18
+ *
19
+ * Batches represent single undo steps, hence changes added to one single batch are undone together.
20
+ *
21
+ * The buffer has a configurable limit of atomic changes that it can accommodate. After the limit was
22
+ * exceeded (see {@link ~ChangeBuffer#input}), a new batch is created in {@link ~ChangeBuffer#batch}.
23
+ *
24
+ * To use the change buffer you need to let it know about the number of changes that were added to the batch:
25
+ *
26
+ * ```ts
27
+ * const buffer = new ChangeBuffer( model, LIMIT );
28
+ *
29
+ * // Later on in your feature:
30
+ * buffer.batch.insert( pos, insertedCharacters );
31
+ * buffer.input( insertedCharacters.length );
32
+ * ```
33
+ */ class ChangeBuffer {
34
+ /**
35
+ * The model instance.
36
+ */ model;
37
+ /**
38
+ * The maximum number of atomic changes which can be contained in one batch.
39
+ */ limit;
40
+ /**
41
+ * Whether the buffer is locked. A locked buffer cannot be reset unless it gets unlocked.
42
+ */ _isLocked;
43
+ /**
44
+ * The number of atomic changes in the buffer. Once it exceeds the {@link #limit},
45
+ * the {@link #batch batch} is set to a new one.
46
+ */ _size;
47
+ /**
48
+ * The current batch instance.
49
+ */ _batch = null;
50
+ /**
51
+ * The callback to document the change event which later needs to be removed.
52
+ */ _changeCallback;
53
+ /**
54
+ * The callback to document selection `change:attribute` and `change:range` events which resets the buffer.
55
+ */ _selectionChangeCallback;
56
+ /**
57
+ * Creates a new instance of the change buffer.
58
+ *
59
+ * @param limit The maximum number of atomic changes which can be contained in one batch.
60
+ */ constructor(model, limit = 20){
61
+ this.model = model;
62
+ this._size = 0;
63
+ this.limit = limit;
64
+ this._isLocked = false;
65
+ // The function to be called in order to notify the buffer about batches which appeared in the document.
66
+ // The callback will check whether it is a new batch and in that case the buffer will be flushed.
67
+ //
68
+ // The reason why the buffer needs to be flushed whenever a new batch appears is that the changes added afterwards
69
+ // should be added to a new batch. For instance, when the user types, then inserts an image, and then types again,
70
+ // the characters typed after inserting the image should be added to a different batch than the characters typed before.
71
+ this._changeCallback = (evt, batch)=>{
72
+ if (batch.isLocal && batch.isUndoable && batch !== this._batch) {
73
+ this._reset(true);
74
+ }
75
+ };
76
+ this._selectionChangeCallback = ()=>{
77
+ this._reset();
78
+ };
79
+ this.model.document.on('change', this._changeCallback);
80
+ this.model.document.selection.on('change:range', this._selectionChangeCallback);
81
+ this.model.document.selection.on('change:attribute', this._selectionChangeCallback);
82
+ }
83
+ /**
84
+ * The current batch to which a feature should add its operations. Once the {@link #size}
85
+ * is reached or exceeds the {@link #limit}, the batch is set to a new instance and the size is reset.
86
+ */ get batch() {
87
+ if (!this._batch) {
88
+ this._batch = this.model.createBatch({
89
+ isTyping: true
90
+ });
91
+ }
92
+ return this._batch;
93
+ }
94
+ /**
95
+ * The number of atomic changes in the buffer. Once it exceeds the {@link #limit},
96
+ * the {@link #batch batch} is set to a new one.
97
+ */ get size() {
98
+ return this._size;
99
+ }
100
+ /**
101
+ * The input number of changes into the buffer. Once the {@link #size} is
102
+ * reached or exceeds the {@link #limit}, the batch is set to a new instance and the size is reset.
103
+ *
104
+ * @param changeCount The number of atomic changes to input.
105
+ */ input(changeCount) {
106
+ this._size += changeCount;
107
+ if (this._size >= this.limit) {
108
+ this._reset(true);
109
+ }
110
+ }
111
+ /**
112
+ * Whether the buffer is locked. A locked buffer cannot be reset unless it gets unlocked.
113
+ */ get isLocked() {
114
+ return this._isLocked;
115
+ }
116
+ /**
117
+ * Locks the buffer.
118
+ */ lock() {
119
+ this._isLocked = true;
120
+ }
121
+ /**
122
+ * Unlocks the buffer.
123
+ */ unlock() {
124
+ this._isLocked = false;
125
+ }
126
+ /**
127
+ * Destroys the buffer.
128
+ */ destroy() {
129
+ this.model.document.off('change', this._changeCallback);
130
+ this.model.document.selection.off('change:range', this._selectionChangeCallback);
131
+ this.model.document.selection.off('change:attribute', this._selectionChangeCallback);
132
+ }
133
+ /**
134
+ * Resets the change buffer.
135
+ *
136
+ * @param ignoreLock Whether internal lock {@link #isLocked} should be ignored.
137
+ */ _reset(ignoreLock = false) {
138
+ if (!this.isLocked || ignoreLock) {
139
+ this._batch = null;
140
+ this._size = 0;
141
+ }
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The insert text command. Used by the {@link module:typing/input~Input input feature} to handle typing.
147
+ */ class InsertTextCommand extends Command {
148
+ /**
149
+ * Typing's change buffer used to group subsequent changes into batches.
150
+ */ _buffer;
151
+ /**
152
+ * Creates an instance of the command.
153
+ *
154
+ * @param undoStepSize The maximum number of atomic changes
155
+ * which can be contained in one batch in the command buffer.
156
+ */ constructor(editor, undoStepSize){
157
+ super(editor);
158
+ this._buffer = new ChangeBuffer(editor.model, undoStepSize);
159
+ // Since this command may execute on different selectable than selection, it should be checked directly in execute block.
160
+ this._isEnabledBasedOnSelection = false;
161
+ }
162
+ /**
163
+ * The current change buffer.
164
+ */ get buffer() {
165
+ return this._buffer;
166
+ }
167
+ /**
168
+ * @inheritDoc
169
+ */ destroy() {
170
+ super.destroy();
171
+ this._buffer.destroy();
172
+ }
173
+ /**
174
+ * Executes the input command. It replaces the content within the given range with the given text.
175
+ * Replacing is a two step process, first the content within the range is removed and then the new text is inserted
176
+ * at the beginning of the range (which after the removal is a collapsed range).
177
+ *
178
+ * @fires execute
179
+ * @param options The command options.
180
+ */ execute(options = {}) {
181
+ const model = this.editor.model;
182
+ const doc = model.document;
183
+ const text = options.text || '';
184
+ const textInsertions = text.length;
185
+ let selection = doc.selection;
186
+ if (options.selection) {
187
+ selection = options.selection;
188
+ } else if (options.range) {
189
+ selection = model.createSelection(options.range);
190
+ }
191
+ // Stop executing if selectable is in non-editable place.
192
+ if (!model.canEditAt(selection)) {
193
+ return;
194
+ }
195
+ const resultRange = options.resultRange;
196
+ model.enqueueChange(this._buffer.batch, (writer)=>{
197
+ this._buffer.lock();
198
+ // Store selection attributes before deleting old content to preserve formatting and link.
199
+ // This unifies the behavior between DocumentSelection and Selection provided as input option.
200
+ const selectionAttributes = Array.from(doc.selection.getAttributes());
201
+ model.deleteContent(selection);
202
+ if (text) {
203
+ model.insertContent(writer.createText(text, selectionAttributes), selection);
204
+ }
205
+ if (resultRange) {
206
+ writer.setSelection(resultRange);
207
+ } else if (!selection.is('documentSelection')) {
208
+ writer.setSelection(selection);
209
+ }
210
+ this._buffer.unlock();
211
+ this._buffer.input(textInsertions);
212
+ });
213
+ }
214
+ }
215
+
216
+ const TYPING_INPUT_TYPES = [
217
+ // For collapsed range:
218
+ // - This one is a regular typing (all browsers, all systems).
219
+ // - This one is used by Chrome when typing accented letter – 2nd step when the user selects the accent (Mac).
220
+ // For non-collapsed range:
221
+ // - This one is used by Chrome when typing accented letter – when the selection box first appears (Mac).
222
+ // - This one is used by Safari when accepting spell check suggestions from the context menu (Mac).
223
+ 'insertText',
224
+ // This one is used by Safari when typing accented letter (Mac).
225
+ // This one is used by Safari when accepting spell check suggestions from the autocorrection pop-up (Mac).
226
+ 'insertReplacementText'
227
+ ];
228
+ const TYPING_INPUT_TYPES_ANDROID = [
229
+ ...TYPING_INPUT_TYPES,
230
+ 'insertCompositionText'
231
+ ];
232
+ /**
233
+ * Text insertion observer introduces the {@link module:engine/view/document~Document#event:insertText} event.
234
+ */ class InsertTextObserver extends Observer {
235
+ /**
236
+ * Instance of the focus observer. Insert text observer calls
237
+ * {@link module:engine/view/observer/focusobserver~FocusObserver#flush} to mark the latest focus change as complete.
238
+ */ focusObserver;
239
+ /**
240
+ * @inheritDoc
241
+ */ constructor(view){
242
+ super(view);
243
+ this.focusObserver = view.getObserver(FocusObserver);
244
+ // On Android composition events should immediately be applied to the model. Rendering is not disabled.
245
+ // On non-Android the model is updated only on composition end.
246
+ // On Android we can't rely on composition start/end to update model.
247
+ const typingInputTypes = env.isAndroid ? TYPING_INPUT_TYPES_ANDROID : TYPING_INPUT_TYPES;
248
+ const viewDocument = view.document;
249
+ viewDocument.on('beforeinput', (evt, data)=>{
250
+ if (!this.isEnabled) {
251
+ return;
252
+ }
253
+ const { data: text, targetRanges, inputType, domEvent } = data;
254
+ if (!typingInputTypes.includes(inputType)) {
255
+ return;
256
+ }
257
+ // Mark the latest focus change as complete (we are typing in editable after the focus
258
+ // so the selection is in the focused element).
259
+ this.focusObserver.flush();
260
+ const eventInfo = new EventInfo(viewDocument, 'insertText');
261
+ viewDocument.fire(eventInfo, new DomEventData(view, domEvent, {
262
+ text,
263
+ selection: view.createSelection(targetRanges)
264
+ }));
265
+ // Stop the beforeinput event if `delete` event was stopped.
266
+ // https://github.com/ckeditor/ckeditor5/issues/753
267
+ if (eventInfo.stop.called) {
268
+ evt.stop();
269
+ }
270
+ });
271
+ // On Android composition events are immediately applied to the model.
272
+ // On non-Android the model is updated only on composition end.
273
+ // On Android we can't rely on composition start/end to update model.
274
+ if (!env.isAndroid) {
275
+ // Note: The priority must be lower than the CompositionObserver handler to call it after the renderer is unblocked.
276
+ // This is important for view to DOM position mapping.
277
+ // This causes the effect of first remove composed DOM and then reapply it after model modification.
278
+ viewDocument.on('compositionend', (evt, { data, domEvent })=>{
279
+ if (!this.isEnabled) {
280
+ return;
281
+ }
282
+ // In case of aborted composition.
283
+ if (!data) {
284
+ return;
285
+ }
286
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
287
+ // @if CK_DEBUG_TYPING // console.log( `%c[InsertTextObserver]%c Fire insertText event, %c${ JSON.stringify( data ) }`,
288
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', 'color: blue'
289
+ // @if CK_DEBUG_TYPING // );
290
+ // @if CK_DEBUG_TYPING // }
291
+ // How do we know where to insert the composed text?
292
+ // 1. The SelectionObserver is blocked and the view is not updated with the composition changes.
293
+ // 2. The last moment before it's locked is the `compositionstart` event.
294
+ // 3. The `SelectionObserver` is listening for `compositionstart` event and immediately converts
295
+ // the selection. Handles this at the lowest priority so after the rendering is blocked.
296
+ viewDocument.fire('insertText', new DomEventData(view, domEvent, {
297
+ text: data
298
+ }));
299
+ }, {
300
+ priority: 'lowest'
301
+ });
302
+ }
303
+ }
304
+ /**
305
+ * @inheritDoc
306
+ */ observe() {}
307
+ /**
308
+ * @inheritDoc
309
+ */ stopObserving() {}
310
+ }
311
+
312
+ /**
313
+ * Handles text input coming from the keyboard or other input methods.
314
+ */ class Input extends Plugin {
315
+ /**
316
+ * The queue of `insertText` command executions that are waiting for the DOM to get updated after beforeinput event.
317
+ */ _compositionQueue;
318
+ /**
319
+ * @inheritDoc
320
+ */ static get pluginName() {
321
+ return 'Input';
322
+ }
323
+ /**
324
+ * @inheritDoc
325
+ */ static get isOfficialPlugin() {
326
+ return true;
327
+ }
328
+ /**
329
+ * @inheritDoc
330
+ */ init() {
331
+ const editor = this.editor;
332
+ const model = editor.model;
333
+ const view = editor.editing.view;
334
+ const mapper = editor.editing.mapper;
335
+ const modelSelection = model.document.selection;
336
+ this._compositionQueue = new CompositionQueue(editor);
337
+ view.addObserver(InsertTextObserver);
338
+ // TODO The above default configuration value should be defined using editor.config.define() once it's fixed.
339
+ const insertTextCommand = new InsertTextCommand(editor, editor.config.get('typing.undoStep') || 20);
340
+ // Register `insertText` command and add `input` command as an alias for backward compatibility.
341
+ editor.commands.add('insertText', insertTextCommand);
342
+ editor.commands.add('input', insertTextCommand);
343
+ this.listenTo(view.document, 'insertText', (evt, data)=>{
344
+ // Rendering is disabled while composing so prevent events that will be rendered by the engine
345
+ // and should not be applied by the browser.
346
+ if (!view.document.isComposing) {
347
+ data.preventDefault();
348
+ }
349
+ // Flush queue on the next beforeinput event because it could happen
350
+ // that the mutation observer does not notice the DOM change in time.
351
+ if (env.isAndroid && view.document.isComposing) {
352
+ this._compositionQueue.flush('next beforeinput');
353
+ }
354
+ const { text, selection: viewSelection } = data;
355
+ let modelRanges;
356
+ // If view selection was specified, translate it to model selection.
357
+ if (viewSelection) {
358
+ modelRanges = Array.from(viewSelection.getRanges()).map((viewRange)=>mapper.toModelRange(viewRange));
359
+ } else {
360
+ modelRanges = Array.from(modelSelection.getRanges());
361
+ }
362
+ let insertText = text;
363
+ // Typing in English on Android is firing composition events for the whole typed word.
364
+ // We need to check the target range text to only apply the difference.
365
+ if (env.isAndroid) {
366
+ const selectedText = Array.from(modelRanges[0].getItems()).reduce((rangeText, node)=>{
367
+ return rangeText + (node.is('$textProxy') ? node.data : '');
368
+ }, '');
369
+ if (selectedText) {
370
+ if (selectedText.length <= insertText.length) {
371
+ if (insertText.startsWith(selectedText)) {
372
+ insertText = insertText.substring(selectedText.length);
373
+ modelRanges[0].start = modelRanges[0].start.getShiftedBy(selectedText.length);
374
+ }
375
+ } else {
376
+ if (selectedText.startsWith(insertText)) {
377
+ // TODO this should be mapped as delete?
378
+ modelRanges[0].start = modelRanges[0].start.getShiftedBy(insertText.length);
379
+ insertText = '';
380
+ }
381
+ }
382
+ }
383
+ if (insertText.length == 0 && modelRanges[0].isCollapsed) {
384
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
385
+ // @if CK_DEBUG_TYPING // console.log( '%c[Input]%c Ignore insertion of an empty data to the collapsed range.',
386
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-style: italic'
387
+ // @if CK_DEBUG_TYPING // );
388
+ // @if CK_DEBUG_TYPING // }
389
+ return;
390
+ }
391
+ }
392
+ const commandData = {
393
+ text: insertText,
394
+ selection: model.createSelection(modelRanges)
395
+ };
396
+ // This is a composition event and those are not cancellable, so we need to wait until browser updates the DOM
397
+ // and we could apply changes to the model and verify if the DOM is valid.
398
+ // The browser applies changes to the DOM not immediately on beforeinput event.
399
+ // We just wait for mutation observer to notice changes or as a fallback a timeout.
400
+ if (env.isAndroid && view.document.isComposing) {
401
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
402
+ // @if CK_DEBUG_TYPING // console.log( `%c[Input]%c Queue insertText:%c "${ commandData.text }"%c ` +
403
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getFirstPosition().path }]-` +
404
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getLastPosition().path }]` +
405
+ // @if CK_DEBUG_TYPING // ` queue size: ${ this._compositionQueue.length + 1 }`,
406
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', 'color: blue', ''
407
+ // @if CK_DEBUG_TYPING // );
408
+ // @if CK_DEBUG_TYPING // }
409
+ this._compositionQueue.push(commandData);
410
+ } else {
411
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
412
+ // @if CK_DEBUG_TYPING // console.log( `%c[Input]%c Execute insertText:%c "${ commandData.text }"%c ` +
413
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getFirstPosition().path }]-` +
414
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getLastPosition().path }]`,
415
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', 'color: blue', ''
416
+ // @if CK_DEBUG_TYPING // );
417
+ // @if CK_DEBUG_TYPING // }
418
+ editor.execute('insertText', commandData);
419
+ view.scrollToTheSelection();
420
+ }
421
+ });
422
+ // Delete selected content on composition start.
423
+ if (env.isAndroid) {
424
+ // On Android with English keyboard, the composition starts just by putting caret
425
+ // at the word end or by selecting a table column. This is not a real composition started.
426
+ // Trigger delete content on first composition key pressed.
427
+ this.listenTo(view.document, 'keydown', (evt, data)=>{
428
+ if (modelSelection.isCollapsed || data.keyCode != 229 || !view.document.isComposing) {
429
+ return;
430
+ }
431
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
432
+ // @if CK_DEBUG_TYPING // const firstPositionPath = modelSelection.getFirstPosition()!.path;
433
+ // @if CK_DEBUG_TYPING // const lastPositionPath = modelSelection.getLastPosition()!.path;
434
+ // @if CK_DEBUG_TYPING // console.log( '%c[Input]%c KeyDown 229%c -> model.deleteContent() ' +
435
+ // @if CK_DEBUG_TYPING // `[${ firstPositionPath }]-[${ lastPositionPath }]`,
436
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', '',
437
+ // @if CK_DEBUG_TYPING // );
438
+ // @if CK_DEBUG_TYPING // }
439
+ deleteSelectionContent(model, insertTextCommand);
440
+ });
441
+ } else {
442
+ // Note: The priority must precede the CompositionObserver handler to call it before
443
+ // the renderer is blocked, because we want to render this change.
444
+ this.listenTo(view.document, 'compositionstart', ()=>{
445
+ if (modelSelection.isCollapsed) {
446
+ return;
447
+ }
448
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
449
+ // @if CK_DEBUG_TYPING // const firstPositionPath = modelSelection.getFirstPosition()!.path;
450
+ // @if CK_DEBUG_TYPING // const lastPositionPath = modelSelection.getLastPosition()!.path;
451
+ // @if CK_DEBUG_TYPING // console.log( '%c[Input]%c Composition start%c -> model.deleteContent() ' +
452
+ // @if CK_DEBUG_TYPING // `[${ firstPositionPath }]-[${ lastPositionPath }]`,
453
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', '',
454
+ // @if CK_DEBUG_TYPING // );
455
+ // @if CK_DEBUG_TYPING // }
456
+ deleteSelectionContent(model, insertTextCommand);
457
+ });
458
+ }
459
+ // Apply composed changes to the model.
460
+ if (env.isAndroid) {
461
+ // Apply changes to the model as they are applied to the DOM by the browser.
462
+ // On beforeinput event, the DOM is not yet modified. We wait for detected mutations to apply model changes.
463
+ this.listenTo(view.document, 'mutations', (evt, { mutations })=>{
464
+ if (!view.document.isComposing) {
465
+ return;
466
+ }
467
+ // Check if mutations are relevant for queued changes.
468
+ for (const { node } of mutations){
469
+ const viewElement = findMappedViewAncestor(node, mapper);
470
+ const modelElement = mapper.toModelElement(viewElement);
471
+ if (this._compositionQueue.isComposedElement(modelElement)) {
472
+ this._compositionQueue.flush('mutations');
473
+ return;
474
+ }
475
+ }
476
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
477
+ // @if CK_DEBUG_TYPING // console.log( '%c[Input]%c Mutations not related to the composition.',
478
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-style: italic'
479
+ // @if CK_DEBUG_TYPING // );
480
+ // @if CK_DEBUG_TYPING // }
481
+ });
482
+ // Make sure that all changes are applied to the model before the end of composition.
483
+ this.listenTo(view.document, 'compositionend', ()=>{
484
+ this._compositionQueue.flush('composition end');
485
+ });
486
+ // Trigger mutations check after the composition completes to fix all DOM changes that got ignored during composition.
487
+ // On Android the Renderer is not disabled while composing. While updating DOM nodes we ignore some changes
488
+ // that are not that important (like NBSP vs plain space character) and could break the composition flow.
489
+ // After composition is completed we trigger additional `mutations` event for elements affected by the composition
490
+ // so the Renderer can adjust the DOM to the expected structure without breaking the composition.
491
+ this.listenTo(view.document, 'compositionend', ()=>{
492
+ const mutations = [];
493
+ for (const element of this._compositionQueue.flushComposedElements()){
494
+ const viewElement = mapper.toViewElement(element);
495
+ if (!viewElement) {
496
+ continue;
497
+ }
498
+ mutations.push({
499
+ type: 'children',
500
+ node: viewElement
501
+ });
502
+ }
503
+ if (mutations.length) {
504
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
505
+ // @if CK_DEBUG_TYPING // console.group( '%c[Input]%c Fire post-composition mutation fixes.',
506
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green', 'font-weight: bold', ''
507
+ // @if CK_DEBUG_TYPING // );
508
+ // @if CK_DEBUG_TYPING // }
509
+ view.document.fire('mutations', {
510
+ mutations
511
+ });
512
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
513
+ // @if CK_DEBUG_TYPING // console.groupEnd();
514
+ // @if CK_DEBUG_TYPING // }
515
+ }
516
+ }, {
517
+ priority: 'lowest'
518
+ });
519
+ } else {
520
+ // After composition end we need to verify if there are no left-overs.
521
+ // Listening at the lowest priority so after the `InsertTextObserver` added above (all composed text
522
+ // should already be applied to the model, view, and DOM).
523
+ // On non-Android the `Renderer` is blocked while user is composing but the `MutationObserver` still collects
524
+ // mutated nodes and fires `mutations` events.
525
+ // Those events are recorded by the `Renderer` but not applied to the DOM while composing.
526
+ // We need to trigger those checks (and fixes) once again but this time without specifying the exact mutations
527
+ // since they are already recorded by the `Renderer`.
528
+ // It in the most cases just clears the internal record of mutated text nodes
529
+ // since all changes should already be applied to the DOM.
530
+ // This is especially needed when user cancels composition, so we can clear nodes marked to sync.
531
+ this.listenTo(view.document, 'compositionend', ()=>{
532
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
533
+ // @if CK_DEBUG_TYPING // console.group( '%c[Input]%c Force render after composition end.',
534
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green', 'font-weight: bold', ''
535
+ // @if CK_DEBUG_TYPING // );
536
+ // @if CK_DEBUG_TYPING // }
537
+ view.document.fire('mutations', {
538
+ mutations: []
539
+ });
540
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
541
+ // @if CK_DEBUG_TYPING // console.groupEnd();
542
+ // @if CK_DEBUG_TYPING // }
543
+ }, {
544
+ priority: 'lowest'
545
+ });
546
+ }
547
+ }
548
+ /**
549
+ * @inheritDoc
550
+ */ destroy() {
551
+ super.destroy();
552
+ this._compositionQueue.destroy();
553
+ }
554
+ }
555
+ /**
556
+ * The queue of `insertText` command executions that are waiting for the DOM to get updated after beforeinput event.
557
+ */ class CompositionQueue {
558
+ /**
559
+ * The editor instance.
560
+ */ editor;
561
+ /**
562
+ * Debounced queue flush as a safety mechanism for cases of mutation observer not triggering.
563
+ */ flushDebounced = debounce(()=>this.flush('timeout'), 50);
564
+ /**
565
+ * The queue of `insertText` command executions that are waiting for the DOM to get updated after beforeinput event.
566
+ */ _queue = [];
567
+ /**
568
+ * A set of model elements. The composition happened in those elements. It's used for mutations check.
569
+ */ _compositionElements = new Set();
570
+ /**
571
+ * @inheritDoc
572
+ */ constructor(editor){
573
+ this.editor = editor;
574
+ }
575
+ /**
576
+ * Destroys the helper object.
577
+ */ destroy() {
578
+ this.flushDebounced.cancel();
579
+ this._compositionElements.clear();
580
+ while(this._queue.length){
581
+ this.shift();
582
+ }
583
+ }
584
+ /**
585
+ * Returns the size of the queue.
586
+ */ get length() {
587
+ return this._queue.length;
588
+ }
589
+ /**
590
+ * Push next insertText command data to the queue.
591
+ */ push(commandData) {
592
+ const commandLiveData = {
593
+ text: commandData.text
594
+ };
595
+ if (commandData.selection) {
596
+ commandLiveData.selectionRanges = [];
597
+ for (const range of commandData.selection.getRanges()){
598
+ commandLiveData.selectionRanges.push(LiveRange.fromRange(range));
599
+ // Keep reference to the model element for later mutation checks.
600
+ this._compositionElements.add(range.start.parent);
601
+ }
602
+ }
603
+ this._queue.push(commandLiveData);
604
+ this.flushDebounced();
605
+ }
606
+ /**
607
+ * Shift the first item from the insertText command data queue.
608
+ */ shift() {
609
+ const commandLiveData = this._queue.shift();
610
+ const commandData = {
611
+ text: commandLiveData.text
612
+ };
613
+ if (commandLiveData.selectionRanges) {
614
+ const ranges = commandLiveData.selectionRanges.map((liveRange)=>detachLiveRange(liveRange)).filter((range)=>!!range);
615
+ if (ranges.length) {
616
+ commandData.selection = this.editor.model.createSelection(ranges);
617
+ }
618
+ }
619
+ return commandData;
620
+ }
621
+ /**
622
+ * Applies all queued insertText command executions.
623
+ *
624
+ * @param reason Used only for debugging.
625
+ */ flush(reason) {
626
+ const editor = this.editor;
627
+ const model = editor.model;
628
+ const view = editor.editing.view;
629
+ this.flushDebounced.cancel();
630
+ if (!this._queue.length) {
631
+ return;
632
+ }
633
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
634
+ // @if CK_DEBUG_TYPING // console.group( `%c[Input]%c Flush insertText queue on ${ reason }.`,
635
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold'
636
+ // @if CK_DEBUG_TYPING // );
637
+ // @if CK_DEBUG_TYPING // }
638
+ const insertTextCommand = editor.commands.get('insertText');
639
+ const buffer = insertTextCommand.buffer;
640
+ model.enqueueChange(buffer.batch, ()=>{
641
+ buffer.lock();
642
+ while(this._queue.length){
643
+ const commandData = this.shift();
644
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
645
+ // @if CK_DEBUG_TYPING // console.log( '%c[Input]%c Execute queued insertText:%c ' +
646
+ // @if CK_DEBUG_TYPING // `"${ commandData.text }"%c ` +
647
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getFirstPosition().path }]-` +
648
+ // @if CK_DEBUG_TYPING // `[${ commandData.selection.getLastPosition().path }]`,
649
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', 'font-weight: bold', 'color: blue', ''
650
+ // @if CK_DEBUG_TYPING // );
651
+ // @if CK_DEBUG_TYPING // }
652
+ editor.execute('insertText', commandData);
653
+ }
654
+ buffer.unlock();
655
+ });
656
+ view.scrollToTheSelection();
657
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
658
+ // @if CK_DEBUG_TYPING // console.groupEnd();
659
+ // @if CK_DEBUG_TYPING // }
660
+ }
661
+ /**
662
+ * Returns `true` if the given model element is related to recent composition.
663
+ */ isComposedElement(element) {
664
+ return this._compositionElements.has(element);
665
+ }
666
+ /**
667
+ * Returns an array of composition-related elements and clears the internal list.
668
+ */ flushComposedElements() {
669
+ const result = Array.from(this._compositionElements);
670
+ this._compositionElements.clear();
671
+ return result;
672
+ }
673
+ }
674
+ /**
675
+ * Deletes the content selected by the document selection at the start of composition.
676
+ */ function deleteSelectionContent(model, insertTextCommand) {
677
+ // By relying on the state of the input command we allow disabling the entire input easily
678
+ // by just disabling the input command. We could’ve used here the delete command but that
679
+ // would mean requiring the delete feature which would block loading one without the other.
680
+ // We could also check the editor.isReadOnly property, but that wouldn't allow to block
681
+ // the input without blocking other features.
682
+ if (!insertTextCommand.isEnabled) {
683
+ return;
684
+ }
685
+ const buffer = insertTextCommand.buffer;
686
+ buffer.lock();
687
+ model.enqueueChange(buffer.batch, ()=>{
688
+ model.deleteContent(model.document.selection);
689
+ });
690
+ buffer.unlock();
691
+ }
692
+ /**
693
+ * Detaches a LiveRange and returns the static range from it.
694
+ */ function detachLiveRange(liveRange) {
695
+ const range = liveRange.toRange();
696
+ liveRange.detach();
697
+ if (range.root.rootName == '$graveyard') {
698
+ return null;
699
+ }
700
+ return range;
701
+ }
702
+ /**
703
+ * For the given `viewNode`, finds and returns the closest ancestor of this node that has a mapping to the model.
704
+ */ function findMappedViewAncestor(viewNode, mapper) {
705
+ let node = viewNode.is('$text') ? viewNode.parent : viewNode;
706
+ while(!mapper.toModelElement(node)){
707
+ node = node.parent;
708
+ }
709
+ return node;
710
+ }
711
+
712
+ /**
713
+ * The delete command. Used by the {@link module:typing/delete~Delete delete feature} to handle the <kbd>Delete</kbd> and
714
+ * <kbd>Backspace</kbd> keys.
715
+ */ class DeleteCommand extends Command {
716
+ /**
717
+ * The directionality of the delete describing in what direction it should
718
+ * consume the content when the selection is collapsed.
719
+ */ direction;
720
+ /**
721
+ * Delete's change buffer used to group subsequent changes into batches.
722
+ */ _buffer;
723
+ /**
724
+ * Creates an instance of the command.
725
+ *
726
+ * @param direction The directionality of the delete describing in what direction it
727
+ * should consume the content when the selection is collapsed.
728
+ */ constructor(editor, direction){
729
+ super(editor);
730
+ this.direction = direction;
731
+ this._buffer = new ChangeBuffer(editor.model, editor.config.get('typing.undoStep'));
732
+ // Since this command may execute on different selectable than selection, it should be checked directly in execute block.
733
+ this._isEnabledBasedOnSelection = false;
734
+ }
735
+ /**
736
+ * The current change buffer.
737
+ */ get buffer() {
738
+ return this._buffer;
739
+ }
740
+ /**
741
+ * Executes the delete command. Depending on whether the selection is collapsed or not, deletes its content
742
+ * or a piece of content in the {@link #direction defined direction}.
743
+ *
744
+ * @fires execute
745
+ * @param options The command options.
746
+ * @param options.unit See {@link module:engine/model/utils/modifyselection~modifySelection}'s options.
747
+ * @param options.sequence A number describing which subsequent delete event it is without the key being released.
748
+ * See the {@link module:engine/view/document~Document#event:delete} event data.
749
+ * @param options.selection Selection to remove. If not set, current model selection will be used.
750
+ */ execute(options = {}) {
751
+ const model = this.editor.model;
752
+ const doc = model.document;
753
+ model.enqueueChange(this._buffer.batch, (writer)=>{
754
+ this._buffer.lock();
755
+ const selection = writer.createSelection(options.selection || doc.selection);
756
+ // Don't execute command when selection is in non-editable place.
757
+ if (!model.canEditAt(selection)) {
758
+ return;
759
+ }
760
+ const sequence = options.sequence || 1;
761
+ // Do not replace the whole selected content if selection was collapsed.
762
+ // This prevents such situation:
763
+ //
764
+ // <h1></h1><p>[]</p> --> <h1>[</h1><p>]</p> --> <p></p>
765
+ // starting content --> after `modifySelection` --> after `deleteContent`.
766
+ const doNotResetEntireContent = selection.isCollapsed;
767
+ // Try to extend the selection in the specified direction.
768
+ if (selection.isCollapsed) {
769
+ model.modifySelection(selection, {
770
+ direction: this.direction,
771
+ unit: options.unit,
772
+ treatEmojiAsSingleUnit: true
773
+ });
774
+ }
775
+ // Check if deleting in an empty editor. See #61.
776
+ if (this._shouldEntireContentBeReplacedWithParagraph(sequence)) {
777
+ this._replaceEntireContentWithParagraph(writer);
778
+ return;
779
+ }
780
+ // Check if deleting in the first empty block.
781
+ // See https://github.com/ckeditor/ckeditor5/issues/8137.
782
+ if (this._shouldReplaceFirstBlockWithParagraph(selection, sequence)) {
783
+ this.editor.execute('paragraph', {
784
+ selection
785
+ });
786
+ return;
787
+ }
788
+ // If selection is still collapsed, then there's nothing to delete.
789
+ if (selection.isCollapsed) {
790
+ return;
791
+ }
792
+ let changeCount = 0;
793
+ selection.getFirstRange().getMinimalFlatRanges().forEach((range)=>{
794
+ changeCount += count(range.getWalker({
795
+ singleCharacters: true,
796
+ ignoreElementEnd: true,
797
+ shallow: true
798
+ }));
799
+ });
800
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
801
+ // @if CK_DEBUG_TYPING // console.log( '%c[DeleteCommand]%c Delete content',
802
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', '',
803
+ // @if CK_DEBUG_TYPING // `[${ selection.getFirstPosition()!.path }]-[${ selection.getLastPosition()!.path }]`, options
804
+ // @if CK_DEBUG_TYPING // );
805
+ // @if CK_DEBUG_TYPING // }
806
+ model.deleteContent(selection, {
807
+ doNotResetEntireContent,
808
+ direction: this.direction
809
+ });
810
+ this._buffer.input(changeCount);
811
+ writer.setSelection(selection);
812
+ this._buffer.unlock();
813
+ });
814
+ }
815
+ /**
816
+ * If the user keeps <kbd>Backspace</kbd> or <kbd>Delete</kbd> key pressed, the content of the current
817
+ * editable will be cleared. However, this will not yet lead to resetting the remaining block to a paragraph
818
+ * (which happens e.g. when the user does <kbd>Ctrl</kbd> + <kbd>A</kbd>, <kbd>Backspace</kbd>).
819
+ *
820
+ * But, if the user pressed the key in an empty editable for the first time,
821
+ * we want to replace the entire content with a paragraph if:
822
+ *
823
+ * * the current limit element is empty,
824
+ * * the paragraph is allowed in the limit element,
825
+ * * the limit doesn't already have a paragraph inside.
826
+ *
827
+ * See https://github.com/ckeditor/ckeditor5-typing/issues/61.
828
+ *
829
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
830
+ */ _shouldEntireContentBeReplacedWithParagraph(sequence) {
831
+ // Does nothing if user pressed and held the "Backspace" or "Delete" key.
832
+ if (sequence > 1) {
833
+ return false;
834
+ }
835
+ const model = this.editor.model;
836
+ const doc = model.document;
837
+ const selection = doc.selection;
838
+ const limitElement = model.schema.getLimitElement(selection);
839
+ // If a collapsed selection contains the whole content it means that the content is empty
840
+ // (from the user perspective).
841
+ const limitElementIsEmpty = selection.isCollapsed && selection.containsEntireContent(limitElement);
842
+ if (!limitElementIsEmpty) {
843
+ return false;
844
+ }
845
+ if (!model.schema.checkChild(limitElement, 'paragraph')) {
846
+ return false;
847
+ }
848
+ const limitElementFirstChild = limitElement.getChild(0);
849
+ // Does nothing if the limit element already contains only a paragraph.
850
+ // We ignore the case when paragraph might have some inline elements (<p><inlineWidget>[]</inlineWidget></p>)
851
+ // because we don't support such cases yet and it's unclear whether inlineWidget shouldn't be a limit itself.
852
+ if (limitElementFirstChild && limitElementFirstChild.is('element', 'paragraph')) {
853
+ return false;
854
+ }
855
+ return true;
856
+ }
857
+ /**
858
+ * The entire content is replaced with the paragraph. Selection is moved inside the paragraph.
859
+ *
860
+ * @param writer The model writer.
861
+ */ _replaceEntireContentWithParagraph(writer) {
862
+ const model = this.editor.model;
863
+ const doc = model.document;
864
+ const selection = doc.selection;
865
+ const limitElement = model.schema.getLimitElement(selection);
866
+ const paragraph = writer.createElement('paragraph');
867
+ writer.remove(writer.createRangeIn(limitElement));
868
+ writer.insert(paragraph, limitElement);
869
+ writer.setSelection(paragraph, 0);
870
+ }
871
+ /**
872
+ * Checks if the selection is inside an empty element that is the first child of the limit element
873
+ * and should be replaced with a paragraph.
874
+ *
875
+ * @param selection The selection.
876
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
877
+ */ _shouldReplaceFirstBlockWithParagraph(selection, sequence) {
878
+ const model = this.editor.model;
879
+ // Does nothing if user pressed and held the "Backspace" key or it was a "Delete" button.
880
+ if (sequence > 1 || this.direction != 'backward') {
881
+ return false;
882
+ }
883
+ if (!selection.isCollapsed) {
884
+ return false;
885
+ }
886
+ const position = selection.getFirstPosition();
887
+ const limitElement = model.schema.getLimitElement(position);
888
+ const limitElementFirstChild = limitElement.getChild(0);
889
+ // Only elements that are direct children of the limit element can be replaced.
890
+ // Unwrapping from a block quote should be handled in a dedicated feature.
891
+ if (position.parent != limitElementFirstChild) {
892
+ return false;
893
+ }
894
+ // A block should be replaced only if it was empty.
895
+ if (!selection.containsEntireContent(limitElementFirstChild)) {
896
+ return false;
897
+ }
898
+ // Replace with a paragraph only if it's allowed there.
899
+ if (!model.schema.checkChild(limitElement, 'paragraph')) {
900
+ return false;
901
+ }
902
+ // Does nothing if the limit element already contains only a paragraph.
903
+ if (limitElementFirstChild.name == 'paragraph') {
904
+ return false;
905
+ }
906
+ return true;
907
+ }
908
+ }
909
+
910
+ const DELETE_CHARACTER = 'character';
911
+ const DELETE_WORD = 'word';
912
+ const DELETE_CODE_POINT = 'codePoint';
913
+ const DELETE_SELECTION = 'selection';
914
+ const DELETE_BACKWARD = 'backward';
915
+ const DELETE_FORWARD = 'forward';
916
+ const DELETE_EVENT_TYPES = {
917
+ // --------------------------------------- Backward delete types -----------------------------------------------------
918
+ // This happens in Safari on Mac when some content is selected and Ctrl + K is pressed.
919
+ deleteContent: {
920
+ unit: DELETE_SELECTION,
921
+ // According to the Input Events Level 2 spec, this delete type has no direction
922
+ // but to keep things simple, let's default to backward.
923
+ direction: DELETE_BACKWARD
924
+ },
925
+ // Chrome and Safari on Mac: Backspace or Ctrl + H
926
+ deleteContentBackward: {
927
+ // This kind of deletions must be done on the code point-level instead of target range provided by the DOM beforeinput event.
928
+ // Take for instance "👨‍👩‍👧‍👧", it equals:
929
+ //
930
+ // * [ "👨", "ZERO WIDTH JOINER", "👩", "ZERO WIDTH JOINER", "👧", "ZERO WIDTH JOINER", "👧" ]
931
+ // * or simply "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F467}"
932
+ //
933
+ // The range provided by the browser would cause the entire multi-byte grapheme to disappear while the user
934
+ // intention when deleting backwards ("👨‍👩‍👧‍👧[]", then backspace) is gradual "decomposition" (first to "👨‍👩‍👧‍[]",
935
+ // then to "👨‍👩‍[]", etc.).
936
+ //
937
+ // * "👨‍👩‍👧‍👧[]" + backward delete (by code point) -> results in "👨‍👩‍👧[]", removed the last "👧" 👍
938
+ // * "👨‍👩‍👧‍👧[]" + backward delete (by character) -> results in "[]", removed the whole grapheme 👎
939
+ //
940
+ // Deleting by code-point is simply a better UX. See "deleteContentForward" to learn more.
941
+ unit: DELETE_CODE_POINT,
942
+ direction: DELETE_BACKWARD
943
+ },
944
+ // On Mac: Option + Backspace.
945
+ // On iOS: Hold the backspace for a while and the whole words will start to disappear.
946
+ deleteWordBackward: {
947
+ unit: DELETE_WORD,
948
+ direction: DELETE_BACKWARD
949
+ },
950
+ // Safari on Mac: Cmd + Backspace
951
+ deleteHardLineBackward: {
952
+ unit: DELETE_SELECTION,
953
+ direction: DELETE_BACKWARD
954
+ },
955
+ // Chrome on Mac: Cmd + Backspace.
956
+ deleteSoftLineBackward: {
957
+ unit: DELETE_SELECTION,
958
+ direction: DELETE_BACKWARD
959
+ },
960
+ // --------------------------------------- Forward delete types -----------------------------------------------------
961
+ // Chrome on Mac: Fn + Backspace or Ctrl + D
962
+ // Safari on Mac: Ctrl + K or Ctrl + D
963
+ deleteContentForward: {
964
+ // Unlike backward delete, this delete must be performed by character instead of by code point, which
965
+ // provides the best UX for working with accented letters.
966
+ // Take, for example "b̂" ("\u0062\u0302", or [ "LATIN SMALL LETTER B", "COMBINING CIRCUMFLEX ACCENT" ]):
967
+ //
968
+ // * "b̂[]" + backward delete (by code point) -> results in "b[]", removed the combining mark 👍
969
+ // * "[]b̂" + forward delete (by code point) -> results in "[]^", a bare combining mark does that not make sense when alone 👎
970
+ // * "[]b̂" + forward delete (by character) -> results in "[]", removed both "b" and the combining mark 👍
971
+ //
972
+ // See: "deleteContentBackward" to learn more.
973
+ unit: DELETE_CHARACTER,
974
+ direction: DELETE_FORWARD
975
+ },
976
+ // On Mac: Fn + Option + Backspace.
977
+ deleteWordForward: {
978
+ unit: DELETE_WORD,
979
+ direction: DELETE_FORWARD
980
+ },
981
+ // Chrome on Mac: Ctrl + K (you have to disable the Link plugin first, though, because it uses the same keystroke)
982
+ // This is weird that it does not work in Safari on Mac despite being listed in the official shortcuts listing
983
+ // on Apple's webpage.
984
+ deleteHardLineForward: {
985
+ unit: DELETE_SELECTION,
986
+ direction: DELETE_FORWARD
987
+ },
988
+ // At this moment there is no known way to trigger this event type but let's keep it for the symmetry with
989
+ // deleteSoftLineBackward.
990
+ deleteSoftLineForward: {
991
+ unit: DELETE_SELECTION,
992
+ direction: DELETE_FORWARD
993
+ }
994
+ };
995
+ /**
996
+ * Delete observer introduces the {@link module:engine/view/document~Document#event:delete} event.
997
+ */ class DeleteObserver extends Observer {
998
+ /**
999
+ * @inheritDoc
1000
+ */ constructor(view){
1001
+ super(view);
1002
+ const document = view.document;
1003
+ // It matters how many subsequent deletions were made, e.g. when the backspace key was pressed and held
1004
+ // by the user for some time. For instance, if such scenario ocurred and the heading the selection was
1005
+ // anchored to was the only content of the editor, it will not be converted into a paragraph (the user
1006
+ // wanted to clean it up, not remove it, it's about UX). Check out the DeleteCommand implementation to learn more.
1007
+ //
1008
+ // Fun fact: Safari on Mac won't fire beforeinput for backspace in an empty heading (only content).
1009
+ let sequence = 0;
1010
+ document.on('keydown', ()=>{
1011
+ sequence++;
1012
+ });
1013
+ document.on('keyup', ()=>{
1014
+ sequence = 0;
1015
+ });
1016
+ document.on('beforeinput', (evt, data)=>{
1017
+ if (!this.isEnabled) {
1018
+ return;
1019
+ }
1020
+ const { targetRanges, domEvent, inputType } = data;
1021
+ const deleteEventSpec = DELETE_EVENT_TYPES[inputType];
1022
+ if (!deleteEventSpec) {
1023
+ return;
1024
+ }
1025
+ const deleteData = {
1026
+ direction: deleteEventSpec.direction,
1027
+ unit: deleteEventSpec.unit,
1028
+ sequence
1029
+ };
1030
+ if (deleteData.unit == DELETE_SELECTION) {
1031
+ deleteData.selectionToRemove = view.createSelection(targetRanges[0]);
1032
+ }
1033
+ // The default deletion unit for deleteContentBackward is a single code point
1034
+ // but if the browser provides a wider target range then we should use it.
1035
+ if (inputType === 'deleteContentBackward') {
1036
+ // On Android, deleteContentBackward has sequence 1 by default.
1037
+ if (env.isAndroid) {
1038
+ deleteData.sequence = 1;
1039
+ }
1040
+ // The beforeInput event wants more than a single character to be removed.
1041
+ if (shouldUseTargetRanges(targetRanges)) {
1042
+ deleteData.unit = DELETE_SELECTION;
1043
+ deleteData.selectionToRemove = view.createSelection(targetRanges);
1044
+ }
1045
+ }
1046
+ const eventInfo = new BubblingEventInfo(document, 'delete', targetRanges[0]);
1047
+ document.fire(eventInfo, new DomEventData(view, domEvent, deleteData));
1048
+ // Stop the beforeinput event if `delete` event was stopped.
1049
+ // https://github.com/ckeditor/ckeditor5/issues/753
1050
+ if (eventInfo.stop.called) {
1051
+ evt.stop();
1052
+ }
1053
+ });
1054
+ // TODO: to be removed when https://bugs.chromium.org/p/chromium/issues/detail?id=1365311 is solved.
1055
+ if (env.isBlink) {
1056
+ enableChromeWorkaround(this);
1057
+ }
1058
+ }
1059
+ /**
1060
+ * @inheritDoc
1061
+ */ observe() {}
1062
+ /**
1063
+ * @inheritDoc
1064
+ */ stopObserving() {}
1065
+ }
1066
+ /**
1067
+ * Enables workaround for the issue https://github.com/ckeditor/ckeditor5/issues/11904.
1068
+ */ function enableChromeWorkaround(observer) {
1069
+ const view = observer.view;
1070
+ const document = view.document;
1071
+ let pressedKeyCode = null;
1072
+ let beforeInputReceived = false;
1073
+ document.on('keydown', (evt, { keyCode })=>{
1074
+ pressedKeyCode = keyCode;
1075
+ beforeInputReceived = false;
1076
+ });
1077
+ document.on('keyup', (evt, { keyCode, domEvent })=>{
1078
+ const selection = document.selection;
1079
+ const shouldFireDeleteEvent = observer.isEnabled && keyCode == pressedKeyCode && isDeleteKeyCode(keyCode) && !selection.isCollapsed && !beforeInputReceived;
1080
+ pressedKeyCode = null;
1081
+ if (shouldFireDeleteEvent) {
1082
+ const targetRange = selection.getFirstRange();
1083
+ const eventInfo = new BubblingEventInfo(document, 'delete', targetRange);
1084
+ const deleteData = {
1085
+ unit: DELETE_SELECTION,
1086
+ direction: getDeleteDirection(keyCode),
1087
+ selectionToRemove: selection
1088
+ };
1089
+ document.fire(eventInfo, new DomEventData(view, domEvent, deleteData));
1090
+ }
1091
+ });
1092
+ document.on('beforeinput', (evt, { inputType })=>{
1093
+ const deleteEventSpec = DELETE_EVENT_TYPES[inputType];
1094
+ const isMatchingBeforeInput = isDeleteKeyCode(pressedKeyCode) && deleteEventSpec && deleteEventSpec.direction == getDeleteDirection(pressedKeyCode);
1095
+ if (isMatchingBeforeInput) {
1096
+ beforeInputReceived = true;
1097
+ }
1098
+ }, {
1099
+ priority: 'high'
1100
+ });
1101
+ document.on('beforeinput', (evt, { inputType, data })=>{
1102
+ const shouldIgnoreBeforeInput = pressedKeyCode == keyCodes.delete && inputType == 'insertText' && data == '\x7f'; // Delete character :P
1103
+ if (shouldIgnoreBeforeInput) {
1104
+ evt.stop();
1105
+ }
1106
+ }, {
1107
+ priority: 'high'
1108
+ });
1109
+ function isDeleteKeyCode(keyCode) {
1110
+ return keyCode == keyCodes.backspace || keyCode == keyCodes.delete;
1111
+ }
1112
+ function getDeleteDirection(keyCode) {
1113
+ return keyCode == keyCodes.backspace ? DELETE_BACKWARD : DELETE_FORWARD;
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Verifies whether the given target ranges cover more than a single character and should be used instead of a single code-point deletion.
1118
+ */ function shouldUseTargetRanges(targetRanges) {
1119
+ // The collapsed target range could happen for example while deleting inside an inline filler
1120
+ // (it's mapped to collapsed position before an inline filler).
1121
+ if (targetRanges.length != 1 || targetRanges[0].isCollapsed) {
1122
+ return false;
1123
+ }
1124
+ const walker = targetRanges[0].getWalker({
1125
+ direction: 'backward',
1126
+ singleCharacters: true,
1127
+ ignoreElementEnd: true
1128
+ });
1129
+ let count = 0;
1130
+ for (const { nextPosition, item } of walker){
1131
+ if (nextPosition.parent.is('$text')) {
1132
+ const data = nextPosition.parent.data;
1133
+ const offset = nextPosition.offset;
1134
+ // Count combined symbols and emoji sequences as a single character.
1135
+ if (isInsideSurrogatePair(data, offset) || isInsideCombinedSymbol(data, offset) || isInsideEmojiSequence(data, offset)) {
1136
+ continue;
1137
+ }
1138
+ count++;
1139
+ } else if (item.is('containerElement') || item.is('emptyElement')) {
1140
+ count++;
1141
+ }
1142
+ if (count > 1) {
1143
+ return true;
1144
+ }
1145
+ }
1146
+ return false;
1147
+ }
1148
+
1149
+ /**
1150
+ * The delete and backspace feature. Handles keys such as <kbd>Delete</kbd> and <kbd>Backspace</kbd>, other
1151
+ * keystrokes and user actions that result in deleting content in the editor.
1152
+ */ class Delete extends Plugin {
1153
+ /**
1154
+ * Whether pressing backspace should trigger undo action
1155
+ */ _undoOnBackspace;
1156
+ /**
1157
+ * @inheritDoc
1158
+ */ static get pluginName() {
1159
+ return 'Delete';
1160
+ }
1161
+ /**
1162
+ * @inheritDoc
1163
+ */ static get isOfficialPlugin() {
1164
+ return true;
1165
+ }
1166
+ /**
1167
+ * @inheritDoc
1168
+ */ init() {
1169
+ const editor = this.editor;
1170
+ const view = editor.editing.view;
1171
+ const viewDocument = view.document;
1172
+ const modelDocument = editor.model.document;
1173
+ view.addObserver(DeleteObserver);
1174
+ this._undoOnBackspace = false;
1175
+ const deleteForwardCommand = new DeleteCommand(editor, 'forward');
1176
+ // Register `deleteForward` command and add `forwardDelete` command as an alias for backward compatibility.
1177
+ editor.commands.add('deleteForward', deleteForwardCommand);
1178
+ editor.commands.add('forwardDelete', deleteForwardCommand);
1179
+ editor.commands.add('delete', new DeleteCommand(editor, 'backward'));
1180
+ this.listenTo(viewDocument, 'delete', (evt, data)=>{
1181
+ // When not in composition, we handle the action, so prevent the default one.
1182
+ // When in composition, it's the browser who modify the DOM (renderer is disabled).
1183
+ if (!viewDocument.isComposing) {
1184
+ data.preventDefault();
1185
+ }
1186
+ const { direction, sequence, selectionToRemove, unit } = data;
1187
+ const commandName = direction === 'forward' ? 'deleteForward' : 'delete';
1188
+ const commandData = {
1189
+ sequence
1190
+ };
1191
+ if (unit == 'selection') {
1192
+ const modelRanges = Array.from(selectionToRemove.getRanges()).map((viewRange)=>{
1193
+ return editor.editing.mapper.toModelRange(viewRange);
1194
+ });
1195
+ commandData.selection = editor.model.createSelection(modelRanges);
1196
+ } else {
1197
+ commandData.unit = unit;
1198
+ }
1199
+ editor.execute(commandName, commandData);
1200
+ view.scrollToTheSelection();
1201
+ }, {
1202
+ priority: 'low'
1203
+ });
1204
+ if (this.editor.plugins.has('UndoEditing')) {
1205
+ this.listenTo(viewDocument, 'delete', (evt, data)=>{
1206
+ if (this._undoOnBackspace && data.direction == 'backward' && data.sequence == 1 && data.unit == 'codePoint') {
1207
+ this._undoOnBackspace = false;
1208
+ editor.execute('undo');
1209
+ data.preventDefault();
1210
+ evt.stop();
1211
+ }
1212
+ }, {
1213
+ context: '$capture'
1214
+ });
1215
+ this.listenTo(modelDocument, 'change', ()=>{
1216
+ this._undoOnBackspace = false;
1217
+ });
1218
+ }
1219
+ }
1220
+ /**
1221
+ * If the next user action after calling this method is pressing backspace, it would undo the last change.
1222
+ *
1223
+ * Requires {@link module:undo/undoediting~UndoEditing} plugin. If not loaded, does nothing.
1224
+ */ requestUndoOnBackspace() {
1225
+ if (this.editor.plugins.has('UndoEditing')) {
1226
+ this._undoOnBackspace = true;
1227
+ }
1228
+ }
1229
+ }
1230
+
1231
+ /**
1232
+ * The typing feature. It handles typing.
1233
+ *
1234
+ * This is a "glue" plugin which loads the {@link module:typing/input~Input} and {@link module:typing/delete~Delete}
1235
+ * plugins.
1236
+ */ class Typing extends Plugin {
1237
+ static get requires() {
1238
+ return [
1239
+ Input,
1240
+ Delete
1241
+ ];
1242
+ }
1243
+ /**
1244
+ * @inheritDoc
1245
+ */ static get pluginName() {
1246
+ return 'Typing';
1247
+ }
1248
+ /**
1249
+ * @inheritDoc
1250
+ */ static get isOfficialPlugin() {
1251
+ return true;
1252
+ }
1253
+ }
1254
+
1255
+ /**
1256
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
1257
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
1258
+ */ /**
1259
+ * @module typing/utils/getlasttextline
1260
+ */ /**
1261
+ * Returns the last text line from the given range.
1262
+ *
1263
+ * "The last text line" is understood as text (from one or more text nodes) which is limited either by a parent block
1264
+ * or by inline elements (e.g. `<softBreak>`).
1265
+ *
1266
+ * ```ts
1267
+ * const rangeToCheck = model.createRange(
1268
+ * model.createPositionAt( paragraph, 0 ),
1269
+ * model.createPositionAt( paragraph, 'end' )
1270
+ * );
1271
+ *
1272
+ * const { text, range } = getLastTextLine( rangeToCheck, model );
1273
+ * ```
1274
+ *
1275
+ * For model below, the returned `text` will be "Foo bar baz" and `range` will be set on whole `<paragraph>` content:
1276
+ *
1277
+ * ```xml
1278
+ * <paragraph>Foo bar baz<paragraph>
1279
+ * ```
1280
+ *
1281
+ * However, in below case, `text` will be set to "baz" and `range` will be set only on "baz".
1282
+ *
1283
+ * ```xml
1284
+ * <paragraph>Foo<softBreak></softBreak>bar<softBreak></softBreak>baz<paragraph>
1285
+ * ```
1286
+ */ function getLastTextLine(range, model) {
1287
+ let start = range.start;
1288
+ const text = Array.from(range.getWalker({
1289
+ ignoreElementEnd: false
1290
+ })).reduce((rangeText, { item })=>{
1291
+ // Trim text to a last occurrence of an inline element and update range start.
1292
+ if (!(item.is('$text') || item.is('$textProxy'))) {
1293
+ start = model.createPositionAfter(item);
1294
+ return '';
1295
+ }
1296
+ return rangeText + item.data;
1297
+ }, '');
1298
+ return {
1299
+ text,
1300
+ range: model.createRange(start, range.end)
1301
+ };
1302
+ }
1303
+
1304
+ /**
1305
+ * The text watcher feature.
1306
+ *
1307
+ * Fires the {@link module:typing/textwatcher~TextWatcher#event:matched:data `matched:data`},
1308
+ * {@link module:typing/textwatcher~TextWatcher#event:matched:selection `matched:selection`} and
1309
+ * {@link module:typing/textwatcher~TextWatcher#event:unmatched `unmatched`} events on typing or selection changes.
1310
+ */ class TextWatcher extends /* #__PURE__ */ ObservableMixin() {
1311
+ /**
1312
+ * The editor's model.
1313
+ */ model;
1314
+ /**
1315
+ * The function used to match the text.
1316
+ *
1317
+ * The test callback can return 3 values:
1318
+ *
1319
+ * * `false` if there is no match,
1320
+ * * `true` if there is a match,
1321
+ * * an object if there is a match and we want to pass some additional information to the {@link #event:matched:data} event.
1322
+ */ testCallback;
1323
+ /**
1324
+ * Whether there is a match currently.
1325
+ */ _hasMatch;
1326
+ /**
1327
+ * Creates a text watcher instance.
1328
+ *
1329
+ * @param testCallback See {@link module:typing/textwatcher~TextWatcher#testCallback}.
1330
+ */ constructor(model, testCallback){
1331
+ super();
1332
+ this.model = model;
1333
+ this.testCallback = testCallback;
1334
+ this._hasMatch = false;
1335
+ this.set('isEnabled', true);
1336
+ // Toggle text watching on isEnabled state change.
1337
+ this.on('change:isEnabled', ()=>{
1338
+ if (this.isEnabled) {
1339
+ this._startListening();
1340
+ } else {
1341
+ this.stopListening(model.document.selection);
1342
+ this.stopListening(model.document);
1343
+ }
1344
+ });
1345
+ this._startListening();
1346
+ }
1347
+ /**
1348
+ * Flag indicating whether there is a match currently.
1349
+ */ get hasMatch() {
1350
+ return this._hasMatch;
1351
+ }
1352
+ /**
1353
+ * Starts listening to the editor for typing and selection events.
1354
+ */ _startListening() {
1355
+ const model = this.model;
1356
+ const document = model.document;
1357
+ this.listenTo(document.selection, 'change:range', (evt, { directChange })=>{
1358
+ // Indirect changes (i.e. when the user types or external changes are applied) are handled in the document's change event.
1359
+ if (!directChange) {
1360
+ return;
1361
+ }
1362
+ // Act only on collapsed selection.
1363
+ if (!document.selection.isCollapsed) {
1364
+ if (this.hasMatch) {
1365
+ this.fire('unmatched');
1366
+ this._hasMatch = false;
1367
+ }
1368
+ return;
1369
+ }
1370
+ this._evaluateTextBeforeSelection('selection');
1371
+ });
1372
+ this.listenTo(document, 'change:data', (evt, batch)=>{
1373
+ if (batch.isUndo || !batch.isLocal) {
1374
+ return;
1375
+ }
1376
+ this._evaluateTextBeforeSelection('data', {
1377
+ batch
1378
+ });
1379
+ });
1380
+ }
1381
+ /**
1382
+ * Checks the editor content for matched text.
1383
+ *
1384
+ * @fires matched:data
1385
+ * @fires matched:selection
1386
+ * @fires unmatched
1387
+ *
1388
+ * @param suffix A suffix used for generating the event name.
1389
+ * @param data Data object for event.
1390
+ */ _evaluateTextBeforeSelection(suffix, data = {}) {
1391
+ const model = this.model;
1392
+ const document = model.document;
1393
+ const selection = document.selection;
1394
+ const rangeBeforeSelection = model.createRange(model.createPositionAt(selection.focus.parent, 0), selection.focus);
1395
+ const { text, range } = getLastTextLine(rangeBeforeSelection, model);
1396
+ const testResult = this.testCallback(text);
1397
+ if (!testResult && this.hasMatch) {
1398
+ this.fire('unmatched');
1399
+ }
1400
+ this._hasMatch = !!testResult;
1401
+ if (testResult) {
1402
+ const eventData = Object.assign(data, {
1403
+ text,
1404
+ range
1405
+ });
1406
+ // If the test callback returns an object with additional data, assign the data as well.
1407
+ if (typeof testResult == 'object') {
1408
+ Object.assign(eventData, testResult);
1409
+ }
1410
+ this.fire(`matched:${suffix}`, eventData);
1411
+ }
1412
+ }
1413
+ }
1414
+
1415
+ /**
1416
+ * This plugin enables the two-step caret (phantom) movement behavior for
1417
+ * {@link module:typing/twostepcaretmovement~TwoStepCaretMovement#registerAttribute registered attributes}
1418
+ * on arrow right (<kbd>→</kbd>) and left (<kbd>←</kbd>) key press.
1419
+ *
1420
+ * Thanks to this (phantom) caret movement the user is able to type before/after as well as at the
1421
+ * beginning/end of an attribute.
1422
+ *
1423
+ * **Note:** This plugin support right–to–left (Arabic, Hebrew, etc.) content by mirroring its behavior
1424
+ * but for the sake of simplicity examples showcase only left–to–right use–cases.
1425
+ *
1426
+ * # Forward movement
1427
+ *
1428
+ * ## "Entering" an attribute:
1429
+ *
1430
+ * When this plugin is enabled and registered for the `a` attribute and the selection is right before it
1431
+ * (at the attribute boundary), pressing the right arrow key will not move the selection but update its
1432
+ * attributes accordingly:
1433
+ *
1434
+ * * When enabled:
1435
+ *
1436
+ * ```xml
1437
+ * foo{}<$text a="true">bar</$text>
1438
+ * ```
1439
+ *
1440
+ * <kbd>→</kbd>
1441
+ *
1442
+ * ```xml
1443
+ * foo<$text a="true">{}bar</$text>
1444
+ * ```
1445
+ *
1446
+ * * When disabled:
1447
+ *
1448
+ * ```xml
1449
+ * foo{}<$text a="true">bar</$text>
1450
+ * ```
1451
+ *
1452
+ * <kbd>→</kbd>
1453
+ *
1454
+ * ```xml
1455
+ * foo<$text a="true">b{}ar</$text>
1456
+ * ```
1457
+ *
1458
+ *
1459
+ * ## "Leaving" an attribute:
1460
+ *
1461
+ * * When enabled:
1462
+ *
1463
+ * ```xml
1464
+ * <$text a="true">bar{}</$text>baz
1465
+ * ```
1466
+ *
1467
+ * <kbd>→</kbd>
1468
+ *
1469
+ * ```xml
1470
+ * <$text a="true">bar</$text>{}baz
1471
+ * ```
1472
+ *
1473
+ * * When disabled:
1474
+ *
1475
+ * ```xml
1476
+ * <$text a="true">bar{}</$text>baz
1477
+ * ```
1478
+ *
1479
+ * <kbd>→</kbd>
1480
+ *
1481
+ * ```xml
1482
+ * <$text a="true">bar</$text>b{}az
1483
+ * ```
1484
+ *
1485
+ * # Backward movement
1486
+ *
1487
+ * * When enabled:
1488
+ *
1489
+ * ```xml
1490
+ * <$text a="true">bar</$text>{}baz
1491
+ * ```
1492
+ *
1493
+ * <kbd>←</kbd>
1494
+ *
1495
+ * ```xml
1496
+ * <$text a="true">bar{}</$text>baz
1497
+ * ```
1498
+ *
1499
+ * * When disabled:
1500
+ *
1501
+ * ```xml
1502
+ * <$text a="true">bar</$text>{}baz
1503
+ * ```
1504
+ *
1505
+ * <kbd>←</kbd>
1506
+ *
1507
+ * ```xml
1508
+ * <$text a="true">ba{}r</$text>b{}az
1509
+ * ```
1510
+ *
1511
+ * # Multiple attributes
1512
+ *
1513
+ * * When enabled and many attributes starts or ends at the same position:
1514
+ *
1515
+ * ```xml
1516
+ * <$text a="true" b="true">bar</$text>{}baz
1517
+ * ```
1518
+ *
1519
+ * <kbd>←</kbd>
1520
+ *
1521
+ * ```xml
1522
+ * <$text a="true" b="true">bar{}</$text>baz
1523
+ * ```
1524
+ *
1525
+ * * When enabled and one procedes another:
1526
+ *
1527
+ * ```xml
1528
+ * <$text a="true">bar</$text><$text b="true">{}bar</$text>
1529
+ * ```
1530
+ *
1531
+ * <kbd>←</kbd>
1532
+ *
1533
+ * ```xml
1534
+ * <$text a="true">bar{}</$text><$text b="true">bar</$text>
1535
+ * ```
1536
+ *
1537
+ */ class TwoStepCaretMovement extends Plugin {
1538
+ /**
1539
+ * A set of attributes to handle.
1540
+ */ attributes;
1541
+ /**
1542
+ * The current UID of the overridden gravity, as returned by
1543
+ * {@link module:engine/model/writer~Writer#overrideSelectionGravity}.
1544
+ */ _overrideUid;
1545
+ /**
1546
+ * A flag indicating that the automatic gravity restoration should not happen upon the next
1547
+ * gravity restoration.
1548
+ * {@link module:engine/model/selection~Selection#event:change:range} event.
1549
+ */ _isNextGravityRestorationSkipped = false;
1550
+ /**
1551
+ * @inheritDoc
1552
+ */ static get pluginName() {
1553
+ return 'TwoStepCaretMovement';
1554
+ }
1555
+ /**
1556
+ * @inheritDoc
1557
+ */ static get isOfficialPlugin() {
1558
+ return true;
1559
+ }
1560
+ /**
1561
+ * @inheritDoc
1562
+ */ constructor(editor){
1563
+ super(editor);
1564
+ this.attributes = new Set();
1565
+ this._overrideUid = null;
1566
+ }
1567
+ /**
1568
+ * @inheritDoc
1569
+ */ init() {
1570
+ const editor = this.editor;
1571
+ const model = editor.model;
1572
+ const view = editor.editing.view;
1573
+ const locale = editor.locale;
1574
+ const modelSelection = model.document.selection;
1575
+ // Listen to keyboard events and handle the caret movement according to the 2-step caret logic.
1576
+ this.listenTo(view.document, 'arrowKey', (evt, data)=>{
1577
+ // This implementation works only for collapsed selection.
1578
+ if (!modelSelection.isCollapsed) {
1579
+ return;
1580
+ }
1581
+ // When user tries to expand the selection or jump over the whole word or to the beginning/end then
1582
+ // two-steps movement is not necessary.
1583
+ if (data.shiftKey || data.altKey || data.ctrlKey) {
1584
+ return;
1585
+ }
1586
+ const arrowRightPressed = data.keyCode == keyCodes.arrowright;
1587
+ const arrowLeftPressed = data.keyCode == keyCodes.arrowleft;
1588
+ // When neither left or right arrow has been pressed then do noting.
1589
+ if (!arrowRightPressed && !arrowLeftPressed) {
1590
+ return;
1591
+ }
1592
+ const contentDirection = locale.contentLanguageDirection;
1593
+ let isMovementHandled = false;
1594
+ if (contentDirection === 'ltr' && arrowRightPressed || contentDirection === 'rtl' && arrowLeftPressed) {
1595
+ isMovementHandled = this._handleForwardMovement(data);
1596
+ } else {
1597
+ isMovementHandled = this._handleBackwardMovement(data);
1598
+ }
1599
+ // Stop the keydown event if the two-step caret movement handled it. Avoid collisions
1600
+ // with other features which may also take over the caret movement (e.g. Widget).
1601
+ if (isMovementHandled === true) {
1602
+ evt.stop();
1603
+ }
1604
+ }, {
1605
+ context: '$text',
1606
+ priority: 'highest'
1607
+ });
1608
+ // The automatic gravity restoration logic.
1609
+ this.listenTo(modelSelection, 'change:range', (evt, data)=>{
1610
+ // Skipping the automatic restoration is needed if the selection should change
1611
+ // but the gravity must remain overridden afterwards. See the #handleBackwardMovement
1612
+ // to learn more.
1613
+ if (this._isNextGravityRestorationSkipped) {
1614
+ this._isNextGravityRestorationSkipped = false;
1615
+ return;
1616
+ }
1617
+ // Skip automatic restore when the gravity is not overridden — simply, there's nothing to restore
1618
+ // at this moment.
1619
+ if (!this._isGravityOverridden) {
1620
+ return;
1621
+ }
1622
+ // Skip automatic restore when the change is indirect AND the selection is at the attribute boundary.
1623
+ // It means that e.g. if the change was external (collaboration) and the user had their
1624
+ // selection around the link, its gravity should remain intact in this change:range event.
1625
+ if (!data.directChange && isBetweenDifferentAttributes(modelSelection.getFirstPosition(), this.attributes)) {
1626
+ return;
1627
+ }
1628
+ this._restoreGravity();
1629
+ });
1630
+ // Handle a click at the beginning/end of a two-step element.
1631
+ this._enableClickingAfterNode();
1632
+ // Change the attributes of the selection in certain situations after the two-step node was inserted into the document.
1633
+ this._enableInsertContentSelectionAttributesFixer();
1634
+ // Handle removing the content after the two-step node.
1635
+ this._handleDeleteContentAfterNode();
1636
+ }
1637
+ /**
1638
+ * Registers a given attribute for the two-step caret movement.
1639
+ *
1640
+ * @param attribute Name of the attribute to handle.
1641
+ */ registerAttribute(attribute) {
1642
+ this.attributes.add(attribute);
1643
+ }
1644
+ /**
1645
+ * Updates the document selection and the view according to the two–step caret movement state
1646
+ * when moving **forwards**. Executed upon `keypress` in the {@link module:engine/view/view~View}.
1647
+ *
1648
+ * @param data Data of the key press.
1649
+ * @returns `true` when the handler prevented caret movement.
1650
+ */ _handleForwardMovement(data) {
1651
+ const attributes = this.attributes;
1652
+ const model = this.editor.model;
1653
+ const selection = model.document.selection;
1654
+ const position = selection.getFirstPosition();
1655
+ // DON'T ENGAGE 2-SCM if gravity is already overridden. It means that we just entered
1656
+ //
1657
+ // <paragraph>foo<$text attribute>{}bar</$text>baz</paragraph>
1658
+ //
1659
+ // or left the attribute
1660
+ //
1661
+ // <paragraph>foo<$text attribute>bar</$text>{}baz</paragraph>
1662
+ //
1663
+ // and the gravity will be restored automatically.
1664
+ if (this._isGravityOverridden) {
1665
+ return false;
1666
+ }
1667
+ // DON'T ENGAGE 2-SCM when the selection is at the beginning of the block AND already has the
1668
+ // attribute:
1669
+ // * when the selection was initially set there using the mouse,
1670
+ // * when the editor has just started
1671
+ //
1672
+ // <paragraph><$text attribute>{}bar</$text>baz</paragraph>
1673
+ //
1674
+ if (position.isAtStart && hasAnyAttribute(selection, attributes)) {
1675
+ return false;
1676
+ }
1677
+ // ENGAGE 2-SCM When at least one of the observed attributes changes its value (incl. starts, ends).
1678
+ //
1679
+ // <paragraph>foo<$text attribute>bar{}</$text>baz</paragraph>
1680
+ // <paragraph>foo<$text attribute>bar{}</$text><$text otherAttribute>baz</$text></paragraph>
1681
+ // <paragraph>foo<$text attribute=1>bar{}</$text><$text attribute=2>baz</$text></paragraph>
1682
+ // <paragraph>foo{}<$text attribute>bar</$text>baz</paragraph>
1683
+ //
1684
+ if (isBetweenDifferentAttributes(position, attributes)) {
1685
+ preventCaretMovement(data);
1686
+ // CLEAR 2-SCM attributes if we are at the end of one 2-SCM and before
1687
+ // the next one with a different value of the same attribute.
1688
+ //
1689
+ // <paragraph>foo<$text attribute=1>bar{}</$text><$text attribute=2>bar</$text>baz</paragraph>
1690
+ //
1691
+ if (hasAnyAttribute(selection, attributes) && isBetweenDifferentAttributes(position, attributes, true)) {
1692
+ clearSelectionAttributes(model, attributes);
1693
+ } else {
1694
+ this._overrideGravity();
1695
+ }
1696
+ return true;
1697
+ }
1698
+ return false;
1699
+ }
1700
+ /**
1701
+ * Updates the document selection and the view according to the two–step caret movement state
1702
+ * when moving **backwards**. Executed upon `keypress` in the {@link module:engine/view/view~View}.
1703
+ *
1704
+ * @param data Data of the key press.
1705
+ * @returns `true` when the handler prevented caret movement
1706
+ */ _handleBackwardMovement(data) {
1707
+ const attributes = this.attributes;
1708
+ const model = this.editor.model;
1709
+ const selection = model.document.selection;
1710
+ const position = selection.getFirstPosition();
1711
+ // When the gravity is already overridden (by this plugin), it means we are on the two-step position.
1712
+ // Prevent the movement, restore the gravity and update selection attributes.
1713
+ //
1714
+ // <paragraph>foo<$text attribute=1>bar</$text><$text attribute=2>{}baz</$text></paragraph>
1715
+ // <paragraph>foo<$text attribute>bar</$text><$text otherAttribute>{}baz</$text></paragraph>
1716
+ // <paragraph>foo<$text attribute>{}bar</$text>baz</paragraph>
1717
+ // <paragraph>foo<$text attribute>bar</$text>{}baz</paragraph>
1718
+ //
1719
+ if (this._isGravityOverridden) {
1720
+ preventCaretMovement(data);
1721
+ this._restoreGravity();
1722
+ // CLEAR 2-SCM attributes if we are at the end of one 2-SCM and before
1723
+ // the next one with a different value of the same attribute.
1724
+ //
1725
+ // <paragraph>foo<$text attribute=1>bar</$text><$text attribute=2>{}bar</$text>baz</paragraph>
1726
+ //
1727
+ if (isBetweenDifferentAttributes(position, attributes, true)) {
1728
+ clearSelectionAttributes(model, attributes);
1729
+ } else {
1730
+ setSelectionAttributesFromTheNodeBefore(model, attributes, position);
1731
+ }
1732
+ return true;
1733
+ } else {
1734
+ // REMOVE SELECTION ATTRIBUTE when restoring gravity towards a non-existent content at the
1735
+ // beginning of the block.
1736
+ //
1737
+ // <paragraph>{}<$text attribute>bar</$text></paragraph>
1738
+ //
1739
+ if (position.isAtStart) {
1740
+ if (hasAnyAttribute(selection, attributes)) {
1741
+ preventCaretMovement(data);
1742
+ setSelectionAttributesFromTheNodeBefore(model, attributes, position);
1743
+ return true;
1744
+ }
1745
+ return false;
1746
+ }
1747
+ // SET 2-SCM attributes if we are between nodes with the same attribute but with different values.
1748
+ //
1749
+ // <paragraph>foo<$text attribute=1>bar</$text>[]<$text attribute=2>bar</$text>baz</paragraph>
1750
+ //
1751
+ if (!hasAnyAttribute(selection, attributes) && isBetweenDifferentAttributes(position, attributes, true)) {
1752
+ preventCaretMovement(data);
1753
+ setSelectionAttributesFromTheNodeBefore(model, attributes, position);
1754
+ return true;
1755
+ }
1756
+ // When we are moving from natural gravity, to the position of the 2SCM, we need to override the gravity,
1757
+ // and make sure it won't be restored. Unless it's at the end of the block and an observed attribute.
1758
+ // We need to check if the caret is a one position before the attribute boundary:
1759
+ //
1760
+ // <paragraph>foo<$text attribute=1>bar</$text><$text attribute=2>b{}az</$text></paragraph>
1761
+ // <paragraph>foo<$text attribute>bar</$text><$text otherAttribute>b{}az</$text></paragraph>
1762
+ // <paragraph>foo<$text attribute>b{}ar</$text>baz</paragraph>
1763
+ // <paragraph>foo<$text attribute>bar</$text>b{}az</paragraph>
1764
+ //
1765
+ if (isStepAfterAnyAttributeBoundary(position, attributes)) {
1766
+ // ENGAGE 2-SCM if the selection has no attribute. This may happen when the user
1767
+ // left the attribute using a FORWARD 2-SCM.
1768
+ //
1769
+ // <paragraph><$text attribute>bar</$text>{}</paragraph>
1770
+ //
1771
+ if (position.isAtEnd && !hasAnyAttribute(selection, attributes) && isBetweenDifferentAttributes(position, attributes)) {
1772
+ preventCaretMovement(data);
1773
+ setSelectionAttributesFromTheNodeBefore(model, attributes, position);
1774
+ return true;
1775
+ }
1776
+ // Skip the automatic gravity restore upon the next selection#change:range event.
1777
+ // If not skipped, it would automatically restore the gravity, which should remain
1778
+ // overridden.
1779
+ this._isNextGravityRestorationSkipped = true;
1780
+ this._overrideGravity();
1781
+ // Don't return "true" here because we didn't call _preventCaretMovement.
1782
+ // Returning here will destabilize the filler logic, which also listens to
1783
+ // keydown (and the event would be stopped).
1784
+ return false;
1785
+ }
1786
+ }
1787
+ return false;
1788
+ }
1789
+ /**
1790
+ * Starts listening to {@link module:engine/view/document~Document#event:mousedown} and
1791
+ * {@link module:engine/view/document~Document#event:selectionChange} and puts the selection before/after a 2-step node
1792
+ * if clicked at the beginning/ending of the 2-step node.
1793
+ *
1794
+ * The purpose of this action is to allow typing around the 2-step node directly after a click.
1795
+ *
1796
+ * See https://github.com/ckeditor/ckeditor5/issues/1016.
1797
+ */ _enableClickingAfterNode() {
1798
+ const editor = this.editor;
1799
+ const model = editor.model;
1800
+ const selection = model.document.selection;
1801
+ const document = editor.editing.view.document;
1802
+ editor.editing.view.addObserver(MouseObserver);
1803
+ let clicked = false;
1804
+ // Detect the click.
1805
+ this.listenTo(document, 'mousedown', ()=>{
1806
+ clicked = true;
1807
+ });
1808
+ // When the selection has changed...
1809
+ this.listenTo(document, 'selectionChange', ()=>{
1810
+ const attributes = this.attributes;
1811
+ if (!clicked) {
1812
+ return;
1813
+ }
1814
+ // ...and it was caused by the click...
1815
+ clicked = false;
1816
+ // ...and no text is selected...
1817
+ if (!selection.isCollapsed) {
1818
+ return;
1819
+ }
1820
+ // ...and clicked text is the 2-step node...
1821
+ if (!hasAnyAttribute(selection, attributes)) {
1822
+ return;
1823
+ }
1824
+ const position = selection.getFirstPosition();
1825
+ if (!isBetweenDifferentAttributes(position, attributes)) {
1826
+ return;
1827
+ }
1828
+ // The selection at the start of a block would use surrounding attributes
1829
+ // from text after the selection so just clear 2-SCM attributes.
1830
+ //
1831
+ // Also, clear attributes for selection between same attribute with different values.
1832
+ if (position.isAtStart || isBetweenDifferentAttributes(position, attributes, true)) {
1833
+ clearSelectionAttributes(model, attributes);
1834
+ } else if (!this._isGravityOverridden) {
1835
+ this._overrideGravity();
1836
+ }
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Starts listening to {@link module:engine/model/model~Model#event:insertContent} and corrects the model
1841
+ * selection attributes if the selection is at the end of a two-step node after inserting the content.
1842
+ *
1843
+ * The purpose of this action is to improve the overall UX because the user is no longer "trapped" by the
1844
+ * two-step attribute of the selection, and they can type a "clean" (`linkHref`–less) text right away.
1845
+ *
1846
+ * See https://github.com/ckeditor/ckeditor5/issues/6053.
1847
+ */ _enableInsertContentSelectionAttributesFixer() {
1848
+ const editor = this.editor;
1849
+ const model = editor.model;
1850
+ const selection = model.document.selection;
1851
+ const attributes = this.attributes;
1852
+ this.listenTo(model, 'insertContent', ()=>{
1853
+ const position = selection.getFirstPosition();
1854
+ if (hasAnyAttribute(selection, attributes) && isBetweenDifferentAttributes(position, attributes)) {
1855
+ clearSelectionAttributes(model, attributes);
1856
+ }
1857
+ }, {
1858
+ priority: 'low'
1859
+ });
1860
+ }
1861
+ /**
1862
+ * Starts listening to {@link module:engine/model/model~Model#deleteContent} and checks whether
1863
+ * removing a content right after the tow-step attribute.
1864
+ *
1865
+ * If so, the selection should not preserve the two-step attribute. However, if
1866
+ * the {@link module:typing/twostepcaretmovement~TwoStepCaretMovement} plugin is active and
1867
+ * the selection has the two-step attribute due to overridden gravity (at the end), the two-step attribute should stay untouched.
1868
+ *
1869
+ * The purpose of this action is to allow removing the link text and keep the selection outside the link.
1870
+ *
1871
+ * See https://github.com/ckeditor/ckeditor5/issues/7521.
1872
+ */ _handleDeleteContentAfterNode() {
1873
+ const editor = this.editor;
1874
+ const model = editor.model;
1875
+ const selection = model.document.selection;
1876
+ const view = editor.editing.view;
1877
+ let isBackspace = false;
1878
+ let shouldPreserveAttributes = false;
1879
+ // Detect pressing `Backspace`.
1880
+ this.listenTo(view.document, 'delete', (evt, data)=>{
1881
+ isBackspace = data.direction === 'backward';
1882
+ }, {
1883
+ priority: 'high'
1884
+ });
1885
+ // Before removing the content, check whether the selection is inside a two-step attribute.
1886
+ // If so, we want to preserve those attributes.
1887
+ this.listenTo(model, 'deleteContent', ()=>{
1888
+ if (!isBackspace) {
1889
+ return;
1890
+ }
1891
+ const position = selection.getFirstPosition();
1892
+ shouldPreserveAttributes = hasAnyAttribute(selection, this.attributes) && !isStepAfterAnyAttributeBoundary(position, this.attributes);
1893
+ }, {
1894
+ priority: 'high'
1895
+ });
1896
+ // After removing the content, check whether the current selection should preserve the `linkHref` attribute.
1897
+ this.listenTo(model, 'deleteContent', ()=>{
1898
+ if (!isBackspace) {
1899
+ return;
1900
+ }
1901
+ isBackspace = false;
1902
+ // Do not escape two-step attribute if it was inside it before content deletion.
1903
+ if (shouldPreserveAttributes) {
1904
+ return;
1905
+ }
1906
+ // Use `model.enqueueChange()` in order to execute the callback at the end of the changes process.
1907
+ editor.model.enqueueChange(()=>{
1908
+ const position = selection.getFirstPosition();
1909
+ if (hasAnyAttribute(selection, this.attributes) && isBetweenDifferentAttributes(position, this.attributes)) {
1910
+ if (position.isAtStart || isBetweenDifferentAttributes(position, this.attributes, true)) {
1911
+ clearSelectionAttributes(model, this.attributes);
1912
+ } else if (!this._isGravityOverridden) {
1913
+ this._overrideGravity();
1914
+ }
1915
+ }
1916
+ });
1917
+ }, {
1918
+ priority: 'low'
1919
+ });
1920
+ }
1921
+ /**
1922
+ * `true` when the gravity is overridden for the plugin.
1923
+ */ get _isGravityOverridden() {
1924
+ return !!this._overrideUid;
1925
+ }
1926
+ /**
1927
+ * Overrides the gravity using the {@link module:engine/model/writer~Writer model writer}
1928
+ * and stores the information about this fact in the {@link #_overrideUid}.
1929
+ *
1930
+ * A shorthand for {@link module:engine/model/writer~Writer#overrideSelectionGravity}.
1931
+ */ _overrideGravity() {
1932
+ this._overrideUid = this.editor.model.change((writer)=>{
1933
+ return writer.overrideSelectionGravity();
1934
+ });
1935
+ }
1936
+ /**
1937
+ * Restores the gravity using the {@link module:engine/model/writer~Writer model writer}.
1938
+ *
1939
+ * A shorthand for {@link module:engine/model/writer~Writer#restoreSelectionGravity}.
1940
+ */ _restoreGravity() {
1941
+ this.editor.model.change((writer)=>{
1942
+ writer.restoreSelectionGravity(this._overrideUid);
1943
+ this._overrideUid = null;
1944
+ });
1945
+ }
1946
+ }
1947
+ /**
1948
+ * Checks whether the selection has any of given attributes.
1949
+ */ function hasAnyAttribute(selection, attributes) {
1950
+ for (const observedAttribute of attributes){
1951
+ if (selection.hasAttribute(observedAttribute)) {
1952
+ return true;
1953
+ }
1954
+ }
1955
+ return false;
1956
+ }
1957
+ /**
1958
+ * Applies the given attributes to the current selection using using the
1959
+ * values from the node before the current position. Uses
1960
+ * the {@link module:engine/model/writer~Writer model writer}.
1961
+ */ function setSelectionAttributesFromTheNodeBefore(model, attributes, position) {
1962
+ const nodeBefore = position.nodeBefore;
1963
+ model.change((writer)=>{
1964
+ if (nodeBefore) {
1965
+ const attributes = [];
1966
+ const isInlineObject = model.schema.isObject(nodeBefore) && model.schema.isInline(nodeBefore);
1967
+ for (const [key, value] of nodeBefore.getAttributes()){
1968
+ if (model.schema.checkAttribute('$text', key) && (!isInlineObject || model.schema.getAttributeProperties(key).copyFromObject !== false)) {
1969
+ attributes.push([
1970
+ key,
1971
+ value
1972
+ ]);
1973
+ }
1974
+ }
1975
+ writer.setSelectionAttribute(attributes);
1976
+ } else {
1977
+ writer.removeSelectionAttribute(attributes);
1978
+ }
1979
+ });
1980
+ }
1981
+ /**
1982
+ * Removes 2-SCM attributes from the selection.
1983
+ */ function clearSelectionAttributes(model, attributes) {
1984
+ model.change((writer)=>{
1985
+ writer.removeSelectionAttribute(attributes);
1986
+ });
1987
+ }
1988
+ /**
1989
+ * Prevents the caret movement in the view by calling `preventDefault` on the event data.
1990
+ *
1991
+ * @alias data.preventDefault
1992
+ */ function preventCaretMovement(data) {
1993
+ data.preventDefault();
1994
+ }
1995
+ /**
1996
+ * Checks whether the step before `isBetweenDifferentAttributes()`.
1997
+ */ function isStepAfterAnyAttributeBoundary(position, attributes) {
1998
+ const positionBefore = position.getShiftedBy(-1);
1999
+ return isBetweenDifferentAttributes(positionBefore, attributes);
2000
+ }
2001
+ /**
2002
+ * Checks whether the given position is between different values of given attributes.
2003
+ */ function isBetweenDifferentAttributes(position, attributes, isStrict = false) {
2004
+ const { nodeBefore, nodeAfter } = position;
2005
+ for (const observedAttribute of attributes){
2006
+ const attrBefore = nodeBefore ? nodeBefore.getAttribute(observedAttribute) : undefined;
2007
+ const attrAfter = nodeAfter ? nodeAfter.getAttribute(observedAttribute) : undefined;
2008
+ if (isStrict && (attrBefore === undefined || attrAfter === undefined)) {
2009
+ continue;
2010
+ }
2011
+ if (attrAfter !== attrBefore) {
2012
+ return true;
2013
+ }
2014
+ }
2015
+ return false;
2016
+ }
2017
+
2018
+ // All named transformations.
2019
+ const TRANSFORMATIONS = {
2020
+ // Common symbols:
2021
+ copyright: {
2022
+ from: '(c)',
2023
+ to: '©'
2024
+ },
2025
+ registeredTrademark: {
2026
+ from: '(r)',
2027
+ to: '®'
2028
+ },
2029
+ trademark: {
2030
+ from: '(tm)',
2031
+ to: '™'
2032
+ },
2033
+ // Mathematical:
2034
+ oneHalf: {
2035
+ from: /(^|[^/a-z0-9])(1\/2)([^/a-z0-9])$/i,
2036
+ to: [
2037
+ null,
2038
+ '½',
2039
+ null
2040
+ ]
2041
+ },
2042
+ oneThird: {
2043
+ from: /(^|[^/a-z0-9])(1\/3)([^/a-z0-9])$/i,
2044
+ to: [
2045
+ null,
2046
+ '⅓',
2047
+ null
2048
+ ]
2049
+ },
2050
+ twoThirds: {
2051
+ from: /(^|[^/a-z0-9])(2\/3)([^/a-z0-9])$/i,
2052
+ to: [
2053
+ null,
2054
+ '⅔',
2055
+ null
2056
+ ]
2057
+ },
2058
+ oneForth: {
2059
+ from: /(^|[^/a-z0-9])(1\/4)([^/a-z0-9])$/i,
2060
+ to: [
2061
+ null,
2062
+ '¼',
2063
+ null
2064
+ ]
2065
+ },
2066
+ threeQuarters: {
2067
+ from: /(^|[^/a-z0-9])(3\/4)([^/a-z0-9])$/i,
2068
+ to: [
2069
+ null,
2070
+ '¾',
2071
+ null
2072
+ ]
2073
+ },
2074
+ lessThanOrEqual: {
2075
+ from: '<=',
2076
+ to: '≤'
2077
+ },
2078
+ greaterThanOrEqual: {
2079
+ from: '>=',
2080
+ to: '≥'
2081
+ },
2082
+ notEqual: {
2083
+ from: '!=',
2084
+ to: '≠'
2085
+ },
2086
+ arrowLeft: {
2087
+ from: '<-',
2088
+ to: '←'
2089
+ },
2090
+ arrowRight: {
2091
+ from: '->',
2092
+ to: '→'
2093
+ },
2094
+ // Typography:
2095
+ horizontalEllipsis: {
2096
+ from: '...',
2097
+ to: '…'
2098
+ },
2099
+ enDash: {
2100
+ from: /(^| )(--)( )$/,
2101
+ to: [
2102
+ null,
2103
+ '–',
2104
+ null
2105
+ ]
2106
+ },
2107
+ emDash: {
2108
+ from: /(^| )(---)( )$/,
2109
+ to: [
2110
+ null,
2111
+ '—',
2112
+ null
2113
+ ]
2114
+ },
2115
+ // Quotations:
2116
+ // English, US
2117
+ quotesPrimary: {
2118
+ from: buildQuotesRegExp('"'),
2119
+ to: [
2120
+ null,
2121
+ '“',
2122
+ null,
2123
+ '”'
2124
+ ]
2125
+ },
2126
+ quotesSecondary: {
2127
+ from: buildQuotesRegExp('\''),
2128
+ to: [
2129
+ null,
2130
+ '‘',
2131
+ null,
2132
+ '’'
2133
+ ]
2134
+ },
2135
+ // English, UK
2136
+ quotesPrimaryEnGb: {
2137
+ from: buildQuotesRegExp('\''),
2138
+ to: [
2139
+ null,
2140
+ '‘',
2141
+ null,
2142
+ '’'
2143
+ ]
2144
+ },
2145
+ quotesSecondaryEnGb: {
2146
+ from: buildQuotesRegExp('"'),
2147
+ to: [
2148
+ null,
2149
+ '“',
2150
+ null,
2151
+ '”'
2152
+ ]
2153
+ },
2154
+ // Polish
2155
+ quotesPrimaryPl: {
2156
+ from: buildQuotesRegExp('"'),
2157
+ to: [
2158
+ null,
2159
+ '„',
2160
+ null,
2161
+ '”'
2162
+ ]
2163
+ },
2164
+ quotesSecondaryPl: {
2165
+ from: buildQuotesRegExp('\''),
2166
+ to: [
2167
+ null,
2168
+ '‚',
2169
+ null,
2170
+ '’'
2171
+ ]
2172
+ }
2173
+ };
2174
+ // Transformation groups.
2175
+ const TRANSFORMATION_GROUPS = {
2176
+ symbols: [
2177
+ 'copyright',
2178
+ 'registeredTrademark',
2179
+ 'trademark'
2180
+ ],
2181
+ mathematical: [
2182
+ 'oneHalf',
2183
+ 'oneThird',
2184
+ 'twoThirds',
2185
+ 'oneForth',
2186
+ 'threeQuarters',
2187
+ 'lessThanOrEqual',
2188
+ 'greaterThanOrEqual',
2189
+ 'notEqual',
2190
+ 'arrowLeft',
2191
+ 'arrowRight'
2192
+ ],
2193
+ typography: [
2194
+ 'horizontalEllipsis',
2195
+ 'enDash',
2196
+ 'emDash'
2197
+ ],
2198
+ quotes: [
2199
+ 'quotesPrimary',
2200
+ 'quotesSecondary'
2201
+ ]
2202
+ };
2203
+ // A set of default transformations provided by the feature.
2204
+ const DEFAULT_TRANSFORMATIONS = [
2205
+ 'symbols',
2206
+ 'mathematical',
2207
+ 'typography',
2208
+ 'quotes'
2209
+ ];
2210
+ /**
2211
+ * The text transformation plugin.
2212
+ */ class TextTransformation extends Plugin {
2213
+ /**
2214
+ * @inheritDoc
2215
+ */ static get requires() {
2216
+ return [
2217
+ 'Delete',
2218
+ 'Input'
2219
+ ];
2220
+ }
2221
+ /**
2222
+ * @inheritDoc
2223
+ */ static get pluginName() {
2224
+ return 'TextTransformation';
2225
+ }
2226
+ /**
2227
+ * @inheritDoc
2228
+ */ static get isOfficialPlugin() {
2229
+ return true;
2230
+ }
2231
+ /**
2232
+ * @inheritDoc
2233
+ */ constructor(editor){
2234
+ super(editor);
2235
+ editor.config.define('typing', {
2236
+ transformations: {
2237
+ include: DEFAULT_TRANSFORMATIONS
2238
+ }
2239
+ });
2240
+ }
2241
+ /**
2242
+ * @inheritDoc
2243
+ */ init() {
2244
+ const model = this.editor.model;
2245
+ const modelSelection = model.document.selection;
2246
+ modelSelection.on('change:range', ()=>{
2247
+ // Disable plugin when selection is inside a code block.
2248
+ this.isEnabled = !modelSelection.anchor.parent.is('element', 'codeBlock');
2249
+ });
2250
+ this._enableTransformationWatchers();
2251
+ }
2252
+ /**
2253
+ * Create new TextWatcher listening to the editor for typing and selection events.
2254
+ */ _enableTransformationWatchers() {
2255
+ const editor = this.editor;
2256
+ const model = editor.model;
2257
+ const deletePlugin = editor.plugins.get('Delete');
2258
+ const normalizedTransformations = normalizeTransformations(editor.config.get('typing.transformations'));
2259
+ const testCallback = (text)=>{
2260
+ for (const normalizedTransformation of normalizedTransformations){
2261
+ const from = normalizedTransformation.from;
2262
+ const match = from.test(text);
2263
+ if (match) {
2264
+ return {
2265
+ normalizedTransformation
2266
+ };
2267
+ }
2268
+ }
2269
+ };
2270
+ const watcher = new TextWatcher(editor.model, testCallback);
2271
+ watcher.on('matched:data', (evt, data)=>{
2272
+ if (!data.batch.isTyping) {
2273
+ return;
2274
+ }
2275
+ const { from, to } = data.normalizedTransformation;
2276
+ const matches = from.exec(data.text);
2277
+ const replaces = to(matches.slice(1));
2278
+ const matchedRange = data.range;
2279
+ let changeIndex = matches.index;
2280
+ model.enqueueChange((writer)=>{
2281
+ for(let i = 1; i < matches.length; i++){
2282
+ const match = matches[i];
2283
+ const replaceWith = replaces[i - 1];
2284
+ if (replaceWith == null) {
2285
+ changeIndex += match.length;
2286
+ continue;
2287
+ }
2288
+ const replacePosition = matchedRange.start.getShiftedBy(changeIndex);
2289
+ const replaceRange = model.createRange(replacePosition, replacePosition.getShiftedBy(match.length));
2290
+ const attributes = getTextAttributesAfterPosition(replacePosition);
2291
+ model.insertContent(writer.createText(replaceWith, attributes), replaceRange);
2292
+ changeIndex += replaceWith.length;
2293
+ }
2294
+ model.enqueueChange(()=>{
2295
+ deletePlugin.requestUndoOnBackspace();
2296
+ });
2297
+ });
2298
+ });
2299
+ watcher.bind('isEnabled').to(this);
2300
+ }
2301
+ }
2302
+ /**
2303
+ * Normalizes the configuration `from` parameter value.
2304
+ * The normalized value for the `from` parameter is a RegExp instance. If the passed `from` is already a RegExp instance,
2305
+ * it is returned unchanged.
2306
+ */ function normalizeFrom(from) {
2307
+ if (typeof from == 'string') {
2308
+ return new RegExp(`(${escapeRegExp(from)})$`);
2309
+ }
2310
+ // `from` is already a regular expression.
2311
+ return from;
2312
+ }
2313
+ /**
2314
+ * Normalizes the configuration `to` parameter value.
2315
+ * The normalized value for the `to` parameter is a function that takes an array and returns an array. See more in the
2316
+ * configuration description. If the passed `to` is already a function, it is returned unchanged.
2317
+ */ function normalizeTo(to) {
2318
+ if (typeof to == 'string') {
2319
+ return ()=>[
2320
+ to
2321
+ ];
2322
+ } else if (to instanceof Array) {
2323
+ return ()=>to;
2324
+ }
2325
+ // `to` is already a function.
2326
+ return to;
2327
+ }
2328
+ /**
2329
+ * For given `position` returns attributes for the text that is after that position.
2330
+ * The text can be in the same text node as the position (`foo[]bar`) or in the next text node (`foo[]<$text bold="true">bar</$text>`).
2331
+ */ function getTextAttributesAfterPosition(position) {
2332
+ const textNode = position.textNode ? position.textNode : position.nodeAfter;
2333
+ return textNode.getAttributes();
2334
+ }
2335
+ /**
2336
+ * Returns a RegExp pattern string that detects a sentence inside a quote.
2337
+ *
2338
+ * @param quoteCharacter The character to create a pattern for.
2339
+ */ function buildQuotesRegExp(quoteCharacter) {
2340
+ return new RegExp(`(^|\\s)(${quoteCharacter})([^${quoteCharacter}]*)(${quoteCharacter})$`);
2341
+ }
2342
+ /**
2343
+ * Reads text transformation config and returns normalized array of transformations objects.
2344
+ */ function normalizeTransformations(config) {
2345
+ const extra = config.extra || [];
2346
+ const remove = config.remove || [];
2347
+ const isNotRemoved = (transformation)=>!remove.includes(transformation);
2348
+ const configured = config.include.concat(extra).filter(isNotRemoved);
2349
+ return expandGroupsAndRemoveDuplicates(configured).filter(isNotRemoved) // Filter out 'remove' transformations as they might be set in group.
2350
+ .map((transformation)=>typeof transformation == 'string' && TRANSFORMATIONS[transformation] ? TRANSFORMATIONS[transformation] : transformation)// Filter out transformations set as string that has not been found.
2351
+ .filter((transformation)=>typeof transformation === 'object').map((transformation)=>({
2352
+ from: normalizeFrom(transformation.from),
2353
+ to: normalizeTo(transformation.to)
2354
+ }));
2355
+ }
2356
+ /**
2357
+ * Reads definitions and expands named groups if needed to transformation names.
2358
+ * This method also removes duplicated named transformations if any.
2359
+ */ function expandGroupsAndRemoveDuplicates(definitions) {
2360
+ // Set is using to make sure that transformation names are not duplicated.
2361
+ const definedTransformations = new Set();
2362
+ for (const transformationOrGroup of definitions){
2363
+ if (typeof transformationOrGroup == 'string' && TRANSFORMATION_GROUPS[transformationOrGroup]) {
2364
+ for (const transformation of TRANSFORMATION_GROUPS[transformationOrGroup]){
2365
+ definedTransformations.add(transformation);
2366
+ }
2367
+ } else {
2368
+ definedTransformations.add(transformationOrGroup);
2369
+ }
2370
+ }
2371
+ return Array.from(definedTransformations);
2372
+ }
2373
+
2374
+ /**
2375
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
2376
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
2377
+ */ /**
2378
+ * @module typing/utils/findattributerange
2379
+ */ /**
2380
+ * Returns a model range that covers all consecutive nodes with the same `attributeName` and its `value`
2381
+ * that intersect the given `position`.
2382
+ *
2383
+ * It can be used e.g. to get the entire range on which the `linkHref` attribute needs to be changed when having a
2384
+ * selection inside a link.
2385
+ *
2386
+ * @param position The start position.
2387
+ * @param attributeName The attribute name.
2388
+ * @param value The attribute value.
2389
+ * @param model The model instance.
2390
+ * @returns The link range.
2391
+ */ function findAttributeRange(position, attributeName, value, model) {
2392
+ return model.createRange(findAttributeRangeBound(position, attributeName, value, true, model), findAttributeRangeBound(position, attributeName, value, false, model));
2393
+ }
2394
+ /**
2395
+ * Walks forward or backward (depends on the `lookBack` flag), node by node, as long as they have the same attribute value
2396
+ * and returns a position just before or after (depends on the `lookBack` flag) the last matched node.
2397
+ *
2398
+ * @param position The start position.
2399
+ * @param attributeName The attribute name.
2400
+ * @param value The attribute value.
2401
+ * @param lookBack Whether the walk direction is forward (`false`) or backward (`true`).
2402
+ * @returns The position just before the last matched node.
2403
+ */ function findAttributeRangeBound(position, attributeName, value, lookBack, model) {
2404
+ // Get node before or after position (depends on `lookBack` flag).
2405
+ // When position is inside text node then start searching from text node.
2406
+ let node = position.textNode || (lookBack ? position.nodeBefore : position.nodeAfter);
2407
+ let lastNode = null;
2408
+ while(node && node.getAttribute(attributeName) == value){
2409
+ lastNode = node;
2410
+ node = lookBack ? node.previousSibling : node.nextSibling;
2411
+ }
2412
+ return lastNode ? model.createPositionAt(lastNode, lookBack ? 'before' : 'after') : position;
2413
+ }
2414
+
2415
+ /**
2416
+ * Adds a visual highlight style to an attribute element in which the selection is anchored.
2417
+ * Together with two-step caret movement, they indicate that the user is typing inside the element.
2418
+ *
2419
+ * Highlight is turned on by adding the given class to the attribute element in the view:
2420
+ *
2421
+ * * The class is removed before the conversion has started, as callbacks added with the `'highest'` priority
2422
+ * to {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher} events.
2423
+ * * The class is added in the view post fixer, after other changes in the model tree were converted to the view.
2424
+ *
2425
+ * This way, adding and removing the highlight does not interfere with conversion.
2426
+ *
2427
+ * Usage:
2428
+ *
2429
+ * ```ts
2430
+ * import inlineHighlight from '@ckeditor/ckeditor5-typing/src/utils/inlinehighlight';
2431
+ *
2432
+ * // Make `ck-link_selected` class be applied on an `a` element
2433
+ * // whenever the corresponding `linkHref` attribute element is selected.
2434
+ * inlineHighlight( editor, 'linkHref', 'a', 'ck-link_selected' );
2435
+ * ```
2436
+ *
2437
+ * @param editor The editor instance.
2438
+ * @param attributeName The attribute name to check.
2439
+ * @param tagName The tagName of a view item.
2440
+ * @param className The class name to apply in the view.
2441
+ */ function inlineHighlight(editor, attributeName, tagName, className) {
2442
+ const view = editor.editing.view;
2443
+ const highlightedElements = new Set();
2444
+ // Adding the class.
2445
+ view.document.registerPostFixer((writer)=>{
2446
+ const selection = editor.model.document.selection;
2447
+ let changed = false;
2448
+ if (selection.hasAttribute(attributeName)) {
2449
+ const modelRange = findAttributeRange(selection.getFirstPosition(), attributeName, selection.getAttribute(attributeName), editor.model);
2450
+ const viewRange = editor.editing.mapper.toViewRange(modelRange);
2451
+ // There might be multiple view elements in the `viewRange`, for example, when the `a` element is
2452
+ // broken by a UIElement.
2453
+ for (const item of viewRange.getItems()){
2454
+ if (item.is('element', tagName) && !item.hasClass(className)) {
2455
+ writer.addClass(className, item);
2456
+ highlightedElements.add(item);
2457
+ changed = true;
2458
+ }
2459
+ }
2460
+ }
2461
+ return changed;
2462
+ });
2463
+ // Removing the class.
2464
+ editor.conversion.for('editingDowncast').add((dispatcher)=>{
2465
+ // Make sure the highlight is removed on every possible event, before conversion is started.
2466
+ dispatcher.on('insert', removeHighlight, {
2467
+ priority: 'highest'
2468
+ });
2469
+ dispatcher.on('remove', removeHighlight, {
2470
+ priority: 'highest'
2471
+ });
2472
+ dispatcher.on('attribute', removeHighlight, {
2473
+ priority: 'highest'
2474
+ });
2475
+ dispatcher.on('selection', removeHighlight, {
2476
+ priority: 'highest'
2477
+ });
2478
+ function removeHighlight() {
2479
+ view.change((writer)=>{
2480
+ for (const item of highlightedElements.values()){
2481
+ writer.removeClass(className, item);
2482
+ highlightedElements.delete(item);
2483
+ }
2484
+ });
2485
+ }
2486
+ });
2487
+ }
2488
+
2489
+ export { Delete, Input, InsertTextCommand, TextTransformation, TextWatcher, TwoStepCaretMovement, Typing, findAttributeRange, findAttributeRangeBound, getLastTextLine, inlineHighlight };
2490
+ //# sourceMappingURL=index.js.map