@ckeditor/ckeditor5-typing 0.0.0-internal-20241017.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/LICENSE.md +21 -0
  3. package/README.md +22 -0
  4. package/ckeditor5-metadata.json +11 -0
  5. package/dist/augmentation.d.ts +31 -0
  6. package/dist/delete.d.ts +40 -0
  7. package/dist/deletecommand.d.ts +87 -0
  8. package/dist/deleteobserver.d.ts +59 -0
  9. package/dist/index-content.css +4 -0
  10. package/dist/index-editor.css +4 -0
  11. package/dist/index.css +4 -0
  12. package/dist/index.d.ts +29 -0
  13. package/dist/index.js +2490 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/input.d.ts +37 -0
  16. package/dist/inserttextcommand.d.ts +80 -0
  17. package/dist/inserttextobserver.d.ts +59 -0
  18. package/dist/texttransformation.d.ts +41 -0
  19. package/dist/textwatcher.d.ts +142 -0
  20. package/dist/twostepcaretmovement.d.ts +240 -0
  21. package/dist/typing.d.ts +31 -0
  22. package/dist/typingconfig.d.ts +208 -0
  23. package/dist/utils/changebuffer.d.ts +107 -0
  24. package/dist/utils/findattributerange.d.ts +37 -0
  25. package/dist/utils/getlasttextline.d.ts +53 -0
  26. package/dist/utils/inlinehighlight.d.ts +37 -0
  27. package/package.json +40 -0
  28. package/src/augmentation.d.ts +27 -0
  29. package/src/augmentation.js +5 -0
  30. package/src/delete.d.ts +36 -0
  31. package/src/delete.js +88 -0
  32. package/src/deletecommand.d.ts +83 -0
  33. package/src/deletecommand.js +201 -0
  34. package/src/deleteobserver.d.ts +55 -0
  35. package/src/deleteobserver.js +260 -0
  36. package/src/index.d.ts +25 -0
  37. package/src/index.js +18 -0
  38. package/src/input.d.ts +33 -0
  39. package/src/input.js +422 -0
  40. package/src/inserttextcommand.d.ts +76 -0
  41. package/src/inserttextcommand.js +83 -0
  42. package/src/inserttextobserver.d.ts +55 -0
  43. package/src/inserttextobserver.js +102 -0
  44. package/src/texttransformation.d.ts +37 -0
  45. package/src/texttransformation.js +234 -0
  46. package/src/textwatcher.d.ts +138 -0
  47. package/src/textwatcher.js +105 -0
  48. package/src/twostepcaretmovement.d.ts +236 -0
  49. package/src/twostepcaretmovement.js +628 -0
  50. package/src/typing.d.ts +27 -0
  51. package/src/typing.js +33 -0
  52. package/src/typingconfig.d.ts +204 -0
  53. package/src/typingconfig.js +5 -0
  54. package/src/utils/changebuffer.d.ts +103 -0
  55. package/src/utils/changebuffer.js +123 -0
  56. package/src/utils/findattributerange.d.ts +33 -0
  57. package/src/utils/findattributerange.js +41 -0
  58. package/src/utils/getlasttextline.d.ts +49 -0
  59. package/src/utils/getlasttextline.js +43 -0
  60. package/src/utils/inlinehighlight.d.ts +33 -0
  61. package/src/utils/inlinehighlight.js +74 -0
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing/deletecommand
7
+ */
8
+ import { Command, type Editor } from '@ckeditor/ckeditor5-core';
9
+ import type { DocumentSelection, Selection } from '@ckeditor/ckeditor5-engine';
10
+ import ChangeBuffer from './utils/changebuffer.js';
11
+ /**
12
+ * The delete command. Used by the {@link module:typing/delete~Delete delete feature} to handle the <kbd>Delete</kbd> and
13
+ * <kbd>Backspace</kbd> keys.
14
+ */
15
+ export default class DeleteCommand extends Command {
16
+ /**
17
+ * The directionality of the delete describing in what direction it should
18
+ * consume the content when the selection is collapsed.
19
+ */
20
+ readonly direction: 'forward' | 'backward';
21
+ /**
22
+ * Delete's change buffer used to group subsequent changes into batches.
23
+ */
24
+ private readonly _buffer;
25
+ /**
26
+ * Creates an instance of the command.
27
+ *
28
+ * @param direction The directionality of the delete describing in what direction it
29
+ * should consume the content when the selection is collapsed.
30
+ */
31
+ constructor(editor: Editor, direction: 'forward' | 'backward');
32
+ /**
33
+ * The current change buffer.
34
+ */
35
+ get buffer(): ChangeBuffer;
36
+ /**
37
+ * Executes the delete command. Depending on whether the selection is collapsed or not, deletes its content
38
+ * or a piece of content in the {@link #direction defined direction}.
39
+ *
40
+ * @fires execute
41
+ * @param options The command options.
42
+ * @param options.unit See {@link module:engine/model/utils/modifyselection~modifySelection}'s options.
43
+ * @param options.sequence A number describing which subsequent delete event it is without the key being released.
44
+ * See the {@link module:engine/view/document~Document#event:delete} event data.
45
+ * @param options.selection Selection to remove. If not set, current model selection will be used.
46
+ */
47
+ execute(options?: {
48
+ unit?: 'character' | 'codePoint' | 'word';
49
+ sequence?: number;
50
+ selection?: Selection | DocumentSelection;
51
+ }): void;
52
+ /**
53
+ * If the user keeps <kbd>Backspace</kbd> or <kbd>Delete</kbd> key pressed, the content of the current
54
+ * editable will be cleared. However, this will not yet lead to resetting the remaining block to a paragraph
55
+ * (which happens e.g. when the user does <kbd>Ctrl</kbd> + <kbd>A</kbd>, <kbd>Backspace</kbd>).
56
+ *
57
+ * But, if the user pressed the key in an empty editable for the first time,
58
+ * we want to replace the entire content with a paragraph if:
59
+ *
60
+ * * the current limit element is empty,
61
+ * * the paragraph is allowed in the limit element,
62
+ * * the limit doesn't already have a paragraph inside.
63
+ *
64
+ * See https://github.com/ckeditor/ckeditor5-typing/issues/61.
65
+ *
66
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
67
+ */
68
+ private _shouldEntireContentBeReplacedWithParagraph;
69
+ /**
70
+ * The entire content is replaced with the paragraph. Selection is moved inside the paragraph.
71
+ *
72
+ * @param writer The model writer.
73
+ */
74
+ private _replaceEntireContentWithParagraph;
75
+ /**
76
+ * Checks if the selection is inside an empty element that is the first child of the limit element
77
+ * and should be replaced with a paragraph.
78
+ *
79
+ * @param selection The selection.
80
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
81
+ */
82
+ private _shouldReplaceFirstBlockWithParagraph;
83
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing/deletecommand
7
+ */
8
+ import { Command } from '@ckeditor/ckeditor5-core';
9
+ import { count } from '@ckeditor/ckeditor5-utils';
10
+ import ChangeBuffer from './utils/changebuffer.js';
11
+ /**
12
+ * The delete command. Used by the {@link module:typing/delete~Delete delete feature} to handle the <kbd>Delete</kbd> and
13
+ * <kbd>Backspace</kbd> keys.
14
+ */
15
+ export default class DeleteCommand extends Command {
16
+ /**
17
+ * Creates an instance of the command.
18
+ *
19
+ * @param direction The directionality of the delete describing in what direction it
20
+ * should consume the content when the selection is collapsed.
21
+ */
22
+ constructor(editor, direction) {
23
+ super(editor);
24
+ this.direction = direction;
25
+ this._buffer = new ChangeBuffer(editor.model, editor.config.get('typing.undoStep'));
26
+ // Since this command may execute on different selectable than selection, it should be checked directly in execute block.
27
+ this._isEnabledBasedOnSelection = false;
28
+ }
29
+ /**
30
+ * The current change buffer.
31
+ */
32
+ get buffer() {
33
+ return this._buffer;
34
+ }
35
+ /**
36
+ * Executes the delete command. Depending on whether the selection is collapsed or not, deletes its content
37
+ * or a piece of content in the {@link #direction defined direction}.
38
+ *
39
+ * @fires execute
40
+ * @param options The command options.
41
+ * @param options.unit See {@link module:engine/model/utils/modifyselection~modifySelection}'s options.
42
+ * @param options.sequence A number describing which subsequent delete event it is without the key being released.
43
+ * See the {@link module:engine/view/document~Document#event:delete} event data.
44
+ * @param options.selection Selection to remove. If not set, current model selection will be used.
45
+ */
46
+ execute(options = {}) {
47
+ const model = this.editor.model;
48
+ const doc = model.document;
49
+ model.enqueueChange(this._buffer.batch, writer => {
50
+ this._buffer.lock();
51
+ const selection = writer.createSelection(options.selection || doc.selection);
52
+ // Don't execute command when selection is in non-editable place.
53
+ if (!model.canEditAt(selection)) {
54
+ return;
55
+ }
56
+ const sequence = options.sequence || 1;
57
+ // Do not replace the whole selected content if selection was collapsed.
58
+ // This prevents such situation:
59
+ //
60
+ // <h1></h1><p>[]</p> --> <h1>[</h1><p>]</p> --> <p></p>
61
+ // starting content --> after `modifySelection` --> after `deleteContent`.
62
+ const doNotResetEntireContent = selection.isCollapsed;
63
+ // Try to extend the selection in the specified direction.
64
+ if (selection.isCollapsed) {
65
+ model.modifySelection(selection, {
66
+ direction: this.direction,
67
+ unit: options.unit,
68
+ treatEmojiAsSingleUnit: true
69
+ });
70
+ }
71
+ // Check if deleting in an empty editor. See #61.
72
+ if (this._shouldEntireContentBeReplacedWithParagraph(sequence)) {
73
+ this._replaceEntireContentWithParagraph(writer);
74
+ return;
75
+ }
76
+ // Check if deleting in the first empty block.
77
+ // See https://github.com/ckeditor/ckeditor5/issues/8137.
78
+ if (this._shouldReplaceFirstBlockWithParagraph(selection, sequence)) {
79
+ this.editor.execute('paragraph', { selection });
80
+ return;
81
+ }
82
+ // If selection is still collapsed, then there's nothing to delete.
83
+ if (selection.isCollapsed) {
84
+ return;
85
+ }
86
+ let changeCount = 0;
87
+ selection.getFirstRange().getMinimalFlatRanges().forEach(range => {
88
+ changeCount += count(range.getWalker({ singleCharacters: true, ignoreElementEnd: true, shallow: true }));
89
+ });
90
+ // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) {
91
+ // @if CK_DEBUG_TYPING // console.log( '%c[DeleteCommand]%c Delete content',
92
+ // @if CK_DEBUG_TYPING // 'font-weight: bold; color: green;', '',
93
+ // @if CK_DEBUG_TYPING // `[${ selection.getFirstPosition()!.path }]-[${ selection.getLastPosition()!.path }]`, options
94
+ // @if CK_DEBUG_TYPING // );
95
+ // @if CK_DEBUG_TYPING // }
96
+ model.deleteContent(selection, {
97
+ doNotResetEntireContent,
98
+ direction: this.direction
99
+ });
100
+ this._buffer.input(changeCount);
101
+ writer.setSelection(selection);
102
+ this._buffer.unlock();
103
+ });
104
+ }
105
+ /**
106
+ * If the user keeps <kbd>Backspace</kbd> or <kbd>Delete</kbd> key pressed, the content of the current
107
+ * editable will be cleared. However, this will not yet lead to resetting the remaining block to a paragraph
108
+ * (which happens e.g. when the user does <kbd>Ctrl</kbd> + <kbd>A</kbd>, <kbd>Backspace</kbd>).
109
+ *
110
+ * But, if the user pressed the key in an empty editable for the first time,
111
+ * we want to replace the entire content with a paragraph if:
112
+ *
113
+ * * the current limit element is empty,
114
+ * * the paragraph is allowed in the limit element,
115
+ * * the limit doesn't already have a paragraph inside.
116
+ *
117
+ * See https://github.com/ckeditor/ckeditor5-typing/issues/61.
118
+ *
119
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
120
+ */
121
+ _shouldEntireContentBeReplacedWithParagraph(sequence) {
122
+ // Does nothing if user pressed and held the "Backspace" or "Delete" key.
123
+ if (sequence > 1) {
124
+ return false;
125
+ }
126
+ const model = this.editor.model;
127
+ const doc = model.document;
128
+ const selection = doc.selection;
129
+ const limitElement = model.schema.getLimitElement(selection);
130
+ // If a collapsed selection contains the whole content it means that the content is empty
131
+ // (from the user perspective).
132
+ const limitElementIsEmpty = selection.isCollapsed && selection.containsEntireContent(limitElement);
133
+ if (!limitElementIsEmpty) {
134
+ return false;
135
+ }
136
+ if (!model.schema.checkChild(limitElement, 'paragraph')) {
137
+ return false;
138
+ }
139
+ const limitElementFirstChild = limitElement.getChild(0);
140
+ // Does nothing if the limit element already contains only a paragraph.
141
+ // We ignore the case when paragraph might have some inline elements (<p><inlineWidget>[]</inlineWidget></p>)
142
+ // because we don't support such cases yet and it's unclear whether inlineWidget shouldn't be a limit itself.
143
+ if (limitElementFirstChild && limitElementFirstChild.is('element', 'paragraph')) {
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ /**
149
+ * The entire content is replaced with the paragraph. Selection is moved inside the paragraph.
150
+ *
151
+ * @param writer The model writer.
152
+ */
153
+ _replaceEntireContentWithParagraph(writer) {
154
+ const model = this.editor.model;
155
+ const doc = model.document;
156
+ const selection = doc.selection;
157
+ const limitElement = model.schema.getLimitElement(selection);
158
+ const paragraph = writer.createElement('paragraph');
159
+ writer.remove(writer.createRangeIn(limitElement));
160
+ writer.insert(paragraph, limitElement);
161
+ writer.setSelection(paragraph, 0);
162
+ }
163
+ /**
164
+ * Checks if the selection is inside an empty element that is the first child of the limit element
165
+ * and should be replaced with a paragraph.
166
+ *
167
+ * @param selection The selection.
168
+ * @param sequence A number describing which subsequent delete event it is without the key being released.
169
+ */
170
+ _shouldReplaceFirstBlockWithParagraph(selection, sequence) {
171
+ const model = this.editor.model;
172
+ // Does nothing if user pressed and held the "Backspace" key or it was a "Delete" button.
173
+ if (sequence > 1 || this.direction != 'backward') {
174
+ return false;
175
+ }
176
+ if (!selection.isCollapsed) {
177
+ return false;
178
+ }
179
+ const position = selection.getFirstPosition();
180
+ const limitElement = model.schema.getLimitElement(position);
181
+ const limitElementFirstChild = limitElement.getChild(0);
182
+ // Only elements that are direct children of the limit element can be replaced.
183
+ // Unwrapping from a block quote should be handled in a dedicated feature.
184
+ if (position.parent != limitElementFirstChild) {
185
+ return false;
186
+ }
187
+ // A block should be replaced only if it was empty.
188
+ if (!selection.containsEntireContent(limitElementFirstChild)) {
189
+ return false;
190
+ }
191
+ // Replace with a paragraph only if it's allowed there.
192
+ if (!model.schema.checkChild(limitElement, 'paragraph')) {
193
+ return false;
194
+ }
195
+ // Does nothing if the limit element already contains only a paragraph.
196
+ if (limitElementFirstChild.name == 'paragraph') {
197
+ return false;
198
+ }
199
+ return true;
200
+ }
201
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ import { DomEventData, Observer, type BubblingEvent, type ViewDocumentSelection, type ViewSelection, type EditingView } from '@ckeditor/ckeditor5-engine';
6
+ /**
7
+ * Delete observer introduces the {@link module:engine/view/document~Document#event:delete} event.
8
+ */
9
+ export default class DeleteObserver extends Observer {
10
+ /**
11
+ * @inheritDoc
12
+ */
13
+ constructor(view: EditingView);
14
+ /**
15
+ * @inheritDoc
16
+ */
17
+ observe(): void;
18
+ /**
19
+ * @inheritDoc
20
+ */
21
+ stopObserving(): void;
22
+ }
23
+ /**
24
+ * Event fired when the user tries to delete content (e.g. presses <kbd>Delete</kbd> or <kbd>Backspace</kbd>).
25
+ *
26
+ * Note: This event is fired by the {@link module:typing/deleteobserver~DeleteObserver delete observer}
27
+ * (usually registered by the {@link module:typing/delete~Delete delete feature}).
28
+ *
29
+ * @eventName module:engine/view/document~Document#delete
30
+ * @param data The event data.
31
+ */
32
+ export type ViewDocumentDeleteEvent = BubblingEvent<{
33
+ name: 'delete';
34
+ args: [data: DeleteEventData];
35
+ }>;
36
+ export interface DeleteEventData extends DomEventData<InputEvent> {
37
+ /**
38
+ * The direction in which the deletion should happen.
39
+ */
40
+ direction: 'backward' | 'forward';
41
+ /**
42
+ * The "amount" of content that should be deleted.
43
+ */
44
+ unit: 'selection' | 'codePoint' | 'character' | 'word';
45
+ /**
46
+ * A number describing which subsequent delete event it is without the key being released.
47
+ * If it's 2 or more it means that the key was pressed and hold.
48
+ */
49
+ sequence: number;
50
+ /**
51
+ * View selection which content should be removed. If not set,
52
+ * current selection should be used.
53
+ */
54
+ selectionToRemove?: ViewSelection | ViewDocumentSelection;
55
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing/deleteobserver
7
+ */
8
+ import { env, keyCodes, isInsideCombinedSymbol, isInsideEmojiSequence, isInsideSurrogatePair } from '@ckeditor/ckeditor5-utils';
9
+ import { BubblingEventInfo, DomEventData, Observer } from '@ckeditor/ckeditor5-engine';
10
+ const DELETE_CHARACTER = 'character';
11
+ const DELETE_WORD = 'word';
12
+ const DELETE_CODE_POINT = 'codePoint';
13
+ const DELETE_SELECTION = 'selection';
14
+ const DELETE_BACKWARD = 'backward';
15
+ const DELETE_FORWARD = 'forward';
16
+ const DELETE_EVENT_TYPES = {
17
+ // --------------------------------------- Backward delete types -----------------------------------------------------
18
+ // This happens in Safari on Mac when some content is selected and Ctrl + K is pressed.
19
+ deleteContent: {
20
+ unit: DELETE_SELECTION,
21
+ // According to the Input Events Level 2 spec, this delete type has no direction
22
+ // but to keep things simple, let's default to backward.
23
+ direction: DELETE_BACKWARD
24
+ },
25
+ // Chrome and Safari on Mac: Backspace or Ctrl + H
26
+ deleteContentBackward: {
27
+ // This kind of deletions must be done on the code point-level instead of target range provided by the DOM beforeinput event.
28
+ // Take for instance "👨‍👩‍👧‍👧", it equals:
29
+ //
30
+ // * [ "👨", "ZERO WIDTH JOINER", "👩", "ZERO WIDTH JOINER", "👧", "ZERO WIDTH JOINER", "👧" ]
31
+ // * or simply "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F467}"
32
+ //
33
+ // The range provided by the browser would cause the entire multi-byte grapheme to disappear while the user
34
+ // intention when deleting backwards ("👨‍👩‍👧‍👧[]", then backspace) is gradual "decomposition" (first to "👨‍👩‍👧‍[]",
35
+ // then to "👨‍👩‍[]", etc.).
36
+ //
37
+ // * "👨‍👩‍👧‍👧[]" + backward delete (by code point) -> results in "👨‍👩‍👧[]", removed the last "👧" 👍
38
+ // * "👨‍👩‍👧‍👧[]" + backward delete (by character) -> results in "[]", removed the whole grapheme 👎
39
+ //
40
+ // Deleting by code-point is simply a better UX. See "deleteContentForward" to learn more.
41
+ unit: DELETE_CODE_POINT,
42
+ direction: DELETE_BACKWARD
43
+ },
44
+ // On Mac: Option + Backspace.
45
+ // On iOS: Hold the backspace for a while and the whole words will start to disappear.
46
+ deleteWordBackward: {
47
+ unit: DELETE_WORD,
48
+ direction: DELETE_BACKWARD
49
+ },
50
+ // Safari on Mac: Cmd + Backspace
51
+ deleteHardLineBackward: {
52
+ unit: DELETE_SELECTION,
53
+ direction: DELETE_BACKWARD
54
+ },
55
+ // Chrome on Mac: Cmd + Backspace.
56
+ deleteSoftLineBackward: {
57
+ unit: DELETE_SELECTION,
58
+ direction: DELETE_BACKWARD
59
+ },
60
+ // --------------------------------------- Forward delete types -----------------------------------------------------
61
+ // Chrome on Mac: Fn + Backspace or Ctrl + D
62
+ // Safari on Mac: Ctrl + K or Ctrl + D
63
+ deleteContentForward: {
64
+ // Unlike backward delete, this delete must be performed by character instead of by code point, which
65
+ // provides the best UX for working with accented letters.
66
+ // Take, for example "b̂" ("\u0062\u0302", or [ "LATIN SMALL LETTER B", "COMBINING CIRCUMFLEX ACCENT" ]):
67
+ //
68
+ // * "b̂[]" + backward delete (by code point) -> results in "b[]", removed the combining mark 👍
69
+ // * "[]b̂" + forward delete (by code point) -> results in "[]^", a bare combining mark does that not make sense when alone 👎
70
+ // * "[]b̂" + forward delete (by character) -> results in "[]", removed both "b" and the combining mark 👍
71
+ //
72
+ // See: "deleteContentBackward" to learn more.
73
+ unit: DELETE_CHARACTER,
74
+ direction: DELETE_FORWARD
75
+ },
76
+ // On Mac: Fn + Option + Backspace.
77
+ deleteWordForward: {
78
+ unit: DELETE_WORD,
79
+ direction: DELETE_FORWARD
80
+ },
81
+ // Chrome on Mac: Ctrl + K (you have to disable the Link plugin first, though, because it uses the same keystroke)
82
+ // This is weird that it does not work in Safari on Mac despite being listed in the official shortcuts listing
83
+ // on Apple's webpage.
84
+ deleteHardLineForward: {
85
+ unit: DELETE_SELECTION,
86
+ direction: DELETE_FORWARD
87
+ },
88
+ // At this moment there is no known way to trigger this event type but let's keep it for the symmetry with
89
+ // deleteSoftLineBackward.
90
+ deleteSoftLineForward: {
91
+ unit: DELETE_SELECTION,
92
+ direction: DELETE_FORWARD
93
+ }
94
+ };
95
+ /**
96
+ * Delete observer introduces the {@link module:engine/view/document~Document#event:delete} event.
97
+ */
98
+ export default class DeleteObserver extends Observer {
99
+ /**
100
+ * @inheritDoc
101
+ */
102
+ constructor(view) {
103
+ super(view);
104
+ const document = view.document;
105
+ // It matters how many subsequent deletions were made, e.g. when the backspace key was pressed and held
106
+ // by the user for some time. For instance, if such scenario ocurred and the heading the selection was
107
+ // anchored to was the only content of the editor, it will not be converted into a paragraph (the user
108
+ // wanted to clean it up, not remove it, it's about UX). Check out the DeleteCommand implementation to learn more.
109
+ //
110
+ // Fun fact: Safari on Mac won't fire beforeinput for backspace in an empty heading (only content).
111
+ let sequence = 0;
112
+ document.on('keydown', () => {
113
+ sequence++;
114
+ });
115
+ document.on('keyup', () => {
116
+ sequence = 0;
117
+ });
118
+ document.on('beforeinput', (evt, data) => {
119
+ if (!this.isEnabled) {
120
+ return;
121
+ }
122
+ const { targetRanges, domEvent, inputType } = data;
123
+ const deleteEventSpec = DELETE_EVENT_TYPES[inputType];
124
+ if (!deleteEventSpec) {
125
+ return;
126
+ }
127
+ const deleteData = {
128
+ direction: deleteEventSpec.direction,
129
+ unit: deleteEventSpec.unit,
130
+ sequence
131
+ };
132
+ if (deleteData.unit == DELETE_SELECTION) {
133
+ deleteData.selectionToRemove = view.createSelection(targetRanges[0]);
134
+ }
135
+ // The default deletion unit for deleteContentBackward is a single code point
136
+ // but if the browser provides a wider target range then we should use it.
137
+ if (inputType === 'deleteContentBackward') {
138
+ // On Android, deleteContentBackward has sequence 1 by default.
139
+ if (env.isAndroid) {
140
+ deleteData.sequence = 1;
141
+ }
142
+ // The beforeInput event wants more than a single character to be removed.
143
+ if (shouldUseTargetRanges(targetRanges)) {
144
+ deleteData.unit = DELETE_SELECTION;
145
+ deleteData.selectionToRemove = view.createSelection(targetRanges);
146
+ }
147
+ }
148
+ const eventInfo = new BubblingEventInfo(document, 'delete', targetRanges[0]);
149
+ document.fire(eventInfo, new DomEventData(view, domEvent, deleteData));
150
+ // Stop the beforeinput event if `delete` event was stopped.
151
+ // https://github.com/ckeditor/ckeditor5/issues/753
152
+ if (eventInfo.stop.called) {
153
+ evt.stop();
154
+ }
155
+ });
156
+ // TODO: to be removed when https://bugs.chromium.org/p/chromium/issues/detail?id=1365311 is solved.
157
+ if (env.isBlink) {
158
+ enableChromeWorkaround(this);
159
+ }
160
+ }
161
+ /**
162
+ * @inheritDoc
163
+ */
164
+ observe() { }
165
+ /**
166
+ * @inheritDoc
167
+ */
168
+ stopObserving() { }
169
+ }
170
+ /**
171
+ * Enables workaround for the issue https://github.com/ckeditor/ckeditor5/issues/11904.
172
+ */
173
+ function enableChromeWorkaround(observer) {
174
+ const view = observer.view;
175
+ const document = view.document;
176
+ let pressedKeyCode = null;
177
+ let beforeInputReceived = false;
178
+ document.on('keydown', (evt, { keyCode }) => {
179
+ pressedKeyCode = keyCode;
180
+ beforeInputReceived = false;
181
+ });
182
+ document.on('keyup', (evt, { keyCode, domEvent }) => {
183
+ const selection = document.selection;
184
+ const shouldFireDeleteEvent = observer.isEnabled &&
185
+ keyCode == pressedKeyCode &&
186
+ isDeleteKeyCode(keyCode) &&
187
+ !selection.isCollapsed &&
188
+ !beforeInputReceived;
189
+ pressedKeyCode = null;
190
+ if (shouldFireDeleteEvent) {
191
+ const targetRange = selection.getFirstRange();
192
+ const eventInfo = new BubblingEventInfo(document, 'delete', targetRange);
193
+ const deleteData = {
194
+ unit: DELETE_SELECTION,
195
+ direction: getDeleteDirection(keyCode),
196
+ selectionToRemove: selection
197
+ };
198
+ document.fire(eventInfo, new DomEventData(view, domEvent, deleteData));
199
+ }
200
+ });
201
+ document.on('beforeinput', (evt, { inputType }) => {
202
+ const deleteEventSpec = DELETE_EVENT_TYPES[inputType];
203
+ const isMatchingBeforeInput = isDeleteKeyCode(pressedKeyCode) &&
204
+ deleteEventSpec &&
205
+ deleteEventSpec.direction == getDeleteDirection(pressedKeyCode);
206
+ if (isMatchingBeforeInput) {
207
+ beforeInputReceived = true;
208
+ }
209
+ }, { priority: 'high' });
210
+ document.on('beforeinput', (evt, { inputType, data }) => {
211
+ const shouldIgnoreBeforeInput = pressedKeyCode == keyCodes.delete &&
212
+ inputType == 'insertText' &&
213
+ data == '\x7f'; // Delete character :P
214
+ if (shouldIgnoreBeforeInput) {
215
+ evt.stop();
216
+ }
217
+ }, { priority: 'high' });
218
+ function isDeleteKeyCode(keyCode) {
219
+ return keyCode == keyCodes.backspace || keyCode == keyCodes.delete;
220
+ }
221
+ function getDeleteDirection(keyCode) {
222
+ return keyCode == keyCodes.backspace ? DELETE_BACKWARD : DELETE_FORWARD;
223
+ }
224
+ }
225
+ /**
226
+ * Verifies whether the given target ranges cover more than a single character and should be used instead of a single code-point deletion.
227
+ */
228
+ function shouldUseTargetRanges(targetRanges) {
229
+ // The collapsed target range could happen for example while deleting inside an inline filler
230
+ // (it's mapped to collapsed position before an inline filler).
231
+ if (targetRanges.length != 1 || targetRanges[0].isCollapsed) {
232
+ return false;
233
+ }
234
+ const walker = targetRanges[0].getWalker({
235
+ direction: 'backward',
236
+ singleCharacters: true,
237
+ ignoreElementEnd: true
238
+ });
239
+ let count = 0;
240
+ for (const { nextPosition, item } of walker) {
241
+ if (nextPosition.parent.is('$text')) {
242
+ const data = nextPosition.parent.data;
243
+ const offset = nextPosition.offset;
244
+ // Count combined symbols and emoji sequences as a single character.
245
+ if (isInsideSurrogatePair(data, offset) ||
246
+ isInsideCombinedSymbol(data, offset) ||
247
+ isInsideEmojiSequence(data, offset)) {
248
+ continue;
249
+ }
250
+ count++;
251
+ }
252
+ else if (item.is('containerElement') || item.is('emptyElement')) {
253
+ count++;
254
+ }
255
+ if (count > 1) {
256
+ return true;
257
+ }
258
+ }
259
+ return false;
260
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing
7
+ */
8
+ export { default as Typing } from './typing.js';
9
+ export { default as Input } from './input.js';
10
+ export { default as Delete } from './delete.js';
11
+ export { default as TextWatcher } from './textwatcher.js';
12
+ export { default as TwoStepCaretMovement } from './twostepcaretmovement.js';
13
+ export { default as TextTransformation } from './texttransformation.js';
14
+ export type { TextTransformationConfig } from './typingconfig.js';
15
+ export { default as inlineHighlight } from './utils/inlinehighlight.js';
16
+ export { default as findAttributeRange, findAttributeRangeBound } from './utils/findattributerange.js';
17
+ export { default as getLastTextLine, type LastTextLineData } from './utils/getlasttextline.js';
18
+ export { default as InsertTextCommand, type InsertTextCommandExecuteEvent } from './inserttextcommand.js';
19
+ export type { default as DeleteCommand } from './deletecommand.js';
20
+ export type { TypingConfig } from './typingconfig.js';
21
+ export type { ViewDocumentDeleteEvent } from './deleteobserver.js';
22
+ export type { ViewDocumentInsertTextEvent, InsertTextEventData } from './inserttextobserver.js';
23
+ export type { TextWatcherMatchedEvent } from './textwatcher.js';
24
+ export type { TextWatcherMatchedDataEvent } from './textwatcher.js';
25
+ import './augmentation.js';
package/src/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing
7
+ */
8
+ export { default as Typing } from './typing.js';
9
+ export { default as Input } from './input.js';
10
+ export { default as Delete } from './delete.js';
11
+ export { default as TextWatcher } from './textwatcher.js';
12
+ export { default as TwoStepCaretMovement } from './twostepcaretmovement.js';
13
+ export { default as TextTransformation } from './texttransformation.js';
14
+ export { default as inlineHighlight } from './utils/inlinehighlight.js';
15
+ export { default as findAttributeRange, findAttributeRangeBound } from './utils/findattributerange.js';
16
+ export { default as getLastTextLine } from './utils/getlasttextline.js';
17
+ export { default as InsertTextCommand } from './inserttextcommand.js';
18
+ import './augmentation.js';
package/src/input.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module typing/input
7
+ */
8
+ import { Plugin } from '@ckeditor/ckeditor5-core';
9
+ /**
10
+ * Handles text input coming from the keyboard or other input methods.
11
+ */
12
+ export default class Input extends Plugin {
13
+ /**
14
+ * The queue of `insertText` command executions that are waiting for the DOM to get updated after beforeinput event.
15
+ */
16
+ private _compositionQueue;
17
+ /**
18
+ * @inheritDoc
19
+ */
20
+ static get pluginName(): "Input";
21
+ /**
22
+ * @inheritDoc
23
+ */
24
+ static get isOfficialPlugin(): true;
25
+ /**
26
+ * @inheritDoc
27
+ */
28
+ init(): void;
29
+ /**
30
+ * @inheritDoc
31
+ */
32
+ destroy(): void;
33
+ }