@ckeditor/ckeditor5-typing 48.2.0-alpha.7 → 48.3.0-alpha.0

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