@ckeditor/ckeditor5-clipboard 48.8.1-alpha.4 → 49.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/augmentation.d.ts +14 -14
  3. package/dist/clipboard.d.ts +35 -35
  4. package/dist/clipboardmarkersutils.d.ts +194 -194
  5. package/dist/clipboardobserver.d.ts +274 -269
  6. package/dist/clipboardpipeline.d.ts +252 -248
  7. package/dist/dragdrop.d.ts +100 -101
  8. package/dist/dragdropblocktoolbar.d.ts +46 -46
  9. package/dist/dragdroptarget.d.ts +95 -94
  10. package/dist/index-content.css +3 -0
  11. package/dist/index-content.css.map +1 -0
  12. package/dist/index-editor.css +68 -68
  13. package/dist/index-editor.css.map +1 -0
  14. package/dist/index.css +48 -50
  15. package/dist/index.css.map +1 -1
  16. package/dist/index.d.ts +23 -21
  17. package/dist/index.js +1713 -2184
  18. package/dist/index.js.map +1 -1
  19. package/dist/lineview.d.ts +42 -42
  20. package/dist/pasteplaintext.d.ts +27 -27
  21. package/dist/translations/af.js +1 -1
  22. package/dist/translations/af.umd.js +5 -3
  23. package/dist/translations/ar.js +1 -1
  24. package/dist/translations/ar.umd.js +5 -3
  25. package/dist/translations/ast.js +1 -1
  26. package/dist/translations/ast.umd.js +5 -3
  27. package/dist/translations/az.js +1 -1
  28. package/dist/translations/az.umd.js +5 -3
  29. package/dist/translations/be.js +1 -1
  30. package/dist/translations/be.umd.js +5 -3
  31. package/dist/translations/bg.js +1 -1
  32. package/dist/translations/bg.umd.js +5 -3
  33. package/dist/translations/bn.js +1 -1
  34. package/dist/translations/bn.umd.js +5 -3
  35. package/dist/translations/bs.js +1 -1
  36. package/dist/translations/bs.umd.js +5 -3
  37. package/dist/translations/ca.js +1 -1
  38. package/dist/translations/ca.umd.js +5 -3
  39. package/dist/translations/cs.js +1 -1
  40. package/dist/translations/cs.umd.js +5 -3
  41. package/dist/translations/da.js +1 -1
  42. package/dist/translations/da.umd.js +5 -3
  43. package/dist/translations/de-ch.js +1 -1
  44. package/dist/translations/de-ch.umd.js +5 -3
  45. package/dist/translations/de.js +1 -1
  46. package/dist/translations/de.umd.js +5 -3
  47. package/dist/translations/el.js +1 -1
  48. package/dist/translations/el.umd.js +5 -3
  49. package/dist/translations/en-au.js +1 -1
  50. package/dist/translations/en-au.umd.js +5 -3
  51. package/dist/translations/en-gb.js +1 -1
  52. package/dist/translations/en-gb.umd.js +5 -3
  53. package/dist/translations/en.js +1 -1
  54. package/dist/translations/en.umd.js +5 -3
  55. package/dist/translations/eo.js +1 -1
  56. package/dist/translations/eo.umd.js +5 -3
  57. package/dist/translations/es-co.js +1 -1
  58. package/dist/translations/es-co.umd.js +5 -3
  59. package/dist/translations/es.js +1 -1
  60. package/dist/translations/es.umd.js +5 -3
  61. package/dist/translations/et.js +1 -1
  62. package/dist/translations/et.umd.js +5 -3
  63. package/dist/translations/eu.js +1 -1
  64. package/dist/translations/eu.umd.js +5 -3
  65. package/dist/translations/fa.js +1 -1
  66. package/dist/translations/fa.umd.js +5 -3
  67. package/dist/translations/fi.js +1 -1
  68. package/dist/translations/fi.umd.js +5 -3
  69. package/dist/translations/fr.js +1 -1
  70. package/dist/translations/fr.umd.js +5 -3
  71. package/dist/translations/gl.js +1 -1
  72. package/dist/translations/gl.umd.js +5 -3
  73. package/dist/translations/gu.js +1 -1
  74. package/dist/translations/gu.umd.js +5 -3
  75. package/dist/translations/he.js +1 -1
  76. package/dist/translations/he.umd.js +5 -3
  77. package/dist/translations/hi.js +1 -1
  78. package/dist/translations/hi.umd.js +5 -3
  79. package/dist/translations/hr.js +1 -1
  80. package/dist/translations/hr.umd.js +5 -3
  81. package/dist/translations/hu.js +1 -1
  82. package/dist/translations/hu.umd.js +5 -3
  83. package/dist/translations/hy.js +1 -1
  84. package/dist/translations/hy.umd.js +5 -3
  85. package/dist/translations/id.js +1 -1
  86. package/dist/translations/id.umd.js +5 -3
  87. package/dist/translations/it.js +1 -1
  88. package/dist/translations/it.umd.js +5 -3
  89. package/dist/translations/ja.js +1 -1
  90. package/dist/translations/ja.umd.js +5 -3
  91. package/dist/translations/jv.js +1 -1
  92. package/dist/translations/jv.umd.js +5 -3
  93. package/dist/translations/kk.js +1 -1
  94. package/dist/translations/kk.umd.js +5 -3
  95. package/dist/translations/km.js +1 -1
  96. package/dist/translations/km.umd.js +5 -3
  97. package/dist/translations/kn.js +1 -1
  98. package/dist/translations/kn.umd.js +5 -3
  99. package/dist/translations/ko.js +1 -1
  100. package/dist/translations/ko.umd.js +5 -3
  101. package/dist/translations/ku.js +1 -1
  102. package/dist/translations/ku.umd.js +5 -3
  103. package/dist/translations/lt.js +1 -1
  104. package/dist/translations/lt.umd.js +5 -3
  105. package/dist/translations/lv.js +1 -1
  106. package/dist/translations/lv.umd.js +5 -3
  107. package/dist/translations/ms.js +1 -1
  108. package/dist/translations/ms.umd.js +5 -3
  109. package/dist/translations/nb.js +1 -1
  110. package/dist/translations/nb.umd.js +5 -3
  111. package/dist/translations/ne.js +1 -1
  112. package/dist/translations/ne.umd.js +5 -3
  113. package/dist/translations/nl.js +1 -1
  114. package/dist/translations/nl.umd.js +5 -3
  115. package/dist/translations/no.js +1 -1
  116. package/dist/translations/no.umd.js +5 -3
  117. package/dist/translations/oc.js +1 -1
  118. package/dist/translations/oc.umd.js +5 -3
  119. package/dist/translations/pl.js +1 -1
  120. package/dist/translations/pl.umd.js +5 -3
  121. package/dist/translations/pt-br.js +1 -1
  122. package/dist/translations/pt-br.umd.js +5 -3
  123. package/dist/translations/pt.js +1 -1
  124. package/dist/translations/pt.umd.js +5 -3
  125. package/dist/translations/ro.js +1 -1
  126. package/dist/translations/ro.umd.js +5 -3
  127. package/dist/translations/ru.js +1 -1
  128. package/dist/translations/ru.umd.js +5 -3
  129. package/dist/translations/si.js +1 -1
  130. package/dist/translations/si.umd.js +5 -3
  131. package/dist/translations/sk.js +1 -1
  132. package/dist/translations/sk.umd.js +5 -3
  133. package/dist/translations/sl.js +1 -1
  134. package/dist/translations/sl.umd.js +5 -3
  135. package/dist/translations/sq.js +1 -1
  136. package/dist/translations/sq.umd.js +5 -3
  137. package/dist/translations/sr-latn.js +1 -1
  138. package/dist/translations/sr-latn.umd.js +5 -3
  139. package/dist/translations/sr.js +1 -1
  140. package/dist/translations/sr.umd.js +5 -3
  141. package/dist/translations/sv.js +1 -1
  142. package/dist/translations/sv.umd.js +5 -3
  143. package/dist/translations/th.js +1 -1
  144. package/dist/translations/th.umd.js +5 -3
  145. package/dist/translations/ti.js +1 -1
  146. package/dist/translations/ti.umd.js +5 -3
  147. package/dist/translations/tk.js +1 -1
  148. package/dist/translations/tk.umd.js +5 -3
  149. package/dist/translations/tr.js +1 -1
  150. package/dist/translations/tr.umd.js +5 -3
  151. package/dist/translations/tt.js +1 -1
  152. package/dist/translations/tt.umd.js +5 -3
  153. package/dist/translations/ug.js +1 -1
  154. package/dist/translations/ug.umd.js +5 -3
  155. package/dist/translations/uk.js +1 -1
  156. package/dist/translations/uk.umd.js +5 -3
  157. package/dist/translations/ur.js +1 -1
  158. package/dist/translations/ur.umd.js +5 -3
  159. package/dist/translations/uz.js +1 -1
  160. package/dist/translations/uz.umd.js +5 -3
  161. package/dist/translations/vi.js +1 -1
  162. package/dist/translations/vi.umd.js +5 -3
  163. package/dist/translations/zh-cn.js +1 -1
  164. package/dist/translations/zh-cn.umd.js +5 -3
  165. package/dist/translations/zh.js +1 -1
  166. package/dist/translations/zh.umd.js +5 -3
  167. package/dist/utils/normalizeclipboarddata.d.ts +12 -12
  168. package/dist/utils/plaintexttohtml.d.ts +10 -10
  169. package/dist/utils/viewtoplaintext.d.ts +12 -12
  170. package/package.json +7 -7
package/dist/index.js CHANGED
@@ -2,2240 +2,1769 @@
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 { Plugin } from '@ckeditor/ckeditor5-core/dist/index.js';
6
- import { EventInfo, getRangeFromMouseEvent, uid, toUnit, delay, DomEmitterMixin, global, Rect, ResizeObserver, env, createElement } from '@ckeditor/ckeditor5-utils/dist/index.js';
7
- import { DomEventObserver, ViewDataTransfer, ModelRange, PointerObserver, ModelLiveRange } from '@ckeditor/ckeditor5-engine/dist/index.js';
8
- import { mapValues, throttle } from 'es-toolkit/compat';
9
- import { Widget, isWidget } from '@ckeditor/ckeditor5-widget/dist/index.js';
10
- import { View } from '@ckeditor/ckeditor5-ui/dist/index.js';
5
+ import { Plugin } from "@ckeditor/ckeditor5-core";
6
+ import { DomEmitterMixin, EventInfo, Rect, ResizeObserver, containsNode, createElement, delay, env, findClosestScrollableAncestor, getElementFromPoint, getRangeFromMouseEvent, global, isShadowRoot, toUnit, uid } from "@ckeditor/ckeditor5-utils";
7
+ import { DomEventObserver, ModelLiveRange, ModelRange, PointerObserver, ViewDataTransfer } from "@ckeditor/ckeditor5-engine";
8
+ import { mapValues, throttle } from "es-toolkit/compat";
9
+ import { Widget, isWidget } from "@ckeditor/ckeditor5-widget";
10
+ import { View } from "@ckeditor/ckeditor5-ui";
11
11
 
12
12
  /**
13
- * Clipboard events observer.
14
- *
15
- * Fires the following events:
16
- *
17
- * * {@link module:engine/view/document~ViewDocument#event:clipboardInput},
18
- * * {@link module:engine/view/document~ViewDocument#event:paste},
19
- * * {@link module:engine/view/document~ViewDocument#event:copy},
20
- * * {@link module:engine/view/document~ViewDocument#event:cut},
21
- * * {@link module:engine/view/document~ViewDocument#event:drop},
22
- * * {@link module:engine/view/document~ViewDocument#event:dragover},
23
- * * {@link module:engine/view/document~ViewDocument#event:dragging},
24
- * * {@link module:engine/view/document~ViewDocument#event:dragstart},
25
- * * {@link module:engine/view/document~ViewDocument#event:dragend},
26
- * * {@link module:engine/view/document~ViewDocument#event:dragenter},
27
- * * {@link module:engine/view/document~ViewDocument#event:dragleave}.
28
- *
29
- * **Note**: This observer is not available by default (ckeditor5-engine does not add it on its own).
30
- * To make it available, it needs to be added to {@link module:engine/view/document~ViewDocument} by using
31
- * the {@link module:engine/view/view~EditingView#addObserver `View#addObserver()`} method. Alternatively, you can load the
32
- * {@link module:clipboard/clipboard~Clipboard} plugin which adds this observer automatically (because it uses it).
33
- */ class ClipboardObserver extends DomEventObserver {
34
- domEventType = [
35
- 'paste',
36
- 'copy',
37
- 'cut',
38
- 'drop',
39
- 'dragover',
40
- 'dragstart',
41
- 'dragend',
42
- 'dragenter',
43
- 'dragleave'
44
- ];
45
- constructor(view){
46
- super(view);
47
- const viewDocument = this.document;
48
- this.listenTo(viewDocument, 'paste', handleInput('clipboardInput'), {
49
- priority: 'low'
50
- });
51
- this.listenTo(viewDocument, 'drop', handleInput('clipboardInput'), {
52
- priority: 'low'
53
- });
54
- this.listenTo(viewDocument, 'dragover', handleInput('dragging'), {
55
- priority: 'low'
56
- });
57
- function handleInput(type) {
58
- return (evt, data)=>{
59
- data.preventDefault();
60
- const targetRanges = data.dropRange ? [
61
- data.dropRange
62
- ] : null;
63
- const eventInfo = new EventInfo(viewDocument, type);
64
- viewDocument.fire(eventInfo, {
65
- dataTransfer: data.dataTransfer,
66
- method: evt.name,
67
- targetRanges,
68
- target: data.target,
69
- domEvent: data.domEvent
70
- });
71
- // If CKEditor handled the input, do not bubble the original event any further.
72
- // This helps external integrations recognize that fact and act accordingly.
73
- // https://github.com/ckeditor/ckeditor5-upload/issues/92
74
- if (eventInfo.stop.called) {
75
- data.stopPropagation();
76
- }
77
- };
78
- }
79
- }
80
- onDomEvent(domEvent) {
81
- const nativeDataTransfer = 'clipboardData' in domEvent ? domEvent.clipboardData : domEvent.dataTransfer;
82
- const cacheFiles = domEvent.type == 'drop' || domEvent.type == 'paste';
83
- const evtData = {
84
- dataTransfer: new ViewDataTransfer(nativeDataTransfer, {
85
- cacheFiles
86
- })
87
- };
88
- if (domEvent.type == 'drop' || domEvent.type == 'dragover') {
89
- const domRange = getRangeFromMouseEvent(domEvent);
90
- evtData.dropRange = domRange && this.view.domConverter.domRangeToView(domRange);
91
- }
92
- this.fire(domEvent.type, domEvent, evtData);
93
- }
13
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
14
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
15
+ */
16
+ /**
17
+ * @module clipboard/utils/plaintexttohtml
18
+ */
19
+ /**
20
+ * Converts plain text to its HTML-ized version.
21
+ *
22
+ * @param text The plain text to convert.
23
+ * @returns HTML generated from the plain text.
24
+ */
25
+ function plainTextToHtml(text) {
26
+ text = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r?\n\r?\n/g, "</p><p>").replace(/\r?\n/g, "<br>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;").replace(/^\s/, "&nbsp;").replace(/\s$/, "&nbsp;").replace(/\s\s/g, " &nbsp;");
27
+ if (text.includes("</p><p>") || text.includes("<br>")) text = `<p>${text}</p>`;
28
+ return text;
94
29
  }
95
30
 
96
31
  /**
97
- * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
98
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
99
- */ /**
100
- * @module clipboard/utils/plaintexttohtml
101
- */ /**
102
- * Converts plain text to its HTML-ized version.
103
- *
104
- * @param text The plain text to convert.
105
- * @returns HTML generated from the plain text.
106
- */ function plainTextToHtml(text) {
107
- text = text// Encode &.
108
- .replace(/&/g, '&amp;')// Encode <>.
109
- .replace(/</g, '&lt;').replace(/>/g, '&gt;')// Creates a paragraph for each double line break.
110
- .replace(/\r?\n\r?\n/g, '</p><p>')// Creates a line break for each single line break.
111
- .replace(/\r?\n/g, '<br>')// Replace tabs with four spaces.
112
- .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')// Preserve trailing spaces (only the first and last one – the rest is handled below).
113
- .replace(/^\s/, '&nbsp;').replace(/\s$/, '&nbsp;')// Preserve other subsequent spaces now.
114
- .replace(/\s\s/g, ' &nbsp;');
115
- if (text.includes('</p><p>') || text.includes('<br>')) {
116
- // If we created paragraphs above, add the trailing ones.
117
- text = `<p>${text}</p>`;
118
- }
119
- // TODO:
120
- // * What about '\nfoo' vs ' foo'?
121
- return text;
122
- }
32
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
33
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
34
+ */
35
+ /**
36
+ * @module clipboard/clipboardobserver
37
+ */
38
+ /**
39
+ * Clipboard events observer.
40
+ *
41
+ * Fires the following events:
42
+ *
43
+ * * {@link module:engine/view/document~ViewDocument#event:clipboardInput},
44
+ * * {@link module:engine/view/document~ViewDocument#event:paste},
45
+ * * {@link module:engine/view/document~ViewDocument#event:copy},
46
+ * * {@link module:engine/view/document~ViewDocument#event:cut},
47
+ * * {@link module:engine/view/document~ViewDocument#event:drop},
48
+ * * {@link module:engine/view/document~ViewDocument#event:dragover},
49
+ * * {@link module:engine/view/document~ViewDocument#event:dragging},
50
+ * * {@link module:engine/view/document~ViewDocument#event:dragstart},
51
+ * * {@link module:engine/view/document~ViewDocument#event:dragend},
52
+ * * {@link module:engine/view/document~ViewDocument#event:dragenter},
53
+ * * {@link module:engine/view/document~ViewDocument#event:dragleave}.
54
+ *
55
+ * **Note**: This observer is not available by default (ckeditor5-engine does not add it on its own).
56
+ * To make it available, it needs to be added to {@link module:engine/view/document~ViewDocument} by using
57
+ * the {@link module:engine/view/view~EditingView#addObserver `View#addObserver()`} method. Alternatively, you can load the
58
+ * {@link module:clipboard/clipboard~Clipboard} plugin which adds this observer automatically (because it uses it).
59
+ */
60
+ var ClipboardObserver = class extends DomEventObserver {
61
+ domEventType = [
62
+ "paste",
63
+ "copy",
64
+ "cut",
65
+ "drop",
66
+ "dragover",
67
+ "dragstart",
68
+ "dragend",
69
+ "dragenter",
70
+ "dragleave"
71
+ ];
72
+ constructor(view) {
73
+ super(view);
74
+ const viewDocument = this.document;
75
+ this.listenTo(viewDocument, "paste", handleInput("clipboardInput"), { priority: "low" });
76
+ this.listenTo(viewDocument, "drop", handleInput("clipboardInput"), { priority: "low" });
77
+ this.listenTo(viewDocument, "dragover", handleInput("dragging"), { priority: "low" });
78
+ function handleInput(type) {
79
+ return (evt, data) => {
80
+ data.preventDefault();
81
+ const targetRanges = data.dropRange ? [data.dropRange] : null;
82
+ const dataTransfer = data.dataTransfer;
83
+ const eventInfo = new EventInfo(viewDocument, type);
84
+ let content = "";
85
+ if (dataTransfer.getData("text/html")) content = dataTransfer.getData("text/html");
86
+ else if (dataTransfer.getData("text/plain")) content = plainTextToHtml(dataTransfer.getData("text/plain"));
87
+ viewDocument.fire(eventInfo, {
88
+ dataTransfer,
89
+ content,
90
+ method: evt.name,
91
+ targetRanges,
92
+ target: data.target,
93
+ domEvent: data.domEvent
94
+ });
95
+ if (eventInfo.stop.called) data.stopPropagation();
96
+ };
97
+ }
98
+ }
99
+ onDomEvent(domEvent) {
100
+ const nativeDataTransfer = "clipboardData" in domEvent ? domEvent.clipboardData : domEvent.dataTransfer;
101
+ const cacheFiles = domEvent.type == "drop" || domEvent.type == "paste";
102
+ const evtData = { dataTransfer: new ViewDataTransfer(nativeDataTransfer, { cacheFiles }) };
103
+ if (domEvent.type == "drop" || domEvent.type == "dragover") {
104
+ const domRange = getRangeFromMouseEvent(domEvent);
105
+ evtData.dropRange = domRange && this.view.domConverter.domRangeToView(domRange);
106
+ }
107
+ this.fire(domEvent.type, domEvent, evtData);
108
+ }
109
+ };
123
110
 
124
111
  /**
125
- * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
126
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
127
- */ /**
128
- * @module clipboard/utils/normalizeclipboarddata
129
- */ /**
130
- * Removes some popular browser quirks out of the clipboard data (HTML).
131
- * Removes all HTML comments. These are considered an internal thing and it makes little sense if they leak into the editor data.
132
- *
133
- * @param data The HTML data to normalize.
134
- * @returns Normalized HTML.
135
- * @internal
136
- */ function normalizeClipboardData(data) {
137
- return data.replace(/<span(?: class="Apple-converted-space"|)>(\s+)<\/span>/g, (fullMatch, spaces)=>{
138
- // Handle the most popular and problematic case when even a single space becomes an nbsp;.
139
- // Decode those to normal spaces. Read more in https://github.com/ckeditor/ckeditor5-clipboard/issues/2.
140
- if (spaces.length == 1) {
141
- return ' ';
142
- }
143
- return spaces;
144
- })// Remove all HTML comments.
145
- .replace(/<!--[\s\S]*?-->/g, '');
112
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
113
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
114
+ */
115
+ /**
116
+ * @module clipboard/utils/normalizeclipboarddata
117
+ */
118
+ /**
119
+ * Removes some popular browser quirks out of the clipboard data (HTML).
120
+ * Removes all HTML comments. These are considered an internal thing and it makes little sense if they leak into the editor data.
121
+ *
122
+ * @param data The HTML data to normalize.
123
+ * @returns Normalized HTML.
124
+ * @internal
125
+ */
126
+ function normalizeClipboardData(data) {
127
+ return data.replace(/<span(?: class="Apple-converted-space"|)>(\s+)<\/span>/g, (fullMatch, spaces) => {
128
+ if (spaces.length == 1) return " ";
129
+ return spaces;
130
+ }).replace(/<!--[\s\S]*?-->/g, "");
146
131
  }
147
132
 
148
133
  /**
149
- * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
150
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
151
- */ /**
152
- * @module clipboard/utils/viewtoplaintext
153
- */ // Elements which should not have empty-line padding.
154
- // Most `view.ContainerElement` want to be separate by new-line, but some are creating one structure
155
- // together (like `<li>`) so it is better to separate them by only one "\n".
156
- const smallPaddingElements = [
157
- 'figcaption',
158
- 'li'
159
- ];
160
- const listElements = [
161
- 'ol',
162
- 'ul'
163
- ];
134
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
135
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
136
+ */
137
+ const smallPaddingElements = ["figcaption", "li"];
138
+ const listElements = ["ol", "ul"];
164
139
  /**
165
- * Converts {@link module:engine/view/item~ViewItem view item} and all of its children to plain text.
166
- *
167
- * @param converter The converter instance.
168
- * @param viewItem View item to convert.
169
- * @returns Plain text representation of `viewItem`.
170
- */ function viewToPlainText(converter, viewItem) {
171
- if (viewItem.is('$text') || viewItem.is('$textProxy')) {
172
- return viewItem.data;
173
- }
174
- if (viewItem.is('element', 'img') && viewItem.hasAttribute('alt')) {
175
- return viewItem.getAttribute('alt');
176
- }
177
- if (viewItem.is('element', 'br')) {
178
- return '\n'; // Convert soft breaks to single line break (#8045).
179
- }
180
- /**
181
- * Item is a document fragment, attribute element or container element. It doesn't
182
- * have it's own text value, so we need to convert its children elements.
183
- */ let text = '';
184
- let prev = null;
185
- for (const child of viewItem.getChildren()){
186
- text += newLinePadding(child, prev) + viewToPlainText(converter, child);
187
- prev = child;
188
- }
189
- // If item is a raw element, the only way to get its content is to render it and read the text directly from DOM.
190
- if (viewItem.is('rawElement')) {
191
- const doc = document.implementation.createHTMLDocument('');
192
- const tempElement = doc.createElement('div');
193
- viewItem.render(tempElement, converter);
194
- text += domElementToPlainText(tempElement);
195
- }
196
- return text;
140
+ * Converts {@link module:engine/view/item~ViewItem view item} and all of its children to plain text.
141
+ *
142
+ * @param converter The converter instance.
143
+ * @param viewItem View item to convert.
144
+ * @returns Plain text representation of `viewItem`.
145
+ */
146
+ function viewToPlainText(converter, viewItem) {
147
+ if (viewItem.is("$text") || viewItem.is("$textProxy")) return viewItem.data;
148
+ if (viewItem.is("element", "img") && viewItem.hasAttribute("alt")) return viewItem.getAttribute("alt");
149
+ if (viewItem.is("element", "br")) return "\n";
150
+ /**
151
+ * Item is a document fragment, attribute element or container element. It doesn't
152
+ * have it's own text value, so we need to convert its children elements.
153
+ */
154
+ let text = "";
155
+ let prev = null;
156
+ for (const child of viewItem.getChildren()) {
157
+ text += newLinePadding(child, prev) + viewToPlainText(converter, child);
158
+ prev = child;
159
+ }
160
+ if (viewItem.is("rawElement")) {
161
+ const tempElement = document.implementation.createHTMLDocument("").createElement("div");
162
+ viewItem.render(tempElement, converter);
163
+ text += domElementToPlainText(tempElement);
164
+ }
165
+ return text;
197
166
  }
198
167
  /**
199
- * Recursively converts DOM element and all of its children to plain text.
200
- */ function domElementToPlainText(element) {
201
- let text = '';
202
- if (element.nodeType === Node.TEXT_NODE) {
203
- return element.textContent;
204
- } else if (element.tagName === 'BR') {
205
- return '\n';
206
- }
207
- for (const child of element.childNodes){
208
- text += domElementToPlainText(child);
209
- }
210
- return text;
168
+ * Recursively converts DOM element and all of its children to plain text.
169
+ */
170
+ function domElementToPlainText(element) {
171
+ let text = "";
172
+ if (element.nodeType === Node.TEXT_NODE) return element.textContent;
173
+ else if (element.tagName === "BR") return "\n";
174
+ for (const child of element.childNodes) text += domElementToPlainText(child);
175
+ return text;
211
176
  }
212
177
  /**
213
- * Returns new line padding to prefix the given elements with.
214
- */ function newLinePadding(element, previous) {
215
- if (!previous) {
216
- // Don't add padding to first elements in a level.
217
- return '';
218
- }
219
- if (element.is('element', 'li') && !element.isEmpty && element.getChild(0).is('containerElement')) {
220
- // Separate document list items with empty lines.
221
- return '\n\n';
222
- }
223
- if (listElements.includes(element.name) && listElements.includes(previous.name)) {
224
- /**
225
- * Because `<ul>` and `<ol>` are ViewAttributeElements, two consecutive lists will not have any padding between
226
- * them (see the `if` statement below). To fix this, we need to make an exception for this case.
227
- */ return '\n\n';
228
- }
229
- if (!element.is('containerElement') && !previous.is('containerElement')) {
230
- // Don't add padding between non-container elements.
231
- return '';
232
- }
233
- if (smallPaddingElements.includes(element.name) || smallPaddingElements.includes(previous.name)) {
234
- // Add small padding between selected container elements.
235
- return '\n';
236
- }
237
- // Do not add padding around the elements that won't be rendered.
238
- if (element.is('element') && element.getCustomProperty('dataPipeline:transparentRendering') || previous.is('element') && previous.getCustomProperty('dataPipeline:transparentRendering')) {
239
- return '';
240
- }
241
- // Add empty lines between container elements.
242
- return '\n\n';
178
+ * Returns new line padding to prefix the given elements with.
179
+ */
180
+ function newLinePadding(element, previous) {
181
+ if (!previous) return "";
182
+ if (element.is("element", "li") && !element.isEmpty && element.getChild(0).is("containerElement")) return "\n\n";
183
+ if (listElements.includes(element.name) && listElements.includes(previous.name))
184
+ /**
185
+ * Because `<ul>` and `<ol>` are ViewAttributeElements, two consecutive lists will not have any padding between
186
+ * them (see the `if` statement below). To fix this, we need to make an exception for this case.
187
+ */
188
+ return "\n\n";
189
+ if (!element.is("containerElement") && !previous.is("containerElement")) return "";
190
+ if (smallPaddingElements.includes(element.name) || smallPaddingElements.includes(previous.name)) return "\n";
191
+ if (element.is("element") && element.getCustomProperty("dataPipeline:transparentRendering") || previous.is("element") && previous.getCustomProperty("dataPipeline:transparentRendering")) return "";
192
+ return "\n\n";
243
193
  }
244
194
 
245
195
  /**
246
- * Part of the clipboard logic. Responsible for collecting markers from selected fragments
247
- * and restoring them with proper positions in pasted elements.
248
- *
249
- * @internal
250
- */ class ClipboardMarkersUtils extends Plugin {
251
- /**
252
- * Map of marker names that can be copied.
253
- *
254
- * @internal
255
- */ _markersToCopy = new Map();
256
- /**
257
- * @inheritDoc
258
- */ static get pluginName() {
259
- return 'ClipboardMarkersUtils';
260
- }
261
- /**
262
- * @inheritDoc
263
- */ static get isOfficialPlugin() {
264
- return true;
265
- }
266
- /**
267
- * Registers marker name as copyable in clipboard pipeline.
268
- *
269
- * @param markerName Name of marker that can be copied.
270
- * @param config Configuration that describes what can be performed on specified marker.
271
- * @internal
272
- */ _registerMarkerToCopy(markerName, config) {
273
- this._markersToCopy.set(markerName, config);
274
- }
275
- /**
276
- * Performs copy markers on provided selection and paste it to fragment returned from `getCopiedFragment`.
277
- *
278
- * 1. Picks all markers in provided selection.
279
- * 2. Inserts fake markers to document.
280
- * 3. Gets copied selection fragment from document.
281
- * 4. Removes fake elements from fragment and document.
282
- * 5. Inserts markers in the place of removed fake markers.
283
- *
284
- * Due to selection modification, when inserting items, `getCopiedFragment` must *always* operate on `writer.model.document.selection'.
285
- * Do not use any other custom selection object within callback, as this will lead to out-of-bounds exceptions in rare scenarios.
286
- *
287
- * @param action Type of clipboard action.
288
- * @param selection Selection to be checked.
289
- * @param getCopiedFragment Callback that performs copy of selection and returns it as fragment.
290
- * @internal
291
- */ _copySelectedFragmentWithMarkers(action, selection, getCopiedFragment = (writer)=>writer.model.getSelectedContent(writer.model.document.selection)) {
292
- return this.editor.model.change((writer)=>{
293
- const oldSelection = writer.model.document.selection;
294
- // In some scenarios, such like in drag & drop, passed `selection` parameter is not actually
295
- // the same `selection` as the `writer.model.document.selection` which means that `_insertFakeMarkersToSelection`
296
- // is not affecting passed `selection` `start` and `end` positions but rather modifies `writer.model.document.selection`.
297
- //
298
- // It is critical due to fact that when we have selection that starts [ 0, 0 ] and ends at [ 1, 0 ]
299
- // and after inserting fake marker it will point to such marker instead of new widget position at start: [ 1, 0 ] end: [2, 0 ].
300
- // `writer.insert` modifies only original `writer.model.document.selection`.
301
- writer.setSelection(selection);
302
- const sourceSelectionInsertedMarkers = this._insertFakeMarkersIntoSelection(writer, writer.model.document.selection, action);
303
- const fragment = getCopiedFragment(writer);
304
- const fakeMarkersRangesInsideRange = this._removeFakeMarkersInsideElement(writer, fragment);
305
- // <fake-marker> [Foo] Bar</fake-marker>
306
- // ^ ^
307
- // In `_insertFakeMarkersIntoSelection` call we inserted fake marker just before first element.
308
- // The problem is that the first element can be start position of selection so insertion fake-marker
309
- // before such element shifts selection (so selection that was at [0, 0] now is at [0, 1]).
310
- // It means that inserted fake-marker is no longer present inside such selection and is orphaned.
311
- // This function checks special case of such problem. Markers that are orphaned at the start position
312
- // and end position in the same time. Basically it means that they overlaps whole element.
313
- for (const [markerName, elements] of Object.entries(sourceSelectionInsertedMarkers)){
314
- fakeMarkersRangesInsideRange[markerName] ||= writer.createRangeIn(fragment);
315
- for (const element of elements){
316
- writer.remove(element);
317
- }
318
- }
319
- fragment.markers.clear();
320
- for (const [markerName, range] of Object.entries(fakeMarkersRangesInsideRange)){
321
- fragment.markers.set(markerName, range);
322
- }
323
- // Revert back selection to previous one.
324
- writer.setSelection(oldSelection);
325
- return fragment;
326
- });
327
- }
328
- /**
329
- * Performs paste of markers on already pasted element.
330
- *
331
- * 1. Inserts fake markers that are present in fragment element (such fragment will be processed in `getPastedDocumentElement`).
332
- * 2. Calls `getPastedDocumentElement` and gets element that is inserted into root model.
333
- * 3. Removes all fake markers present in transformed element.
334
- * 4. Inserts new markers with removed fake markers ranges into pasted fragment.
335
- *
336
- * There are multiple edge cases that have to be considered before calling this function:
337
- *
338
- * * `markers` are inserted into the same element that must be later transformed inside `getPastedDocumentElement`.
339
- * * Fake marker elements inside `getPastedDocumentElement` can be cloned, but their ranges cannot overlap.
340
- * * If `duplicateOnPaste` is `true` in marker config then associated marker ID is regenerated before pasting.
341
- *
342
- * @param markers Object that maps marker name to corresponding range.
343
- * @param getPastedDocumentElement Getter used to get target markers element.
344
- * @internal
345
- */ _pasteMarkersIntoTransformedElement(markers, getPastedDocumentElement) {
346
- const pasteMarkers = this._getPasteMarkersFromRangeMap(markers);
347
- return this.editor.model.change((writer)=>{
348
- // Inserts fake markers into source fragment / element that is later transformed inside `getPastedDocumentElement`.
349
- const sourceFragmentFakeMarkers = this._insertFakeMarkersElements(writer, pasteMarkers);
350
- // Modifies document fragment (for example, cloning table cells) and then inserts it into the document.
351
- const transformedElement = getPastedDocumentElement(writer);
352
- // Removes markers in pasted and transformed fragment in root document.
353
- const removedFakeMarkers = this._removeFakeMarkersInsideElement(writer, transformedElement);
354
- // Cleans up fake markers inserted into source fragment (that one before transformation which is not pasted).
355
- for (const element of Object.values(sourceFragmentFakeMarkers).flat()){
356
- writer.remove(element);
357
- }
358
- // Inserts to root document fake markers.
359
- for (const [markerName, range] of Object.entries(removedFakeMarkers)){
360
- if (!writer.model.markers.has(markerName)) {
361
- writer.addMarker(markerName, {
362
- usingOperation: true,
363
- affectsData: true,
364
- range
365
- });
366
- }
367
- }
368
- return transformedElement;
369
- });
370
- }
371
- /**
372
- * Pastes document fragment with markers to document.
373
- * If `duplicateOnPaste` is `true` in marker config then associated markers IDs
374
- * are regenerated before pasting to avoid markers duplications in content.
375
- *
376
- * @param fragment Document fragment that should contain already processed by pipeline markers.
377
- * @internal
378
- */ _pasteFragmentWithMarkers(fragment) {
379
- const pasteMarkers = this._getPasteMarkersFromRangeMap(fragment.markers);
380
- fragment.markers.clear();
381
- for (const copyableMarker of pasteMarkers){
382
- fragment.markers.set(copyableMarker.name, copyableMarker.range);
383
- }
384
- return this.editor.model.insertContent(fragment);
385
- }
386
- /**
387
- * In some situations we have to perform copy on selected fragment with certain markers. This function allows to temporarily bypass
388
- * restrictions on markers that we want to copy.
389
- *
390
- * This function executes `executor()` callback. For the duration of the callback, if the clipboard pipeline is used to copy
391
- * content, markers with the specified name will be copied to the clipboard as well.
392
- *
393
- * @param markerName Which markers should be copied.
394
- * @param executor Callback executed.
395
- * @param config Optional configuration flags used to copy (such like partial copy flag).
396
- * @internal
397
- */ _forceMarkersCopy(markerName, executor, config = {
398
- allowedActions: 'all',
399
- copyPartiallySelected: true,
400
- duplicateOnPaste: true
401
- }) {
402
- const before = this._markersToCopy.get(markerName);
403
- this._markersToCopy.set(markerName, config);
404
- executor();
405
- if (before) {
406
- this._markersToCopy.set(markerName, before);
407
- } else {
408
- this._markersToCopy.delete(markerName);
409
- }
410
- }
411
- /**
412
- * Checks if marker can be copied.
413
- *
414
- * @param markerName Name of checked marker.
415
- * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
416
- * @internal
417
- */ _isMarkerCopyable(markerName, action) {
418
- const config = this._getMarkerClipboardConfig(markerName);
419
- if (!config) {
420
- return false;
421
- }
422
- // If there is no action provided then only presence of marker is checked.
423
- if (!action) {
424
- return true;
425
- }
426
- const { allowedActions } = config;
427
- return allowedActions === 'all' || allowedActions.includes(action);
428
- }
429
- /**
430
- * Checks if marker has any clipboard copy behavior configuration.
431
- *
432
- * @param markerName Name of checked marker.
433
- */ _hasMarkerConfiguration(markerName) {
434
- return !!this._getMarkerClipboardConfig(markerName);
435
- }
436
- /**
437
- * Returns marker's configuration flags passed during registration.
438
- *
439
- * @param markerName Name of marker that should be returned.
440
- * @internal
441
- */ _getMarkerClipboardConfig(markerName) {
442
- const [markerNamePrefix] = markerName.split(':');
443
- return this._markersToCopy.get(markerNamePrefix) || null;
444
- }
445
- /**
446
- * First step of copying markers. It looks for markers intersecting with given selection and inserts `$marker` elements
447
- * at positions where document markers start or end. This way `$marker` elements can be easily copied together with
448
- * the rest of the content of the selection.
449
- *
450
- * @param writer An instance of the model writer.
451
- * @param selection Selection to be checked.
452
- * @param action Type of clipboard action.
453
- */ _insertFakeMarkersIntoSelection(writer, selection, action) {
454
- const copyableMarkers = this._getCopyableMarkersFromSelection(writer, selection, action);
455
- return this._insertFakeMarkersElements(writer, copyableMarkers);
456
- }
457
- /**
458
- * Returns array of markers that can be copied in specified selection.
459
- *
460
- * If marker cannot be copied partially (according to `copyPartiallySelected` configuration flag) and
461
- * is not present entirely in any selection range then it will be skipped.
462
- *
463
- * @param writer An instance of the model writer.
464
- * @param selection Selection which will be checked.
465
- * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
466
- */ _getCopyableMarkersFromSelection(writer, selection, action) {
467
- const selectionRanges = Array.from(selection.getRanges());
468
- // Picks all markers in provided ranges. Ensures that there are no duplications if
469
- // there are multiple ranges that intersects with the same marker.
470
- const markersInRanges = new Set(selectionRanges.flatMap((selectionRange)=>Array.from(writer.model.markers.getMarkersIntersectingRange(selectionRange))));
471
- const isSelectionMarkerCopyable = (marker)=>{
472
- // Check if marker exists in configuration and provided action can be performed on it.
473
- const isCopyable = this._isMarkerCopyable(marker.name, action);
474
- if (!isCopyable) {
475
- return false;
476
- }
477
- // Checks if configuration disallows to copy marker only if part of its content is selected.
478
- //
479
- // Example:
480
- // <marker-a> Hello [ World ] </marker-a>
481
- // ^ selection
482
- //
483
- // In this scenario `marker-a` won't be copied because selection doesn't overlap its content entirely.
484
- const { copyPartiallySelected } = this._getMarkerClipboardConfig(marker.name);
485
- if (!copyPartiallySelected) {
486
- const markerRange = marker.getRange();
487
- return selectionRanges.some((selectionRange)=>selectionRange.containsRange(markerRange, true));
488
- }
489
- return true;
490
- };
491
- return Array.from(markersInRanges).filter(isSelectionMarkerCopyable).map((copyableMarker)=>{
492
- // During `dragstart` event original marker is still present in tree.
493
- // It is removed after the clipboard drop event, so none of the copied markers are inserted at the end.
494
- // It happens because there already markers with specified `marker.name` when clipboard is trying to insert data
495
- // and it aborts inserting.
496
- const name = action === 'dragstart' ? this._getUniqueMarkerName(copyableMarker.name) : copyableMarker.name;
497
- return {
498
- name,
499
- range: copyableMarker.getRange()
500
- };
501
- });
502
- }
503
- /**
504
- * Picks all markers from markers map that can be pasted.
505
- * If `duplicateOnPaste` is `true`, it regenerates their IDs to ensure uniqueness.
506
- * If marker is not registered, it will be kept in the array anyway.
507
- *
508
- * @param markers Object that maps marker name to corresponding range.
509
- * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
510
- */ _getPasteMarkersFromRangeMap(markers, action = null) {
511
- const { model } = this.editor;
512
- const entries = markers instanceof Map ? Array.from(markers.entries()) : Object.entries(markers);
513
- return entries.flatMap(([markerName, range])=>{
514
- if (!this._hasMarkerConfiguration(markerName)) {
515
- return [
516
- {
517
- name: markerName,
518
- range
519
- }
520
- ];
521
- }
522
- if (this._isMarkerCopyable(markerName, action)) {
523
- const copyMarkerConfig = this._getMarkerClipboardConfig(markerName);
524
- const isInGraveyard = model.markers.has(markerName) && model.markers.get(markerName).getRange().root.rootName === '$graveyard';
525
- if (copyMarkerConfig.duplicateOnPaste || isInGraveyard) {
526
- markerName = this._getUniqueMarkerName(markerName);
527
- }
528
- return [
529
- {
530
- name: markerName,
531
- range
532
- }
533
- ];
534
- }
535
- return [];
536
- });
537
- }
538
- /**
539
- * Inserts specified array of fake markers elements to document and assigns them `type` and `name` attributes.
540
- * Fake markers elements are used to calculate position of markers on pasted fragment that were transformed during
541
- * steps between copy and paste.
542
- *
543
- * @param writer An instance of the model writer.
544
- * @param markers Array of markers that will be inserted.
545
- */ _insertFakeMarkersElements(writer, markers) {
546
- const mappedMarkers = {};
547
- const sortedMarkers = markers.flatMap((marker)=>{
548
- const { start, end } = marker.range;
549
- return [
550
- {
551
- position: start,
552
- marker,
553
- type: 'start'
554
- },
555
- {
556
- position: end,
557
- marker,
558
- type: 'end'
559
- }
560
- ];
561
- })// Markers position is sorted backwards to ensure that the insertion of fake markers will not change
562
- // the position of the next markers.
563
- .sort(({ position: posA }, { position: posB })=>posA.isBefore(posB) ? 1 : -1);
564
- for (const { position, marker, type } of sortedMarkers){
565
- const fakeMarker = writer.createElement('$marker', {
566
- 'data-name': marker.name,
567
- 'data-type': type
568
- });
569
- if (!mappedMarkers[marker.name]) {
570
- mappedMarkers[marker.name] = [];
571
- }
572
- mappedMarkers[marker.name].push(fakeMarker);
573
- writer.insert(fakeMarker, position);
574
- }
575
- return mappedMarkers;
576
- }
577
- /**
578
- * Removes all `$marker` elements from the given document fragment.
579
- *
580
- * Returns an object where keys are marker names, and values are ranges corresponding to positions
581
- * where `$marker` elements were inserted.
582
- *
583
- * If the document fragment had only one `$marker` element for given marker (start or end) the other boundary is set automatically
584
- * (to the end or start of the document fragment, respectively).
585
- *
586
- * @param writer An instance of the model writer.
587
- * @param rootElement The element to be checked.
588
- */ _removeFakeMarkersInsideElement(writer, rootElement) {
589
- const fakeMarkersElements = this._getAllFakeMarkersFromElement(writer, rootElement);
590
- const fakeMarkersRanges = fakeMarkersElements.reduce((acc, fakeMarker)=>{
591
- const position = fakeMarker.markerElement && writer.createPositionBefore(fakeMarker.markerElement);
592
- let prevFakeMarker = acc[fakeMarker.name];
593
- // Handle scenario when tables clone cells with the same fake node. Example:
594
- //
595
- // <cell><fake-marker-a></cell> <cell><fake-marker-a></cell> <cell><fake-marker-a></cell>
596
- // ^ cloned ^ cloned
597
- //
598
- // The easiest way to bypass this issue is to rename already existing in map nodes and
599
- // set them new unique name.
600
- let skipAssign = false;
601
- if (prevFakeMarker?.start && prevFakeMarker?.end) {
602
- const config = this._getMarkerClipboardConfig(fakeMarker.name);
603
- if (config.duplicateOnPaste) {
604
- acc[this._getUniqueMarkerName(fakeMarker.name)] = acc[fakeMarker.name];
605
- } else {
606
- skipAssign = true;
607
- }
608
- prevFakeMarker = null;
609
- }
610
- if (!skipAssign) {
611
- acc[fakeMarker.name] = {
612
- ...prevFakeMarker,
613
- [fakeMarker.type]: position
614
- };
615
- }
616
- if (fakeMarker.markerElement) {
617
- writer.remove(fakeMarker.markerElement);
618
- }
619
- return acc;
620
- }, {});
621
- // We cannot construct ranges directly in previous reduce because element ranges can overlap.
622
- // In other words lets assume we have such scenario:
623
- // <fake-marker-start /> <paragraph /> <fake-marker-2-start /> <fake-marker-end /> <fake-marker-2-end />
624
- //
625
- // We have to remove `fake-marker-start` firstly and then remove `fake-marker-2-start`.
626
- // Removal of `fake-marker-2-start` affects `fake-marker-end` position so we cannot create
627
- // connection between `fake-marker-start` and `fake-marker-end` without iterating whole set firstly.
628
- return mapValues(fakeMarkersRanges, (range)=>new ModelRange(range.start || writer.createPositionFromPath(rootElement, [
629
- 0
630
- ]), range.end || writer.createPositionAt(rootElement, 'end')));
631
- }
632
- /**
633
- * Returns array that contains list of fake markers with corresponding `$marker` elements.
634
- *
635
- * For each marker, there can be two `$marker` elements or only one (if the document fragment contained
636
- * only the beginning or only the end of a marker).
637
- *
638
- * @param writer An instance of the model writer.
639
- * @param rootElement The element to be checked.
640
- */ _getAllFakeMarkersFromElement(writer, rootElement) {
641
- const foundFakeMarkers = Array.from(writer.createRangeIn(rootElement)).flatMap(({ item })=>{
642
- if (!item.is('element', '$marker')) {
643
- return [];
644
- }
645
- const name = item.getAttribute('data-name');
646
- const type = item.getAttribute('data-type');
647
- return [
648
- {
649
- markerElement: item,
650
- name,
651
- type
652
- }
653
- ];
654
- });
655
- const prependFakeMarkers = [];
656
- const appendFakeMarkers = [];
657
- for (const fakeMarker of foundFakeMarkers){
658
- if (fakeMarker.type === 'end') {
659
- // <fake-marker> [ phrase</fake-marker> phrase ]
660
- // ^
661
- // Handle case when marker is just before start of selection.
662
- // Only end marker is inside selection.
663
- const hasMatchingStartMarker = foundFakeMarkers.some((otherFakeMarker)=>otherFakeMarker.name === fakeMarker.name && otherFakeMarker.type === 'start');
664
- if (!hasMatchingStartMarker) {
665
- prependFakeMarkers.push({
666
- markerElement: null,
667
- name: fakeMarker.name,
668
- type: 'start'
669
- });
670
- }
671
- }
672
- if (fakeMarker.type === 'start') {
673
- // [<fake-marker>phrase]</fake-marker>
674
- // ^
675
- // Handle case when fake marker is after selection.
676
- // Only start marker is inside selection.
677
- const hasMatchingEndMarker = foundFakeMarkers.some((otherFakeMarker)=>otherFakeMarker.name === fakeMarker.name && otherFakeMarker.type === 'end');
678
- if (!hasMatchingEndMarker) {
679
- appendFakeMarkers.unshift({
680
- markerElement: null,
681
- name: fakeMarker.name,
682
- type: 'end'
683
- });
684
- }
685
- }
686
- }
687
- return [
688
- ...prependFakeMarkers,
689
- ...foundFakeMarkers,
690
- ...appendFakeMarkers
691
- ];
692
- }
693
- /**
694
- * When copy of markers occurs we have to make sure that pasted markers have different names
695
- * than source markers. This functions helps with assigning unique part to marker name to
696
- * prevent duplicated markers error.
697
- *
698
- * @param name Name of marker
699
- */ _getUniqueMarkerName(name) {
700
- const parts = name.split(':');
701
- const newId = uid().substring(1, 6);
702
- // It looks like the marker already is UID marker so in this scenario just swap
703
- // last part of marker name and assign new UID.
704
- //
705
- // example: comment:{ threadId }:{ id } => comment:{ threadId }:{ newId }
706
- if (parts.length === 3) {
707
- return `${parts.slice(0, 2).join(':')}:${newId}`;
708
- }
709
- // Assign new segment to marker name with id.
710
- //
711
- // example: comment => comment:{ newId }
712
- return `${parts.join(':')}:${newId}`;
713
- }
714
- }
196
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
197
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
198
+ */
199
+ /**
200
+ * @module clipboard/clipboardmarkersutils
201
+ */
202
+ /**
203
+ * Part of the clipboard logic. Responsible for collecting markers from selected fragments
204
+ * and restoring them with proper positions in pasted elements.
205
+ *
206
+ * @internal
207
+ */
208
+ var ClipboardMarkersUtils = class extends Plugin {
209
+ /**
210
+ * Map of marker names that can be copied.
211
+ *
212
+ * @internal
213
+ */
214
+ _markersToCopy = /* @__PURE__ */ new Map();
215
+ /**
216
+ * @inheritDoc
217
+ */
218
+ static get pluginName() {
219
+ return "ClipboardMarkersUtils";
220
+ }
221
+ /**
222
+ * @inheritDoc
223
+ */
224
+ static get isOfficialPlugin() {
225
+ return true;
226
+ }
227
+ /**
228
+ * Registers marker name as copyable in clipboard pipeline.
229
+ *
230
+ * @param markerName Name of marker that can be copied.
231
+ * @param config Configuration that describes what can be performed on specified marker.
232
+ * @internal
233
+ */
234
+ _registerMarkerToCopy(markerName, config) {
235
+ this._markersToCopy.set(markerName, config);
236
+ }
237
+ /**
238
+ * Performs copy markers on provided selection and paste it to fragment returned from `getCopiedFragment`.
239
+ *
240
+ * 1. Picks all markers in provided selection.
241
+ * 2. Inserts fake markers to document.
242
+ * 3. Gets copied selection fragment from document.
243
+ * 4. Removes fake elements from fragment and document.
244
+ * 5. Inserts markers in the place of removed fake markers.
245
+ *
246
+ * Due to selection modification, when inserting items, `getCopiedFragment` must *always* operate on `writer.model.document.selection'.
247
+ * Do not use any other custom selection object within callback, as this will lead to out-of-bounds exceptions in rare scenarios.
248
+ *
249
+ * @param action Type of clipboard action.
250
+ * @param selection Selection to be checked.
251
+ * @param getCopiedFragment Callback that performs copy of selection and returns it as fragment.
252
+ * @internal
253
+ */
254
+ _copySelectedFragmentWithMarkers(action, selection, getCopiedFragment = (writer) => writer.model.getSelectedContent(writer.model.document.selection)) {
255
+ return this.editor.model.change((writer) => {
256
+ const oldSelection = writer.model.document.selection;
257
+ writer.setSelection(selection);
258
+ const sourceSelectionInsertedMarkers = this._insertFakeMarkersIntoSelection(writer, writer.model.document.selection, action);
259
+ const fragment = getCopiedFragment(writer);
260
+ const fakeMarkersRangesInsideRange = this._removeFakeMarkersInsideElement(writer, fragment);
261
+ for (const [markerName, elements] of Object.entries(sourceSelectionInsertedMarkers)) {
262
+ fakeMarkersRangesInsideRange[markerName] ||= writer.createRangeIn(fragment);
263
+ for (const element of elements) writer.remove(element);
264
+ }
265
+ fragment.markers.clear();
266
+ for (const [markerName, range] of Object.entries(fakeMarkersRangesInsideRange)) fragment.markers.set(markerName, range);
267
+ writer.setSelection(oldSelection);
268
+ return fragment;
269
+ });
270
+ }
271
+ /**
272
+ * Performs paste of markers on already pasted element.
273
+ *
274
+ * 1. Inserts fake markers that are present in fragment element (such fragment will be processed in `getPastedDocumentElement`).
275
+ * 2. Calls `getPastedDocumentElement` and gets element that is inserted into root model.
276
+ * 3. Removes all fake markers present in transformed element.
277
+ * 4. Inserts new markers with removed fake markers ranges into pasted fragment.
278
+ *
279
+ * There are multiple edge cases that have to be considered before calling this function:
280
+ *
281
+ * * `markers` are inserted into the same element that must be later transformed inside `getPastedDocumentElement`.
282
+ * * Fake marker elements inside `getPastedDocumentElement` can be cloned, but their ranges cannot overlap.
283
+ * * If `duplicateOnPaste` is `true` in marker config then associated marker ID is regenerated before pasting.
284
+ *
285
+ * @param markers Object that maps marker name to corresponding range.
286
+ * @param getPastedDocumentElement Getter used to get target markers element.
287
+ * @internal
288
+ */
289
+ _pasteMarkersIntoTransformedElement(markers, getPastedDocumentElement) {
290
+ const pasteMarkers = this._getPasteMarkersFromRangeMap(markers);
291
+ return this.editor.model.change((writer) => {
292
+ const sourceFragmentFakeMarkers = this._insertFakeMarkersElements(writer, pasteMarkers);
293
+ const transformedElement = getPastedDocumentElement(writer);
294
+ const removedFakeMarkers = this._removeFakeMarkersInsideElement(writer, transformedElement);
295
+ for (const element of Object.values(sourceFragmentFakeMarkers).flat()) writer.remove(element);
296
+ for (const [markerName, range] of Object.entries(removedFakeMarkers)) if (!writer.model.markers.has(markerName)) writer.addMarker(markerName, {
297
+ usingOperation: true,
298
+ affectsData: true,
299
+ range
300
+ });
301
+ return transformedElement;
302
+ });
303
+ }
304
+ /**
305
+ * Pastes document fragment with markers to document.
306
+ * If `duplicateOnPaste` is `true` in marker config then associated markers IDs
307
+ * are regenerated before pasting to avoid markers duplications in content.
308
+ *
309
+ * @param fragment Document fragment that should contain already processed by pipeline markers.
310
+ * @internal
311
+ */
312
+ _pasteFragmentWithMarkers(fragment) {
313
+ const pasteMarkers = this._getPasteMarkersFromRangeMap(fragment.markers);
314
+ fragment.markers.clear();
315
+ for (const copyableMarker of pasteMarkers) fragment.markers.set(copyableMarker.name, copyableMarker.range);
316
+ return this.editor.model.insertContent(fragment);
317
+ }
318
+ /**
319
+ * In some situations we have to perform copy on selected fragment with certain markers. This function allows to temporarily bypass
320
+ * restrictions on markers that we want to copy.
321
+ *
322
+ * This function executes `executor()` callback. For the duration of the callback, if the clipboard pipeline is used to copy
323
+ * content, markers with the specified name will be copied to the clipboard as well.
324
+ *
325
+ * @param markerName Which markers should be copied.
326
+ * @param executor Callback executed.
327
+ * @param config Optional configuration flags used to copy (such like partial copy flag).
328
+ * @internal
329
+ */
330
+ _forceMarkersCopy(markerName, executor, config = {
331
+ allowedActions: "all",
332
+ copyPartiallySelected: true,
333
+ duplicateOnPaste: true
334
+ }) {
335
+ const before = this._markersToCopy.get(markerName);
336
+ this._markersToCopy.set(markerName, config);
337
+ executor();
338
+ if (before) this._markersToCopy.set(markerName, before);
339
+ else this._markersToCopy.delete(markerName);
340
+ }
341
+ /**
342
+ * Checks if marker can be copied.
343
+ *
344
+ * @param markerName Name of checked marker.
345
+ * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
346
+ * @internal
347
+ */
348
+ _isMarkerCopyable(markerName, action) {
349
+ const config = this._getMarkerClipboardConfig(markerName);
350
+ if (!config) return false;
351
+ if (!action) return true;
352
+ const { allowedActions } = config;
353
+ return allowedActions === "all" || allowedActions.includes(action);
354
+ }
355
+ /**
356
+ * Checks if marker has any clipboard copy behavior configuration.
357
+ *
358
+ * @param markerName Name of checked marker.
359
+ */
360
+ _hasMarkerConfiguration(markerName) {
361
+ return !!this._getMarkerClipboardConfig(markerName);
362
+ }
363
+ /**
364
+ * Returns marker's configuration flags passed during registration.
365
+ *
366
+ * @param markerName Name of marker that should be returned.
367
+ * @internal
368
+ */
369
+ _getMarkerClipboardConfig(markerName) {
370
+ const [markerNamePrefix] = markerName.split(":");
371
+ return this._markersToCopy.get(markerNamePrefix) || null;
372
+ }
373
+ /**
374
+ * First step of copying markers. It looks for markers intersecting with given selection and inserts `$marker` elements
375
+ * at positions where document markers start or end. This way `$marker` elements can be easily copied together with
376
+ * the rest of the content of the selection.
377
+ *
378
+ * @param writer An instance of the model writer.
379
+ * @param selection Selection to be checked.
380
+ * @param action Type of clipboard action.
381
+ */
382
+ _insertFakeMarkersIntoSelection(writer, selection, action) {
383
+ const copyableMarkers = this._getCopyableMarkersFromSelection(writer, selection, action);
384
+ return this._insertFakeMarkersElements(writer, copyableMarkers);
385
+ }
386
+ /**
387
+ * Returns array of markers that can be copied in specified selection.
388
+ *
389
+ * If marker cannot be copied partially (according to `copyPartiallySelected` configuration flag) and
390
+ * is not present entirely in any selection range then it will be skipped.
391
+ *
392
+ * @param writer An instance of the model writer.
393
+ * @param selection Selection which will be checked.
394
+ * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
395
+ */
396
+ _getCopyableMarkersFromSelection(writer, selection, action) {
397
+ const selectionRanges = Array.from(selection.getRanges());
398
+ const markersInRanges = new Set(selectionRanges.flatMap((selectionRange) => Array.from(writer.model.markers.getMarkersIntersectingRange(selectionRange))));
399
+ const isSelectionMarkerCopyable = (marker) => {
400
+ if (!this._isMarkerCopyable(marker.name, action)) return false;
401
+ const { copyPartiallySelected } = this._getMarkerClipboardConfig(marker.name);
402
+ if (!copyPartiallySelected) {
403
+ const markerRange = marker.getRange();
404
+ return selectionRanges.some((selectionRange) => selectionRange.containsRange(markerRange, true));
405
+ }
406
+ return true;
407
+ };
408
+ return Array.from(markersInRanges).filter(isSelectionMarkerCopyable).map((copyableMarker) => {
409
+ return {
410
+ name: action === "dragstart" ? this._getUniqueMarkerName(copyableMarker.name) : copyableMarker.name,
411
+ range: copyableMarker.getRange()
412
+ };
413
+ });
414
+ }
415
+ /**
416
+ * Picks all markers from markers map that can be pasted.
417
+ * If `duplicateOnPaste` is `true`, it regenerates their IDs to ensure uniqueness.
418
+ * If marker is not registered, it will be kept in the array anyway.
419
+ *
420
+ * @param markers Object that maps marker name to corresponding range.
421
+ * @param action Type of clipboard action. If null then checks only if marker is registered as copyable.
422
+ */
423
+ _getPasteMarkersFromRangeMap(markers, action = null) {
424
+ const { model } = this.editor;
425
+ return (markers instanceof Map ? Array.from(markers.entries()) : Object.entries(markers)).flatMap(([markerName, range]) => {
426
+ if (!this._hasMarkerConfiguration(markerName)) return [{
427
+ name: markerName,
428
+ range
429
+ }];
430
+ if (this._isMarkerCopyable(markerName, action)) {
431
+ const copyMarkerConfig = this._getMarkerClipboardConfig(markerName);
432
+ const isInGraveyard = model.markers.has(markerName) && model.markers.get(markerName).getRange().root.rootName === "$graveyard";
433
+ if (copyMarkerConfig.duplicateOnPaste || isInGraveyard) markerName = this._getUniqueMarkerName(markerName);
434
+ return [{
435
+ name: markerName,
436
+ range
437
+ }];
438
+ }
439
+ return [];
440
+ });
441
+ }
442
+ /**
443
+ * Inserts specified array of fake markers elements to document and assigns them `type` and `name` attributes.
444
+ * Fake markers elements are used to calculate position of markers on pasted fragment that were transformed during
445
+ * steps between copy and paste.
446
+ *
447
+ * @param writer An instance of the model writer.
448
+ * @param markers Array of markers that will be inserted.
449
+ */
450
+ _insertFakeMarkersElements(writer, markers) {
451
+ const mappedMarkers = {};
452
+ const sortedMarkers = markers.flatMap((marker) => {
453
+ const { start, end } = marker.range;
454
+ return [{
455
+ position: start,
456
+ marker,
457
+ type: "start"
458
+ }, {
459
+ position: end,
460
+ marker,
461
+ type: "end"
462
+ }];
463
+ }).sort(({ position: posA }, { position: posB }) => posA.isBefore(posB) ? 1 : -1);
464
+ for (const { position, marker, type } of sortedMarkers) {
465
+ const fakeMarker = writer.createElement("$marker", {
466
+ "data-name": marker.name,
467
+ "data-type": type
468
+ });
469
+ if (!mappedMarkers[marker.name]) mappedMarkers[marker.name] = [];
470
+ mappedMarkers[marker.name].push(fakeMarker);
471
+ writer.insert(fakeMarker, position);
472
+ }
473
+ return mappedMarkers;
474
+ }
475
+ /**
476
+ * Removes all `$marker` elements from the given document fragment.
477
+ *
478
+ * Returns an object where keys are marker names, and values are ranges corresponding to positions
479
+ * where `$marker` elements were inserted.
480
+ *
481
+ * If the document fragment had only one `$marker` element for given marker (start or end) the other boundary is set automatically
482
+ * (to the end or start of the document fragment, respectively).
483
+ *
484
+ * @param writer An instance of the model writer.
485
+ * @param rootElement The element to be checked.
486
+ */
487
+ _removeFakeMarkersInsideElement(writer, rootElement) {
488
+ const fakeMarkersRanges = this._getAllFakeMarkersFromElement(writer, rootElement).reduce((acc, fakeMarker) => {
489
+ const position = fakeMarker.markerElement && writer.createPositionBefore(fakeMarker.markerElement);
490
+ let prevFakeMarker = acc[fakeMarker.name];
491
+ let skipAssign = false;
492
+ if (prevFakeMarker?.start && prevFakeMarker?.end) {
493
+ if (this._getMarkerClipboardConfig(fakeMarker.name).duplicateOnPaste) acc[this._getUniqueMarkerName(fakeMarker.name)] = acc[fakeMarker.name];
494
+ else skipAssign = true;
495
+ prevFakeMarker = null;
496
+ }
497
+ if (!skipAssign) acc[fakeMarker.name] = {
498
+ ...prevFakeMarker,
499
+ [fakeMarker.type]: position
500
+ };
501
+ if (fakeMarker.markerElement) writer.remove(fakeMarker.markerElement);
502
+ return acc;
503
+ }, {});
504
+ return mapValues(fakeMarkersRanges, (range) => new ModelRange(range.start || writer.createPositionFromPath(rootElement, [0]), range.end || writer.createPositionAt(rootElement, "end")));
505
+ }
506
+ /**
507
+ * Returns array that contains list of fake markers with corresponding `$marker` elements.
508
+ *
509
+ * For each marker, there can be two `$marker` elements or only one (if the document fragment contained
510
+ * only the beginning or only the end of a marker).
511
+ *
512
+ * @param writer An instance of the model writer.
513
+ * @param rootElement The element to be checked.
514
+ */
515
+ _getAllFakeMarkersFromElement(writer, rootElement) {
516
+ const foundFakeMarkers = Array.from(writer.createRangeIn(rootElement)).flatMap(({ item }) => {
517
+ if (!item.is("element", "$marker")) return [];
518
+ return [{
519
+ markerElement: item,
520
+ name: item.getAttribute("data-name"),
521
+ type: item.getAttribute("data-type")
522
+ }];
523
+ });
524
+ const prependFakeMarkers = [];
525
+ const appendFakeMarkers = [];
526
+ for (const fakeMarker of foundFakeMarkers) {
527
+ if (fakeMarker.type === "end") {
528
+ if (!foundFakeMarkers.some((otherFakeMarker) => otherFakeMarker.name === fakeMarker.name && otherFakeMarker.type === "start")) prependFakeMarkers.push({
529
+ markerElement: null,
530
+ name: fakeMarker.name,
531
+ type: "start"
532
+ });
533
+ }
534
+ if (fakeMarker.type === "start") {
535
+ if (!foundFakeMarkers.some((otherFakeMarker) => otherFakeMarker.name === fakeMarker.name && otherFakeMarker.type === "end")) appendFakeMarkers.unshift({
536
+ markerElement: null,
537
+ name: fakeMarker.name,
538
+ type: "end"
539
+ });
540
+ }
541
+ }
542
+ return [
543
+ ...prependFakeMarkers,
544
+ ...foundFakeMarkers,
545
+ ...appendFakeMarkers
546
+ ];
547
+ }
548
+ /**
549
+ * When copy of markers occurs we have to make sure that pasted markers have different names
550
+ * than source markers. This functions helps with assigning unique part to marker name to
551
+ * prevent duplicated markers error.
552
+ *
553
+ * @param name Name of marker
554
+ */
555
+ _getUniqueMarkerName(name) {
556
+ const parts = name.split(":");
557
+ const newId = uid().substring(1, 6);
558
+ if (parts.length === 3) return `${parts.slice(0, 2).join(":")}:${newId}`;
559
+ return `${parts.join(":")}:${newId}`;
560
+ }
561
+ };
715
562
 
716
- // Input pipeline events overview:
717
- //
718
- // ┌──────────────────────┐ ┌──────────────────────┐
719
- // │ view.Document │ │ view.Document │
720
- // │ paste │ │ drop │
721
- // └───────────┬──────────┘ └───────────┬──────────┘
722
- // │ │
723
- // └────────────────┌────────────────┘
724
- // │
725
- // ┌─────────V────────┐
726
- // │ view.Document │ Retrieves text/html or text/plain from data.dataTransfer
727
- // │ clipboardInput │ and processes it to view.DocumentFragment.
728
- // └─────────┬────────┘
729
- // │
730
- // ┌───────────V───────────┐
731
- // │ ClipboardPipeline │ Converts view.DocumentFragment to model.DocumentFragment.
732
- // │ inputTransformation │
733
- // └───────────┬───────────┘
734
- // │
735
- // ┌──────────V──────────┐
736
- // │ ClipboardPipeline │ Calls model.insertContent().
737
- // │ contentInsertion │
738
- // └─────────────────────┘
739
- //
740
- //
741
- // Output pipeline events overview:
742
- //
743
- // ┌──────────────────────┐ ┌──────────────────────┐
744
- // │ view.Document │ │ view.Document │ Retrieves the selected model.DocumentFragment
745
- // │ copy │ │ cut │ and fires the `outputTransformation` event.
746
- // └───────────┬──────────┘ └───────────┬──────────┘
747
- // │ │
748
- // └────────────────┌────────────────┘
749
- // │
750
- // ┌───────────V───────────┐
751
- // │ ClipboardPipeline │ Processes model.DocumentFragment and converts it to
752
- // │ outputTransformation │ view.DocumentFragment.
753
- // └───────────┬───────────┘
754
- // │
755
- // ┌─────────V────────┐
756
- // │ view.Document │ Processes view.DocumentFragment to text/html and text/plain
757
- // │ clipboardOutput │ and stores the results in data.dataTransfer.
758
- // └──────────────────┘
759
- //
760
563
  /**
761
- * The clipboard pipeline feature. It is responsible for intercepting the `paste` and `drop` events and
762
- * passing the pasted content through a series of events in order to insert it into the editor's content.
763
- * It also handles the `cut` and `copy` events to fill the native clipboard with the serialized editor's data.
764
- *
765
- * # Input pipeline
766
- *
767
- * The behavior of the default handlers (all at a `low` priority):
768
- *
769
- * ## Event: `paste` or `drop`
770
- *
771
- * 1. Translates the event data.
772
- * 2. Fires the {@link module:engine/view/document~ViewDocument#event:clipboardInput `view.Document#clipboardInput`} event.
773
- *
774
- * ## Event: `view.Document#clipboardInput`
775
- *
776
- * 1. If the `data.content` event field is already set (by some listener on a higher priority), it takes this content and fires the event
777
- * from the last point.
778
- * 2. Otherwise, it retrieves `text/html` or `text/plain` from `data.dataTransfer`.
779
- * 3. Normalizes the raw data by applying simple filters on string data.
780
- * 4. Processes the raw data to {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`} with the
781
- * {@link module:engine/controller/datacontroller~DataController#htmlProcessor `DataController#htmlProcessor`}.
782
- * 5. Fires the {@link module:clipboard/clipboardpipeline~ClipboardPipeline#event:inputTransformation
783
- * `ClipboardPipeline#inputTransformation`} event with the view document fragment in the `data.content` event field.
784
- *
785
- * ## Event: `ClipboardPipeline#inputTransformation`
786
- *
787
- * 1. Converts {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`} from the `data.content` field to
788
- * {@link module:engine/model/documentfragment~ModelDocumentFragment `model.DocumentFragment`}.
789
- * 2. Fires the {@link module:clipboard/clipboardpipeline~ClipboardPipeline#event:contentInsertion `ClipboardPipeline#contentInsertion`}
790
- * event with the model document fragment in the `data.content` event field.
791
- * **Note**: The `ClipboardPipeline#contentInsertion` event is fired within a model change block to allow other handlers
792
- * to run in the same block without post-fixers called in between (i.e., the selection post-fixer).
793
- *
794
- * ## Event: `ClipboardPipeline#contentInsertion`
795
- *
796
- * 1. Calls {@link module:engine/model/model~Model#insertContent `model.insertContent()`} to insert `data.content`
797
- * at the current selection position.
798
- *
799
- * # Output pipeline
800
- *
801
- * The behavior of the default handlers (all at a `low` priority):
802
- *
803
- * ## Event: `copy`, `cut` or `dragstart`
804
- *
805
- * 1. Retrieves the selected {@link module:engine/model/documentfragment~ModelDocumentFragment `model.DocumentFragment`} by calling
806
- * {@link module:engine/model/model~Model#getSelectedContent `model#getSelectedContent()`}.
807
- * 2. Converts the model document fragment to {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`}.
808
- * 3. Fires the {@link module:engine/view/document~ViewDocument#event:clipboardOutput `view.Document#clipboardOutput`} event
809
- * with the view document fragment in the `data.content` event field.
810
- *
811
- * ## Event: `view.Document#clipboardOutput`
812
- *
813
- * 1. Processes `data.content` to HTML and plain text with the
814
- * {@link module:engine/controller/datacontroller~DataController#htmlProcessor `DataController#htmlProcessor`}.
815
- * 2. Updates the `data.dataTransfer` data for `text/html` and `text/plain` with the processed data.
816
- * 3. For the `cut` method, calls {@link module:engine/model/model~Model#deleteContent `model.deleteContent()`}
817
- * on the current selection.
818
- *
819
- * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
820
- */ class ClipboardPipeline extends Plugin {
821
- /**
822
- * @inheritDoc
823
- */ static get pluginName() {
824
- return 'ClipboardPipeline';
825
- }
826
- /**
827
- * @inheritDoc
828
- */ static get isOfficialPlugin() {
829
- return true;
830
- }
831
- /**
832
- * @inheritDoc
833
- */ static get requires() {
834
- return [
835
- ClipboardMarkersUtils
836
- ];
837
- }
838
- /**
839
- * @inheritDoc
840
- */ init() {
841
- const editor = this.editor;
842
- const view = editor.editing.view;
843
- view.addObserver(ClipboardObserver);
844
- this._setupPasteDrop();
845
- this._setupCopyCut();
846
- }
847
- /**
848
- * Fires Clipboard `'outputTransformation'` event for given parameters.
849
- *
850
- * @internal
851
- */ _fireOutputTransformationEvent(dataTransfer, selection, method) {
852
- const clipboardMarkersUtils = this.editor.plugins.get('ClipboardMarkersUtils');
853
- this.editor.model.enqueueChange({
854
- isUndoable: method === 'cut'
855
- }, ()=>{
856
- const documentFragment = clipboardMarkersUtils._copySelectedFragmentWithMarkers(method, selection);
857
- this.fire('outputTransformation', {
858
- dataTransfer,
859
- content: documentFragment,
860
- method
861
- });
862
- });
863
- }
864
- /**
865
- * The clipboard paste pipeline.
866
- */ _setupPasteDrop() {
867
- const editor = this.editor;
868
- const model = editor.model;
869
- const view = editor.editing.view;
870
- const viewDocument = view.document;
871
- const clipboardMarkersUtils = this.editor.plugins.get('ClipboardMarkersUtils');
872
- // Pasting is disabled when selection is in non-editable place.
873
- // Dropping is disabled in drag and drop handler.
874
- this.listenTo(viewDocument, 'clipboardInput', (evt, data)=>{
875
- if (data.method == 'paste' && !editor.model.canEditAt(editor.model.document.selection)) {
876
- evt.stop();
877
- }
878
- }, {
879
- priority: 'highest'
880
- });
881
- this.listenTo(viewDocument, 'clipboardInput', (evt, data)=>{
882
- const dataTransfer = data.dataTransfer;
883
- let content;
884
- // Some feature could already inject content in the higher priority event handler (i.e., codeBlock).
885
- if (data.content) {
886
- content = data.content;
887
- } else {
888
- let contentData = '';
889
- if (dataTransfer.getData('text/html')) {
890
- contentData = normalizeClipboardData(dataTransfer.getData('text/html'));
891
- } else if (dataTransfer.getData('text/plain')) {
892
- contentData = plainTextToHtml(dataTransfer.getData('text/plain'));
893
- }
894
- content = this.editor.data.htmlProcessor.toView(contentData);
895
- }
896
- const eventInfo = new EventInfo(this, 'inputTransformation');
897
- const sourceEditorId = dataTransfer.getData('application/ckeditor5-editor-id') || null;
898
- this.fire(eventInfo, {
899
- content,
900
- dataTransfer,
901
- sourceEditorId,
902
- targetRanges: data.targetRanges,
903
- method: data.method
904
- });
905
- // If CKEditor handled the input, do not bubble the original event any further.
906
- // This helps external integrations recognize this fact and act accordingly.
907
- // https://github.com/ckeditor/ckeditor5-upload/issues/92
908
- if (eventInfo.stop.called) {
909
- evt.stop();
910
- }
911
- view.scrollToTheSelection();
912
- }, {
913
- priority: 'low'
914
- });
915
- this.listenTo(this, 'inputTransformation', (evt, data)=>{
916
- if (data.content.isEmpty) {
917
- return;
918
- }
919
- const dataController = this.editor.data;
920
- // Convert the pasted content into a model document fragment.
921
- // The conversion is contextual, but in this case an "all allowed" context is needed
922
- // and for that we use the $clipboardHolder item.
923
- const modelFragment = dataController.toModel(data.content, '$clipboardHolder');
924
- if (modelFragment.childCount == 0) {
925
- return;
926
- }
927
- evt.stop();
928
- // Fire content insertion event in a single change block to allow other handlers to run in the same block
929
- // without post-fixers called in between (i.e., the selection post-fixer).
930
- model.change(()=>{
931
- this.fire('contentInsertion', {
932
- content: modelFragment,
933
- method: data.method,
934
- sourceEditorId: data.sourceEditorId,
935
- dataTransfer: data.dataTransfer,
936
- targetRanges: data.targetRanges
937
- });
938
- });
939
- }, {
940
- priority: 'low'
941
- });
942
- this.listenTo(this, 'contentInsertion', (evt, data)=>{
943
- data.resultRange = clipboardMarkersUtils._pasteFragmentWithMarkers(data.content);
944
- }, {
945
- priority: 'low'
946
- });
947
- }
948
- /**
949
- * The clipboard copy/cut pipeline.
950
- */ _setupCopyCut() {
951
- const editor = this.editor;
952
- const modelDocument = editor.model.document;
953
- const view = editor.editing.view;
954
- const viewDocument = view.document;
955
- const onCopyCut = (evt, data)=>{
956
- const dataTransfer = data.dataTransfer;
957
- data.preventDefault();
958
- this._fireOutputTransformationEvent(dataTransfer, modelDocument.selection, evt.name);
959
- };
960
- this.listenTo(viewDocument, 'copy', onCopyCut, {
961
- priority: 'low'
962
- });
963
- this.listenTo(viewDocument, 'cut', (evt, data)=>{
964
- // Cutting is disabled when selection is in non-editable place.
965
- // See: https://github.com/ckeditor/ckeditor5-clipboard/issues/26.
966
- if (!editor.model.canEditAt(editor.model.document.selection)) {
967
- data.preventDefault();
968
- } else {
969
- onCopyCut(evt, data);
970
- }
971
- }, {
972
- priority: 'low'
973
- });
974
- this.listenTo(this, 'outputTransformation', (evt, data)=>{
975
- const content = editor.data.toView(data.content, {
976
- isClipboardPipeline: true
977
- });
978
- viewDocument.fire('clipboardOutput', {
979
- dataTransfer: data.dataTransfer,
980
- content,
981
- method: data.method
982
- });
983
- }, {
984
- priority: 'low'
985
- });
986
- this.listenTo(viewDocument, 'clipboardOutput', (evt, data)=>{
987
- if (!data.content.isEmpty) {
988
- data.dataTransfer.setData('text/html', this.editor.data.htmlProcessor.toData(data.content));
989
- data.dataTransfer.setData('text/plain', viewToPlainText(editor.data.htmlProcessor.domConverter, data.content));
990
- data.dataTransfer.setData('application/ckeditor5-editor-id', this.editor.id);
991
- }
992
- if (data.method == 'cut') {
993
- editor.model.deleteContent(modelDocument.selection);
994
- }
995
- }, {
996
- priority: 'low'
997
- });
998
- }
999
- }
564
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
565
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
566
+ */
567
+ /**
568
+ * @module clipboard/clipboardpipeline
569
+ */
570
+ /**
571
+ * The clipboard pipeline feature. It is responsible for intercepting the `paste` and `drop` events and
572
+ * passing the pasted content through a series of events in order to insert it into the editor's content.
573
+ * It also handles the `cut` and `copy` events to fill the native clipboard with the serialized editor's data.
574
+ *
575
+ * # Input pipeline
576
+ *
577
+ * The behavior of the default handlers (all at a `low` priority):
578
+ *
579
+ * ## Event: `paste` or `drop`
580
+ *
581
+ * 1. Translates the event data.
582
+ * 2. Fires the {@link module:engine/view/document~ViewDocument#event:clipboardInput `view.Document#clipboardInput`} event.
583
+ *
584
+ * ## Event: `view.Document#clipboardInput`
585
+ *
586
+ * 1. If the `data.content` event field is already set (by some listener on a higher priority), it takes this content and fires the event
587
+ * from the last point.
588
+ * 2. Otherwise, it retrieves `text/html` or `text/plain` from `data.dataTransfer`.
589
+ * 3. Normalizes the raw data by applying simple filters on string data.
590
+ * 4. Processes the raw data to {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`} with the
591
+ * {@link module:engine/controller/datacontroller~DataController#htmlProcessor `DataController#htmlProcessor`}.
592
+ * 5. Fires the {@link module:clipboard/clipboardpipeline~ClipboardPipeline#event:inputTransformation
593
+ * `ClipboardPipeline#inputTransformation`} event with the view document fragment in the `data.content` event field.
594
+ *
595
+ * ## Event: `ClipboardPipeline#inputTransformation`
596
+ *
597
+ * 1. Converts {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`} from the `data.content` field to
598
+ * {@link module:engine/model/documentfragment~ModelDocumentFragment `model.DocumentFragment`}.
599
+ * 2. Fires the {@link module:clipboard/clipboardpipeline~ClipboardPipeline#event:contentInsertion `ClipboardPipeline#contentInsertion`}
600
+ * event with the model document fragment in the `data.content` event field.
601
+ * **Note**: The `ClipboardPipeline#contentInsertion` event is fired within a model change block to allow other handlers
602
+ * to run in the same block without post-fixers called in between (i.e., the selection post-fixer).
603
+ *
604
+ * ## Event: `ClipboardPipeline#contentInsertion`
605
+ *
606
+ * 1. Calls {@link module:engine/model/model~Model#insertContent `model.insertContent()`} to insert `data.content`
607
+ * at the current selection position.
608
+ *
609
+ * # Output pipeline
610
+ *
611
+ * The behavior of the default handlers (all at a `low` priority):
612
+ *
613
+ * ## Event: `copy`, `cut` or `dragstart`
614
+ *
615
+ * 1. Retrieves the selected {@link module:engine/model/documentfragment~ModelDocumentFragment `model.DocumentFragment`} by calling
616
+ * {@link module:engine/model/model~Model#getSelectedContent `model#getSelectedContent()`}.
617
+ * 2. Converts the model document fragment to {@link module:engine/view/documentfragment~ViewDocumentFragment `view.DocumentFragment`}.
618
+ * 3. Fires the {@link module:engine/view/document~ViewDocument#event:clipboardOutput `view.Document#clipboardOutput`} event
619
+ * with the view document fragment in the `data.content` event field.
620
+ *
621
+ * ## Event: `view.Document#clipboardOutput`
622
+ *
623
+ * 1. Processes `data.content` to HTML and plain text with the
624
+ * {@link module:engine/controller/datacontroller~DataController#htmlProcessor `DataController#htmlProcessor`}.
625
+ * 2. Updates the `data.dataTransfer` data for `text/html` and `text/plain` with the processed data.
626
+ * 3. For the `cut` method, calls {@link module:engine/model/model~Model#deleteContent `model.deleteContent()`}
627
+ * on the current selection.
628
+ *
629
+ * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
630
+ */
631
+ var ClipboardPipeline = class extends Plugin {
632
+ /**
633
+ * @inheritDoc
634
+ */
635
+ static get pluginName() {
636
+ return "ClipboardPipeline";
637
+ }
638
+ /**
639
+ * @inheritDoc
640
+ */
641
+ static get isOfficialPlugin() {
642
+ return true;
643
+ }
644
+ /**
645
+ * @inheritDoc
646
+ */
647
+ static get requires() {
648
+ return [ClipboardMarkersUtils];
649
+ }
650
+ /**
651
+ * @inheritDoc
652
+ */
653
+ init() {
654
+ this.editor.editing.view.addObserver(ClipboardObserver);
655
+ this._setupPasteDrop();
656
+ this._setupCopyCut();
657
+ }
658
+ /**
659
+ * Fires Clipboard `'outputTransformation'` event for given parameters.
660
+ *
661
+ * @internal
662
+ */
663
+ _fireOutputTransformationEvent(dataTransfer, selection, method) {
664
+ const clipboardMarkersUtils = this.editor.plugins.get("ClipboardMarkersUtils");
665
+ this.editor.model.enqueueChange({ isUndoable: method === "cut" }, () => {
666
+ const documentFragment = clipboardMarkersUtils._copySelectedFragmentWithMarkers(method, selection);
667
+ this.fire("outputTransformation", {
668
+ dataTransfer,
669
+ content: documentFragment,
670
+ method
671
+ });
672
+ });
673
+ }
674
+ /**
675
+ * The clipboard paste pipeline.
676
+ */
677
+ _setupPasteDrop() {
678
+ const editor = this.editor;
679
+ const model = editor.model;
680
+ const view = editor.editing.view;
681
+ const viewDocument = view.document;
682
+ const clipboardMarkersUtils = this.editor.plugins.get("ClipboardMarkersUtils");
683
+ this.listenTo(viewDocument, "clipboardInput", (evt, data) => {
684
+ if (data.method == "paste" && !editor.model.canEditAt(editor.model.document.selection)) evt.stop();
685
+ }, { priority: "highest" });
686
+ this.listenTo(viewDocument, "clipboardInput", (evt, data) => {
687
+ const dataTransfer = data.dataTransfer;
688
+ const eventInfo = new EventInfo(this, "inputTransformation");
689
+ const sourceEditorId = dataTransfer.getData("application/ckeditor5-editor-id") || null;
690
+ const content = typeof data.content == "string" ? this.editor.data.htmlProcessor.toView(normalizeClipboardData(data.content)) : data.content;
691
+ this.fire(eventInfo, {
692
+ content,
693
+ dataTransfer,
694
+ sourceEditorId,
695
+ extraContent: data.extraContent,
696
+ targetRanges: data.targetRanges,
697
+ method: data.method
698
+ });
699
+ if (eventInfo.stop.called) evt.stop();
700
+ view.scrollToTheSelection();
701
+ }, { priority: "low" });
702
+ this.listenTo(this, "inputTransformation", (evt, data) => {
703
+ if (data.content.isEmpty) return;
704
+ const modelFragment = this.editor.data.toModel(data.content, "$clipboardHolder");
705
+ if (modelFragment.childCount == 0) return;
706
+ evt.stop();
707
+ model.change(() => {
708
+ this.fire("contentInsertion", {
709
+ content: modelFragment,
710
+ method: data.method,
711
+ sourceEditorId: data.sourceEditorId,
712
+ dataTransfer: data.dataTransfer,
713
+ targetRanges: data.targetRanges
714
+ });
715
+ });
716
+ }, { priority: "low" });
717
+ this.listenTo(this, "contentInsertion", (evt, data) => {
718
+ data.resultRange = clipboardMarkersUtils._pasteFragmentWithMarkers(data.content);
719
+ }, { priority: "low" });
720
+ }
721
+ /**
722
+ * The clipboard copy/cut pipeline.
723
+ */
724
+ _setupCopyCut() {
725
+ const editor = this.editor;
726
+ const modelDocument = editor.model.document;
727
+ const viewDocument = editor.editing.view.document;
728
+ const onCopyCut = (evt, data) => {
729
+ const dataTransfer = data.dataTransfer;
730
+ data.preventDefault();
731
+ this._fireOutputTransformationEvent(dataTransfer, modelDocument.selection, evt.name);
732
+ };
733
+ this.listenTo(viewDocument, "copy", onCopyCut, { priority: "low" });
734
+ this.listenTo(viewDocument, "cut", (evt, data) => {
735
+ if (!editor.model.canEditAt(editor.model.document.selection)) data.preventDefault();
736
+ else onCopyCut(evt, data);
737
+ }, { priority: "low" });
738
+ this.listenTo(this, "outputTransformation", (evt, data) => {
739
+ const content = editor.data.toView(data.content, { isClipboardPipeline: true });
740
+ viewDocument.fire("clipboardOutput", {
741
+ dataTransfer: data.dataTransfer,
742
+ content,
743
+ method: data.method
744
+ });
745
+ }, { priority: "low" });
746
+ this.listenTo(viewDocument, "clipboardOutput", (evt, data) => {
747
+ if (!data.content.isEmpty) {
748
+ data.dataTransfer.setData("text/html", this.editor.data.htmlProcessor.toData(data.content));
749
+ data.dataTransfer.setData("text/plain", viewToPlainText(editor.data.htmlProcessor.domConverter, data.content));
750
+ data.dataTransfer.setData("application/ckeditor5-editor-id", this.editor.id);
751
+ }
752
+ if (data.method == "cut") editor.model.deleteContent(modelDocument.selection);
753
+ }, { priority: "low" });
754
+ }
755
+ };
1000
756
 
1001
- const toPx = /* #__PURE__ */ toUnit('px');
1002
757
  /**
1003
- * The horizontal drop target line view.
1004
- *
1005
- * @internal
1006
- */ class LineView extends View {
1007
- /**
1008
- * @inheritDoc
1009
- */ constructor(){
1010
- super();
1011
- const bind = this.bindTemplate;
1012
- this.set({
1013
- isVisible: false,
1014
- left: null,
1015
- top: null,
1016
- width: null
1017
- });
1018
- this.setTemplate({
1019
- tag: 'div',
1020
- attributes: {
1021
- class: [
1022
- 'ck',
1023
- 'ck-clipboard-drop-target-line',
1024
- bind.if('isVisible', 'ck-hidden', (value)=>!value)
1025
- ],
1026
- style: {
1027
- left: bind.to('left', (left)=>toPx(left)),
1028
- top: bind.to('top', (top)=>toPx(top)),
1029
- width: bind.to('width', (width)=>toPx(width))
1030
- }
1031
- }
1032
- });
1033
- }
1034
- }
758
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
759
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
760
+ */
761
+ /**
762
+ * @module clipboard/lineview
763
+ */
764
+ /* istanbul ignore file -- @preserve */
765
+ const toPx = /* #__PURE__ */ toUnit("px");
766
+ /**
767
+ * The horizontal drop target line view.
768
+ *
769
+ * @internal
770
+ */
771
+ var LineView = class extends View {
772
+ /**
773
+ * @inheritDoc
774
+ */
775
+ constructor() {
776
+ super();
777
+ const bind = this.bindTemplate;
778
+ this.set({
779
+ isVisible: false,
780
+ left: null,
781
+ top: null,
782
+ width: null
783
+ });
784
+ this.setTemplate({
785
+ tag: "div",
786
+ attributes: {
787
+ class: [
788
+ "ck",
789
+ "ck-clipboard-drop-target-line",
790
+ bind.if("isVisible", "ck-hidden", (value) => !value)
791
+ ],
792
+ style: {
793
+ left: bind.to("left", (left) => toPx(left)),
794
+ top: bind.to("top", (top) => toPx(top)),
795
+ width: bind.to("width", (width) => toPx(width))
796
+ }
797
+ }
798
+ });
799
+ }
800
+ };
1035
801
 
1036
802
  /**
1037
- * Part of the Drag and Drop handling. Responsible for finding and displaying the drop target.
1038
- *
1039
- * @internal
1040
- */ class DragDropTarget extends Plugin {
1041
- /**
1042
- * A delayed callback removing the drop marker.
1043
- *
1044
- * @internal
1045
- */ removeDropMarkerDelayed = delay(()=>this.removeDropMarker(), 40);
1046
- /**
1047
- * A throttled callback updating the drop marker.
1048
- */ _updateDropMarkerThrottled = throttle((targetRange)=>this._updateDropMarker(targetRange), 40);
1049
- /**
1050
- * A throttled callback reconverting the drop parker.
1051
- */ _reconvertMarkerThrottled = throttle(()=>{
1052
- if (this.editor.model.markers.has('drop-target')) {
1053
- this.editor.editing.reconvertMarker('drop-target');
1054
- }
1055
- }, 0);
1056
- /**
1057
- * The horizontal drop target line view.
1058
- */ _dropTargetLineView = new LineView();
1059
- /**
1060
- * DOM Emitter.
1061
- */ _domEmitter = new (DomEmitterMixin())();
1062
- /**
1063
- * Map of document scrollable elements.
1064
- */ _scrollables = new Map();
1065
- /**
1066
- * @inheritDoc
1067
- */ static get pluginName() {
1068
- return 'DragDropTarget';
1069
- }
1070
- /**
1071
- * @inheritDoc
1072
- */ static get isOfficialPlugin() {
1073
- return true;
1074
- }
1075
- /**
1076
- * @inheritDoc
1077
- */ init() {
1078
- this._setupDropMarker();
1079
- }
1080
- /**
1081
- * @inheritDoc
1082
- */ destroy() {
1083
- this._domEmitter.stopListening();
1084
- for (const { resizeObserver } of this._scrollables.values()){
1085
- resizeObserver.destroy();
1086
- }
1087
- this._updateDropMarkerThrottled.cancel();
1088
- this.removeDropMarkerDelayed.cancel();
1089
- this._reconvertMarkerThrottled.cancel();
1090
- return super.destroy();
1091
- }
1092
- /**
1093
- * Finds the drop target range and updates the drop marker.
1094
- *
1095
- * @return The updated drop target range or null if no valid range was found.
1096
- * @internal
1097
- */ updateDropMarker(targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
1098
- this.removeDropMarkerDelayed.cancel();
1099
- const targetRange = findDropTargetRange(this.editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange);
1100
- /* istanbul ignore next -- @preserve */ if (!targetRange) {
1101
- return null;
1102
- }
1103
- if (draggedRange && draggedRange.containsRange(targetRange)) {
1104
- // Target range is inside the dragged range.
1105
- this.removeDropMarker();
1106
- return null;
1107
- }
1108
- if (targetRange && !this.editor.model.canEditAt(targetRange)) {
1109
- // Do not show drop marker if target place is not editable.
1110
- this.removeDropMarker();
1111
- return null;
1112
- }
1113
- this._updateDropMarkerThrottled(targetRange);
1114
- return targetRange;
1115
- }
1116
- /**
1117
- * Finds the final drop target range.
1118
- *
1119
- * @internal
1120
- */ getFinalDropRange(targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
1121
- const targetRange = findDropTargetRange(this.editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange);
1122
- // The dragging markers must be removed after searching for the target range because sometimes
1123
- // the target lands on the marker itself.
1124
- this.removeDropMarker();
1125
- return targetRange;
1126
- }
1127
- /**
1128
- * Removes the drop target marker.
1129
- *
1130
- * @internal
1131
- */ removeDropMarker() {
1132
- const model = this.editor.model;
1133
- this.removeDropMarkerDelayed.cancel();
1134
- this._updateDropMarkerThrottled.cancel();
1135
- this._dropTargetLineView.isVisible = false;
1136
- if (model.markers.has('drop-target')) {
1137
- model.change((writer)=>{
1138
- writer.removeMarker('drop-target');
1139
- });
1140
- }
1141
- }
1142
- /**
1143
- * Creates downcast conversion for the drop target marker.
1144
- */ _setupDropMarker() {
1145
- const editor = this.editor;
1146
- editor.ui.view.body.add(this._dropTargetLineView);
1147
- // Drop marker conversion for hovering over widgets.
1148
- editor.conversion.for('editingDowncast').markerToHighlight({
1149
- model: 'drop-target',
1150
- view: {
1151
- classes: [
1152
- 'ck-clipboard-drop-target-range'
1153
- ]
1154
- }
1155
- });
1156
- // Drop marker conversion for in text and block drop target.
1157
- editor.conversion.for('editingDowncast').markerToElement({
1158
- model: 'drop-target',
1159
- view: (data, { writer })=>{
1160
- // Inline drop.
1161
- if (editor.model.schema.checkChild(data.markerRange.start, '$text')) {
1162
- this._dropTargetLineView.isVisible = false;
1163
- return this._createDropTargetPosition(writer);
1164
- } else {
1165
- if (data.markerRange.isCollapsed) {
1166
- this._updateDropTargetLine(data.markerRange);
1167
- } else {
1168
- this._dropTargetLineView.isVisible = false;
1169
- }
1170
- }
1171
- }
1172
- });
1173
- }
1174
- /**
1175
- * Updates the drop target marker to the provided range.
1176
- *
1177
- * @param targetRange The range to set the marker to.
1178
- */ _updateDropMarker(targetRange) {
1179
- const editor = this.editor;
1180
- const markers = editor.model.markers;
1181
- editor.model.change((writer)=>{
1182
- if (markers.has('drop-target')) {
1183
- if (!markers.get('drop-target').getRange().isEqual(targetRange)) {
1184
- writer.updateMarker('drop-target', {
1185
- range: targetRange
1186
- });
1187
- }
1188
- } else {
1189
- writer.addMarker('drop-target', {
1190
- range: targetRange,
1191
- usingOperation: false,
1192
- affectsData: false
1193
- });
1194
- }
1195
- });
1196
- }
1197
- /**
1198
- * Creates the UI element for vertical (in-line) drop target.
1199
- */ _createDropTargetPosition(writer) {
1200
- return writer.createUIElement('span', {
1201
- class: 'ck ck-clipboard-drop-target-position'
1202
- }, function(domDocument) {
1203
- const domElement = this.toDomElement(domDocument);
1204
- // Using word joiner to make this marker as high as text and also making text not break on marker.
1205
- domElement.append('\u2060', domDocument.createElement('span'), '\u2060');
1206
- return domElement;
1207
- });
1208
- }
1209
- /**
1210
- * Updates the horizontal drop target line.
1211
- */ _updateDropTargetLine(range) {
1212
- const editing = this.editor.editing;
1213
- const nodeBefore = range.start.nodeBefore;
1214
- const nodeAfter = range.start.nodeAfter;
1215
- const nodeParent = range.start.parent;
1216
- const viewElementBefore = nodeBefore ? editing.mapper.toViewElement(nodeBefore) : null;
1217
- const domElementBefore = viewElementBefore ? editing.view.domConverter.mapViewToDom(viewElementBefore) : null;
1218
- const viewElementAfter = nodeAfter ? editing.mapper.toViewElement(nodeAfter) : null;
1219
- const domElementAfter = viewElementAfter ? editing.view.domConverter.mapViewToDom(viewElementAfter) : null;
1220
- const viewElementParent = editing.mapper.toViewElement(nodeParent);
1221
- if (!viewElementParent) {
1222
- return;
1223
- }
1224
- const domElementParent = editing.view.domConverter.mapViewToDom(viewElementParent);
1225
- const domScrollableRect = this._getScrollableRect(viewElementParent);
1226
- const { scrollX, scrollY } = global.window;
1227
- const rectBefore = domElementBefore ? new Rect(domElementBefore) : null;
1228
- const rectAfter = domElementAfter ? new Rect(domElementAfter) : null;
1229
- const rectParent = new Rect(domElementParent).excludeScrollbarsAndBorders();
1230
- const above = rectBefore ? rectBefore.bottom : rectParent.top;
1231
- const below = rectAfter ? rectAfter.top : rectParent.bottom;
1232
- const parentStyle = global.window.getComputedStyle(domElementParent);
1233
- const top = above <= below ? (above + below) / 2 : below;
1234
- if (domScrollableRect.top < top && top < domScrollableRect.bottom) {
1235
- const left = rectParent.left + parseFloat(parentStyle.paddingLeft);
1236
- const right = rectParent.right - parseFloat(parentStyle.paddingRight);
1237
- const leftClamped = Math.max(left + scrollX, domScrollableRect.left);
1238
- const rightClamped = Math.min(right + scrollX, domScrollableRect.right);
1239
- this._dropTargetLineView.set({
1240
- isVisible: true,
1241
- left: leftClamped,
1242
- top: top + scrollY,
1243
- width: rightClamped - leftClamped
1244
- });
1245
- } else {
1246
- this._dropTargetLineView.isVisible = false;
1247
- }
1248
- }
1249
- /**
1250
- * Finds the closest scrollable element rect for the given view element.
1251
- */ _getScrollableRect(viewElement) {
1252
- const rootName = viewElement.root.rootName;
1253
- let domScrollable;
1254
- if (this._scrollables.has(rootName)) {
1255
- domScrollable = this._scrollables.get(rootName).domElement;
1256
- } else {
1257
- const domElement = this.editor.editing.view.domConverter.mapViewToDom(viewElement);
1258
- domScrollable = findScrollableElement(domElement);
1259
- this._domEmitter.listenTo(domScrollable, 'scroll', this._reconvertMarkerThrottled, {
1260
- usePassive: true
1261
- });
1262
- const resizeObserver = new ResizeObserver(domScrollable, this._reconvertMarkerThrottled);
1263
- this._scrollables.set(rootName, {
1264
- domElement: domScrollable,
1265
- resizeObserver
1266
- });
1267
- }
1268
- return new Rect(domScrollable).excludeScrollbarsAndBorders();
1269
- }
1270
- }
803
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
804
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
805
+ */
1271
806
  /**
1272
- * Returns fixed selection range for given position and target element.
1273
- */ function findDropTargetRange(editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
1274
- const model = editor.model;
1275
- const mapper = editor.editing.mapper;
1276
- const targetModelElement = getClosestMappedModelElement(editor, targetViewElement);
1277
- let modelElement = targetModelElement;
1278
- while(modelElement){
1279
- if (!blockMode) {
1280
- if (model.schema.checkChild(modelElement, '$text')) {
1281
- if (targetViewRanges) {
1282
- const targetViewPosition = targetViewRanges[0].start;
1283
- const targetModelPosition = mapper.toModelPosition(targetViewPosition);
1284
- const canDropOnPosition = !draggedRange || Array.from(draggedRange.getItems({
1285
- shallow: true
1286
- })).some((item)=>model.schema.checkChild(targetModelPosition, item));
1287
- if (canDropOnPosition) {
1288
- if (model.schema.checkChild(targetModelPosition, '$text')) {
1289
- return model.createRange(targetModelPosition);
1290
- } else if (targetViewPosition) {
1291
- // This is the case of dropping inside a span wrapper of an inline image.
1292
- return findDropTargetRangeForElement(editor, getClosestMappedModelElement(editor, targetViewPosition.parent), clientX, clientY);
1293
- }
1294
- }
1295
- }
1296
- } else if (model.schema.isInline(modelElement)) {
1297
- return findDropTargetRangeForElement(editor, modelElement, clientX, clientY);
1298
- }
1299
- }
1300
- if (model.schema.isBlock(modelElement)) {
1301
- return findDropTargetRangeForElement(editor, modelElement, clientX, clientY);
1302
- } else if (model.schema.checkChild(modelElement, '$block')) {
1303
- const childNodes = Array.from(modelElement.getChildren()).filter((node)=>node.is('element') && !shouldIgnoreElement(editor, node));
1304
- let startIndex = 0;
1305
- let endIndex = childNodes.length;
1306
- if (endIndex == 0) {
1307
- return model.createRange(model.createPositionAt(modelElement, 'end'));
1308
- }
1309
- while(startIndex < endIndex - 1){
1310
- const middleIndex = Math.floor((startIndex + endIndex) / 2);
1311
- const side = findElementSide(editor, childNodes[middleIndex], clientX, clientY);
1312
- if (side == 'before') {
1313
- endIndex = middleIndex;
1314
- } else {
1315
- startIndex = middleIndex;
1316
- }
1317
- }
1318
- return findDropTargetRangeForElement(editor, childNodes[startIndex], clientX, clientY);
1319
- }
1320
- modelElement = modelElement.parent;
1321
- }
1322
- return null;
1323
- }
807
+ * @module clipboard/dragdroptarget
808
+ */
809
+ /**
810
+ * Part of the Drag and Drop handling. Responsible for finding and displaying the drop target.
811
+ *
812
+ * @internal
813
+ */
814
+ var DragDropTarget = class extends Plugin {
815
+ /**
816
+ * A delayed callback removing the drop marker.
817
+ *
818
+ * @internal
819
+ */
820
+ removeDropMarkerDelayed = delay(() => this.removeDropMarker(), 40);
821
+ /**
822
+ * A throttled callback updating the drop marker.
823
+ */
824
+ _updateDropMarkerThrottled = throttle((targetRange) => this._updateDropMarker(targetRange), 40);
825
+ /**
826
+ * A throttled callback reconverting the drop parker.
827
+ */
828
+ _reconvertMarkerThrottled = throttle(() => {
829
+ if (this.editor.model.markers.has("drop-target")) this.editor.editing.reconvertMarker("drop-target");
830
+ }, 0);
831
+ /**
832
+ * The horizontal drop target line view.
833
+ */
834
+ _dropTargetLineView = new LineView();
835
+ /**
836
+ * DOM Emitter.
837
+ */
838
+ _domEmitter = new (DomEmitterMixin())();
839
+ /**
840
+ * Map of document scrollable elements.
841
+ */
842
+ _scrollables = /* @__PURE__ */ new Map();
843
+ /**
844
+ * @inheritDoc
845
+ */
846
+ static get pluginName() {
847
+ return "DragDropTarget";
848
+ }
849
+ /**
850
+ * @inheritDoc
851
+ */
852
+ static get isOfficialPlugin() {
853
+ return true;
854
+ }
855
+ /**
856
+ * @inheritDoc
857
+ */
858
+ init() {
859
+ this._setupDropMarker();
860
+ }
861
+ /**
862
+ * @inheritDoc
863
+ */
864
+ destroy() {
865
+ this._domEmitter.stopListening();
866
+ for (const { resizeObserver } of this._scrollables.values()) resizeObserver.destroy();
867
+ this._updateDropMarkerThrottled.cancel();
868
+ this.removeDropMarkerDelayed.cancel();
869
+ this._reconvertMarkerThrottled.cancel();
870
+ return super.destroy();
871
+ }
872
+ /**
873
+ * Finds the drop target range and updates the drop marker.
874
+ *
875
+ * @return The updated drop target range or null if no valid range was found.
876
+ * @internal
877
+ */
878
+ updateDropMarker(targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
879
+ this.removeDropMarkerDelayed.cancel();
880
+ const targetRange = findDropTargetRange(this.editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange);
881
+ /* istanbul ignore next -- @preserve */
882
+ if (!targetRange) return null;
883
+ if (draggedRange && draggedRange.containsRange(targetRange)) {
884
+ this.removeDropMarker();
885
+ return null;
886
+ }
887
+ if (targetRange && !this.editor.model.canEditAt(targetRange)) {
888
+ this.removeDropMarker();
889
+ return null;
890
+ }
891
+ this._updateDropMarkerThrottled(targetRange);
892
+ return targetRange;
893
+ }
894
+ /**
895
+ * Finds the final drop target range.
896
+ *
897
+ * @internal
898
+ */
899
+ getFinalDropRange(targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
900
+ const targetRange = findDropTargetRange(this.editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange);
901
+ this.removeDropMarker();
902
+ return targetRange;
903
+ }
904
+ /**
905
+ * Removes the drop target marker.
906
+ *
907
+ * @internal
908
+ */
909
+ removeDropMarker() {
910
+ const model = this.editor.model;
911
+ this.removeDropMarkerDelayed.cancel();
912
+ this._updateDropMarkerThrottled.cancel();
913
+ this._dropTargetLineView.isVisible = false;
914
+ if (model.markers.has("drop-target")) model.change((writer) => {
915
+ writer.removeMarker("drop-target");
916
+ });
917
+ }
918
+ /**
919
+ * Creates downcast conversion for the drop target marker.
920
+ */
921
+ _setupDropMarker() {
922
+ const editor = this.editor;
923
+ editor.ui.view.body.add(this._dropTargetLineView);
924
+ editor.conversion.for("editingDowncast").markerToHighlight({
925
+ model: "drop-target",
926
+ view: { classes: ["ck-clipboard-drop-target-range"] }
927
+ });
928
+ editor.conversion.for("editingDowncast").markerToElement({
929
+ model: "drop-target",
930
+ view: (data, { writer }) => {
931
+ if (editor.model.schema.checkChild(data.markerRange.start, "$text")) {
932
+ this._dropTargetLineView.isVisible = false;
933
+ return this._createDropTargetPosition(writer);
934
+ } else if (data.markerRange.isCollapsed) this._updateDropTargetLine(data.markerRange);
935
+ else this._dropTargetLineView.isVisible = false;
936
+ }
937
+ });
938
+ }
939
+ /**
940
+ * Updates the drop target marker to the provided range.
941
+ *
942
+ * @param targetRange The range to set the marker to.
943
+ */
944
+ _updateDropMarker(targetRange) {
945
+ const editor = this.editor;
946
+ const markers = editor.model.markers;
947
+ editor.model.change((writer) => {
948
+ if (markers.has("drop-target")) {
949
+ if (!markers.get("drop-target").getRange().isEqual(targetRange)) writer.updateMarker("drop-target", { range: targetRange });
950
+ } else writer.addMarker("drop-target", {
951
+ range: targetRange,
952
+ usingOperation: false,
953
+ affectsData: false
954
+ });
955
+ });
956
+ }
957
+ /**
958
+ * Creates the UI element for vertical (in-line) drop target.
959
+ */
960
+ _createDropTargetPosition(writer) {
961
+ return writer.createUIElement("span", { class: "ck ck-clipboard-drop-target-position" }, function(domDocument) {
962
+ const domElement = this.toDomElement(domDocument);
963
+ domElement.append("⁠", domDocument.createElement("span"), "⁠");
964
+ return domElement;
965
+ });
966
+ }
967
+ /**
968
+ * Updates the horizontal drop target line.
969
+ */
970
+ _updateDropTargetLine(range) {
971
+ const editing = this.editor.editing;
972
+ const nodeBefore = range.start.nodeBefore;
973
+ const nodeAfter = range.start.nodeAfter;
974
+ const nodeParent = range.start.parent;
975
+ const viewElementBefore = nodeBefore ? editing.mapper.toViewElement(nodeBefore) : null;
976
+ const domElementBefore = viewElementBefore ? editing.view.domConverter.mapViewToDom(viewElementBefore) : null;
977
+ const viewElementAfter = nodeAfter ? editing.mapper.toViewElement(nodeAfter) : null;
978
+ const domElementAfter = viewElementAfter ? editing.view.domConverter.mapViewToDom(viewElementAfter) : null;
979
+ const viewElementParent = editing.mapper.toViewElement(nodeParent);
980
+ if (!viewElementParent) return;
981
+ const domElementParent = editing.view.domConverter.mapViewToDom(viewElementParent);
982
+ const domScrollableRect = this._getScrollableRect(viewElementParent);
983
+ const { scrollX, scrollY } = global.window;
984
+ const rectBefore = domElementBefore ? new Rect(domElementBefore) : null;
985
+ const rectAfter = domElementAfter ? new Rect(domElementAfter) : null;
986
+ const rectParent = new Rect(domElementParent).excludeScrollbarsAndBorders();
987
+ const above = rectBefore ? rectBefore.bottom : rectParent.top;
988
+ const below = rectAfter ? rectAfter.top : rectParent.bottom;
989
+ const parentStyle = global.window.getComputedStyle(domElementParent);
990
+ const top = above <= below ? (above + below) / 2 : below;
991
+ if (domScrollableRect.top < top && top < domScrollableRect.bottom) {
992
+ const left = rectParent.left + parseFloat(parentStyle.paddingLeft);
993
+ const right = rectParent.right - parseFloat(parentStyle.paddingRight);
994
+ const leftClamped = Math.max(left + scrollX, domScrollableRect.left);
995
+ const rightClamped = Math.min(right + scrollX, domScrollableRect.right);
996
+ this._dropTargetLineView.set({
997
+ isVisible: true,
998
+ left: leftClamped,
999
+ top: top + scrollY,
1000
+ width: rightClamped - leftClamped
1001
+ });
1002
+ } else this._dropTargetLineView.isVisible = false;
1003
+ }
1004
+ /**
1005
+ * Finds the closest scrollable element rect for the given view element.
1006
+ */
1007
+ _getScrollableRect(viewElement) {
1008
+ const rootName = viewElement.root.rootName;
1009
+ let domScrollable;
1010
+ if (this._scrollables.has(rootName)) domScrollable = this._scrollables.get(rootName).domElement;
1011
+ else {
1012
+ const domElement = this.editor.editing.view.domConverter.mapViewToDom(viewElement);
1013
+ domScrollable = findClosestScrollableAncestor(domElement);
1014
+ this._domEmitter.listenTo(domScrollable, "scroll", this._reconvertMarkerThrottled, { usePassive: true });
1015
+ const resizeObserver = new ResizeObserver(domScrollable, this._reconvertMarkerThrottled);
1016
+ this._scrollables.set(rootName, {
1017
+ domElement: domScrollable,
1018
+ resizeObserver
1019
+ });
1020
+ }
1021
+ return new Rect(domScrollable).excludeScrollbarsAndBorders();
1022
+ }
1023
+ };
1324
1024
  /**
1325
- * Returns true for elements which should be ignored.
1326
- */ function shouldIgnoreElement(editor, modelElement) {
1327
- const mapper = editor.editing.mapper;
1328
- const domConverter = editor.editing.view.domConverter;
1329
- const viewElement = mapper.toViewElement(modelElement);
1330
- if (!viewElement) {
1331
- return true;
1332
- }
1333
- const domElement = domConverter.mapViewToDom(viewElement);
1334
- return global.window.getComputedStyle(domElement).float != 'none';
1025
+ * Returns fixed selection range for given position and target element.
1026
+ */
1027
+ function findDropTargetRange(editor, targetViewElement, targetViewRanges, clientX, clientY, blockMode, draggedRange) {
1028
+ const model = editor.model;
1029
+ const mapper = editor.editing.mapper;
1030
+ let modelElement = getClosestMappedModelElement(editor, targetViewElement);
1031
+ while (modelElement) {
1032
+ if (!blockMode) {
1033
+ if (model.schema.checkChild(modelElement, "$text")) {
1034
+ if (targetViewRanges) {
1035
+ const targetViewPosition = targetViewRanges[0].start;
1036
+ const targetModelPosition = mapper.toModelPosition(targetViewPosition);
1037
+ if (!draggedRange || Array.from(draggedRange.getItems({ shallow: true })).some((item) => model.schema.checkChild(targetModelPosition, item))) {
1038
+ if (model.schema.checkChild(targetModelPosition, "$text")) return model.createRange(targetModelPosition);
1039
+ else if (targetViewPosition) return findDropTargetRangeForElement(editor, getClosestMappedModelElement(editor, targetViewPosition.parent), clientX, clientY);
1040
+ }
1041
+ }
1042
+ } else if (model.schema.isInline(modelElement)) return findDropTargetRangeForElement(editor, modelElement, clientX, clientY);
1043
+ }
1044
+ if (model.schema.isBlock(modelElement)) return findDropTargetRangeForElement(editor, modelElement, clientX, clientY);
1045
+ else if (model.schema.checkChild(modelElement, "$block")) {
1046
+ const childNodes = Array.from(modelElement.getChildren()).filter((node) => node.is("element") && !shouldIgnoreElement(editor, node));
1047
+ let startIndex = 0;
1048
+ let endIndex = childNodes.length;
1049
+ if (endIndex == 0) return model.createRange(model.createPositionAt(modelElement, "end"));
1050
+ while (startIndex < endIndex - 1) {
1051
+ const middleIndex = Math.floor((startIndex + endIndex) / 2);
1052
+ if (findElementSide(editor, childNodes[middleIndex], clientX, clientY) == "before") endIndex = middleIndex;
1053
+ else startIndex = middleIndex;
1054
+ }
1055
+ return findDropTargetRangeForElement(editor, childNodes[startIndex], clientX, clientY);
1056
+ }
1057
+ modelElement = modelElement.parent;
1058
+ }
1059
+ return null;
1335
1060
  }
1336
1061
  /**
1337
- * Returns target range relative to the given element.
1338
- */ function findDropTargetRangeForElement(editor, modelElement, clientX, clientY) {
1339
- const model = editor.model;
1340
- return model.createRange(model.createPositionAt(modelElement, findElementSide(editor, modelElement, clientX, clientY)));
1062
+ * Returns true for elements which should be ignored.
1063
+ */
1064
+ function shouldIgnoreElement(editor, modelElement) {
1065
+ const mapper = editor.editing.mapper;
1066
+ const domConverter = editor.editing.view.domConverter;
1067
+ const viewElement = mapper.toViewElement(modelElement);
1068
+ if (!viewElement) return true;
1069
+ const domElement = domConverter.mapViewToDom(viewElement);
1070
+ return global.window.getComputedStyle(domElement).float != "none";
1341
1071
  }
1342
1072
  /**
1343
- * Resolves whether drop marker should be before or after the given element.
1344
- */ function findElementSide(editor, modelElement, clientX, clientY) {
1345
- const mapper = editor.editing.mapper;
1346
- const domConverter = editor.editing.view.domConverter;
1347
- const viewElement = mapper.toViewElement(modelElement);
1348
- const domElement = domConverter.mapViewToDom(viewElement);
1349
- const rect = new Rect(domElement);
1350
- if (editor.model.schema.isInline(modelElement)) {
1351
- return clientX < (rect.left + rect.right) / 2 ? 'before' : 'after';
1352
- } else {
1353
- return clientY < (rect.top + rect.bottom) / 2 ? 'before' : 'after';
1354
- }
1073
+ * Returns target range relative to the given element.
1074
+ */
1075
+ function findDropTargetRangeForElement(editor, modelElement, clientX, clientY) {
1076
+ const model = editor.model;
1077
+ return model.createRange(model.createPositionAt(modelElement, findElementSide(editor, modelElement, clientX, clientY)));
1355
1078
  }
1356
1079
  /**
1357
- * Returns the closest model element for the specified view element.
1358
- */ function getClosestMappedModelElement(editor, element) {
1359
- const mapper = editor.editing.mapper;
1360
- const view = editor.editing.view;
1361
- const targetModelElement = mapper.toModelElement(element);
1362
- if (targetModelElement) {
1363
- return targetModelElement;
1364
- }
1365
- // Find mapped ancestor if the target is inside not mapped element (for example inline code element).
1366
- const viewPosition = view.createPositionBefore(element);
1367
- const viewElement = mapper.findMappedViewAncestor(viewPosition);
1368
- return mapper.toModelElement(viewElement);
1080
+ * Resolves whether drop marker should be before or after the given element.
1081
+ */
1082
+ function findElementSide(editor, modelElement, clientX, clientY) {
1083
+ const mapper = editor.editing.mapper;
1084
+ const domConverter = editor.editing.view.domConverter;
1085
+ const viewElement = mapper.toViewElement(modelElement);
1086
+ const domElement = domConverter.mapViewToDom(viewElement);
1087
+ const rect = new Rect(domElement);
1088
+ if (editor.model.schema.isInline(modelElement)) return clientX < (rect.left + rect.right) / 2 ? "before" : "after";
1089
+ else return clientY < (rect.top + rect.bottom) / 2 ? "before" : "after";
1369
1090
  }
1370
1091
  /**
1371
- * Returns the closest scrollable ancestor DOM element.
1372
- *
1373
- * It is assumed that `domNode` is attached to the document.
1374
- */ function findScrollableElement(domNode) {
1375
- let domElement = domNode;
1376
- do {
1377
- domElement = domElement.parentElement;
1378
- const overflow = global.window.getComputedStyle(domElement).overflowY;
1379
- if (overflow == 'auto' || overflow == 'scroll') {
1380
- break;
1381
- }
1382
- }while (domElement.tagName != 'BODY')
1383
- return domElement;
1092
+ * Returns the closest model element for the specified view element.
1093
+ */
1094
+ function getClosestMappedModelElement(editor, element) {
1095
+ const mapper = editor.editing.mapper;
1096
+ const view = editor.editing.view;
1097
+ const targetModelElement = mapper.toModelElement(element);
1098
+ if (targetModelElement) return targetModelElement;
1099
+ const viewPosition = view.createPositionBefore(element);
1100
+ const viewElement = mapper.findMappedViewAncestor(viewPosition);
1101
+ return mapper.toModelElement(viewElement);
1384
1102
  }
1385
1103
 
1386
1104
  /**
1387
- * Integration of a block Drag and Drop support with the block toolbar.
1388
- *
1389
- * @internal
1390
- */ class DragDropBlockToolbar extends Plugin {
1391
- /**
1392
- * Whether current dragging is started by block toolbar button dragging.
1393
- */ _isBlockDragging = false;
1394
- /**
1395
- * DOM Emitter.
1396
- */ _domEmitter = new (DomEmitterMixin())();
1397
- /**
1398
- * @inheritDoc
1399
- */ static get pluginName() {
1400
- return 'DragDropBlockToolbar';
1401
- }
1402
- /**
1403
- * @inheritDoc
1404
- */ static get isOfficialPlugin() {
1405
- return true;
1406
- }
1407
- /**
1408
- * @inheritDoc
1409
- */ init() {
1410
- const editor = this.editor;
1411
- this.listenTo(editor, 'change:isReadOnly', (evt, name, isReadOnly)=>{
1412
- if (isReadOnly) {
1413
- this.forceDisabled('readOnlyMode');
1414
- this._isBlockDragging = false;
1415
- } else {
1416
- this.clearForceDisabled('readOnlyMode');
1417
- }
1418
- });
1419
- if (env.isAndroid) {
1420
- this.forceDisabled('noAndroidSupport');
1421
- }
1422
- if (editor.plugins.has('BlockToolbar')) {
1423
- const blockToolbar = editor.plugins.get('BlockToolbar');
1424
- const element = blockToolbar.buttonView.element;
1425
- this._domEmitter.listenTo(element, 'dragstart', (evt, data)=>this._handleBlockDragStart(data));
1426
- this._domEmitter.listenTo(global.document, 'dragover', (evt, data)=>this._handleBlockDragging(data));
1427
- this._domEmitter.listenTo(global.document, 'drop', (evt, data)=>this._handleBlockDragging(data));
1428
- this._domEmitter.listenTo(global.document, 'dragend', ()=>this._handleBlockDragEnd(), {
1429
- useCapture: true
1430
- });
1431
- if (this.isEnabled) {
1432
- element.setAttribute('draggable', 'true');
1433
- }
1434
- this.on('change:isEnabled', (evt, name, isEnabled)=>{
1435
- element.setAttribute('draggable', isEnabled ? 'true' : 'false');
1436
- });
1437
- }
1438
- }
1439
- /**
1440
- * @inheritDoc
1441
- */ destroy() {
1442
- this._domEmitter.stopListening();
1443
- return super.destroy();
1444
- }
1445
- /**
1446
- * The `dragstart` event handler.
1447
- */ _handleBlockDragStart(domEvent) {
1448
- if (!this.isEnabled) {
1449
- return;
1450
- }
1451
- const model = this.editor.model;
1452
- const selection = model.document.selection;
1453
- const view = this.editor.editing.view;
1454
- const blocks = Array.from(selection.getSelectedBlocks());
1455
- const draggedRange = model.createRange(model.createPositionBefore(blocks[0]), model.createPositionAfter(blocks[blocks.length - 1]));
1456
- model.change((writer)=>writer.setSelection(draggedRange));
1457
- this._isBlockDragging = true;
1458
- view.focus();
1459
- view.getObserver(ClipboardObserver).onDomEvent(domEvent);
1460
- }
1461
- /**
1462
- * The `dragover` and `drop` event handler.
1463
- */ _handleBlockDragging(domEvent) {
1464
- if (!this.isEnabled || !this._isBlockDragging) {
1465
- return;
1466
- }
1467
- const clientX = domEvent.clientX + (this.editor.locale.contentLanguageDirection == 'ltr' ? 100 : -100);
1468
- const clientY = domEvent.clientY;
1469
- const target = document.elementFromPoint(clientX, clientY);
1470
- const view = this.editor.editing.view;
1471
- if (!target || !target.closest('.ck-editor__editable')) {
1472
- return;
1473
- }
1474
- view.getObserver(ClipboardObserver).onDomEvent({
1475
- ...domEvent,
1476
- type: domEvent.type,
1477
- dataTransfer: domEvent.dataTransfer,
1478
- target,
1479
- clientX,
1480
- clientY,
1481
- preventDefault: ()=>domEvent.preventDefault(),
1482
- stopPropagation: ()=>domEvent.stopPropagation()
1483
- });
1484
- }
1485
- /**
1486
- * The `dragend` event handler.
1487
- */ _handleBlockDragEnd() {
1488
- this._isBlockDragging = false;
1489
- }
1105
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1106
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1107
+ */
1108
+ /**
1109
+ * @module clipboard/dragdropblocktoolbar
1110
+ */
1111
+ /**
1112
+ * Integration of a block Drag and Drop support with the block toolbar.
1113
+ *
1114
+ * @internal
1115
+ */
1116
+ var DragDropBlockToolbar = class extends Plugin {
1117
+ /**
1118
+ * Whether current dragging is started by block toolbar button dragging.
1119
+ */
1120
+ _isBlockDragging = false;
1121
+ /**
1122
+ * DOM Emitter.
1123
+ */
1124
+ _domEmitter = new (DomEmitterMixin())();
1125
+ /**
1126
+ * @inheritDoc
1127
+ */
1128
+ static get pluginName() {
1129
+ return "DragDropBlockToolbar";
1130
+ }
1131
+ /**
1132
+ * @inheritDoc
1133
+ */
1134
+ static get isOfficialPlugin() {
1135
+ return true;
1136
+ }
1137
+ /**
1138
+ * @inheritDoc
1139
+ */
1140
+ init() {
1141
+ const editor = this.editor;
1142
+ this.listenTo(editor, "change:isReadOnly", (evt, name, isReadOnly) => {
1143
+ if (isReadOnly) {
1144
+ this.forceDisabled("readOnlyMode");
1145
+ this._isBlockDragging = false;
1146
+ } else this.clearForceDisabled("readOnlyMode");
1147
+ });
1148
+ if (env.isAndroid) this.forceDisabled("noAndroidSupport");
1149
+ if (editor.plugins.has("BlockToolbar")) {
1150
+ const element = editor.plugins.get("BlockToolbar").buttonView.element;
1151
+ this._domEmitter.listenTo(element, "dragstart", (evt, data) => this._handleBlockDragStart(data));
1152
+ this._domEmitter.listenTo(global.document, "dragover", (evt, data) => this._handleBlockDragging(data));
1153
+ this._domEmitter.listenTo(global.document, "drop", (evt, data) => this._handleBlockDragging(data));
1154
+ this._domEmitter.listenTo(global.document, "dragend", () => this._handleBlockDragEnd(), { useCapture: true });
1155
+ if (this.isEnabled) element.setAttribute("draggable", "true");
1156
+ this.on("change:isEnabled", (evt, name, isEnabled) => {
1157
+ element.setAttribute("draggable", isEnabled ? "true" : "false");
1158
+ });
1159
+ }
1160
+ }
1161
+ /**
1162
+ * @inheritDoc
1163
+ */
1164
+ destroy() {
1165
+ this._domEmitter.stopListening();
1166
+ return super.destroy();
1167
+ }
1168
+ /**
1169
+ * The `dragstart` event handler.
1170
+ */
1171
+ _handleBlockDragStart(domEvent) {
1172
+ if (!this.isEnabled) return;
1173
+ const model = this.editor.model;
1174
+ const selection = model.document.selection;
1175
+ const view = this.editor.editing.view;
1176
+ const blocks = Array.from(selection.getSelectedBlocks());
1177
+ const draggedRange = model.createRange(model.createPositionBefore(blocks[0]), model.createPositionAfter(blocks[blocks.length - 1]));
1178
+ model.change((writer) => writer.setSelection(draggedRange));
1179
+ this._isBlockDragging = true;
1180
+ view.focus();
1181
+ view.getObserver(ClipboardObserver).onDomEvent(domEvent);
1182
+ }
1183
+ /**
1184
+ * The `dragover` and `drop` event handler.
1185
+ */
1186
+ _handleBlockDragging(domEvent) {
1187
+ if (!this.isEnabled || !this._isBlockDragging) return;
1188
+ const clientX = domEvent.clientX + (this.editor.locale.contentLanguageDirection == "ltr" ? 100 : -100);
1189
+ const clientY = domEvent.clientY;
1190
+ const view = this.editor.editing.view;
1191
+ const target = getTargetAcrossRoots(view, clientX, clientY);
1192
+ if (!target) return;
1193
+ view.getObserver(ClipboardObserver).onDomEvent({
1194
+ ...domEvent,
1195
+ type: domEvent.type,
1196
+ dataTransfer: domEvent.dataTransfer,
1197
+ target,
1198
+ clientX,
1199
+ clientY,
1200
+ preventDefault: () => domEvent.preventDefault(),
1201
+ stopPropagation: () => domEvent.stopPropagation()
1202
+ });
1203
+ }
1204
+ /**
1205
+ * The `dragend` event handler.
1206
+ */
1207
+ _handleBlockDragEnd() {
1208
+ this._isBlockDragging = false;
1209
+ }
1210
+ };
1211
+ /**
1212
+ * Returns the topmost `.ck-editor__editable`-contained element at the given point, resolved across
1213
+ * every DOM root the editing view knows about (including open and closed shadow roots).
1214
+ */
1215
+ function getTargetAcrossRoots(view, x, y) {
1216
+ const shadowRoots = /* @__PURE__ */ new Set();
1217
+ for (const domRoot of view.domRoots.values()) {
1218
+ const root = domRoot.getRootNode();
1219
+ if (isShadowRoot(root)) shadowRoots.add(root);
1220
+ }
1221
+ const target = getElementFromPoint(x, y, Array.from(shadowRoots));
1222
+ return target && target.closest(".ck-editor__editable") ? target : null;
1490
1223
  }
1491
1224
 
1492
- // Drag and drop events overview:
1493
- //
1494
- // ┌──────────────────┐
1495
- // │ mousedown │ Sets the draggable attribute.
1496
- // └─────────┬────────┘
1497
- // │
1498
- // └─────────────────────┐
1499
- // │ │
1500
- // │ ┌─────────V────────┐
1501
- // │ │ mouseup │ Dragging did not start, removes the draggable attribute.
1502
- // │ └──────────────────┘
1503
- // │
1504
- // ┌─────────V────────┐ Retrieves the selected model.DocumentFragment
1505
- // │ dragstart │ and converts it to view.DocumentFragment.
1506
- // └─────────┬────────┘
1507
- // │
1508
- // ┌─────────V────────┐ Processes view.DocumentFragment to text/html and text/plain
1509
- // │ clipboardOutput │ and stores the results in data.dataTransfer.
1510
- // └─────────┬────────┘
1511
- // │
1512
- // │ DOM dragover
1513
- // ┌────────────┐
1514
- // │ │
1515
- // ┌─────────V────────┐ │
1516
- // │ dragging │ │ Updates the drop target marker.
1517
- // └─────────┬────────┘ │
1518
- // │ │
1519
- // ┌─────────────└────────────┘
1520
- // │ │ │
1521
- // │ ┌─────────V────────┐ │
1522
- // │ │ dragleave │ │ Removes the drop target marker.
1523
- // │ └─────────┬────────┘ │
1524
- // │ │ │
1525
- // ┌───│─────────────┘ │
1526
- // │ │ │ │
1527
- // │ │ ┌─────────V────────┐ │
1528
- // │ │ │ dragenter │ │ Focuses the editor view.
1529
- // │ │ └─────────┬────────┘ │
1530
- // │ │ │ │
1531
- // │ │ └────────────┘
1532
- // │ │
1533
- // │ └─────────────┐
1534
- // │ │ │
1535
- // │ │ ┌─────────V────────┐
1536
- // └───┐ │ drop │ (The default handler of the clipboard pipeline).
1537
- // │ └─────────┬────────┘
1538
- // │ │
1539
- // │ ┌─────────V────────┐ Resolves the final data.targetRanges.
1540
- // │ │ clipboardInput │ Aborts if dropping on dragged content.
1541
- // │ └─────────┬────────┘
1542
- // │ │
1543
- // │ ┌─────────V────────┐
1544
- // │ │ clipboardInput │ (The default handler of the clipboard pipeline).
1545
- // │ └─────────┬────────┘
1546
- // │ │
1547
- // │ ┌───────────V───────────┐
1548
- // │ │ inputTransformation │ (The default handler of the clipboard pipeline).
1549
- // │ └───────────┬───────────┘
1550
- // │ │
1551
- // │ ┌──────────V──────────┐
1552
- // │ │ contentInsertion │ Updates the document selection to drop range.
1553
- // │ └──────────┬──────────┘
1554
- // │ │
1555
- // │ ┌──────────V──────────┐
1556
- // │ │ contentInsertion │ (The default handler of the clipboard pipeline).
1557
- // │ └──────────┬──────────┘
1558
- // │ │
1559
- // │ ┌──────────V──────────┐
1560
- // │ │ contentInsertion │ Removes the content from the original range if the insertion was successful.
1561
- // │ └──────────┬──────────┘
1562
- // │ │
1563
- // └─────────────┐
1564
- // │
1565
- // ┌─────────V────────┐
1566
- // │ dragend │ Removes the drop marker and cleans the state.
1567
- // └──────────────────┘
1568
- //
1569
1225
  /**
1570
- * The drag and drop feature. It works on top of the {@link module:clipboard/clipboardpipeline~ClipboardPipeline}.
1571
- *
1572
- * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
1573
- *
1574
- * @internal
1575
- */ class DragDrop extends Plugin {
1576
- /**
1577
- * The live range over the original content that is being dragged.
1578
- */ _draggedRange;
1579
- /**
1580
- * The UID of current dragging that is used to verify if the drop started in the same editor as the drag start.
1581
- *
1582
- * **Note**: This is a workaround for broken 'dragend' events (they are not fired if the source text node got removed).
1583
- */ _draggingUid;
1584
- /**
1585
- * The reference to the model element that currently has a `draggable` attribute set (it is set while dragging).
1586
- */ _draggableElement;
1587
- /**
1588
- * A delayed callback removing draggable attributes.
1589
- */ _clearDraggableAttributesDelayed = delay(()=>this._clearDraggableAttributes(), 40);
1590
- /**
1591
- * Whether the dragged content can be dropped only in block context.
1592
- */ // TODO handle drag from other editor instance
1593
- // TODO configure to use block, inline or both
1594
- _blockMode = false;
1595
- /**
1596
- * DOM Emitter.
1597
- */ _domEmitter = new (DomEmitterMixin())();
1598
- /**
1599
- * The DOM element used to generate dragged preview image.
1600
- */ _previewContainer;
1601
- /**
1602
- * @inheritDoc
1603
- */ static get pluginName() {
1604
- return 'DragDrop';
1605
- }
1606
- /**
1607
- * @inheritDoc
1608
- */ static get isOfficialPlugin() {
1609
- return true;
1610
- }
1611
- /**
1612
- * @inheritDoc
1613
- */ static get requires() {
1614
- return [
1615
- ClipboardPipeline,
1616
- Widget,
1617
- DragDropTarget,
1618
- DragDropBlockToolbar
1619
- ];
1620
- }
1621
- /**
1622
- * @inheritDoc
1623
- */ init() {
1624
- const editor = this.editor;
1625
- const view = editor.editing.view;
1626
- this._draggedRange = null;
1627
- this._draggingUid = '';
1628
- this._draggableElement = null;
1629
- view.addObserver(ClipboardObserver);
1630
- view.addObserver(PointerObserver);
1631
- this._setupDragging();
1632
- this._setupContentInsertionIntegration();
1633
- this._setupClipboardInputIntegration();
1634
- this._setupDraggableAttributeHandling();
1635
- this.listenTo(editor, 'change:isReadOnly', (evt, name, isReadOnly)=>{
1636
- if (isReadOnly) {
1637
- this.forceDisabled('readOnlyMode');
1638
- } else {
1639
- this.clearForceDisabled('readOnlyMode');
1640
- }
1641
- });
1642
- this.on('change:isEnabled', (evt, name, isEnabled)=>{
1643
- if (!isEnabled) {
1644
- this._finalizeDragging(false);
1645
- }
1646
- });
1647
- if (env.isAndroid) {
1648
- this.forceDisabled('noAndroidSupport');
1649
- }
1650
- }
1651
- /**
1652
- * @inheritDoc
1653
- */ destroy() {
1654
- if (this._draggedRange) {
1655
- this._draggedRange.detach();
1656
- this._draggedRange = null;
1657
- }
1658
- if (this._previewContainer) {
1659
- this._previewContainer.remove();
1660
- }
1661
- this._domEmitter.stopListening();
1662
- this._clearDraggableAttributesDelayed.cancel();
1663
- return super.destroy();
1664
- }
1665
- /**
1666
- * Drag and drop events handling.
1667
- */ _setupDragging() {
1668
- const editor = this.editor;
1669
- const model = editor.model;
1670
- const view = editor.editing.view;
1671
- const viewDocument = view.document;
1672
- const dragDropTarget = editor.plugins.get(DragDropTarget);
1673
- // The handler for the drag start; it is responsible for setting data transfer object.
1674
- this.listenTo(viewDocument, 'dragstart', (evt, data)=>{
1675
- // Don't drag the editable element itself.
1676
- if (data.target?.is('editableElement')) {
1677
- data.preventDefault();
1678
- return;
1679
- }
1680
- this._prepareDraggedRange(data.target);
1681
- if (!this._draggedRange) {
1682
- data.preventDefault();
1683
- return;
1684
- }
1685
- this._draggingUid = uid();
1686
- const canEditAtDraggedRange = this.isEnabled && editor.model.canEditAt(this._draggedRange);
1687
- data.dataTransfer.effectAllowed = canEditAtDraggedRange ? 'copyMove' : 'copy';
1688
- data.dataTransfer.setData('application/ckeditor5-dragging-uid', this._draggingUid);
1689
- const draggedSelection = model.createSelection(this._draggedRange.toRange());
1690
- const clipboardPipeline = this.editor.plugins.get('ClipboardPipeline');
1691
- clipboardPipeline._fireOutputTransformationEvent(data.dataTransfer, draggedSelection, 'dragstart');
1692
- const { dataTransfer, domTarget, domEvent } = data;
1693
- const { clientX } = domEvent;
1694
- this._updatePreview({
1695
- dataTransfer,
1696
- domTarget,
1697
- clientX
1698
- });
1699
- data.stopPropagation();
1700
- if (!canEditAtDraggedRange) {
1701
- this._draggedRange.detach();
1702
- this._draggedRange = null;
1703
- this._draggingUid = '';
1704
- }
1705
- }, {
1706
- priority: 'low'
1707
- });
1708
- // The handler for finalizing drag and drop. It should always be triggered after dragging completes
1709
- // even if it was completed in a different application.
1710
- // Note: This is not fired if source text node got removed while downcasting a marker.
1711
- this.listenTo(viewDocument, 'dragend', (evt, data)=>{
1712
- this._finalizeDragging(!data.dataTransfer.isCanceled && data.dataTransfer.dropEffect == 'move');
1713
- }, {
1714
- priority: 'low'
1715
- });
1716
- // Reset block dragging mode even if dropped outside the editable.
1717
- this._domEmitter.listenTo(global.document, 'dragend', ()=>{
1718
- this._blockMode = false;
1719
- }, {
1720
- useCapture: true
1721
- });
1722
- // Dragging over the editable.
1723
- this.listenTo(viewDocument, 'dragenter', ()=>{
1724
- if (!this.isEnabled) {
1725
- return;
1726
- }
1727
- view.focus();
1728
- });
1729
- // Dragging out of the editable.
1730
- this.listenTo(viewDocument, 'dragleave', ()=>{
1731
- // We do not know if the mouse left the editor or just some element in it, so let us wait a few milliseconds
1732
- // to check if 'dragover' is not fired.
1733
- dragDropTarget.removeDropMarkerDelayed();
1734
- });
1735
- // Handler for moving dragged content over the target area.
1736
- this.listenTo(viewDocument, 'dragging', (evt, data)=>{
1737
- if (!this.isEnabled) {
1738
- data.dataTransfer.dropEffect = 'none';
1739
- return;
1740
- }
1741
- const { clientX, clientY } = data.domEvent;
1742
- const targetRange = dragDropTarget.updateDropMarker(data.target, data.targetRanges, clientX, clientY, this._blockMode, this._draggedRange);
1743
- // Do not allow dropping if there is no valid target range (e.g., dropping on non-editable place).
1744
- if (!targetRange) {
1745
- data.dataTransfer.dropEffect = 'none';
1746
- return;
1747
- }
1748
- // If this is content being dragged from another editor, moving out of current editor instance
1749
- // is not possible until 'dragend' event case will be fixed.
1750
- if (!this._draggedRange) {
1751
- data.dataTransfer.dropEffect = 'copy';
1752
- }
1753
- // In Firefox it is already set and effect allowed remains the same as originally set.
1754
- if (!env.isGecko) {
1755
- if (data.dataTransfer.effectAllowed == 'copy') {
1756
- data.dataTransfer.dropEffect = 'copy';
1757
- } else if ([
1758
- 'all',
1759
- 'copyMove'
1760
- ].includes(data.dataTransfer.effectAllowed)) {
1761
- data.dataTransfer.dropEffect = 'move';
1762
- }
1763
- }
1764
- evt.stop();
1765
- }, {
1766
- priority: 'low'
1767
- });
1768
- }
1769
- /**
1770
- * Integration with the `clipboardInput` event.
1771
- */ _setupClipboardInputIntegration() {
1772
- const editor = this.editor;
1773
- const view = editor.editing.view;
1774
- const viewDocument = view.document;
1775
- const dragDropTarget = editor.plugins.get(DragDropTarget);
1776
- // Update the event target ranges and abort dropping if dropping over itself.
1777
- this.listenTo(viewDocument, 'clipboardInput', (evt, data)=>{
1778
- if (data.method != 'drop') {
1779
- return;
1780
- }
1781
- const { clientX, clientY } = data.domEvent;
1782
- const targetRange = dragDropTarget.getFinalDropRange(data.target, data.targetRanges, clientX, clientY, this._blockMode, this._draggedRange);
1783
- if (!targetRange) {
1784
- this._finalizeDragging(false);
1785
- evt.stop();
1786
- return;
1787
- }
1788
- // Since we cannot rely on the drag end event, we must check if the local drag range is from the current drag and drop
1789
- // or it is from some previous not cleared one.
1790
- if (this._draggedRange && this._draggingUid != data.dataTransfer.getData('application/ckeditor5-dragging-uid')) {
1791
- this._draggedRange.detach();
1792
- this._draggedRange = null;
1793
- this._draggingUid = '';
1794
- }
1795
- // Do not do anything if some content was dragged within the same document to the same position.
1796
- const isMove = getFinalDropEffect(data.dataTransfer) == 'move';
1797
- if (isMove && this._draggedRange && this._draggedRange.containsRange(targetRange, true)) {
1798
- this._finalizeDragging(false);
1799
- evt.stop();
1800
- return;
1801
- }
1802
- // Override the target ranges with the one adjusted to the best one for a drop.
1803
- data.targetRanges = [
1804
- editor.editing.mapper.toViewRange(targetRange)
1805
- ];
1806
- }, {
1807
- priority: 'high'
1808
- });
1809
- }
1810
- /**
1811
- * Integration with the `contentInsertion` event of the clipboard pipeline.
1812
- */ _setupContentInsertionIntegration() {
1813
- const clipboardPipeline = this.editor.plugins.get(ClipboardPipeline);
1814
- clipboardPipeline.on('contentInsertion', (evt, data)=>{
1815
- if (!this.isEnabled || data.method !== 'drop') {
1816
- return;
1817
- }
1818
- // Update the selection to the target range in the same change block to avoid selection post-fixing
1819
- // and to be able to clone text attributes for plain text dropping.
1820
- const ranges = data.targetRanges.map((viewRange)=>this.editor.editing.mapper.toModelRange(viewRange));
1821
- this.editor.model.change((writer)=>writer.setSelection(ranges));
1822
- }, {
1823
- priority: 'high'
1824
- });
1825
- clipboardPipeline.on('contentInsertion', (evt, data)=>{
1826
- if (!this.isEnabled || data.method !== 'drop') {
1827
- return;
1828
- }
1829
- // Remove dragged range content, remove markers, clean after dragging.
1830
- const isMove = getFinalDropEffect(data.dataTransfer) == 'move';
1831
- // Whether any content was inserted (insertion might fail if the schema is disallowing some elements
1832
- // (for example an image caption allows only the content of a block but not blocks themselves.
1833
- // Some integrations might not return valid range (i.e., table pasting).
1834
- const isSuccess = !data.resultRange || !data.resultRange.isCollapsed;
1835
- this._finalizeDragging(isSuccess && isMove);
1836
- }, {
1837
- priority: 'lowest'
1838
- });
1839
- }
1840
- /**
1841
- * Adds listeners that add the `draggable` attribute to the elements while the mouse button is down so the dragging could start.
1842
- */ _setupDraggableAttributeHandling() {
1843
- const editor = this.editor;
1844
- const view = editor.editing.view;
1845
- const viewDocument = view.document;
1846
- // Add the 'draggable' attribute to the widget while pressing the selection handle.
1847
- // This is required for widgets to be draggable. In Chrome it will enable dragging text nodes.
1848
- this.listenTo(viewDocument, 'pointerdown', (evt, data)=>{
1849
- // The lack of data can be caused by editor tests firing fake mouse events. This should not occur
1850
- // in real-life scenarios but this greatly simplifies editor tests that would otherwise fail a lot.
1851
- if (env.isAndroid || !data) {
1852
- return;
1853
- }
1854
- this._clearDraggableAttributesDelayed.cancel();
1855
- // Check if this is a mousedown over the widget (but not a nested editable).
1856
- let draggableElement = findDraggableWidget(data.target);
1857
- // Note: There is a limitation that if more than a widget is selected (a widget and some text)
1858
- // and dragging starts on the widget, then only the widget is dragged.
1859
- // If this was not a widget then we should check if we need to drag some text content.
1860
- // In Chrome set a 'draggable' attribute on closest editable to allow immediate dragging of the selected text range.
1861
- // In Firefox this is not needed. In Safari it makes the whole editable draggable (not just textual content).
1862
- // Disabled in read-only mode because draggable="true" + contenteditable="false" results
1863
- // in not firing selectionchange event ever, which makes the selection stuck in read-only mode.
1864
- if (env.isBlink && !editor.isReadOnly && !draggableElement && !viewDocument.selection.isCollapsed) {
1865
- const selectedElement = viewDocument.selection.getSelectedElement();
1866
- if (!selectedElement || !isWidget(selectedElement)) {
1867
- draggableElement = viewDocument.selection.editableElement;
1868
- }
1869
- }
1870
- if (draggableElement) {
1871
- view.change((writer)=>{
1872
- writer.setAttribute('draggable', 'true', draggableElement);
1873
- });
1874
- // Keep the reference to the model element in case the view element gets removed while dragging.
1875
- this._draggableElement = editor.editing.mapper.toModelElement(draggableElement);
1876
- }
1877
- });
1878
- // Remove the draggable attribute in case no dragging started (only mousedown + mouseup).
1879
- this.listenTo(viewDocument, 'pointerup', ()=>{
1880
- if (!env.isAndroid) {
1881
- this._clearDraggableAttributesDelayed();
1882
- }
1883
- });
1884
- }
1885
- /**
1886
- * Removes the `draggable` attribute from the element that was used for dragging.
1887
- */ _clearDraggableAttributes() {
1888
- const editing = this.editor.editing;
1889
- editing.view.change((writer)=>{
1890
- // Remove 'draggable' attribute.
1891
- if (this._draggableElement && this._draggableElement.root.rootName != '$graveyard') {
1892
- writer.removeAttribute('draggable', editing.mapper.toViewElement(this._draggableElement));
1893
- }
1894
- this._draggableElement = null;
1895
- });
1896
- }
1897
- /**
1898
- * Deletes the dragged content from its original range and clears the dragging state.
1899
- *
1900
- * @param moved Whether the move succeeded.
1901
- */ _finalizeDragging(moved) {
1902
- const editor = this.editor;
1903
- const model = editor.model;
1904
- const dragDropTarget = editor.plugins.get(DragDropTarget);
1905
- dragDropTarget.removeDropMarker();
1906
- this._clearDraggableAttributes();
1907
- if (editor.plugins.has('WidgetToolbarRepository')) {
1908
- const widgetToolbarRepository = editor.plugins.get('WidgetToolbarRepository');
1909
- widgetToolbarRepository.clearForceDisabled('dragDrop');
1910
- }
1911
- this._draggingUid = '';
1912
- if (this._previewContainer) {
1913
- this._previewContainer.remove();
1914
- this._previewContainer = undefined;
1915
- }
1916
- if (!this._draggedRange) {
1917
- return;
1918
- }
1919
- // Delete moved content.
1920
- if (moved && this.isEnabled) {
1921
- model.change((writer)=>{
1922
- const selection = model.createSelection(this._draggedRange);
1923
- model.deleteContent(selection, {
1924
- doNotAutoparagraph: true
1925
- });
1926
- // Check result selection if it does not require auto-paragraphing of empty container.
1927
- const selectionParent = selection.getFirstPosition().parent;
1928
- if (selectionParent.isEmpty && !model.schema.checkChild(selectionParent, '$text') && model.schema.checkChild(selectionParent, 'paragraph')) {
1929
- writer.insertElement('paragraph', selectionParent, 0);
1930
- }
1931
- });
1932
- }
1933
- this._draggedRange.detach();
1934
- this._draggedRange = null;
1935
- }
1936
- /**
1937
- * Sets the dragged source range based on event target and document selection.
1938
- */ _prepareDraggedRange(target) {
1939
- const editor = this.editor;
1940
- const model = editor.model;
1941
- const selection = model.document.selection;
1942
- // Check if this is dragstart over the widget (but not a nested editable).
1943
- const draggableWidget = target ? findDraggableWidget(target) : null;
1944
- if (draggableWidget) {
1945
- const modelElement = editor.editing.mapper.toModelElement(draggableWidget);
1946
- this._draggedRange = ModelLiveRange.fromRange(model.createRangeOn(modelElement));
1947
- this._blockMode = model.schema.isBlock(modelElement);
1948
- // Disable toolbars so they won't obscure the drop area.
1949
- if (editor.plugins.has('WidgetToolbarRepository')) {
1950
- const widgetToolbarRepository = editor.plugins.get('WidgetToolbarRepository');
1951
- widgetToolbarRepository.forceDisabled('dragDrop');
1952
- }
1953
- return;
1954
- }
1955
- // If this was not a widget we should check if we need to drag some text content.
1956
- if (selection.isCollapsed && !selection.getFirstPosition().parent.isEmpty) {
1957
- return;
1958
- }
1959
- const blocks = Array.from(selection.getSelectedBlocks());
1960
- const draggedRange = selection.getFirstRange();
1961
- if (blocks.length == 0) {
1962
- this._draggedRange = ModelLiveRange.fromRange(draggedRange);
1963
- return;
1964
- }
1965
- const blockRange = getRangeIncludingFullySelectedParents(model, blocks);
1966
- if (blocks.length > 1) {
1967
- this._draggedRange = ModelLiveRange.fromRange(blockRange);
1968
- this._blockMode = true;
1969
- // TODO block mode for dragging from outside editor? or inline? or both?
1970
- } else if (blocks.length == 1) {
1971
- const touchesBlockEdges = draggedRange.start.isTouching(blockRange.start) && draggedRange.end.isTouching(blockRange.end);
1972
- this._draggedRange = ModelLiveRange.fromRange(touchesBlockEdges ? blockRange : draggedRange);
1973
- this._blockMode = touchesBlockEdges;
1974
- }
1975
- model.change((writer)=>writer.setSelection(this._draggedRange.toRange()));
1976
- }
1977
- /**
1978
- * Updates the dragged preview image.
1979
- */ _updatePreview({ dataTransfer, domTarget, clientX }) {
1980
- const view = this.editor.editing.view;
1981
- const editable = view.document.selection.editableElement;
1982
- const domEditable = view.domConverter.mapViewToDom(editable);
1983
- const computedStyle = global.window.getComputedStyle(domEditable);
1984
- if (!this._previewContainer) {
1985
- this._previewContainer = createElement(global.document, 'div', {
1986
- style: 'position: fixed; left: -999999px;'
1987
- });
1988
- global.document.body.appendChild(this._previewContainer);
1989
- } else if (this._previewContainer.firstElementChild) {
1990
- this._previewContainer.removeChild(this._previewContainer.firstElementChild);
1991
- }
1992
- const preview = createElement(global.document, 'div');
1993
- preview.className = 'ck ck-content ck-clipboard-preview';
1994
- const domRect = new Rect(domEditable);
1995
- const domEditablePaddingLeft = parseFloat(computedStyle.paddingLeft);
1996
- const domEditablePaddingRight = parseFloat(computedStyle.paddingRight);
1997
- const editableWidth = parseFloat(computedStyle.width) - domEditablePaddingLeft - domEditablePaddingRight;
1998
- // Dragging by the drag handle outside editable element.
1999
- if (!domEditable.contains(domTarget)) {
2000
- if (!env.isiOS) {
2001
- const offsetLeft = domRect.left - clientX + domEditablePaddingLeft;
2002
- preview.style.width = `${editableWidth + offsetLeft}px`;
2003
- preview.style.paddingLeft = `${offsetLeft}px`;
2004
- } else {
2005
- // Without a padding as on iOS preview have a background and padding would be visible.
2006
- preview.style.width = `${editableWidth}px`;
2007
- preview.style.backgroundColor = 'var(--ck-color-base-background)';
2008
- }
2009
- } else if (env.isiOS) {
2010
- // Custom preview for iOS. Note that it must have some dimensions for iOS to start dragging element.
2011
- preview.style.maxWidth = `${editableWidth}px`;
2012
- preview.style.padding = '10px';
2013
- preview.style.minWidth = '200px';
2014
- preview.style.minHeight = '20px';
2015
- preview.style.boxSizing = 'border-box';
2016
- preview.style.backgroundColor = 'var(--ck-color-base-background)';
2017
- } else {
2018
- // If domTarget is inside the editable root, browsers will display the preview correctly by themselves.
2019
- return;
2020
- }
2021
- view.domConverter.setContentOf(preview, dataTransfer.getData('text/html'));
2022
- dataTransfer.setDragImage(preview, 0, 0);
2023
- this._previewContainer.appendChild(preview);
2024
- }
2025
- }
1226
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1227
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1228
+ */
1229
+ /**
1230
+ * @module clipboard/dragdrop
1231
+ */
2026
1232
  /**
2027
- * Returns the drop effect that should be a result of dragging the content.
2028
- * This function is handling a quirk when checking the effect in the 'drop' DOM event.
2029
- */ function getFinalDropEffect(dataTransfer) {
2030
- if (env.isGecko) {
2031
- return dataTransfer.dropEffect;
2032
- }
2033
- return [
2034
- 'all',
2035
- 'copyMove'
2036
- ].includes(dataTransfer.effectAllowed) ? 'move' : 'copy';
1233
+ * The drag and drop feature. It works on top of the {@link module:clipboard/clipboardpipeline~ClipboardPipeline}.
1234
+ *
1235
+ * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
1236
+ *
1237
+ * @internal
1238
+ */
1239
+ var DragDrop = class extends Plugin {
1240
+ /**
1241
+ * The live range over the original content that is being dragged.
1242
+ */
1243
+ _draggedRange;
1244
+ /**
1245
+ * The UID of current dragging that is used to verify if the drop started in the same editor as the drag start.
1246
+ *
1247
+ * **Note**: This is a workaround for broken 'dragend' events (they are not fired if the source text node got removed).
1248
+ */
1249
+ _draggingUid;
1250
+ /**
1251
+ * The reference to the model element that currently has a `draggable` attribute set (it is set while dragging).
1252
+ */
1253
+ _draggableElement;
1254
+ /**
1255
+ * A delayed callback removing draggable attributes.
1256
+ */
1257
+ _clearDraggableAttributesDelayed = delay(() => this._clearDraggableAttributes(), 40);
1258
+ /**
1259
+ * Whether the dragged content can be dropped only in block context.
1260
+ */
1261
+ _blockMode = false;
1262
+ /**
1263
+ * DOM Emitter.
1264
+ */
1265
+ _domEmitter = new (DomEmitterMixin())();
1266
+ /**
1267
+ * The DOM element used to generate dragged preview image.
1268
+ */
1269
+ _previewContainer;
1270
+ /**
1271
+ * @inheritDoc
1272
+ */
1273
+ static get pluginName() {
1274
+ return "DragDrop";
1275
+ }
1276
+ /**
1277
+ * @inheritDoc
1278
+ */
1279
+ static get isOfficialPlugin() {
1280
+ return true;
1281
+ }
1282
+ /**
1283
+ * @inheritDoc
1284
+ */
1285
+ static get requires() {
1286
+ return [
1287
+ ClipboardPipeline,
1288
+ Widget,
1289
+ DragDropTarget,
1290
+ DragDropBlockToolbar
1291
+ ];
1292
+ }
1293
+ /**
1294
+ * @inheritDoc
1295
+ */
1296
+ init() {
1297
+ const editor = this.editor;
1298
+ const view = editor.editing.view;
1299
+ this._draggedRange = null;
1300
+ this._draggingUid = "";
1301
+ this._draggableElement = null;
1302
+ view.addObserver(ClipboardObserver);
1303
+ view.addObserver(PointerObserver);
1304
+ this._setupDragging();
1305
+ this._setupContentInsertionIntegration();
1306
+ this._setupClipboardInputIntegration();
1307
+ this._setupDraggableAttributeHandling();
1308
+ this.listenTo(editor, "change:isReadOnly", (evt, name, isReadOnly) => {
1309
+ if (isReadOnly) this.forceDisabled("readOnlyMode");
1310
+ else this.clearForceDisabled("readOnlyMode");
1311
+ });
1312
+ this.on("change:isEnabled", (evt, name, isEnabled) => {
1313
+ if (!isEnabled) this._finalizeDragging(false);
1314
+ });
1315
+ if (env.isAndroid) this.forceDisabled("noAndroidSupport");
1316
+ }
1317
+ /**
1318
+ * @inheritDoc
1319
+ */
1320
+ destroy() {
1321
+ if (this._draggedRange) {
1322
+ this._draggedRange.detach();
1323
+ this._draggedRange = null;
1324
+ }
1325
+ if (this._previewContainer) this._previewContainer.remove();
1326
+ this._domEmitter.stopListening();
1327
+ this._clearDraggableAttributesDelayed.cancel();
1328
+ return super.destroy();
1329
+ }
1330
+ /**
1331
+ * Drag and drop events handling.
1332
+ */
1333
+ _setupDragging() {
1334
+ const editor = this.editor;
1335
+ const model = editor.model;
1336
+ const view = editor.editing.view;
1337
+ const viewDocument = view.document;
1338
+ const dragDropTarget = editor.plugins.get(DragDropTarget);
1339
+ this.listenTo(viewDocument, "dragstart", (evt, data) => {
1340
+ if (data.target?.is("editableElement")) {
1341
+ data.preventDefault();
1342
+ return;
1343
+ }
1344
+ this._prepareDraggedRange(data.target);
1345
+ if (!this._draggedRange) {
1346
+ data.preventDefault();
1347
+ return;
1348
+ }
1349
+ this._draggingUid = uid();
1350
+ const canEditAtDraggedRange = this.isEnabled && editor.model.canEditAt(this._draggedRange);
1351
+ data.dataTransfer.effectAllowed = canEditAtDraggedRange ? "copyMove" : "copy";
1352
+ data.dataTransfer.setData("application/ckeditor5-dragging-uid", this._draggingUid);
1353
+ const draggedSelection = model.createSelection(this._draggedRange.toRange());
1354
+ this.editor.plugins.get("ClipboardPipeline")._fireOutputTransformationEvent(data.dataTransfer, draggedSelection, "dragstart");
1355
+ const { dataTransfer, domTarget, domEvent } = data;
1356
+ const { clientX } = domEvent;
1357
+ this._updatePreview({
1358
+ dataTransfer,
1359
+ domTarget,
1360
+ clientX
1361
+ });
1362
+ data.stopPropagation();
1363
+ if (!canEditAtDraggedRange) {
1364
+ this._draggedRange.detach();
1365
+ this._draggedRange = null;
1366
+ this._draggingUid = "";
1367
+ }
1368
+ }, { priority: "low" });
1369
+ this.listenTo(viewDocument, "dragend", (evt, data) => {
1370
+ this._finalizeDragging(!data.dataTransfer.isCanceled && data.dataTransfer.dropEffect == "move");
1371
+ }, { priority: "low" });
1372
+ this._domEmitter.listenTo(global.document, "dragend", () => {
1373
+ this._blockMode = false;
1374
+ }, { useCapture: true });
1375
+ this.listenTo(viewDocument, "dragenter", () => {
1376
+ if (!this.isEnabled) return;
1377
+ view.focus();
1378
+ });
1379
+ this.listenTo(viewDocument, "dragleave", () => {
1380
+ dragDropTarget.removeDropMarkerDelayed();
1381
+ });
1382
+ this.listenTo(viewDocument, "dragging", (evt, data) => {
1383
+ if (!this.isEnabled) {
1384
+ data.dataTransfer.dropEffect = "none";
1385
+ return;
1386
+ }
1387
+ const { clientX, clientY } = data.domEvent;
1388
+ if (!dragDropTarget.updateDropMarker(data.target, data.targetRanges, clientX, clientY, this._blockMode, this._draggedRange)) {
1389
+ data.dataTransfer.dropEffect = "none";
1390
+ return;
1391
+ }
1392
+ if (!this._draggedRange) data.dataTransfer.dropEffect = "copy";
1393
+ if (!env.isGecko) {
1394
+ if (data.dataTransfer.effectAllowed == "copy") data.dataTransfer.dropEffect = "copy";
1395
+ else if (["all", "copyMove"].includes(data.dataTransfer.effectAllowed)) data.dataTransfer.dropEffect = "move";
1396
+ }
1397
+ evt.stop();
1398
+ }, { priority: "low" });
1399
+ }
1400
+ /**
1401
+ * Integration with the `clipboardInput` event.
1402
+ */
1403
+ _setupClipboardInputIntegration() {
1404
+ const editor = this.editor;
1405
+ const viewDocument = editor.editing.view.document;
1406
+ const dragDropTarget = editor.plugins.get(DragDropTarget);
1407
+ this.listenTo(viewDocument, "clipboardInput", (evt, data) => {
1408
+ if (data.method != "drop") return;
1409
+ const { clientX, clientY } = data.domEvent;
1410
+ const targetRange = dragDropTarget.getFinalDropRange(data.target, data.targetRanges, clientX, clientY, this._blockMode, this._draggedRange);
1411
+ if (!targetRange) {
1412
+ this._finalizeDragging(false);
1413
+ evt.stop();
1414
+ return;
1415
+ }
1416
+ if (this._draggedRange && this._draggingUid != data.dataTransfer.getData("application/ckeditor5-dragging-uid")) {
1417
+ this._draggedRange.detach();
1418
+ this._draggedRange = null;
1419
+ this._draggingUid = "";
1420
+ }
1421
+ if (getFinalDropEffect(data.dataTransfer) == "move" && this._draggedRange && this._draggedRange.containsRange(targetRange, true)) {
1422
+ this._finalizeDragging(false);
1423
+ evt.stop();
1424
+ return;
1425
+ }
1426
+ data.targetRanges = [editor.editing.mapper.toViewRange(targetRange)];
1427
+ }, { priority: "high" });
1428
+ }
1429
+ /**
1430
+ * Integration with the `contentInsertion` event of the clipboard pipeline.
1431
+ */
1432
+ _setupContentInsertionIntegration() {
1433
+ const clipboardPipeline = this.editor.plugins.get(ClipboardPipeline);
1434
+ clipboardPipeline.on("contentInsertion", (evt, data) => {
1435
+ if (!this.isEnabled || data.method !== "drop") return;
1436
+ const ranges = data.targetRanges.map((viewRange) => this.editor.editing.mapper.toModelRange(viewRange));
1437
+ this.editor.model.change((writer) => writer.setSelection(ranges));
1438
+ }, { priority: "high" });
1439
+ clipboardPipeline.on("contentInsertion", (evt, data) => {
1440
+ if (!this.isEnabled || data.method !== "drop") return;
1441
+ const isMove = getFinalDropEffect(data.dataTransfer) == "move";
1442
+ const isSuccess = !data.resultRange || !data.resultRange.isCollapsed;
1443
+ this._finalizeDragging(isSuccess && isMove);
1444
+ }, { priority: "lowest" });
1445
+ }
1446
+ /**
1447
+ * Adds listeners that add the `draggable` attribute to the elements while the mouse button is down so the dragging could start.
1448
+ */
1449
+ _setupDraggableAttributeHandling() {
1450
+ const editor = this.editor;
1451
+ const view = editor.editing.view;
1452
+ const viewDocument = view.document;
1453
+ this.listenTo(viewDocument, "pointerdown", (evt, data) => {
1454
+ if (env.isAndroid || !data) return;
1455
+ this._clearDraggableAttributesDelayed.cancel();
1456
+ let draggableElement = findDraggableWidget(data.target);
1457
+ if (env.isBlink && !editor.isReadOnly && !draggableElement && !viewDocument.selection.isCollapsed) {
1458
+ const selectedElement = viewDocument.selection.getSelectedElement();
1459
+ if (!selectedElement || !isWidget(selectedElement)) draggableElement = viewDocument.selection.editableElement;
1460
+ }
1461
+ if (draggableElement) {
1462
+ view.change((writer) => {
1463
+ writer.setAttribute("draggable", "true", draggableElement);
1464
+ });
1465
+ this._draggableElement = editor.editing.mapper.toModelElement(draggableElement);
1466
+ }
1467
+ });
1468
+ this.listenTo(viewDocument, "pointerup", () => {
1469
+ if (!env.isAndroid) this._clearDraggableAttributesDelayed();
1470
+ });
1471
+ }
1472
+ /**
1473
+ * Removes the `draggable` attribute from the element that was used for dragging.
1474
+ */
1475
+ _clearDraggableAttributes() {
1476
+ const editing = this.editor.editing;
1477
+ editing.view.change((writer) => {
1478
+ if (this._draggableElement && this._draggableElement.root.rootName != "$graveyard") writer.removeAttribute("draggable", editing.mapper.toViewElement(this._draggableElement));
1479
+ this._draggableElement = null;
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Deletes the dragged content from its original range and clears the dragging state.
1484
+ *
1485
+ * @param moved Whether the move succeeded.
1486
+ */
1487
+ _finalizeDragging(moved) {
1488
+ const editor = this.editor;
1489
+ const model = editor.model;
1490
+ editor.plugins.get(DragDropTarget).removeDropMarker();
1491
+ this._clearDraggableAttributes();
1492
+ if (editor.plugins.has("WidgetToolbarRepository")) editor.plugins.get("WidgetToolbarRepository").clearForceDisabled("dragDrop");
1493
+ this._draggingUid = "";
1494
+ if (this._previewContainer) {
1495
+ this._previewContainer.remove();
1496
+ this._previewContainer = void 0;
1497
+ }
1498
+ if (!this._draggedRange) return;
1499
+ if (moved && this.isEnabled) model.change((writer) => {
1500
+ const selection = model.createSelection(this._draggedRange);
1501
+ model.deleteContent(selection, { doNotAutoparagraph: true });
1502
+ const selectionParent = selection.getFirstPosition().parent;
1503
+ if (selectionParent.isEmpty && !model.schema.checkChild(selectionParent, "$text") && model.schema.checkChild(selectionParent, "paragraph")) writer.insertElement("paragraph", selectionParent, 0);
1504
+ });
1505
+ this._draggedRange.detach();
1506
+ this._draggedRange = null;
1507
+ }
1508
+ /**
1509
+ * Sets the dragged source range based on event target and document selection.
1510
+ */
1511
+ _prepareDraggedRange(target) {
1512
+ const editor = this.editor;
1513
+ const model = editor.model;
1514
+ const selection = model.document.selection;
1515
+ const draggableWidget = target ? findDraggableWidget(target) : null;
1516
+ if (draggableWidget) {
1517
+ const modelElement = editor.editing.mapper.toModelElement(draggableWidget);
1518
+ this._draggedRange = ModelLiveRange.fromRange(model.createRangeOn(modelElement));
1519
+ this._blockMode = model.schema.isBlock(modelElement);
1520
+ if (editor.plugins.has("WidgetToolbarRepository")) editor.plugins.get("WidgetToolbarRepository").forceDisabled("dragDrop");
1521
+ return;
1522
+ }
1523
+ if (selection.isCollapsed && !selection.getFirstPosition().parent.isEmpty) return;
1524
+ const blocks = Array.from(selection.getSelectedBlocks());
1525
+ const draggedRange = selection.getFirstRange();
1526
+ if (blocks.length == 0) {
1527
+ this._draggedRange = ModelLiveRange.fromRange(draggedRange);
1528
+ return;
1529
+ }
1530
+ const blockRange = getRangeIncludingFullySelectedParents(model, blocks);
1531
+ if (blocks.length > 1) {
1532
+ this._draggedRange = ModelLiveRange.fromRange(blockRange);
1533
+ this._blockMode = true;
1534
+ } else if (blocks.length == 1) {
1535
+ const touchesBlockEdges = draggedRange.start.isTouching(blockRange.start) && draggedRange.end.isTouching(blockRange.end);
1536
+ this._draggedRange = ModelLiveRange.fromRange(touchesBlockEdges ? blockRange : draggedRange);
1537
+ this._blockMode = touchesBlockEdges;
1538
+ }
1539
+ model.change((writer) => writer.setSelection(this._draggedRange.toRange()));
1540
+ }
1541
+ /**
1542
+ * Updates the dragged preview image.
1543
+ */
1544
+ _updatePreview({ dataTransfer, domTarget, clientX }) {
1545
+ const view = this.editor.editing.view;
1546
+ const editable = view.document.selection.editableElement;
1547
+ const domEditable = view.domConverter.mapViewToDom(editable);
1548
+ const computedStyle = global.window.getComputedStyle(domEditable);
1549
+ const editableDocument = domEditable.ownerDocument;
1550
+ if (!this._previewContainer) this._previewContainer = createElement(editableDocument, "div", { style: "position: fixed; left: -999999px;" });
1551
+ else if (this._previewContainer.firstElementChild) this._previewContainer.removeChild(this._previewContainer.firstElementChild);
1552
+ const editableRoot = domEditable.getRootNode();
1553
+ if (isShadowRoot(editableRoot)) editableRoot.appendChild(this._previewContainer);
1554
+ else editableDocument.body.appendChild(this._previewContainer);
1555
+ const preview = createElement(editableDocument, "div");
1556
+ preview.className = "ck ck-content ck-clipboard-preview";
1557
+ const domRect = new Rect(domEditable);
1558
+ const domEditablePaddingLeft = parseFloat(computedStyle.paddingLeft);
1559
+ const domEditablePaddingRight = parseFloat(computedStyle.paddingRight);
1560
+ const editableWidth = parseFloat(computedStyle.width) - domEditablePaddingLeft - domEditablePaddingRight;
1561
+ if (!containsNode(domEditable, domTarget)) {
1562
+ if (!env.isiOS) {
1563
+ const offsetLeft = domRect.left - clientX + domEditablePaddingLeft;
1564
+ preview.style.width = `${editableWidth + offsetLeft}px`;
1565
+ preview.style.paddingLeft = `${offsetLeft}px`;
1566
+ } else {
1567
+ preview.style.width = `${editableWidth}px`;
1568
+ preview.style.backgroundColor = "var(--ck-color-base-background)";
1569
+ }
1570
+ } else if (env.isiOS) {
1571
+ preview.style.maxWidth = `${editableWidth}px`;
1572
+ preview.style.padding = "10px";
1573
+ preview.style.minWidth = "200px";
1574
+ preview.style.minHeight = "20px";
1575
+ preview.style.boxSizing = "border-box";
1576
+ preview.style.backgroundColor = "var(--ck-color-base-background)";
1577
+ } else return;
1578
+ view.domConverter.setContentOf(preview, dataTransfer.getData("text/html"));
1579
+ dataTransfer.setDragImage(preview, 0, 0);
1580
+ this._previewContainer.appendChild(preview);
1581
+ }
1582
+ };
1583
+ /**
1584
+ * Returns the drop effect that should be a result of dragging the content.
1585
+ * This function is handling a quirk when checking the effect in the 'drop' DOM event.
1586
+ */
1587
+ function getFinalDropEffect(dataTransfer) {
1588
+ if (env.isGecko) return dataTransfer.dropEffect;
1589
+ return ["all", "copyMove"].includes(dataTransfer.effectAllowed) ? "move" : "copy";
2037
1590
  }
2038
1591
  /**
2039
- * Returns a widget element that should be dragged.
2040
- */ function findDraggableWidget(target) {
2041
- // This is directly an editable so not a widget for sure.
2042
- if (target.is('editableElement')) {
2043
- return null;
2044
- }
2045
- // TODO: Let's have a isWidgetSelectionHandleDomElement() helper in ckeditor5-widget utils.
2046
- if (target.hasClass('ck-widget__selection-handle')) {
2047
- return target.findAncestor(isWidget);
2048
- }
2049
- // Direct hit on a widget.
2050
- if (isWidget(target)) {
2051
- return target;
2052
- }
2053
- // Find closest ancestor that is either a widget or an editable element...
2054
- const ancestor = target.findAncestor((node)=>isWidget(node) || node.is('editableElement'));
2055
- // ...and if closer was the widget then enable dragging it.
2056
- if (isWidget(ancestor)) {
2057
- return ancestor;
2058
- }
2059
- return null;
1592
+ * Returns a widget element that should be dragged.
1593
+ */
1594
+ function findDraggableWidget(target) {
1595
+ if (target.is("editableElement")) return null;
1596
+ if (target.hasClass("ck-widget__selection-handle")) return target.findAncestor(isWidget);
1597
+ if (isWidget(target)) return target;
1598
+ const ancestor = target.findAncestor((node) => isWidget(node) || node.is("editableElement"));
1599
+ if (isWidget(ancestor)) return ancestor;
1600
+ return null;
2060
1601
  }
2061
1602
  /**
2062
- * Recursively checks if common parent of provided elements doesn't have any other children. If that's the case,
2063
- * it returns range including this parent. Otherwise, it returns only the range from first to last element.
2064
- *
2065
- * Example:
2066
- *
2067
- * <blockQuote>
2068
- * <paragraph>[Test 1</paragraph>
2069
- * <paragraph>Test 2</paragraph>
2070
- * <paragraph>Test 3]</paragraph>
2071
- * <blockQuote>
2072
- *
2073
- * Because all elements inside the `blockQuote` are selected, the range is extended to include the `blockQuote` too.
2074
- * If only first and second paragraphs would be selected, the range would not include it.
2075
- */ function getRangeIncludingFullySelectedParents(model, elements) {
2076
- const firstElement = elements[0];
2077
- const lastElement = elements[elements.length - 1];
2078
- const parent = firstElement.getCommonAncestor(lastElement);
2079
- const startPosition = model.createPositionBefore(firstElement);
2080
- const endPosition = model.createPositionAfter(lastElement);
2081
- if (parent && parent.is('element') && !model.schema.isLimit(parent)) {
2082
- const parentRange = model.createRangeOn(parent);
2083
- const touchesStart = startPosition.isTouching(parentRange.start);
2084
- const touchesEnd = endPosition.isTouching(parentRange.end);
2085
- if (touchesStart && touchesEnd) {
2086
- // Selection includes all elements in the parent.
2087
- return getRangeIncludingFullySelectedParents(model, [
2088
- parent
2089
- ]);
2090
- }
2091
- }
2092
- return model.createRange(startPosition, endPosition);
1603
+ * Recursively checks if common parent of provided elements doesn't have any other children. If that's the case,
1604
+ * it returns range including this parent. Otherwise, it returns only the range from first to last element.
1605
+ *
1606
+ * Example:
1607
+ *
1608
+ * <blockQuote>
1609
+ * <paragraph>[Test 1</paragraph>
1610
+ * <paragraph>Test 2</paragraph>
1611
+ * <paragraph>Test 3]</paragraph>
1612
+ * <blockQuote>
1613
+ *
1614
+ * Because all elements inside the `blockQuote` are selected, the range is extended to include the `blockQuote` too.
1615
+ * If only first and second paragraphs would be selected, the range would not include it.
1616
+ */
1617
+ function getRangeIncludingFullySelectedParents(model, elements) {
1618
+ const firstElement = elements[0];
1619
+ const lastElement = elements[elements.length - 1];
1620
+ const parent = firstElement.getCommonAncestor(lastElement);
1621
+ const startPosition = model.createPositionBefore(firstElement);
1622
+ const endPosition = model.createPositionAfter(lastElement);
1623
+ if (parent && parent.is("element") && !model.schema.isLimit(parent)) {
1624
+ const parentRange = model.createRangeOn(parent);
1625
+ const touchesStart = startPosition.isTouching(parentRange.start);
1626
+ const touchesEnd = endPosition.isTouching(parentRange.end);
1627
+ if (touchesStart && touchesEnd) return getRangeIncludingFullySelectedParents(model, [parent]);
1628
+ }
1629
+ return model.createRange(startPosition, endPosition);
2093
1630
  }
2094
1631
 
2095
1632
  /**
2096
- * The plugin detects the user's intention to paste plain text.
2097
- *
2098
- * For example, it detects the <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>V</kbd> keystroke.
2099
- */ class PastePlainText extends Plugin {
2100
- /**
2101
- * @inheritDoc
2102
- */ static get pluginName() {
2103
- return 'PastePlainText';
2104
- }
2105
- /**
2106
- * @inheritDoc
2107
- */ static get isOfficialPlugin() {
2108
- return true;
2109
- }
2110
- /**
2111
- * @inheritDoc
2112
- */ static get requires() {
2113
- return [
2114
- ClipboardPipeline
2115
- ];
2116
- }
2117
- /**
2118
- * @inheritDoc
2119
- */ init() {
2120
- const editor = this.editor;
2121
- const model = editor.model;
2122
- const view = editor.editing.view;
2123
- const selection = model.document.selection;
2124
- view.addObserver(ClipboardObserver);
2125
- editor.plugins.get(ClipboardPipeline).on('contentInsertion', (evt, data)=>{
2126
- if (!isUnformattedInlineContent(data.content, model)) {
2127
- return;
2128
- }
2129
- model.change((writer)=>{
2130
- // Formatting attributes should be preserved.
2131
- const textAttributes = Array.from(selection.getAttributes()).filter(([key])=>model.schema.getAttributeProperties(key).isFormatting);
2132
- if (!selection.isCollapsed) {
2133
- model.deleteContent(selection, {
2134
- doNotAutoparagraph: true
2135
- });
2136
- }
2137
- // Also preserve other attributes if they survived the content deletion (because they were not fully selected).
2138
- // For example linkHref is not a formatting attribute but it should be preserved if pasted text was in the middle
2139
- // of a link.
2140
- textAttributes.push(...selection.getAttributes());
2141
- const range = writer.createRangeIn(data.content);
2142
- for (const item of range.getItems()){
2143
- for (const attribute of textAttributes){
2144
- if (model.schema.checkAttribute(item, attribute[0])) {
2145
- writer.setAttribute(attribute[0], attribute[1], item);
2146
- }
2147
- }
2148
- }
2149
- });
2150
- });
2151
- }
2152
- }
1633
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1634
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1635
+ */
1636
+ /**
1637
+ * @module clipboard/pasteplaintext
1638
+ */
2153
1639
  /**
2154
- * Returns true if specified `documentFragment` represents the unformatted inline content.
2155
- */ function isUnformattedInlineContent(documentFragment, model) {
2156
- let range = model.createRangeIn(documentFragment);
2157
- // We consider three scenarios here. The document fragment may include:
2158
- //
2159
- // 1. Only text and inline objects. Then it could be unformatted inline content.
2160
- // 2. Exactly one block element on top-level, eg. <p>Foobar</p> or <h2>Title</h2>.
2161
- // In this case, check this element content, it could be treated as unformatted inline content.
2162
- // 3. More block elements or block objects, then it is not unformatted inline content.
2163
- //
2164
- // We will check for scenario 2. specifically, and if it happens, we will unwrap it and follow with the regular algorithm.
2165
- //
2166
- if (documentFragment.childCount == 1) {
2167
- const child = documentFragment.getChild(0);
2168
- if (child.is('element') && model.schema.isBlock(child) && !model.schema.isObject(child) && !model.schema.isLimit(child)) {
2169
- // Scenario 2. as described above.
2170
- range = model.createRangeIn(child);
2171
- }
2172
- }
2173
- for (const child of range.getItems()){
2174
- if (!model.schema.isInline(child)) {
2175
- return false;
2176
- }
2177
- const attributeKeys = Array.from(child.getAttributeKeys());
2178
- if (attributeKeys.find((key)=>model.schema.getAttributeProperties(key).isFormatting)) {
2179
- return false;
2180
- }
2181
- }
2182
- return true;
1640
+ * The plugin detects the user's intention to paste plain text.
1641
+ *
1642
+ * For example, it detects the <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>V</kbd> keystroke.
1643
+ */
1644
+ var PastePlainText = class extends Plugin {
1645
+ /**
1646
+ * @inheritDoc
1647
+ */
1648
+ static get pluginName() {
1649
+ return "PastePlainText";
1650
+ }
1651
+ /**
1652
+ * @inheritDoc
1653
+ */
1654
+ static get isOfficialPlugin() {
1655
+ return true;
1656
+ }
1657
+ /**
1658
+ * @inheritDoc
1659
+ */
1660
+ static get requires() {
1661
+ return [ClipboardPipeline];
1662
+ }
1663
+ /**
1664
+ * @inheritDoc
1665
+ */
1666
+ init() {
1667
+ const editor = this.editor;
1668
+ const model = editor.model;
1669
+ const view = editor.editing.view;
1670
+ const selection = model.document.selection;
1671
+ view.addObserver(ClipboardObserver);
1672
+ editor.plugins.get(ClipboardPipeline).on("contentInsertion", (evt, data) => {
1673
+ if (!isUnformattedInlineContent(data.content, model)) return;
1674
+ model.change((writer) => {
1675
+ const textAttributes = Array.from(selection.getAttributes()).filter(([key]) => model.schema.getAttributeProperties(key).isFormatting);
1676
+ if (!selection.isCollapsed) model.deleteContent(selection, { doNotAutoparagraph: true });
1677
+ textAttributes.push(...selection.getAttributes());
1678
+ const range = writer.createRangeIn(data.content);
1679
+ for (const item of range.getItems()) for (const attribute of textAttributes) if (model.schema.checkAttribute(item, attribute[0])) writer.setAttribute(attribute[0], attribute[1], item);
1680
+ });
1681
+ });
1682
+ }
1683
+ };
1684
+ /**
1685
+ * Returns true if specified `documentFragment` represents the unformatted inline content.
1686
+ */
1687
+ function isUnformattedInlineContent(documentFragment, model) {
1688
+ let range = model.createRangeIn(documentFragment);
1689
+ if (documentFragment.childCount == 1) {
1690
+ const child = documentFragment.getChild(0);
1691
+ if (child.is("element") && model.schema.isBlock(child) && !model.schema.isObject(child) && !model.schema.isLimit(child)) range = model.createRangeIn(child);
1692
+ }
1693
+ for (const child of range.getItems()) {
1694
+ if (!model.schema.isInline(child)) return false;
1695
+ if (Array.from(child.getAttributeKeys()).find((key) => model.schema.getAttributeProperties(key).isFormatting)) return false;
1696
+ }
1697
+ return true;
2183
1698
  }
2184
1699
 
2185
1700
  /**
2186
- * The clipboard feature.
2187
- *
2188
- * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
2189
- *
2190
- * This is a "glue" plugin which loads the following plugins:
2191
- * * {@link module:clipboard/clipboardpipeline~ClipboardPipeline}
2192
- * * {@link module:clipboard/dragdrop~DragDrop}
2193
- * * {@link module:clipboard/pasteplaintext~PastePlainText}
2194
- */ class Clipboard extends Plugin {
2195
- /**
2196
- * @inheritDoc
2197
- */ static get pluginName() {
2198
- return 'Clipboard';
2199
- }
2200
- /**
2201
- * @inheritDoc
2202
- */ static get isOfficialPlugin() {
2203
- return true;
2204
- }
2205
- /**
2206
- * @inheritDoc
2207
- */ static get requires() {
2208
- return [
2209
- ClipboardMarkersUtils,
2210
- ClipboardPipeline,
2211
- DragDrop,
2212
- PastePlainText
2213
- ];
2214
- }
2215
- /**
2216
- * @inheritDoc
2217
- */ init() {
2218
- const editor = this.editor;
2219
- const t = this.editor.t;
2220
- // Add the information about the keystrokes to the accessibility database.
2221
- editor.accessibility.addKeystrokeInfos({
2222
- keystrokes: [
2223
- {
2224
- label: t('Copy selected content'),
2225
- keystroke: 'CTRL+C'
2226
- },
2227
- {
2228
- label: t('Paste content'),
2229
- keystroke: 'CTRL+V'
2230
- },
2231
- {
2232
- label: t('Paste content as plain text'),
2233
- keystroke: 'CTRL+SHIFT+V'
2234
- }
2235
- ]
2236
- });
2237
- }
2238
- }
1701
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1702
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1703
+ */
1704
+ /**
1705
+ * @module clipboard/clipboard
1706
+ */
1707
+ /**
1708
+ * The clipboard feature.
1709
+ *
1710
+ * Read more about the clipboard integration in the {@glink framework/deep-dive/clipboard clipboard deep-dive} guide.
1711
+ *
1712
+ * This is a "glue" plugin which loads the following plugins:
1713
+ * * {@link module:clipboard/clipboardpipeline~ClipboardPipeline}
1714
+ * * {@link module:clipboard/dragdrop~DragDrop}
1715
+ * * {@link module:clipboard/pasteplaintext~PastePlainText}
1716
+ */
1717
+ var Clipboard = class extends Plugin {
1718
+ /**
1719
+ * @inheritDoc
1720
+ */
1721
+ static get pluginName() {
1722
+ return "Clipboard";
1723
+ }
1724
+ /**
1725
+ * @inheritDoc
1726
+ */
1727
+ static get isOfficialPlugin() {
1728
+ return true;
1729
+ }
1730
+ /**
1731
+ * @inheritDoc
1732
+ */
1733
+ static get requires() {
1734
+ return [
1735
+ ClipboardMarkersUtils,
1736
+ ClipboardPipeline,
1737
+ DragDrop,
1738
+ PastePlainText
1739
+ ];
1740
+ }
1741
+ /**
1742
+ * @inheritDoc
1743
+ */
1744
+ init() {
1745
+ const editor = this.editor;
1746
+ const t = this.editor.t;
1747
+ editor.accessibility.addKeystrokeInfos({ keystrokes: [
1748
+ {
1749
+ label: t("Copy selected content"),
1750
+ keystroke: "CTRL+C"
1751
+ },
1752
+ {
1753
+ label: t("Paste content"),
1754
+ keystroke: "CTRL+V"
1755
+ },
1756
+ {
1757
+ label: t("Paste content as plain text"),
1758
+ keystroke: "CTRL+SHIFT+V"
1759
+ }
1760
+ ] });
1761
+ }
1762
+ };
1763
+
1764
+ /**
1765
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1766
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1767
+ */
2239
1768
 
2240
- export { Clipboard, ClipboardMarkersUtils, ClipboardObserver, ClipboardPipeline, DragDrop, DragDropBlockToolbar, DragDropTarget, PastePlainText, LineView as _ClipboardLineView, DragDrop as _DragDrop, DragDropBlockToolbar as _DragDropBlockToolbar, DragDropTarget as _DragDropTarget, normalizeClipboardData as _normalizeClipboardData, plainTextToHtml, viewToPlainText };
2241
- //# sourceMappingURL=index.js.map
1769
+ export { Clipboard, ClipboardMarkersUtils, ClipboardObserver, ClipboardPipeline, DragDrop, DragDrop as _DragDrop, DragDropBlockToolbar, DragDropBlockToolbar as _DragDropBlockToolbar, DragDropTarget, DragDropTarget as _DragDropTarget, PastePlainText, LineView as _ClipboardLineView, normalizeClipboardData as _normalizeClipboardData, plainTextToHtml, viewToPlainText };
1770
+ //# sourceMappingURL=index.js.map