@ckeditor/ckeditor5-media-embed 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 (186) hide show
  1. package/ckeditor5-metadata.json +108 -12
  2. package/dist/augmentation.d.ts +33 -23
  3. package/dist/automediaembed.d.ts +50 -50
  4. package/dist/converters.d.ts +37 -37
  5. package/dist/index-content.css +54 -6
  6. package/dist/index-content.css.map +1 -0
  7. package/dist/index-editor.css +145 -111
  8. package/dist/index-editor.css.map +1 -0
  9. package/dist/index.css +179 -101
  10. package/dist/index.css.map +1 -1
  11. package/dist/index.d.ts +31 -18
  12. package/dist/index.js +2645 -1087
  13. package/dist/index.js.map +1 -1
  14. package/dist/mediaembed.d.ts +32 -33
  15. package/dist/mediaembedcommand.d.ts +32 -32
  16. package/dist/mediaembedconfig.d.ts +574 -270
  17. package/dist/mediaembedediting.d.ts +29 -30
  18. package/dist/mediaembedresize/constants.d.ts +17 -0
  19. package/dist/mediaembedresize/mediaembedcustomresizeui.d.ts +64 -0
  20. package/dist/mediaembedresize/mediaembedresizebuttons.d.ts +54 -0
  21. package/dist/mediaembedresize/mediaembedresizeediting.d.ts +51 -0
  22. package/dist/mediaembedresize/mediaembedresizehandles.d.ts +42 -0
  23. package/dist/mediaembedresize/resizemediaembedcommand.d.ts +40 -0
  24. package/dist/mediaembedresize/ui/mediaembedcustomresizeformview.d.ts +117 -0
  25. package/dist/mediaembedresize/utils/getselectedmediaembededitornodes.d.ts +23 -0
  26. package/dist/mediaembedresize/utils/getselectedmediaembedpossibleresizerange.d.ts +25 -0
  27. package/dist/mediaembedresize/utils/getselectedmediaembedwidthinunits.d.ts +21 -0
  28. package/dist/mediaembedresize.d.ts +32 -0
  29. package/dist/mediaembedstyle/constants.d.ts +29 -0
  30. package/dist/mediaembedstyle/mediaembedstylecommand.d.ts +72 -0
  31. package/dist/mediaembedstyle/mediaembedstyleediting.d.ts +43 -0
  32. package/dist/mediaembedstyle/mediaembedstyleui.d.ts +81 -0
  33. package/dist/mediaembedstyle/utils.d.ts +23 -0
  34. package/dist/mediaembedstyle.d.ts +33 -0
  35. package/dist/mediaembedtoolbar.d.ts +28 -29
  36. package/dist/mediaembedui.d.ts +33 -33
  37. package/dist/mediaregistry.d.ts +59 -59
  38. package/dist/translations/af.js +1 -1
  39. package/dist/translations/af.umd.js +5 -3
  40. package/dist/translations/ar.js +1 -1
  41. package/dist/translations/ar.umd.js +5 -3
  42. package/dist/translations/ast.js +1 -1
  43. package/dist/translations/ast.umd.js +5 -3
  44. package/dist/translations/az.js +1 -1
  45. package/dist/translations/az.umd.js +5 -3
  46. package/dist/translations/be.js +1 -1
  47. package/dist/translations/be.umd.js +5 -3
  48. package/dist/translations/bg.js +1 -1
  49. package/dist/translations/bg.umd.js +5 -3
  50. package/dist/translations/bn.js +1 -1
  51. package/dist/translations/bn.umd.js +5 -3
  52. package/dist/translations/bs.js +1 -1
  53. package/dist/translations/bs.umd.js +5 -3
  54. package/dist/translations/ca.js +1 -1
  55. package/dist/translations/ca.umd.js +5 -3
  56. package/dist/translations/cs.js +1 -1
  57. package/dist/translations/cs.umd.js +5 -3
  58. package/dist/translations/da.js +1 -1
  59. package/dist/translations/da.umd.js +5 -3
  60. package/dist/translations/de-ch.js +1 -1
  61. package/dist/translations/de-ch.umd.js +5 -3
  62. package/dist/translations/de.js +1 -1
  63. package/dist/translations/de.umd.js +5 -3
  64. package/dist/translations/el.js +1 -1
  65. package/dist/translations/el.umd.js +5 -3
  66. package/dist/translations/en-au.js +1 -1
  67. package/dist/translations/en-au.umd.js +5 -3
  68. package/dist/translations/en-gb.js +1 -1
  69. package/dist/translations/en-gb.umd.js +5 -3
  70. package/dist/translations/en.js +1 -1
  71. package/dist/translations/en.umd.js +5 -3
  72. package/dist/translations/eo.js +1 -1
  73. package/dist/translations/eo.umd.js +5 -3
  74. package/dist/translations/es-co.js +1 -1
  75. package/dist/translations/es-co.umd.js +5 -3
  76. package/dist/translations/es.js +1 -1
  77. package/dist/translations/es.umd.js +5 -3
  78. package/dist/translations/et.js +1 -1
  79. package/dist/translations/et.umd.js +5 -3
  80. package/dist/translations/eu.js +1 -1
  81. package/dist/translations/eu.umd.js +5 -3
  82. package/dist/translations/fa.js +1 -1
  83. package/dist/translations/fa.umd.js +5 -3
  84. package/dist/translations/fi.js +1 -1
  85. package/dist/translations/fi.umd.js +5 -3
  86. package/dist/translations/fr.js +1 -1
  87. package/dist/translations/fr.umd.js +5 -3
  88. package/dist/translations/gl.js +1 -1
  89. package/dist/translations/gl.umd.js +5 -3
  90. package/dist/translations/gu.js +1 -1
  91. package/dist/translations/gu.umd.js +5 -3
  92. package/dist/translations/he.js +1 -1
  93. package/dist/translations/he.umd.js +5 -3
  94. package/dist/translations/hi.js +1 -1
  95. package/dist/translations/hi.umd.js +5 -3
  96. package/dist/translations/hr.js +1 -1
  97. package/dist/translations/hr.umd.js +5 -3
  98. package/dist/translations/hu.js +1 -1
  99. package/dist/translations/hu.umd.js +5 -3
  100. package/dist/translations/hy.js +1 -1
  101. package/dist/translations/hy.umd.js +5 -3
  102. package/dist/translations/id.js +1 -1
  103. package/dist/translations/id.umd.js +5 -3
  104. package/dist/translations/it.js +1 -1
  105. package/dist/translations/it.umd.js +5 -3
  106. package/dist/translations/ja.js +1 -1
  107. package/dist/translations/ja.umd.js +5 -3
  108. package/dist/translations/jv.js +1 -1
  109. package/dist/translations/jv.umd.js +5 -3
  110. package/dist/translations/kk.js +1 -1
  111. package/dist/translations/kk.umd.js +5 -3
  112. package/dist/translations/km.js +1 -1
  113. package/dist/translations/km.umd.js +5 -3
  114. package/dist/translations/kn.js +1 -1
  115. package/dist/translations/kn.umd.js +5 -3
  116. package/dist/translations/ko.js +1 -1
  117. package/dist/translations/ko.umd.js +5 -3
  118. package/dist/translations/ku.js +1 -1
  119. package/dist/translations/ku.umd.js +5 -3
  120. package/dist/translations/lt.js +1 -1
  121. package/dist/translations/lt.umd.js +5 -3
  122. package/dist/translations/lv.js +1 -1
  123. package/dist/translations/lv.umd.js +5 -3
  124. package/dist/translations/ms.js +1 -1
  125. package/dist/translations/ms.umd.js +5 -3
  126. package/dist/translations/nb.js +1 -1
  127. package/dist/translations/nb.umd.js +5 -3
  128. package/dist/translations/ne.js +1 -1
  129. package/dist/translations/ne.umd.js +5 -3
  130. package/dist/translations/nl.js +1 -1
  131. package/dist/translations/nl.umd.js +5 -3
  132. package/dist/translations/no.js +1 -1
  133. package/dist/translations/no.umd.js +5 -3
  134. package/dist/translations/oc.js +1 -1
  135. package/dist/translations/oc.umd.js +5 -3
  136. package/dist/translations/pl.js +1 -1
  137. package/dist/translations/pl.umd.js +5 -3
  138. package/dist/translations/pt-br.js +1 -1
  139. package/dist/translations/pt-br.umd.js +5 -3
  140. package/dist/translations/pt.js +1 -1
  141. package/dist/translations/pt.umd.js +5 -3
  142. package/dist/translations/ro.js +1 -1
  143. package/dist/translations/ro.umd.js +5 -3
  144. package/dist/translations/ru.js +1 -1
  145. package/dist/translations/ru.umd.js +5 -3
  146. package/dist/translations/si.js +1 -1
  147. package/dist/translations/si.umd.js +5 -3
  148. package/dist/translations/sk.js +1 -1
  149. package/dist/translations/sk.umd.js +5 -3
  150. package/dist/translations/sl.js +1 -1
  151. package/dist/translations/sl.umd.js +5 -3
  152. package/dist/translations/sq.js +1 -1
  153. package/dist/translations/sq.umd.js +5 -3
  154. package/dist/translations/sr-latn.js +1 -1
  155. package/dist/translations/sr-latn.umd.js +5 -3
  156. package/dist/translations/sr.js +1 -1
  157. package/dist/translations/sr.umd.js +5 -3
  158. package/dist/translations/sv.js +1 -1
  159. package/dist/translations/sv.umd.js +5 -3
  160. package/dist/translations/th.js +1 -1
  161. package/dist/translations/th.umd.js +5 -3
  162. package/dist/translations/ti.js +1 -1
  163. package/dist/translations/ti.umd.js +5 -3
  164. package/dist/translations/tk.js +1 -1
  165. package/dist/translations/tk.umd.js +5 -3
  166. package/dist/translations/tr.js +1 -1
  167. package/dist/translations/tr.umd.js +5 -3
  168. package/dist/translations/tt.js +1 -1
  169. package/dist/translations/tt.umd.js +5 -3
  170. package/dist/translations/ug.js +1 -1
  171. package/dist/translations/ug.umd.js +5 -3
  172. package/dist/translations/uk.js +1 -1
  173. package/dist/translations/uk.umd.js +5 -3
  174. package/dist/translations/ur.js +1 -1
  175. package/dist/translations/ur.umd.js +5 -3
  176. package/dist/translations/uz.js +1 -1
  177. package/dist/translations/uz.umd.js +5 -3
  178. package/dist/translations/vi.js +1 -1
  179. package/dist/translations/vi.umd.js +5 -3
  180. package/dist/translations/zh-cn.js +1 -1
  181. package/dist/translations/zh-cn.umd.js +5 -3
  182. package/dist/translations/zh.js +1 -1
  183. package/dist/translations/zh.umd.js +5 -3
  184. package/dist/ui/mediaformview.d.ts +82 -83
  185. package/dist/utils.d.ts +61 -61
  186. package/package.json +10 -10
package/dist/index.js CHANGED
@@ -2,1137 +2,2695 @@
2
2
  * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
4
4
  */
5
- import { Command, Plugin } from '@ckeditor/ckeditor5-core/dist/index.js';
6
- import { isWidget, toWidget, findOptimalInsertionRange, Widget, WidgetToolbarRepository } from '@ckeditor/ckeditor5-widget/dist/index.js';
7
- import { logWarning, toArray, first, global, FocusTracker, KeystrokeHandler } from '@ckeditor/ckeditor5-utils/dist/index.js';
8
- import { IconView, Template, View, submitHandler, LabeledFieldView, createLabeledInputText, Dialog, ButtonView, MenuBarMenuListItemButtonView, CssTransitionDisablerMixin } from '@ckeditor/ckeditor5-ui/dist/index.js';
9
- import { IconMediaPlaceholder, IconMedia } from '@ckeditor/ckeditor5-icons/dist/index.js';
10
- import { ModelLivePosition, ModelLiveRange } from '@ckeditor/ckeditor5-engine/dist/index.js';
11
- import { Clipboard } from '@ckeditor/ckeditor5-clipboard/dist/index.js';
12
- import { Delete } from '@ckeditor/ckeditor5-typing/dist/index.js';
13
- import { Undo } from '@ckeditor/ckeditor5-undo/dist/index.js';
5
+ import { Command, Plugin } from "@ckeditor/ckeditor5-core";
6
+ import { Widget, WidgetResize, WidgetToolbarRepository, calculateResizeHostAncestorWidth, findOptimalInsertionRange, isWidget, toWidget } from "@ckeditor/ckeditor5-widget";
7
+ import { CKEditorError, Collection, FocusTracker, KeystrokeHandler, Rect, _tryCastDimensionsToUnit, _tryParseDimensionWithUnit, first, global, logWarning, toArray } from "@ckeditor/ckeditor5-utils";
8
+ import { BalloonPanelView, ButtonView, ContextualBalloon, CssTransitionDisablerMixin, Dialog, DropdownButtonView, FocusCycler, FormHeaderView, FormRowView, IconView, LabeledFieldView, MenuBarMenuListItemButtonView, SplitButtonView, Template, UIModel, View, ViewCollection, addListToDropdown, addToolbarToDropdown, clickOutsideHandler, createDropdown, createLabeledInputNumber, createLabeledInputText, submitHandler } from "@ckeditor/ckeditor5-ui";
9
+ import { IconMedia, IconMediaPlaceholder, IconObjectCenter, IconObjectInlineLeft, IconObjectInlineRight, IconObjectLeft, IconObjectRight, IconObjectSizeCustom, IconObjectSizeFull, IconObjectSizeLarge, IconObjectSizeMedium, IconObjectSizeSmall, IconPreviousArrow } from "@ckeditor/ckeditor5-icons";
10
+ import { ModelLivePosition, ModelLiveRange } from "@ckeditor/ckeditor5-engine";
11
+ import { Clipboard } from "@ckeditor/ckeditor5-clipboard";
12
+ import { Delete } from "@ckeditor/ckeditor5-typing";
13
+ import { Undo } from "@ckeditor/ckeditor5-undo";
14
14
 
15
15
  /**
16
- * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
17
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
18
- */ /**
19
- * @module media-embed/converters
20
- */ /**
21
- * Returns a function that converts the model "url" attribute to the view representation.
22
- *
23
- * Depending on the configuration, the view representation can be "semantic" (for the data pipeline):
24
- *
25
- * ```html
26
- * <figure class="media">
27
- * <oembed url="foo"></oembed>
28
- * </figure>
29
- * ```
30
- *
31
- * or "non-semantic" (for the editing view pipeline):
32
- *
33
- * ```html
34
- * <figure class="media">
35
- * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
36
- * </figure>
37
- * ```
38
- *
39
- * **Note:** Changing the model "url" attribute replaces the entire content of the
40
- * `<figure>` in the view.
41
- *
42
- * @param registry The registry providing
43
- * the media and their content.
44
- * @param options options object with following properties:
45
- * - elementName When set, overrides the default element name for semantic media embeds.
46
- * - renderMediaPreview When `true`, the converter will create the view in the non-semantic form.
47
- * - renderForEditingView When `true`, the converter will create a view specific for the
48
- * editing pipeline (e.g. including CSS classes, content placeholders).
49
- *
50
- * @internal
51
- */ function modelToViewUrlAttributeConverter(registry, options) {
52
- const converter = (evt, data, conversionApi)=>{
53
- if (!conversionApi.consumable.consume(data.item, evt.name)) {
54
- return;
55
- }
56
- const url = data.attributeNewValue;
57
- const viewWriter = conversionApi.writer;
58
- const figure = conversionApi.mapper.toViewElement(data.item);
59
- const mediaContentElement = [
60
- ...figure.getChildren()
61
- ].find((child)=>child.getCustomProperty('media-content'));
62
- // TODO: removing the wrapper and creating it from scratch is a hack. We can do better than that.
63
- viewWriter.remove(mediaContentElement);
64
- const mediaViewElement = registry.getMediaViewElement(viewWriter, url, options);
65
- viewWriter.insert(viewWriter.createPositionAt(figure, 0), mediaViewElement);
66
- };
67
- return (dispatcher)=>{
68
- dispatcher.on('attribute:url:media', converter);
69
- };
16
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
17
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
18
+ */
19
+ /**
20
+ * Returns a function that converts the model "url" attribute to the view representation.
21
+ *
22
+ * Depending on the configuration, the view representation can be "semantic" (for the data pipeline):
23
+ *
24
+ * ```html
25
+ * <figure class="media">
26
+ * <oembed url="foo"></oembed>
27
+ * </figure>
28
+ * ```
29
+ *
30
+ * or "non-semantic" (for the editing view pipeline):
31
+ *
32
+ * ```html
33
+ * <figure class="media">
34
+ * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
35
+ * </figure>
36
+ * ```
37
+ *
38
+ * **Note:** Changing the model "url" attribute replaces the entire content of the
39
+ * `<figure>` in the view.
40
+ *
41
+ * @param registry The registry providing
42
+ * the media and their content.
43
+ * @param options options object with following properties:
44
+ * - elementName When set, overrides the default element name for semantic media embeds.
45
+ * - renderMediaPreview When `true`, the converter will create the view in the non-semantic form.
46
+ * - renderForEditingView When `true`, the converter will create a view specific for the
47
+ * editing pipeline (e.g. including CSS classes, content placeholders).
48
+ *
49
+ * @internal
50
+ */
51
+ function modelToViewUrlAttributeConverter(registry, options) {
52
+ const converter = (evt, data, conversionApi) => {
53
+ if (!conversionApi.consumable.consume(data.item, evt.name)) return;
54
+ const url = data.attributeNewValue;
55
+ const viewWriter = conversionApi.writer;
56
+ const figure = conversionApi.mapper.toViewElement(data.item);
57
+ const mediaContentElement = [...figure.getChildren()].find((child) => child.getCustomProperty("media-content"));
58
+ viewWriter.remove(mediaContentElement);
59
+ const mediaViewElement = registry.getMediaViewElement(viewWriter, url, options);
60
+ viewWriter.insert(viewWriter.createPositionAt(figure, 0), mediaViewElement);
61
+ };
62
+ return (dispatcher) => {
63
+ dispatcher.on("attribute:url:media", converter);
64
+ };
70
65
  }
71
66
 
72
67
  /**
73
- * Converts a given {@link module:engine/view/element~ViewElement} to a media embed widget:
74
- * * Adds a {@link module:engine/view/element~ViewElement#_setCustomProperty custom property}
75
- * allowing to recognize the media widget element.
76
- * * Calls the {@link module:widget/utils~toWidget} function with the proper element's label creator.
77
- *
78
- * @param writer An instance of the view writer.
79
- * @param label The element's label.
80
- * @internal
81
- */ function toMediaWidget(viewElement, writer, label) {
82
- writer.setCustomProperty('media', true, viewElement);
83
- return toWidget(viewElement, writer, {
84
- label
85
- });
68
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
69
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
70
+ */
71
+ /**
72
+ * Converts a given {@link module:engine/view/element~ViewElement} to a media embed widget:
73
+ * * Adds a {@link module:engine/view/element~ViewElement#_setCustomProperty custom property}
74
+ * allowing to recognize the media widget element.
75
+ * * Calls the {@link module:widget/utils~toWidget} function with the proper element's label creator.
76
+ *
77
+ * @param writer An instance of the view writer.
78
+ * @param label The element's label.
79
+ * @internal
80
+ */
81
+ function toMediaWidget(viewElement, writer, label) {
82
+ writer.setCustomProperty("media", true, viewElement);
83
+ return toWidget(viewElement, writer, { label });
86
84
  }
87
85
  /**
88
- * Returns a media widget editing view element if one is selected.
89
- *
90
- * @internal
91
- */ function getSelectedMediaViewWidget(selection) {
92
- const viewElement = selection.getSelectedElement();
93
- if (viewElement && isMediaWidget(viewElement)) {
94
- return viewElement;
95
- }
96
- return null;
86
+ * Returns a media widget editing view element if one is selected.
87
+ *
88
+ * @internal
89
+ */
90
+ function getSelectedMediaViewWidget(selection) {
91
+ const viewElement = selection.getSelectedElement();
92
+ if (viewElement && isMediaWidget(viewElement)) return viewElement;
93
+ return null;
97
94
  }
98
95
  /**
99
- * Checks if a given view element is a media widget.
100
- *
101
- * @internal
102
- */ function isMediaWidget(viewElement) {
103
- return !!viewElement.getCustomProperty('media') && isWidget(viewElement);
96
+ * Checks if a given view element is a media widget.
97
+ *
98
+ * @internal
99
+ */
100
+ function isMediaWidget(viewElement) {
101
+ return !!viewElement.getCustomProperty("media") && isWidget(viewElement);
104
102
  }
105
103
  /**
106
- * Creates a view element representing the media. Either a "semantic" one for the data pipeline:
107
- *
108
- * ```html
109
- * <figure class="media">
110
- * <oembed url="foo"></oembed>
111
- * </figure>
112
- * ```
113
- *
114
- * or a "non-semantic" (for the editing view pipeline):
115
- *
116
- * ```html
117
- * <figure class="media">
118
- * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
119
- * </figure>
120
- * ```
121
- *
122
- * @internal
123
- */ function createMediaFigureElement(writer, registry, url, options) {
124
- return writer.createContainerElement('figure', {
125
- class: 'media'
126
- }, [
127
- registry.getMediaViewElement(writer, url, options),
128
- writer.createSlot()
129
- ]);
104
+ * Creates a view element representing the media. Either a "semantic" one for the data pipeline:
105
+ *
106
+ * ```html
107
+ * <figure class="media">
108
+ * <oembed url="foo"></oembed>
109
+ * </figure>
110
+ * ```
111
+ *
112
+ * or a "non-semantic" (for the editing view pipeline):
113
+ *
114
+ * ```html
115
+ * <figure class="media">
116
+ * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
117
+ * </figure>
118
+ * ```
119
+ *
120
+ * @internal
121
+ */
122
+ function createMediaFigureElement(writer, registry, url, options) {
123
+ return writer.createContainerElement("figure", { class: "media" }, [registry.getMediaViewElement(writer, url, options), writer.createSlot()]);
130
124
  }
131
125
  /**
132
- * Returns a selected media element in the model, if any.
133
- *
134
- * @internal
135
- */ function getSelectedMediaModelWidget(selection) {
136
- const selectedElement = selection.getSelectedElement();
137
- if (selectedElement && selectedElement.is('element', 'media')) {
138
- return selectedElement;
139
- }
140
- return null;
126
+ * Returns a selected media element in the model, if any.
127
+ *
128
+ * @internal
129
+ */
130
+ function getSelectedMediaModelWidget(selection) {
131
+ const selectedElement = selection.getSelectedElement();
132
+ if (selectedElement && selectedElement.is("element", "media")) return selectedElement;
133
+ return null;
141
134
  }
142
135
  /**
143
- * Creates a media element and inserts it into the model.
144
- *
145
- * **Note**: This method will use {@link module:engine/model/model~Model#insertContent `model.insertContent()`} logic of inserting content
146
- * if no `insertPosition` is passed.
147
- *
148
- * @param url An URL of an embeddable media.
149
- * @param findOptimalPosition If true it will try to find optimal position to insert media without breaking content
150
- * in which a selection is.
151
- * @internal
152
- */ function insertMedia(model, url, selectable, findOptimalPosition) {
153
- model.change((writer)=>{
154
- const mediaElement = writer.createElement('media', {
155
- url
156
- });
157
- model.insertObject(mediaElement, selectable, null, {
158
- setSelection: 'on',
159
- findOptimalPosition: findOptimalPosition ? 'auto' : undefined
160
- });
161
- });
136
+ * Creates a media element and inserts it into the model.
137
+ *
138
+ * **Note**: This method will use {@link module:engine/model/model~Model#insertContent `model.insertContent()`} logic of inserting content
139
+ * if no `insertPosition` is passed.
140
+ *
141
+ * @param url An URL of an embeddable media.
142
+ * @param findOptimalPosition If true it will try to find optimal position to insert media without breaking content
143
+ * in which a selection is.
144
+ * @internal
145
+ */
146
+ function insertMedia(model, url, selectable, findOptimalPosition) {
147
+ model.change((writer) => {
148
+ const mediaElement = writer.createElement("media", { url });
149
+ model.insertObject(mediaElement, selectable, null, {
150
+ setSelection: "on",
151
+ findOptimalPosition: findOptimalPosition ? "auto" : void 0
152
+ });
153
+ });
162
154
  }
163
155
 
164
156
  /**
165
- * The insert media command.
166
- *
167
- * The command is registered by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} as `'mediaEmbed'`.
168
- *
169
- * To insert media at the current selection, execute the command and specify the URL:
170
- *
171
- * ```ts
172
- * editor.execute( 'mediaEmbed', 'http://url.to.the/media' );
173
- * ```
174
- */ class MediaEmbedCommand extends Command {
175
- /**
176
- * @inheritDoc
177
- */ refresh() {
178
- const model = this.editor.model;
179
- const selection = model.document.selection;
180
- const selectedMedia = getSelectedMediaModelWidget(selection);
181
- this.value = selectedMedia ? selectedMedia.getAttribute('url') : undefined;
182
- this.isEnabled = isMediaSelected(selection) || isAllowedInParent(selection, model);
183
- }
184
- /**
185
- * Executes the command, which either:
186
- *
187
- * * updates the URL of the selected media,
188
- * * inserts the new media into the editor and puts the selection around it.
189
- *
190
- * @fires execute
191
- * @param url The URL of the media.
192
- */ execute(url) {
193
- const model = this.editor.model;
194
- const selection = model.document.selection;
195
- const selectedMedia = getSelectedMediaModelWidget(selection);
196
- if (selectedMedia) {
197
- model.change((writer)=>{
198
- writer.setAttribute('url', url, selectedMedia);
199
- });
200
- } else {
201
- insertMedia(model, url, selection, true);
202
- }
203
- }
157
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
158
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
159
+ */
160
+ /**
161
+ * The insert media command.
162
+ *
163
+ * The command is registered by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} as `'mediaEmbed'`.
164
+ *
165
+ * To insert media at the current selection, execute the command and specify the URL:
166
+ *
167
+ * ```ts
168
+ * editor.execute( 'mediaEmbed', 'http://url.to.the/media' );
169
+ * ```
170
+ */
171
+ var MediaEmbedCommand = class extends Command {
172
+ /**
173
+ * @inheritDoc
174
+ */
175
+ refresh() {
176
+ const model = this.editor.model;
177
+ const selection = model.document.selection;
178
+ const selectedMedia = getSelectedMediaModelWidget(selection);
179
+ this.value = selectedMedia ? selectedMedia.getAttribute("url") : void 0;
180
+ this.isEnabled = isMediaSelected(selection) || isAllowedInParent(selection, model);
181
+ }
182
+ /**
183
+ * Executes the command, which either:
184
+ *
185
+ * * updates the URL of the selected media,
186
+ * * inserts the new media into the editor and puts the selection around it.
187
+ *
188
+ * @fires execute
189
+ * @param url The URL of the media.
190
+ */
191
+ execute(url) {
192
+ const model = this.editor.model;
193
+ const selection = model.document.selection;
194
+ const selectedMedia = getSelectedMediaModelWidget(selection);
195
+ if (selectedMedia) model.change((writer) => {
196
+ writer.setAttribute("url", url, selectedMedia);
197
+ });
198
+ else insertMedia(model, url, selection, true);
199
+ }
200
+ };
201
+ /**
202
+ * Checks if the media embed is allowed in the parent.
203
+ */
204
+ function isAllowedInParent(selection, model) {
205
+ let parent = findOptimalInsertionRange(selection, model).start.parent;
206
+ if (parent.isEmpty && !model.schema.isLimit(parent)) parent = parent.parent;
207
+ return model.schema.checkChild(parent, "media");
204
208
  }
205
209
  /**
206
- * Checks if the media embed is allowed in the parent.
207
- */ function isAllowedInParent(selection, model) {
208
- const insertionRange = findOptimalInsertionRange(selection, model);
209
- let parent = insertionRange.start.parent;
210
- // The model.insertContent() will remove empty parent (unless it is a $root or a limit).
211
- if (parent.isEmpty && !model.schema.isLimit(parent)) {
212
- parent = parent.parent;
213
- }
214
- return model.schema.checkChild(parent, 'media');
210
+ * Checks if the media object is selected.
211
+ */
212
+ function isMediaSelected(selection) {
213
+ const element = selection.getSelectedElement();
214
+ return !!element && element.name === "media";
215
215
  }
216
+
217
+ /**
218
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
219
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
220
+ */
221
+ /**
222
+ * @module media-embed/mediaregistry
223
+ */
224
+ const mediaPlaceholderIconViewBox = "0 0 64 42";
225
+ /**
226
+ * A bridge between the raw media content provider definitions and the editor view content.
227
+ *
228
+ * It helps translating media URLs to corresponding {@link module:engine/view/element~ViewElement view elements}.
229
+ *
230
+ * Mostly used by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} plugin.
231
+ */
232
+ var MediaRegistry = class {
233
+ /**
234
+ * The {@link module:utils/locale~Locale} instance.
235
+ */
236
+ locale;
237
+ /**
238
+ * The media provider definitions available for the registry. Usually corresponding with the
239
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig media configuration}.
240
+ */
241
+ providerDefinitions;
242
+ /**
243
+ * Creates an instance of the {@link module:media-embed/mediaregistry~MediaRegistry} class.
244
+ *
245
+ * @param locale The localization services instance.
246
+ * @param config The configuration of the media embed feature.
247
+ */
248
+ constructor(locale, config) {
249
+ const providers = config.providers;
250
+ const extraProviders = config.extraProviders || [];
251
+ const removedProviders = new Set(config.removeProviders);
252
+ const providerDefinitions = providers.concat(extraProviders).filter((provider) => {
253
+ const name = provider.name;
254
+ if (!name) {
255
+ /**
256
+ * One of the providers (or extra providers) specified in the media embed configuration
257
+ * has no name and will not be used by the editor. In order to get this media
258
+ * provider working, double check your editor configuration.
259
+ *
260
+ * @error media-embed-no-provider-name
261
+ */
262
+ logWarning("media-embed-no-provider-name", { provider });
263
+ return false;
264
+ }
265
+ return !removedProviders.has(name);
266
+ });
267
+ this.locale = locale;
268
+ this.providerDefinitions = providerDefinitions;
269
+ }
270
+ /**
271
+ * Checks whether the passed URL is representing a certain media type allowed in the editor.
272
+ *
273
+ * @param url The URL to be checked
274
+ */
275
+ hasMedia(url) {
276
+ return !!this._getMedia(url);
277
+ }
278
+ /**
279
+ * For the given media URL string and options, it returns the {@link module:engine/view/element~ViewElement view element}
280
+ * representing that media.
281
+ *
282
+ * **Note:** If no URL is specified, an empty view element is returned.
283
+ *
284
+ * @param writer The view writer used to produce a view element.
285
+ * @param url The URL to be translated into a view element.
286
+ */
287
+ getMediaViewElement(writer, url, options) {
288
+ return this._getMedia(url).getViewElement(writer, options);
289
+ }
290
+ /**
291
+ * Returns a `Media` instance for the given URL.
292
+ *
293
+ * @param url The URL of the media.
294
+ * @returns The `Media` instance or `null` when there is none.
295
+ */
296
+ _getMedia(url) {
297
+ if (!url) return new Media(this.locale);
298
+ url = url.trim();
299
+ for (const definition of this.providerDefinitions) {
300
+ const previewRenderer = definition.html;
301
+ const pattern = toArray(definition.url);
302
+ for (const subPattern of pattern) {
303
+ const match = this._getUrlMatches(url, subPattern);
304
+ if (match) return new Media(this.locale, url, match, previewRenderer);
305
+ }
306
+ }
307
+ return null;
308
+ }
309
+ /**
310
+ * Tries to match `url` to `pattern`.
311
+ *
312
+ * @param url The URL of the media.
313
+ * @param pattern The pattern that should accept the media URL.
314
+ */
315
+ _getUrlMatches(url, pattern) {
316
+ let match = url.match(pattern);
317
+ if (match) return match;
318
+ let rawUrl = url.replace(/^https?:\/\//, "");
319
+ match = rawUrl.match(pattern);
320
+ if (match) return match;
321
+ rawUrl = rawUrl.replace(/^www\./, "");
322
+ match = rawUrl.match(pattern);
323
+ if (match) return match;
324
+ return null;
325
+ }
326
+ };
327
+ /**
328
+ * Represents media defined by the provider configuration.
329
+ *
330
+ * It can be rendered to the {@link module:engine/view/element~ViewElement view element} and used in the editing or data pipeline.
331
+ */
332
+ var Media = class {
333
+ /**
334
+ * The URL this Media instance represents.
335
+ */
336
+ url;
337
+ /**
338
+ * Shorthand for {@link module:utils/locale~Locale#t}.
339
+ *
340
+ * @see module:utils/locale~Locale#t
341
+ */
342
+ _locale;
343
+ /**
344
+ * The output of the `RegExp.match` which validated the {@link #url} of this media.
345
+ */
346
+ _match;
347
+ /**
348
+ * The function returning the HTML string preview of this media.
349
+ */
350
+ _previewRenderer;
351
+ constructor(locale, url, match, previewRenderer) {
352
+ this.url = this._getValidUrl(url);
353
+ this._locale = locale;
354
+ this._match = match;
355
+ this._previewRenderer = previewRenderer;
356
+ }
357
+ /**
358
+ * Returns the view element representation of the media.
359
+ *
360
+ * @param writer The view writer used to produce a view element.
361
+ */
362
+ getViewElement(writer, options) {
363
+ const attributes = {};
364
+ let viewElement;
365
+ if (options.renderForEditingView || options.renderMediaPreview && this.url && this._previewRenderer) {
366
+ if (this.url) attributes["data-oembed-url"] = this.url;
367
+ if (options.renderForEditingView) attributes.class = "ck-media__wrapper";
368
+ const mediaHtml = this._getPreviewHtml(options);
369
+ viewElement = writer.createRawElement("div", attributes, (domElement, domConverter) => {
370
+ domConverter.setContentOf(domElement, mediaHtml);
371
+ });
372
+ } else {
373
+ if (this.url) attributes.url = this.url;
374
+ viewElement = writer.createEmptyElement(options.elementName, attributes);
375
+ }
376
+ writer.setCustomProperty("media-content", true, viewElement);
377
+ return viewElement;
378
+ }
379
+ /**
380
+ * Returns the HTML string of the media content preview.
381
+ */
382
+ _getPreviewHtml(options) {
383
+ if (this._previewRenderer) return this._previewRenderer(this._match);
384
+ else {
385
+ if (this.url && options.renderForEditingView) return this._getPlaceholderHtml();
386
+ return "";
387
+ }
388
+ }
389
+ /**
390
+ * Returns the placeholder HTML when the media has no content preview.
391
+ */
392
+ _getPlaceholderHtml() {
393
+ const icon = new IconView();
394
+ const t = this._locale.t;
395
+ icon.content = IconMediaPlaceholder;
396
+ icon.viewBox = mediaPlaceholderIconViewBox;
397
+ return new Template({
398
+ tag: "div",
399
+ attributes: { class: "ck ck-reset_all ck-media__placeholder" },
400
+ children: [{
401
+ tag: "div",
402
+ attributes: { class: "ck-media__placeholder__icon" },
403
+ children: [icon]
404
+ }, {
405
+ tag: "a",
406
+ attributes: {
407
+ class: "ck-media__placeholder__url",
408
+ target: "_blank",
409
+ rel: "noopener noreferrer",
410
+ href: this.url,
411
+ "data-cke-tooltip-text": t("Open media in new tab")
412
+ },
413
+ children: [{
414
+ tag: "span",
415
+ attributes: { class: "ck-media__placeholder__url__text" },
416
+ children: [this.url]
417
+ }]
418
+ }]
419
+ }).render().outerHTML;
420
+ }
421
+ /**
422
+ * Returns the full URL to the specified media.
423
+ *
424
+ * @param url The URL of the media.
425
+ */
426
+ _getValidUrl(url) {
427
+ if (!url) return null;
428
+ if (url.match(/^https?/)) return url;
429
+ return "https://" + url;
430
+ }
431
+ };
432
+
433
+ /**
434
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
435
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
436
+ */
437
+ /**
438
+ * @module media-embed/mediaembedediting
439
+ */
440
+ /**
441
+ * The media embed editing feature.
442
+ */
443
+ var MediaEmbedEditing = class extends Plugin {
444
+ /**
445
+ * @inheritDoc
446
+ */
447
+ static get pluginName() {
448
+ return "MediaEmbedEditing";
449
+ }
450
+ /**
451
+ * @inheritDoc
452
+ */
453
+ static get isOfficialPlugin() {
454
+ return true;
455
+ }
456
+ /**
457
+ * The media registry managing the media providers in the editor.
458
+ */
459
+ registry;
460
+ /**
461
+ * @inheritDoc
462
+ */
463
+ constructor(editor) {
464
+ super(editor);
465
+ editor.config.define("mediaEmbed", {
466
+ elementName: "oembed",
467
+ providers: [
468
+ {
469
+ name: "dailymotion",
470
+ url: [/^dailymotion\.com\/video\/(\w+)/, /^dai.ly\/(\w+)/],
471
+ html: (match) => {
472
+ return `<div><iframe src="https://www.dailymotion.com/embed/video/${match[1]}" width="1280" height="720" style="width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; display: block;" frameborder="0" allowfullscreen allow="autoplay"></iframe></div>`;
473
+ }
474
+ },
475
+ {
476
+ name: "spotify",
477
+ url: [
478
+ /^open\.spotify\.com\/(artist\/\w+)/,
479
+ /^open\.spotify\.com\/(album\/\w+)/,
480
+ /^open\.spotify\.com\/(track\/\w+)/
481
+ ],
482
+ html: (match) => {
483
+ const id = match[1];
484
+ const isTrack = id.startsWith("track/");
485
+ return `<div><iframe src="https://open.spotify.com/embed/${id}" width="300" height="${isTrack ? "80" : "378"}" style="${isTrack ? "width: 100%; height: 80px; border: 0; display: block;" : "width: 100%; height: auto; aspect-ratio: 100 / 126; border: 0; display: block;"}" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe></div>`;
486
+ }
487
+ },
488
+ {
489
+ name: "youtube",
490
+ url: [
491
+ /^(?:m\.)?youtube\.com\/watch\?v=([\w-]+)(?:&t=(\d+))?/,
492
+ /^(?:m\.)?youtube\.com\/shorts\/([\w-]+)(?:\?t=(\d+))?/,
493
+ /^(?:m\.)?youtube\.com\/v\/([\w-]+)(?:\?t=(\d+))?/,
494
+ /^youtube\.com\/embed\/([\w-]+)(?:\?start=(\d+))?/,
495
+ /^youtu\.be\/([\w-]+)(?:\?t=(\d+))?/
496
+ ],
497
+ html: (match) => {
498
+ const id = match[1];
499
+ const time = match[2];
500
+ return `<div><iframe src="https://www.youtube.com/embed/${id}${time ? `?start=${time}` : ""}" width="1280" height="720" style="width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; display: block;" frameborder="0" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></div>`;
501
+ }
502
+ },
503
+ {
504
+ name: "vimeo",
505
+ url: [
506
+ /^vimeo\.com\/(\d+)/,
507
+ /^vimeo\.com\/[^/]+\/[^/]+\/video\/(\d+)/,
508
+ /^vimeo\.com\/album\/[^/]+\/video\/(\d+)/,
509
+ /^vimeo\.com\/channels\/[^/]+\/(\d+)/,
510
+ /^vimeo\.com\/groups\/[^/]+\/videos\/(\d+)/,
511
+ /^vimeo\.com\/ondemand\/[^/]+\/(\d+)/,
512
+ /^player\.vimeo\.com\/video\/(\d+)/
513
+ ],
514
+ html: (match) => {
515
+ return `<div><iframe src="https://player.vimeo.com/video/${match[1]}" width="1280" height="720" style="width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; display: block;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>`;
516
+ }
517
+ },
518
+ {
519
+ name: "instagram",
520
+ url: [/^instagram\.com\/p\/(\w+)/, /^instagram\.com\/reel\/(\w+)/]
521
+ },
522
+ {
523
+ name: "twitter",
524
+ url: [/^twitter\.com/, /^x\.com/]
525
+ },
526
+ {
527
+ name: "googleMaps",
528
+ url: [
529
+ /^google\.com\/maps/,
530
+ /^goo\.gl\/maps/,
531
+ /^maps\.google\.com/,
532
+ /^maps\.app\.goo\.gl/
533
+ ]
534
+ },
535
+ {
536
+ name: "flickr",
537
+ url: /^flickr\.com/
538
+ },
539
+ {
540
+ name: "facebook",
541
+ url: /^facebook\.com/
542
+ }
543
+ ]
544
+ });
545
+ this.registry = new MediaRegistry(editor.locale, editor.config.get("mediaEmbed"));
546
+ }
547
+ /**
548
+ * @inheritDoc
549
+ */
550
+ init() {
551
+ const editor = this.editor;
552
+ const schema = editor.model.schema;
553
+ const t = editor.t;
554
+ const conversion = editor.conversion;
555
+ const renderMediaPreview = editor.config.get("mediaEmbed.previewsInData");
556
+ const elementName = editor.config.get("mediaEmbed.elementName");
557
+ const registry = this.registry;
558
+ editor.commands.add("mediaEmbed", new MediaEmbedCommand(editor));
559
+ schema.register("media", {
560
+ inheritAllFrom: "$blockObject",
561
+ allowAttributes: ["url"]
562
+ });
563
+ conversion.for("dataDowncast").elementToStructure({
564
+ model: "media",
565
+ view: (modelElement, { writer }) => {
566
+ const url = modelElement.getAttribute("url");
567
+ return createMediaFigureElement(writer, registry, url, {
568
+ elementName,
569
+ renderMediaPreview: !!url && renderMediaPreview
570
+ });
571
+ }
572
+ });
573
+ conversion.for("dataDowncast").add(modelToViewUrlAttributeConverter(registry, {
574
+ elementName,
575
+ renderMediaPreview
576
+ }));
577
+ conversion.for("editingDowncast").elementToStructure({
578
+ model: "media",
579
+ view: (modelElement, { writer }) => {
580
+ const url = modelElement.getAttribute("url");
581
+ const figure = createMediaFigureElement(writer, registry, url, {
582
+ elementName,
583
+ renderForEditingView: true
584
+ });
585
+ return toMediaWidget(figure, writer, t("media widget"));
586
+ }
587
+ });
588
+ conversion.for("editingDowncast").add(modelToViewUrlAttributeConverter(registry, {
589
+ elementName,
590
+ renderForEditingView: true
591
+ }));
592
+ conversion.for("upcast").elementToElement({
593
+ view: (element) => ["oembed", elementName].includes(element.name) && element.getAttribute("url") ? { name: true } : null,
594
+ model: (viewMedia, { writer }) => {
595
+ const url = viewMedia.getAttribute("url");
596
+ if (registry.hasMedia(url)) return writer.createElement("media", { url });
597
+ return null;
598
+ }
599
+ }).elementToElement({
600
+ view: {
601
+ name: "div",
602
+ attributes: { "data-oembed-url": true }
603
+ },
604
+ model: (viewMedia, { writer }) => {
605
+ const url = viewMedia.getAttribute("data-oembed-url");
606
+ if (registry.hasMedia(url)) return writer.createElement("media", { url });
607
+ return null;
608
+ }
609
+ }).add((dispatcher) => {
610
+ const converter = (evt, data, conversionApi) => {
611
+ if (!conversionApi.consumable.consume(data.viewItem, {
612
+ name: true,
613
+ classes: "media"
614
+ })) return;
615
+ const { modelRange, modelCursor } = conversionApi.convertChildren(data.viewItem, data.modelCursor);
616
+ data.modelRange = modelRange;
617
+ data.modelCursor = modelCursor;
618
+ if (!first(modelRange.getItems())) conversionApi.consumable.revert(data.viewItem, {
619
+ name: true,
620
+ classes: "media"
621
+ });
622
+ };
623
+ dispatcher.on("element:figure", converter);
624
+ });
625
+ }
626
+ };
627
+
628
+ /**
629
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
630
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
631
+ */
632
+ /**
633
+ * @module media-embed/automediaembed
634
+ */
635
+ const URL_REGEXP = /^(?:http(s)?:\/\/)?[\w-]+\.[\w-.~:/?#[\]@!$&'()*+,;=%]+$/;
636
+ /**
637
+ * The auto-media embed plugin. It recognizes media links in the pasted content and embeds
638
+ * them shortly after they are injected into the document.
639
+ */
640
+ var AutoMediaEmbed = class extends Plugin {
641
+ /**
642
+ * @inheritDoc
643
+ */
644
+ static get requires() {
645
+ return [
646
+ Clipboard,
647
+ Delete,
648
+ Undo
649
+ ];
650
+ }
651
+ /**
652
+ * @inheritDoc
653
+ */
654
+ static get pluginName() {
655
+ return "AutoMediaEmbed";
656
+ }
657
+ /**
658
+ * @inheritDoc
659
+ */
660
+ static get isOfficialPlugin() {
661
+ return true;
662
+ }
663
+ /**
664
+ * The paste–to–embed `setTimeout` ID. Stored as a property to allow
665
+ * cleaning of the timeout.
666
+ */
667
+ _timeoutId;
668
+ /**
669
+ * The position where the `<media>` element will be inserted after the timeout,
670
+ * determined each time the new content is pasted into the document.
671
+ */
672
+ _positionToInsert;
673
+ /**
674
+ * @inheritDoc
675
+ */
676
+ constructor(editor) {
677
+ super(editor);
678
+ this._timeoutId = null;
679
+ this._positionToInsert = null;
680
+ }
681
+ /**
682
+ * @inheritDoc
683
+ */
684
+ init() {
685
+ const editor = this.editor;
686
+ const modelDocument = editor.model.document;
687
+ const clipboardPipeline = editor.plugins.get("ClipboardPipeline");
688
+ this.listenTo(clipboardPipeline, "inputTransformation", () => {
689
+ const firstRange = modelDocument.selection.getFirstRange();
690
+ const leftLivePosition = ModelLivePosition.fromPosition(firstRange.start);
691
+ leftLivePosition.stickiness = "toPrevious";
692
+ const rightLivePosition = ModelLivePosition.fromPosition(firstRange.end);
693
+ rightLivePosition.stickiness = "toNext";
694
+ modelDocument.once("change:data", () => {
695
+ this._embedMediaBetweenPositions(leftLivePosition, rightLivePosition);
696
+ leftLivePosition.detach();
697
+ rightLivePosition.detach();
698
+ }, { priority: "high" });
699
+ });
700
+ editor.commands.get("undo").on("execute", () => {
701
+ if (this._timeoutId) {
702
+ global.window.clearTimeout(this._timeoutId);
703
+ this._positionToInsert.detach();
704
+ this._timeoutId = null;
705
+ this._positionToInsert = null;
706
+ }
707
+ }, { priority: "high" });
708
+ }
709
+ /**
710
+ * Analyzes the part of the document between provided positions in search for a URL representing media.
711
+ * When the URL is found, it is automatically converted into media.
712
+ *
713
+ * @param leftPosition Left position of the selection.
714
+ * @param rightPosition Right position of the selection.
715
+ */
716
+ _embedMediaBetweenPositions(leftPosition, rightPosition) {
717
+ const editor = this.editor;
718
+ const mediaRegistry = editor.plugins.get(MediaEmbedEditing).registry;
719
+ const urlRange = new ModelLiveRange(leftPosition, rightPosition);
720
+ const walker = urlRange.getWalker({ ignoreElementEnd: true });
721
+ let url = "";
722
+ for (const node of walker) if (node.item.is("$textProxy")) url += node.item.data;
723
+ url = url.trim();
724
+ if (!url.match(URL_REGEXP)) {
725
+ urlRange.detach();
726
+ return;
727
+ }
728
+ if (!mediaRegistry.hasMedia(url)) {
729
+ urlRange.detach();
730
+ return;
731
+ }
732
+ if (!editor.commands.get("mediaEmbed").isEnabled) {
733
+ urlRange.detach();
734
+ return;
735
+ }
736
+ this._positionToInsert = ModelLivePosition.fromPosition(leftPosition);
737
+ this._timeoutId = global.window.setTimeout(() => {
738
+ editor.model.change((writer) => {
739
+ this._timeoutId = null;
740
+ writer.remove(urlRange);
741
+ urlRange.detach();
742
+ let insertionPosition = null;
743
+ if (this._positionToInsert.root.rootName !== "$graveyard") insertionPosition = this._positionToInsert;
744
+ insertMedia(editor.model, url, insertionPosition, false);
745
+ this._positionToInsert.detach();
746
+ this._positionToInsert = null;
747
+ });
748
+ editor.plugins.get(Delete).requestUndoOnBackspace();
749
+ }, 100);
750
+ }
751
+ };
752
+
753
+ /**
754
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
755
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
756
+ */
757
+ /**
758
+ * @module media-embed/ui/mediaformview
759
+ */
760
+ /**
761
+ * The media form view controller class.
762
+ *
763
+ * See {@link module:media-embed/ui/mediaformview~MediaFormView}.
764
+ */
765
+ var MediaFormView = class extends View {
766
+ /**
767
+ * Tracks information about the DOM focus in the form.
768
+ */
769
+ focusTracker;
770
+ /**
771
+ * An instance of the {@link module:utils/keystrokehandler~KeystrokeHandler}.
772
+ */
773
+ keystrokes;
774
+ /**
775
+ * The URL input view.
776
+ */
777
+ urlInputView;
778
+ /**
779
+ * An array of form validators used by {@link #isValid}.
780
+ */
781
+ _validators;
782
+ /**
783
+ * The default info text for the {@link #urlInputView}.
784
+ */
785
+ _urlInputViewInfoDefault;
786
+ /**
787
+ * The info text with an additional tip for the {@link #urlInputView},
788
+ * displayed when the input has some value.
789
+ */
790
+ _urlInputViewInfoTip;
791
+ /**
792
+ * @param validators Form validators used by {@link #isValid}.
793
+ * @param locale The localization services instance.
794
+ */
795
+ constructor(validators, locale) {
796
+ super(locale);
797
+ this.focusTracker = new FocusTracker();
798
+ this.keystrokes = new KeystrokeHandler();
799
+ this.set("mediaURLInputValue", "");
800
+ this.urlInputView = this._createUrlInput();
801
+ this._validators = validators;
802
+ this.setTemplate({
803
+ tag: "form",
804
+ attributes: {
805
+ class: [
806
+ "ck",
807
+ "ck-media-form",
808
+ "ck-responsive-form"
809
+ ],
810
+ tabindex: "-1"
811
+ },
812
+ children: [this.urlInputView]
813
+ });
814
+ }
815
+ /**
816
+ * @inheritDoc
817
+ */
818
+ render() {
819
+ super.render();
820
+ submitHandler({ view: this });
821
+ this.focusTracker.add(this.urlInputView.element);
822
+ this.keystrokes.listenTo(this.element);
823
+ }
824
+ /**
825
+ * @inheritDoc
826
+ */
827
+ destroy() {
828
+ super.destroy();
829
+ this.focusTracker.destroy();
830
+ this.keystrokes.destroy();
831
+ }
832
+ /**
833
+ * Focuses the {@link #urlInputView}.
834
+ */
835
+ focus() {
836
+ this.urlInputView.focus();
837
+ }
838
+ /**
839
+ * The native DOM `value` of the {@link #urlInputView} element.
840
+ *
841
+ * **Note**: Do not confuse it with the {@link module:ui/inputtext/inputtextview~InputTextView#value}
842
+ * which works one way only and may not represent the actual state of the component in the DOM.
843
+ */
844
+ get url() {
845
+ return this.urlInputView.fieldView.element.value.trim();
846
+ }
847
+ set url(url) {
848
+ this.urlInputView.fieldView.value = url.trim();
849
+ }
850
+ /**
851
+ * Validates the form and returns `false` when some fields are invalid.
852
+ */
853
+ isValid() {
854
+ this.resetFormStatus();
855
+ for (const validator of this._validators) {
856
+ const errorText = validator(this);
857
+ if (errorText) {
858
+ this.urlInputView.errorText = errorText;
859
+ return false;
860
+ }
861
+ }
862
+ return true;
863
+ }
864
+ /**
865
+ * Cleans up the supplementary error and information text of the {@link #urlInputView}
866
+ * bringing them back to the state when the form has been displayed for the first time.
867
+ *
868
+ * See {@link #isValid}.
869
+ */
870
+ resetFormStatus() {
871
+ this.urlInputView.errorText = null;
872
+ this.urlInputView.infoText = this._urlInputViewInfoDefault;
873
+ }
874
+ /**
875
+ * Creates a labeled input view.
876
+ *
877
+ * @returns Labeled input view instance.
878
+ */
879
+ _createUrlInput() {
880
+ const t = this.locale.t;
881
+ const labeledInput = new LabeledFieldView(this.locale, createLabeledInputText);
882
+ const inputField = labeledInput.fieldView;
883
+ this._urlInputViewInfoDefault = t("Paste the media URL in the input.");
884
+ this._urlInputViewInfoTip = t("Tip: Paste the URL into the content to embed faster.");
885
+ labeledInput.label = t("Media URL");
886
+ labeledInput.infoText = this._urlInputViewInfoDefault;
887
+ inputField.inputMode = "url";
888
+ inputField.on("input", () => {
889
+ labeledInput.infoText = inputField.element.value ? this._urlInputViewInfoTip : this._urlInputViewInfoDefault;
890
+ this.mediaURLInputValue = inputField.element.value.trim();
891
+ });
892
+ return labeledInput;
893
+ }
894
+ };
895
+
896
+ /**
897
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
898
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
899
+ */
900
+ /**
901
+ * @module media-embed/mediaembedui
902
+ */
216
903
  /**
217
- * Checks if the media object is selected.
218
- */ function isMediaSelected(selection) {
219
- const element = selection.getSelectedElement();
220
- return !!element && element.name === 'media';
904
+ * The media embed UI plugin.
905
+ */
906
+ var MediaEmbedUI = class extends Plugin {
907
+ /**
908
+ * @inheritDoc
909
+ */
910
+ static get requires() {
911
+ return [MediaEmbedEditing, Dialog];
912
+ }
913
+ /**
914
+ * @inheritDoc
915
+ */
916
+ static get pluginName() {
917
+ return "MediaEmbedUI";
918
+ }
919
+ /**
920
+ * @inheritDoc
921
+ */
922
+ static get isOfficialPlugin() {
923
+ return true;
924
+ }
925
+ _formView;
926
+ /**
927
+ * @inheritDoc
928
+ */
929
+ init() {
930
+ const editor = this.editor;
931
+ editor.ui.componentFactory.add("mediaEmbed", () => {
932
+ const t = this.editor.locale.t;
933
+ const button = this._createDialogButton(ButtonView);
934
+ button.tooltip = true;
935
+ button.label = t("Insert media");
936
+ return button;
937
+ });
938
+ editor.ui.componentFactory.add("menuBar:mediaEmbed", () => {
939
+ const t = this.editor.locale.t;
940
+ const button = this._createDialogButton(MenuBarMenuListItemButtonView);
941
+ button.label = t("Media");
942
+ return button;
943
+ });
944
+ }
945
+ /**
946
+ * Creates a button for menu bar that will show media embed dialog.
947
+ */
948
+ _createDialogButton(ButtonClass) {
949
+ const editor = this.editor;
950
+ const buttonView = new ButtonClass(editor.locale);
951
+ const command = editor.commands.get("mediaEmbed");
952
+ const dialogPlugin = this.editor.plugins.get("Dialog");
953
+ buttonView.icon = IconMedia;
954
+ buttonView.bind("isEnabled").to(command, "isEnabled");
955
+ buttonView.on("execute", () => {
956
+ if (dialogPlugin.id === "mediaEmbed") dialogPlugin.hide();
957
+ else this._showDialog();
958
+ });
959
+ return buttonView;
960
+ }
961
+ _showDialog() {
962
+ const editor = this.editor;
963
+ const dialog = editor.plugins.get("Dialog");
964
+ const command = editor.commands.get("mediaEmbed");
965
+ const t = editor.locale.t;
966
+ const isMediaSelected = command.value !== void 0;
967
+ if (!this._formView) {
968
+ const registry = editor.plugins.get(MediaEmbedEditing).registry;
969
+ this._formView = new (CssTransitionDisablerMixin(MediaFormView))(getFormValidators$1(editor.t, registry), editor.locale);
970
+ this._formView.on("submit", () => this._handleSubmitForm());
971
+ }
972
+ dialog.show({
973
+ id: "mediaEmbed",
974
+ title: t("Media embed"),
975
+ content: this._formView,
976
+ isModal: true,
977
+ onShow: () => {
978
+ this._formView.url = command.value || "";
979
+ this._formView.resetFormStatus();
980
+ this._formView.urlInputView.fieldView.select();
981
+ },
982
+ actionButtons: [{
983
+ label: t("Cancel"),
984
+ withText: true,
985
+ onExecute: () => dialog.hide()
986
+ }, {
987
+ label: isMediaSelected ? t("Save") : t("Insert"),
988
+ class: "ck-button-action",
989
+ withText: true,
990
+ onExecute: () => this._handleSubmitForm()
991
+ }]
992
+ });
993
+ }
994
+ _handleSubmitForm() {
995
+ const editor = this.editor;
996
+ const dialog = editor.plugins.get("Dialog");
997
+ if (this._formView.isValid()) {
998
+ editor.execute("mediaEmbed", this._formView.url);
999
+ dialog.hide();
1000
+ editor.editing.view.focus();
1001
+ }
1002
+ }
1003
+ };
1004
+ function getFormValidators$1(t, registry) {
1005
+ return [(form) => {
1006
+ if (!form.url.length) return t("The URL must not be empty.");
1007
+ }, (form) => {
1008
+ if (!registry.hasMedia(form.url)) return t("This media URL is not supported.");
1009
+ }];
221
1010
  }
222
1011
 
223
- const mediaPlaceholderIconViewBox = '0 0 64 42';
224
- /**
225
- * A bridge between the raw media content provider definitions and the editor view content.
226
- *
227
- * It helps translating media URLs to corresponding {@link module:engine/view/element~ViewElement view elements}.
228
- *
229
- * Mostly used by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} plugin.
230
- */ class MediaRegistry {
231
- /**
232
- * The {@link module:utils/locale~Locale} instance.
233
- */ locale;
234
- /**
235
- * The media provider definitions available for the registry. Usually corresponding with the
236
- * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig media configuration}.
237
- */ providerDefinitions;
238
- /**
239
- * Creates an instance of the {@link module:media-embed/mediaregistry~MediaRegistry} class.
240
- *
241
- * @param locale The localization services instance.
242
- * @param config The configuration of the media embed feature.
243
- */ constructor(locale, config){
244
- const providers = config.providers;
245
- const extraProviders = config.extraProviders || [];
246
- const removedProviders = new Set(config.removeProviders);
247
- const providerDefinitions = providers.concat(extraProviders).filter((provider)=>{
248
- const name = provider.name;
249
- if (!name) {
250
- /**
251
- * One of the providers (or extra providers) specified in the media embed configuration
252
- * has no name and will not be used by the editor. In order to get this media
253
- * provider working, double check your editor configuration.
254
- *
255
- * @error media-embed-no-provider-name
256
- */ logWarning('media-embed-no-provider-name', {
257
- provider
258
- });
259
- return false;
260
- }
261
- return !removedProviders.has(name);
262
- });
263
- this.locale = locale;
264
- this.providerDefinitions = providerDefinitions;
265
- }
266
- /**
267
- * Checks whether the passed URL is representing a certain media type allowed in the editor.
268
- *
269
- * @param url The URL to be checked
270
- */ hasMedia(url) {
271
- return !!this._getMedia(url);
272
- }
273
- /**
274
- * For the given media URL string and options, it returns the {@link module:engine/view/element~ViewElement view element}
275
- * representing that media.
276
- *
277
- * **Note:** If no URL is specified, an empty view element is returned.
278
- *
279
- * @param writer The view writer used to produce a view element.
280
- * @param url The URL to be translated into a view element.
281
- */ getMediaViewElement(writer, url, options) {
282
- return this._getMedia(url).getViewElement(writer, options);
283
- }
284
- /**
285
- * Returns a `Media` instance for the given URL.
286
- *
287
- * @param url The URL of the media.
288
- * @returns The `Media` instance or `null` when there is none.
289
- */ _getMedia(url) {
290
- if (!url) {
291
- return new Media(this.locale);
292
- }
293
- url = url.trim();
294
- for (const definition of this.providerDefinitions){
295
- const previewRenderer = definition.html;
296
- const pattern = toArray(definition.url);
297
- for (const subPattern of pattern){
298
- const match = this._getUrlMatches(url, subPattern);
299
- if (match) {
300
- return new Media(this.locale, url, match, previewRenderer);
301
- }
302
- }
303
- }
304
- return null;
305
- }
306
- /**
307
- * Tries to match `url` to `pattern`.
308
- *
309
- * @param url The URL of the media.
310
- * @param pattern The pattern that should accept the media URL.
311
- */ _getUrlMatches(url, pattern) {
312
- // 1. Try to match without stripping the protocol and "www" subdomain.
313
- let match = url.match(pattern);
314
- if (match) {
315
- return match;
316
- }
317
- // 2. Try to match after stripping the protocol.
318
- let rawUrl = url.replace(/^https?:\/\//, '');
319
- match = rawUrl.match(pattern);
320
- if (match) {
321
- return match;
322
- }
323
- // 3. Try to match after stripping the "www" subdomain.
324
- rawUrl = rawUrl.replace(/^www\./, '');
325
- match = rawUrl.match(pattern);
326
- if (match) {
327
- return match;
328
- }
329
- return null;
330
- }
1012
+ /**
1013
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1014
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1015
+ */
1016
+ /**
1017
+ * @module media-embed/mediaembed
1018
+ */
1019
+ /**
1020
+ * The media embed plugin.
1021
+ *
1022
+ * For a detailed overview, check the {@glink features/media-embed/media-embed Media Embed feature documentation}.
1023
+ *
1024
+ * This is a "glue" plugin which loads the following plugins:
1025
+ *
1026
+ * * The {@link module:media-embed/mediaembedediting~MediaEmbedEditing media embed editing feature},
1027
+ * * The {@link module:media-embed/mediaembedui~MediaEmbedUI media embed UI feature} and
1028
+ * * The {@link module:media-embed/automediaembed~AutoMediaEmbed auto-media embed feature}.
1029
+ */
1030
+ var MediaEmbed = class extends Plugin {
1031
+ /**
1032
+ * @inheritDoc
1033
+ */
1034
+ static get requires() {
1035
+ return [
1036
+ MediaEmbedEditing,
1037
+ MediaEmbedUI,
1038
+ AutoMediaEmbed,
1039
+ Widget
1040
+ ];
1041
+ }
1042
+ /**
1043
+ * @inheritDoc
1044
+ */
1045
+ static get pluginName() {
1046
+ return "MediaEmbed";
1047
+ }
1048
+ /**
1049
+ * @inheritDoc
1050
+ */
1051
+ static get isOfficialPlugin() {
1052
+ return true;
1053
+ }
1054
+ };
1055
+
1056
+ /**
1057
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1058
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1059
+ */
1060
+ /**
1061
+ * @module media-embed/mediaembedstyle/constants
1062
+ */
1063
+ /**
1064
+ * Built-in style options provided by the plugin. Integrators can refer to these by
1065
+ * name in {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles`}
1066
+ * to opt out, override individual fields, or coexist with custom styles.
1067
+ *
1068
+ * @internal
1069
+ */
1070
+ const DEFAULT_OPTIONS = {
1071
+ alignLeft: {
1072
+ name: "alignLeft",
1073
+ title: "Left aligned media",
1074
+ icon: IconObjectInlineLeft,
1075
+ className: "media-style-align-left"
1076
+ },
1077
+ alignBlockLeft: {
1078
+ name: "alignBlockLeft",
1079
+ title: "Left aligned media",
1080
+ icon: IconObjectLeft,
1081
+ className: "media-style-block-align-left"
1082
+ },
1083
+ alignCenter: {
1084
+ name: "alignCenter",
1085
+ title: "Centered media",
1086
+ icon: IconObjectCenter,
1087
+ isDefault: true
1088
+ },
1089
+ alignBlockRight: {
1090
+ name: "alignBlockRight",
1091
+ title: "Right aligned media",
1092
+ icon: IconObjectRight,
1093
+ className: "media-style-block-align-right"
1094
+ },
1095
+ alignRight: {
1096
+ name: "alignRight",
1097
+ title: "Right aligned media",
1098
+ icon: IconObjectInlineRight,
1099
+ className: "media-style-align-right"
1100
+ }
1101
+ };
1102
+ /**
1103
+ * Short icon-name aliases that can be used as the `icon` value in a media style
1104
+ * option definition. Matches the alias set exposed by the image styles feature so
1105
+ * the two APIs feel symmetrical.
1106
+ *
1107
+ * @internal
1108
+ */
1109
+ const DEFAULT_ICONS = {
1110
+ inlineLeft: IconObjectInlineLeft,
1111
+ left: IconObjectLeft,
1112
+ center: IconObjectCenter,
1113
+ right: IconObjectRight,
1114
+ inlineRight: IconObjectInlineRight
1115
+ };
1116
+ /**
1117
+ * Built-in dropdown groupings. Each entry references built-in style component names. If any
1118
+ * items are filtered out by configuration, the dropdown is rebuilt from the remaining names
1119
+ * (or skipped entirely if fewer than two remain).
1120
+ *
1121
+ * @internal
1122
+ */
1123
+ const DEFAULT_DROPDOWN_DEFINITIONS = [{
1124
+ name: "mediaEmbed:wrapText",
1125
+ title: "Wrap text",
1126
+ items: ["mediaEmbed:alignLeft", "mediaEmbed:alignRight"],
1127
+ defaultItem: "mediaEmbed:alignLeft"
1128
+ }, {
1129
+ name: "mediaEmbed:breakText",
1130
+ title: "Break text",
1131
+ items: [
1132
+ "mediaEmbed:alignBlockLeft",
1133
+ "mediaEmbed:alignCenter",
1134
+ "mediaEmbed:alignBlockRight"
1135
+ ],
1136
+ defaultItem: "mediaEmbed:alignCenter"
1137
+ }];
1138
+
1139
+ /**
1140
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1141
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1142
+ */
1143
+ /**
1144
+ * @module media-embed/mediaembedstyle/utils
1145
+ */
1146
+ /**
1147
+ * Normalizes the {@link module:media-embed/mediaembedconfig~MediaStyleConfig#options style options}
1148
+ * provided by the integrator. Each entry is resolved into a full
1149
+ * {@link module:media-embed/mediaembedconfig~MediaStyleOptionDefinition} and invalid entries
1150
+ * are filtered out with a console warning.
1151
+ *
1152
+ * @internal
1153
+ */
1154
+ function normalizeStyles(configuredStyles) {
1155
+ return (configuredStyles.options || []).map((entry) => normalizeDefinition(entry)).filter((entry) => isValidOption(entry));
331
1156
  }
332
1157
  /**
333
- * Represents media defined by the provider configuration.
334
- *
335
- * It can be rendered to the {@link module:engine/view/element~ViewElement view element} and used in the editing or data pipeline.
336
- */ class Media {
337
- /**
338
- * The URL this Media instance represents.
339
- */ url;
340
- /**
341
- * Shorthand for {@link module:utils/locale~Locale#t}.
342
- *
343
- * @see module:utils/locale~Locale#t
344
- */ _locale;
345
- /**
346
- * The output of the `RegExp.match` which validated the {@link #url} of this media.
347
- */ _match;
348
- /**
349
- * The function returning the HTML string preview of this media.
350
- */ _previewRenderer;
351
- constructor(locale, url, match, previewRenderer){
352
- this.url = this._getValidUrl(url);
353
- this._locale = locale;
354
- this._match = match;
355
- this._previewRenderer = previewRenderer;
356
- }
357
- /**
358
- * Returns the view element representation of the media.
359
- *
360
- * @param writer The view writer used to produce a view element.
361
- */ getViewElement(writer, options) {
362
- const attributes = {};
363
- let viewElement;
364
- if (options.renderForEditingView || options.renderMediaPreview && this.url && this._previewRenderer) {
365
- if (this.url) {
366
- attributes['data-oembed-url'] = this.url;
367
- }
368
- if (options.renderForEditingView) {
369
- attributes.class = 'ck-media__wrapper';
370
- }
371
- const mediaHtml = this._getPreviewHtml(options);
372
- viewElement = writer.createRawElement('div', attributes, (domElement, domConverter)=>{
373
- domConverter.setContentOf(domElement, mediaHtml);
374
- });
375
- } else {
376
- if (this.url) {
377
- attributes.url = this.url;
378
- }
379
- viewElement = writer.createEmptyElement(options.elementName, attributes);
380
- }
381
- writer.setCustomProperty('media-content', true, viewElement);
382
- return viewElement;
383
- }
384
- /**
385
- * Returns the HTML string of the media content preview.
386
- */ _getPreviewHtml(options) {
387
- if (this._previewRenderer) {
388
- return this._previewRenderer(this._match);
389
- } else {
390
- // The placeholder only makes sense for editing view and media which have URLs.
391
- // Placeholder is never displayed in data and URL-less media have no content.
392
- if (this.url && options.renderForEditingView) {
393
- return this._getPlaceholderHtml();
394
- }
395
- return '';
396
- }
397
- }
398
- /**
399
- * Returns the placeholder HTML when the media has no content preview.
400
- */ _getPlaceholderHtml() {
401
- const icon = new IconView();
402
- const t = this._locale.t;
403
- icon.content = IconMediaPlaceholder;
404
- icon.viewBox = mediaPlaceholderIconViewBox;
405
- const placeholder = new Template({
406
- tag: 'div',
407
- attributes: {
408
- class: 'ck ck-reset_all ck-media__placeholder'
409
- },
410
- children: [
411
- {
412
- tag: 'div',
413
- attributes: {
414
- class: 'ck-media__placeholder__icon'
415
- },
416
- children: [
417
- icon
418
- ]
419
- },
420
- {
421
- tag: 'a',
422
- attributes: {
423
- class: 'ck-media__placeholder__url',
424
- target: '_blank',
425
- rel: 'noopener noreferrer',
426
- href: this.url,
427
- 'data-cke-tooltip-text': t('Open media in new tab')
428
- },
429
- children: [
430
- {
431
- tag: 'span',
432
- attributes: {
433
- class: 'ck-media__placeholder__url__text'
434
- },
435
- children: [
436
- this.url
437
- ]
438
- }
439
- ]
440
- }
441
- ]
442
- }).render();
443
- return placeholder.outerHTML;
444
- }
445
- /**
446
- * Returns the full URL to the specified media.
447
- *
448
- * @param url The URL of the media.
449
- */ _getValidUrl(url) {
450
- if (!url) {
451
- return null;
452
- }
453
- if (url.match(/^https?/)) {
454
- return url;
455
- }
456
- return 'https://' + url;
457
- }
1158
+ * Resolves a single config entry into a style option definition. A string entry is first
1159
+ * promoted to its object form (`{ name }`) and then shallow-merged on top of the matching
1160
+ * built-in default — entries without a matching built-in pass through unchanged and are
1161
+ * rejected by {@link ~isValidOption} if they lack required fields.
1162
+ *
1163
+ * Also resolves icon-name aliases (`'left'`, `'inlineLeft'`, etc.) to the corresponding
1164
+ * SVG sources from {@link module:media-embed/mediaembedstyle/constants~DEFAULT_ICONS}.
1165
+ */
1166
+ function normalizeDefinition(entry) {
1167
+ const override = typeof entry === "string" ? { name: entry } : entry;
1168
+ const definition = {
1169
+ ...DEFAULT_OPTIONS[override.name],
1170
+ ...override
1171
+ };
1172
+ if (typeof definition.icon === "string" && DEFAULT_ICONS[definition.icon]) definition.icon = DEFAULT_ICONS[definition.icon];
1173
+ return definition;
1174
+ }
1175
+ /**
1176
+ * Validates a normalized style option. `name`, `title`, and `icon` are always required.
1177
+ * `className` is required unless the entry is the default style (defaults encode as
1178
+ * attribute-absence and intentionally have no class). Emits a console warning and returns
1179
+ * `false` when any of these checks fails.
1180
+ */
1181
+ function isValidOption(option) {
1182
+ if (!option.name || !option.title || !option.icon || !option.isDefault && !option.className) {
1183
+ warnInvalidStyle({ style: option });
1184
+ return false;
1185
+ }
1186
+ return true;
1187
+ }
1188
+ function warnInvalidStyle(info) {
1189
+ /**
1190
+ * The media style configuration provided in the editor config is invalid. The warning is
1191
+ * emitted in two situations:
1192
+ *
1193
+ * * An entry in {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles.options`}
1194
+ * does not reference a built-in style by name (`'alignLeft'`, `'alignBlockLeft'`,
1195
+ * `'alignCenter'`, `'alignBlockRight'`, `'alignRight'`) and does not follow the
1196
+ * {@link module:media-embed/mediaembedconfig~MediaStyleOptionDefinition} shape —
1197
+ * `name`, `title`, `icon`, and (unless `isDefault: true`) `className` are required.
1198
+ * The offending entry is reported under the `style` parameter.
1199
+ * * A dropdown entry placed inline in
1200
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#toolbar `config.mediaEmbed.toolbar`}
1201
+ * does not follow the {@link module:media-embed/mediaembedconfig~MediaStyleDropdownDefinition} shape
1202
+ * (`name` and every `items[]` entry must use the full `mediaEmbed:` prefix, `defaultItem` must
1203
+ * be one of the `items`, `title` must be a non-empty string), or its `items[]` reference styles
1204
+ * that are not in the resolved
1205
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles`} list.
1206
+ * The offending entry is reported under the `dropdown` parameter.
1207
+ *
1208
+ * @error media-style-configuration-definition-invalid
1209
+ */
1210
+ logWarning("media-style-configuration-definition-invalid", info);
1211
+ }
1212
+ /**
1213
+ * Type guard for toolbar config entries shaped like a media style dropdown definition. The
1214
+ * discriminator is `defaultItem` — generic toolbar groupings use `items` + `label` and never
1215
+ * carry a `defaultItem` field.
1216
+ *
1217
+ * @internal
1218
+ */
1219
+ function isMediaStyleDropdown(item) {
1220
+ return typeof item === "object" && item !== null && typeof item.defaultItem === "string";
458
1221
  }
459
1222
 
460
1223
  /**
461
- * The media embed editing feature.
462
- */ class MediaEmbedEditing extends Plugin {
463
- /**
464
- * @inheritDoc
465
- */ static get pluginName() {
466
- return 'MediaEmbedEditing';
467
- }
468
- /**
469
- * @inheritDoc
470
- */ static get isOfficialPlugin() {
471
- return true;
472
- }
473
- /**
474
- * The media registry managing the media providers in the editor.
475
- */ registry;
476
- /**
477
- * @inheritDoc
478
- */ constructor(editor){
479
- super(editor);
480
- editor.config.define('mediaEmbed', {
481
- elementName: 'oembed',
482
- providers: [
483
- {
484
- name: 'dailymotion',
485
- url: [
486
- /^dailymotion\.com\/video\/(\w+)/,
487
- /^dai.ly\/(\w+)/
488
- ],
489
- html: (match)=>{
490
- const id = match[1];
491
- return '<div style="position: relative; padding-bottom: 100%; height: 0; ">' + `<iframe src="https://www.dailymotion.com/embed/video/${id}" ` + 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' + 'frameborder="0" width="480" height="270" allowfullscreen allow="autoplay">' + '</iframe>' + '</div>';
492
- }
493
- },
494
- {
495
- name: 'spotify',
496
- url: [
497
- /^open\.spotify\.com\/(artist\/\w+)/,
498
- /^open\.spotify\.com\/(album\/\w+)/,
499
- /^open\.spotify\.com\/(track\/\w+)/
500
- ],
501
- html: (match)=>{
502
- const id = match[1];
503
- return '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 126%;">' + `<iframe src="https://open.spotify.com/embed/${id}" ` + 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' + 'frameborder="0" allowtransparency="true" allow="encrypted-media">' + '</iframe>' + '</div>';
504
- }
505
- },
506
- {
507
- name: 'youtube',
508
- url: [
509
- /^(?:m\.)?youtube\.com\/watch\?v=([\w-]+)(?:&t=(\d+))?/,
510
- /^(?:m\.)?youtube\.com\/shorts\/([\w-]+)(?:\?t=(\d+))?/,
511
- /^(?:m\.)?youtube\.com\/v\/([\w-]+)(?:\?t=(\d+))?/,
512
- /^youtube\.com\/embed\/([\w-]+)(?:\?start=(\d+))?/,
513
- /^youtu\.be\/([\w-]+)(?:\?t=(\d+))?/
514
- ],
515
- html: (match)=>{
516
- const id = match[1];
517
- const time = match[2];
518
- return '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 56.2493%;">' + `<iframe src="https://www.youtube.com/embed/${id}${time ? `?start=${time}` : ''}" ` + 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' + 'frameborder="0" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin" ' + 'allowfullscreen>' + '</iframe>' + '</div>';
519
- }
520
- },
521
- {
522
- name: 'vimeo',
523
- url: [
524
- /^vimeo\.com\/(\d+)/,
525
- /^vimeo\.com\/[^/]+\/[^/]+\/video\/(\d+)/,
526
- /^vimeo\.com\/album\/[^/]+\/video\/(\d+)/,
527
- /^vimeo\.com\/channels\/[^/]+\/(\d+)/,
528
- /^vimeo\.com\/groups\/[^/]+\/videos\/(\d+)/,
529
- /^vimeo\.com\/ondemand\/[^/]+\/(\d+)/,
530
- /^player\.vimeo\.com\/video\/(\d+)/
531
- ],
532
- html: (match)=>{
533
- const id = match[1];
534
- return '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 56.2493%;">' + `<iframe src="https://player.vimeo.com/video/${id}" ` + 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' + 'frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen>' + '</iframe>' + '</div>';
535
- }
536
- },
537
- {
538
- name: 'instagram',
539
- url: [
540
- /^instagram\.com\/p\/(\w+)/,
541
- /^instagram\.com\/reel\/(\w+)/
542
- ]
543
- },
544
- {
545
- name: 'twitter',
546
- url: [
547
- /^twitter\.com/,
548
- /^x\.com/
549
- ]
550
- },
551
- {
552
- name: 'googleMaps',
553
- url: [
554
- /^google\.com\/maps/,
555
- /^goo\.gl\/maps/,
556
- /^maps\.google\.com/,
557
- /^maps\.app\.goo\.gl/
558
- ]
559
- },
560
- {
561
- name: 'flickr',
562
- url: /^flickr\.com/
563
- },
564
- {
565
- name: 'facebook',
566
- url: /^facebook\.com/
567
- }
568
- ]
569
- });
570
- this.registry = new MediaRegistry(editor.locale, editor.config.get('mediaEmbed'));
571
- }
572
- /**
573
- * @inheritDoc
574
- */ init() {
575
- const editor = this.editor;
576
- const schema = editor.model.schema;
577
- const t = editor.t;
578
- const conversion = editor.conversion;
579
- const renderMediaPreview = editor.config.get('mediaEmbed.previewsInData');
580
- const elementName = editor.config.get('mediaEmbed.elementName');
581
- const registry = this.registry;
582
- editor.commands.add('mediaEmbed', new MediaEmbedCommand(editor));
583
- // Configure the schema.
584
- schema.register('media', {
585
- inheritAllFrom: '$blockObject',
586
- allowAttributes: [
587
- 'url'
588
- ]
589
- });
590
- // Model -> Data
591
- conversion.for('dataDowncast').elementToStructure({
592
- model: 'media',
593
- view: (modelElement, { writer })=>{
594
- const url = modelElement.getAttribute('url');
595
- return createMediaFigureElement(writer, registry, url, {
596
- elementName,
597
- renderMediaPreview: !!url && renderMediaPreview
598
- });
599
- }
600
- });
601
- // Model -> Data (url -> data-oembed-url)
602
- conversion.for('dataDowncast').add(modelToViewUrlAttributeConverter(registry, {
603
- elementName,
604
- renderMediaPreview
605
- }));
606
- // Model -> View (element)
607
- conversion.for('editingDowncast').elementToStructure({
608
- model: 'media',
609
- view: (modelElement, { writer })=>{
610
- const url = modelElement.getAttribute('url');
611
- const figure = createMediaFigureElement(writer, registry, url, {
612
- elementName,
613
- renderForEditingView: true
614
- });
615
- return toMediaWidget(figure, writer, t('media widget'));
616
- }
617
- });
618
- // Model -> View (url -> data-oembed-url)
619
- conversion.for('editingDowncast').add(modelToViewUrlAttributeConverter(registry, {
620
- elementName,
621
- renderForEditingView: true
622
- }));
623
- // View -> Model (data-oembed-url -> url)
624
- conversion.for('upcast')// Upcast semantic media.
625
- .elementToElement({
626
- view: (element)=>[
627
- 'oembed',
628
- elementName
629
- ].includes(element.name) && element.getAttribute('url') ? {
630
- name: true
631
- } : null,
632
- model: (viewMedia, { writer })=>{
633
- const url = viewMedia.getAttribute('url');
634
- if (registry.hasMedia(url)) {
635
- return writer.createElement('media', {
636
- url
637
- });
638
- }
639
- return null;
640
- }
641
- })// Upcast non-semantic media.
642
- .elementToElement({
643
- view: {
644
- name: 'div',
645
- attributes: {
646
- 'data-oembed-url': true
647
- }
648
- },
649
- model: (viewMedia, { writer })=>{
650
- const url = viewMedia.getAttribute('data-oembed-url');
651
- if (registry.hasMedia(url)) {
652
- return writer.createElement('media', {
653
- url
654
- });
655
- }
656
- return null;
657
- }
658
- })// Consume `<figure class="media">` elements, that were left after upcast.
659
- .add((dispatcher)=>{
660
- const converter = (evt, data, conversionApi)=>{
661
- if (!conversionApi.consumable.consume(data.viewItem, {
662
- name: true,
663
- classes: 'media'
664
- })) {
665
- return;
666
- }
667
- const { modelRange, modelCursor } = conversionApi.convertChildren(data.viewItem, data.modelCursor);
668
- data.modelRange = modelRange;
669
- data.modelCursor = modelCursor;
670
- const modelElement = first(modelRange.getItems());
671
- if (!modelElement) {
672
- // Revert consumed figure so other features can convert it.
673
- conversionApi.consumable.revert(data.viewItem, {
674
- name: true,
675
- classes: 'media'
676
- });
677
- }
678
- };
679
- dispatcher.on('element:figure', converter);
680
- });
681
- }
1224
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1225
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1226
+ */
1227
+ /**
1228
+ * @module media-embed/mediaembedtoolbar
1229
+ */
1230
+ /**
1231
+ * The media embed toolbar plugin. It creates a toolbar for media embed that shows up when the media element is selected.
1232
+ *
1233
+ * Instances of toolbar components (e.g. buttons) are created based on the
1234
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#toolbar `media.toolbar` configuration option}.
1235
+ */
1236
+ var MediaEmbedToolbar = class extends Plugin {
1237
+ /**
1238
+ * @inheritDoc
1239
+ */
1240
+ static get requires() {
1241
+ return [WidgetToolbarRepository];
1242
+ }
1243
+ /**
1244
+ * @inheritDoc
1245
+ */
1246
+ static get pluginName() {
1247
+ return "MediaEmbedToolbar";
1248
+ }
1249
+ /**
1250
+ * @inheritDoc
1251
+ */
1252
+ static get isOfficialPlugin() {
1253
+ return true;
1254
+ }
1255
+ /**
1256
+ * @inheritDoc
1257
+ */
1258
+ afterInit() {
1259
+ const editor = this.editor;
1260
+ const t = editor.t;
1261
+ editor.plugins.get(WidgetToolbarRepository).register("mediaEmbed", {
1262
+ ariaLabel: t("Media toolbar"),
1263
+ items: normalizeDeclarativeConfig(editor.ui.componentFactory, editor.config.get("mediaEmbed.toolbar") || []),
1264
+ getRelatedElement: getSelectedMediaViewWidget
1265
+ });
1266
+ }
1267
+ };
1268
+ /**
1269
+ * Flattens dropdown definitions to their factory names, dropping any `mediaEmbed:`-prefixed
1270
+ * name the style UI did not register — otherwise the toolbar crashes with `componentfactory-item-missing`.
1271
+ * Non-string entries (e.g. generic `{ label, items }` toolbar groupings) pass through unchanged.
1272
+ */
1273
+ function normalizeDeclarativeConfig(factory, config) {
1274
+ return config.map((item) => isMediaStyleDropdown(item) ? item.name : item).filter((item) => typeof item !== "string" || !item.startsWith("mediaEmbed:") || factory.has(item));
682
1275
  }
683
1276
 
684
- const URL_REGEXP = /^(?:http(s)?:\/\/)?[\w-]+\.[\w-.~:/?#[\]@!$&'()*+,;=%]+$/;
685
1277
  /**
686
- * The auto-media embed plugin. It recognizes media links in the pasted content and embeds
687
- * them shortly after they are injected into the document.
688
- */ class AutoMediaEmbed extends Plugin {
689
- /**
690
- * @inheritDoc
691
- */ static get requires() {
692
- return [
693
- Clipboard,
694
- Delete,
695
- Undo
696
- ];
697
- }
698
- /**
699
- * @inheritDoc
700
- */ static get pluginName() {
701
- return 'AutoMediaEmbed';
702
- }
703
- /**
704
- * @inheritDoc
705
- */ static get isOfficialPlugin() {
706
- return true;
707
- }
708
- /**
709
- * The paste–to–embed `setTimeout` ID. Stored as a property to allow
710
- * cleaning of the timeout.
711
- */ _timeoutId;
712
- /**
713
- * The position where the `<media>` element will be inserted after the timeout,
714
- * determined each time the new content is pasted into the document.
715
- */ _positionToInsert;
716
- /**
717
- * @inheritDoc
718
- */ constructor(editor){
719
- super(editor);
720
- this._timeoutId = null;
721
- this._positionToInsert = null;
722
- }
723
- /**
724
- * @inheritDoc
725
- */ init() {
726
- const editor = this.editor;
727
- const modelDocument = editor.model.document;
728
- // We need to listen on `Clipboard#inputTransformation` because we need to save positions of selection.
729
- // After pasting, the content between those positions will be checked for a URL that could be transformed
730
- // into media.
731
- const clipboardPipeline = editor.plugins.get('ClipboardPipeline');
732
- this.listenTo(clipboardPipeline, 'inputTransformation', ()=>{
733
- const firstRange = modelDocument.selection.getFirstRange();
734
- const leftLivePosition = ModelLivePosition.fromPosition(firstRange.start);
735
- leftLivePosition.stickiness = 'toPrevious';
736
- const rightLivePosition = ModelLivePosition.fromPosition(firstRange.end);
737
- rightLivePosition.stickiness = 'toNext';
738
- modelDocument.once('change:data', ()=>{
739
- this._embedMediaBetweenPositions(leftLivePosition, rightLivePosition);
740
- leftLivePosition.detach();
741
- rightLivePosition.detach();
742
- }, {
743
- priority: 'high'
744
- });
745
- });
746
- const undoCommand = editor.commands.get('undo');
747
- undoCommand.on('execute', ()=>{
748
- if (this._timeoutId) {
749
- global.window.clearTimeout(this._timeoutId);
750
- this._positionToInsert.detach();
751
- this._timeoutId = null;
752
- this._positionToInsert = null;
753
- }
754
- }, {
755
- priority: 'high'
756
- });
757
- }
758
- /**
759
- * Analyzes the part of the document between provided positions in search for a URL representing media.
760
- * When the URL is found, it is automatically converted into media.
761
- *
762
- * @param leftPosition Left position of the selection.
763
- * @param rightPosition Right position of the selection.
764
- */ _embedMediaBetweenPositions(leftPosition, rightPosition) {
765
- const editor = this.editor;
766
- const mediaRegistry = editor.plugins.get(MediaEmbedEditing).registry;
767
- // TODO: Use marker instead of ModelLiveRange & LivePositions.
768
- const urlRange = new ModelLiveRange(leftPosition, rightPosition);
769
- const walker = urlRange.getWalker({
770
- ignoreElementEnd: true
771
- });
772
- let url = '';
773
- for (const node of walker){
774
- if (node.item.is('$textProxy')) {
775
- url += node.item.data;
776
- }
777
- }
778
- url = url.trim();
779
- // If the URL does not match to universal URL regexp, let's skip that.
780
- if (!url.match(URL_REGEXP)) {
781
- urlRange.detach();
782
- return;
783
- }
784
- // If the URL represents a media, let's use it.
785
- if (!mediaRegistry.hasMedia(url)) {
786
- urlRange.detach();
787
- return;
788
- }
789
- const mediaEmbedCommand = editor.commands.get('mediaEmbed');
790
- // Do not anything if media element cannot be inserted at the current position (#47).
791
- if (!mediaEmbedCommand.isEnabled) {
792
- urlRange.detach();
793
- return;
794
- }
795
- // Position won't be available in the `setTimeout` function so let's clone it.
796
- this._positionToInsert = ModelLivePosition.fromPosition(leftPosition);
797
- // This action mustn't be executed if undo was called between pasting and auto-embedding.
798
- this._timeoutId = global.window.setTimeout(()=>{
799
- editor.model.change((writer)=>{
800
- this._timeoutId = null;
801
- writer.remove(urlRange);
802
- urlRange.detach();
803
- let insertionPosition = null;
804
- // Check if position where the media element should be inserted is still valid.
805
- // Otherwise leave it as undefined to use document.selection - default behavior of model.insertContent().
806
- if (this._positionToInsert.root.rootName !== '$graveyard') {
807
- insertionPosition = this._positionToInsert;
808
- }
809
- insertMedia(editor.model, url, insertionPosition, false);
810
- this._positionToInsert.detach();
811
- this._positionToInsert = null;
812
- });
813
- editor.plugins.get(Delete).requestUndoOnBackspace();
814
- }, 100);
815
- }
1278
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1279
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1280
+ */
1281
+ /**
1282
+ * @module media-embed/mediaembedresize/resizemediaembedcommand
1283
+ */
1284
+ /**
1285
+ * The resize media embed command.
1286
+ */
1287
+ var ResizeMediaEmbedCommand = class extends Command {
1288
+ /**
1289
+ * @inheritDoc
1290
+ */
1291
+ refresh() {
1292
+ const element = getSelectedMediaModelWidget(this.editor.model.document.selection);
1293
+ this.isEnabled = !!element;
1294
+ if (!element || !element.hasAttribute("resizedWidth")) this.value = null;
1295
+ else this.value = element.getAttribute("resizedWidth");
1296
+ }
1297
+ /**
1298
+ * Executes the command.
1299
+ *
1300
+ * ```ts
1301
+ * // Sets the width as a percentage of the parent width:
1302
+ * editor.execute( 'resizeMediaEmbed', { width: '50%' } );
1303
+ *
1304
+ * // Removes the resize and restores the default width:
1305
+ * editor.execute( 'resizeMediaEmbed', { width: null } );
1306
+ * ```
1307
+ *
1308
+ * @param options
1309
+ * @param options.width The new width of the media embed as a CSS `width` value
1310
+ * (e.g. `'50%'`), or `null` to remove the resize.
1311
+ * @fires execute
1312
+ */
1313
+ execute(options) {
1314
+ const model = this.editor.model;
1315
+ const mediaElement = getSelectedMediaModelWidget(model.document.selection);
1316
+ if (mediaElement) model.change((writer) => {
1317
+ writer.setAttribute("resizedWidth", options.width, mediaElement);
1318
+ });
1319
+ }
1320
+ };
1321
+
1322
+ /**
1323
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1324
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1325
+ */
1326
+ /**
1327
+ * @module media-embed/mediaembedresize/constants
1328
+ */
1329
+ /**
1330
+ * The view class applied to a resized media embed figure.
1331
+ *
1332
+ * Shared between the editing plugin (which toggles it via downcast of `resizedWidth` and consumes
1333
+ * it on upcast) and the handles plugin (which adds it during drag and strips it on commit), so
1334
+ * both layers agree on the exact class name.
1335
+ *
1336
+ * @internal
1337
+ */
1338
+ const RESIZED_MEDIA_CLASS = "media_resized";
1339
+
1340
+ /**
1341
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1342
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1343
+ */
1344
+ /**
1345
+ * The media embed resize editing feature.
1346
+ *
1347
+ * It adds the ability to resize each media embed using handles.
1348
+ */
1349
+ var MediaEmbedResizeEditing = class extends Plugin {
1350
+ /**
1351
+ * @inheritDoc
1352
+ */
1353
+ static get requires() {
1354
+ return [MediaEmbedEditing];
1355
+ }
1356
+ /**
1357
+ * @inheritDoc
1358
+ */
1359
+ static get pluginName() {
1360
+ return "MediaEmbedResizeEditing";
1361
+ }
1362
+ /**
1363
+ * @inheritDoc
1364
+ * @internal
1365
+ */
1366
+ static get licenseFeatureCode() {
1367
+ return "MER";
1368
+ }
1369
+ /**
1370
+ * @inheritDoc
1371
+ */
1372
+ static get isOfficialPlugin() {
1373
+ return true;
1374
+ }
1375
+ /**
1376
+ * @inheritDoc
1377
+ */
1378
+ static get isPremiumPlugin() {
1379
+ return true;
1380
+ }
1381
+ /**
1382
+ * @inheritDoc
1383
+ */
1384
+ constructor(editor) {
1385
+ super(editor);
1386
+ editor.config.define("mediaEmbed", {
1387
+ resizeUnit: "%",
1388
+ resizeOptions: [
1389
+ {
1390
+ name: "resizeMediaEmbed:original",
1391
+ value: null,
1392
+ icon: "original"
1393
+ },
1394
+ {
1395
+ name: "resizeMediaEmbed:custom",
1396
+ value: "custom",
1397
+ icon: "custom"
1398
+ },
1399
+ {
1400
+ name: "resizeMediaEmbed:25",
1401
+ value: "25",
1402
+ icon: "small"
1403
+ },
1404
+ {
1405
+ name: "resizeMediaEmbed:50",
1406
+ value: "50",
1407
+ icon: "medium"
1408
+ },
1409
+ {
1410
+ name: "resizeMediaEmbed:75",
1411
+ value: "75",
1412
+ icon: "large"
1413
+ }
1414
+ ]
1415
+ });
1416
+ }
1417
+ /**
1418
+ * @inheritDoc
1419
+ */
1420
+ init() {
1421
+ const editor = this.editor;
1422
+ editor.commands.add("resizeMediaEmbed", new ResizeMediaEmbedCommand(editor));
1423
+ this._registerConverters();
1424
+ }
1425
+ /**
1426
+ * @inheritDoc
1427
+ */
1428
+ afterInit() {
1429
+ this._registerSchema();
1430
+ }
1431
+ _registerSchema() {
1432
+ const schema = this.editor.model.schema;
1433
+ schema.extend("media", { allowAttributes: ["resizedWidth"] });
1434
+ schema.setAttributeProperties("resizedWidth", { isFormatting: true });
1435
+ }
1436
+ /**
1437
+ * Registers media embed resize converters.
1438
+ */
1439
+ _registerConverters() {
1440
+ const editor = this.editor;
1441
+ editor.conversion.for("downcast").add((dispatcher) => dispatcher.on("attribute:resizedWidth:media", (evt, data, conversionApi) => {
1442
+ if (!conversionApi.consumable.consume(data.item, evt.name)) return;
1443
+ const viewWriter = conversionApi.writer;
1444
+ const figure = conversionApi.mapper.toViewElement(data.item);
1445
+ if (data.attributeNewValue !== null) {
1446
+ viewWriter.setStyle("width", data.attributeNewValue, figure);
1447
+ viewWriter.addClass(RESIZED_MEDIA_CLASS, figure);
1448
+ } else {
1449
+ viewWriter.removeStyle("width", figure);
1450
+ viewWriter.removeClass(RESIZED_MEDIA_CLASS, figure);
1451
+ }
1452
+ }));
1453
+ editor.conversion.for("upcast").attributeToAttribute({
1454
+ view: {
1455
+ name: "figure",
1456
+ styles: { width: /.+/ }
1457
+ },
1458
+ model: {
1459
+ key: "resizedWidth",
1460
+ value: (viewElement) => {
1461
+ if (!viewElement.hasClass("media")) return null;
1462
+ return viewElement.getStyle("width");
1463
+ }
1464
+ }
1465
+ });
1466
+ editor.conversion.for("upcast").add((dispatcher) => {
1467
+ dispatcher.on("element:figure", (evt, data, conversionApi) => {
1468
+ conversionApi.consumable.consume(data.viewItem, { classes: [RESIZED_MEDIA_CLASS] });
1469
+ });
1470
+ });
1471
+ }
1472
+ };
1473
+
1474
+ /**
1475
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1476
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1477
+ */
1478
+ /**
1479
+ * The media embed resize by handles feature.
1480
+ *
1481
+ * It adds the ability to resize each media embed using handles.
1482
+ */
1483
+ var MediaEmbedResizeHandles = class extends Plugin {
1484
+ /**
1485
+ * @inheritDoc
1486
+ */
1487
+ static get requires() {
1488
+ return [WidgetResize];
1489
+ }
1490
+ /**
1491
+ * @inheritDoc
1492
+ */
1493
+ static get pluginName() {
1494
+ return "MediaEmbedResizeHandles";
1495
+ }
1496
+ /**
1497
+ * @inheritDoc
1498
+ */
1499
+ static get isOfficialPlugin() {
1500
+ return true;
1501
+ }
1502
+ /**
1503
+ * @inheritDoc
1504
+ */
1505
+ init() {
1506
+ const command = this.editor.commands.get("resizeMediaEmbed");
1507
+ this.bind("isEnabled").to(command);
1508
+ this._setupResizerCreator();
1509
+ }
1510
+ /**
1511
+ * Attaches a resizer to every newly inserted media widget. Walks only the ranges
1512
+ * reported by the differ — never the whole document — so unrelated inserts (e.g.
1513
+ * pressing Enter to create a paragraph) cost only the differ check.
1514
+ *
1515
+ * Each resizer's `isEnabled` is bound to the plugin in {@link #_attachResizer},
1516
+ * so it auto-tracks the resize command's state.
1517
+ */
1518
+ _setupResizerCreator() {
1519
+ const editor = this.editor;
1520
+ const model = editor.model;
1521
+ const widgetResize = editor.plugins.get(WidgetResize);
1522
+ this.listenTo(model.document, "change:data", () => {
1523
+ for (const change of model.document.differ.getChanges()) {
1524
+ if (change.type !== "insert" || change.name === "$text") continue;
1525
+ const insertedRange = model.createRange(change.position, change.position.getShiftedBy(change.length));
1526
+ for (const item of insertedRange.getItems()) {
1527
+ if (!item.is("element", "media")) continue;
1528
+ const viewElement = editor.editing.mapper.toViewElement(item);
1529
+ /* v8 ignore next -- @preserve */
1530
+ if (!viewElement) continue;
1531
+ /* v8 ignore else -- @preserve */
1532
+ if (!widgetResize.getResizerByViewElement(viewElement)) this._attachResizer(item, viewElement);
1533
+ }
1534
+ }
1535
+ }, { priority: "low" });
1536
+ }
1537
+ /**
1538
+ * Attaches a resizer to a single media widget.
1539
+ */
1540
+ _attachResizer(modelElement, widgetView) {
1541
+ const editor = this.editor;
1542
+ const editingView = editor.editing.view;
1543
+ const resizer = editor.plugins.get(WidgetResize).attachTo({
1544
+ unit: editor.config.get("mediaEmbed.resizeUnit"),
1545
+ modelElement,
1546
+ viewElement: widgetView,
1547
+ editor,
1548
+ getHandleHost: (domWidgetElement) => domWidgetElement.querySelector(".ck-media__wrapper"),
1549
+ getResizeHost: (domWidgetElement) => domWidgetElement,
1550
+ onCommit: (newValue) => {
1551
+ editingView.change((writer) => writer.removeClass(RESIZED_MEDIA_CLASS, widgetView));
1552
+ editor.execute("resizeMediaEmbed", { width: newValue });
1553
+ }
1554
+ });
1555
+ resizer.bind("isEnabled").to(this);
1556
+ resizer.on("updateSize", () => {
1557
+ if (!widgetView.hasClass("media_resized")) editingView.change((writer) => writer.addClass(RESIZED_MEDIA_CLASS, widgetView));
1558
+ });
1559
+ editingView.once("render", () => resizer.redraw());
1560
+ }
1561
+ };
1562
+
1563
+ /**
1564
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1565
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1566
+ */
1567
+ /**
1568
+ * @module media-embed/mediaembedresize/mediaembedresizebuttons
1569
+ */
1570
+ const RESIZE_ICONS = /* #__PURE__ */ (() => ({
1571
+ small: IconObjectSizeSmall,
1572
+ medium: IconObjectSizeMedium,
1573
+ large: IconObjectSizeLarge,
1574
+ custom: IconObjectSizeCustom,
1575
+ original: IconObjectSizeFull
1576
+ }))();
1577
+ /**
1578
+ * The media embed resize buttons plugin.
1579
+ *
1580
+ * It adds a possibility to resize media embeds using the toolbar dropdown or individual buttons,
1581
+ * depending on the plugin configuration.
1582
+ */
1583
+ var MediaEmbedResizeButtons = class extends Plugin {
1584
+ /**
1585
+ * @inheritDoc
1586
+ */
1587
+ static get requires() {
1588
+ return [MediaEmbedResizeEditing];
1589
+ }
1590
+ /**
1591
+ * @inheritDoc
1592
+ */
1593
+ static get pluginName() {
1594
+ return "MediaEmbedResizeButtons";
1595
+ }
1596
+ /**
1597
+ * @inheritDoc
1598
+ */
1599
+ static get isOfficialPlugin() {
1600
+ return true;
1601
+ }
1602
+ _resizeUnit;
1603
+ /**
1604
+ * @inheritDoc
1605
+ */
1606
+ constructor(editor) {
1607
+ super(editor);
1608
+ this._resizeUnit = editor.config.get("mediaEmbed.resizeUnit");
1609
+ }
1610
+ /**
1611
+ * @inheritDoc
1612
+ */
1613
+ init() {
1614
+ const editor = this.editor;
1615
+ const options = editor.config.get("mediaEmbed.resizeOptions");
1616
+ const command = editor.commands.get("resizeMediaEmbed");
1617
+ this.bind("isEnabled").to(command);
1618
+ for (const option of options) this._registerMediaEmbedResizeButton(option);
1619
+ this._registerMediaEmbedResizeDropdown(options);
1620
+ }
1621
+ /**
1622
+ * Creates a standalone button component for the given resize option.
1623
+ */
1624
+ _registerMediaEmbedResizeButton(option) {
1625
+ const editor = this.editor;
1626
+ const { name, value, icon } = option;
1627
+ editor.ui.componentFactory.add(name, (locale) => {
1628
+ const button = new ButtonView(locale);
1629
+ const command = editor.commands.get("resizeMediaEmbed");
1630
+ const labelText = this._getOptionLabelValue(option, true);
1631
+ if (!RESIZE_ICONS[icon])
1632
+ /**
1633
+ * When configuring {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#resizeOptions
1634
+ * `config.mediaEmbed.resizeOptions`} for standalone buttons, a valid `icon` token must be set for each option.
1635
+ *
1636
+ * See all valid options described in the
1637
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedResizeOption plugin configuration}.
1638
+ *
1639
+ * @error mediaembedresizebuttons-missing-icon
1640
+ * @param {module:media-embed/mediaembedconfig~MediaEmbedResizeOption} option Invalid media embed resize option.
1641
+ */
1642
+ throw new CKEditorError("mediaembedresizebuttons-missing-icon", editor, option);
1643
+ button.set({
1644
+ label: labelText,
1645
+ icon: RESIZE_ICONS[icon],
1646
+ tooltip: labelText,
1647
+ isToggleable: true
1648
+ });
1649
+ button.bind("isEnabled").to(this);
1650
+ if (editor.plugins.has("MediaEmbedCustomResizeUI") && isCustomMediaEmbedResizeOption(option)) {
1651
+ const customResizeUI = editor.plugins.get("MediaEmbedCustomResizeUI");
1652
+ this.listenTo(button, "execute", () => {
1653
+ customResizeUI._showForm(this._resizeUnit);
1654
+ });
1655
+ } else {
1656
+ const optionValueWithUnit = value ? value + this._resizeUnit : null;
1657
+ button.bind("isOn").to(command, "value", command, "isEnabled", getIsOnButtonCallback(optionValueWithUnit));
1658
+ this.listenTo(button, "execute", () => {
1659
+ editor.execute("resizeMediaEmbed", { width: optionValueWithUnit });
1660
+ });
1661
+ }
1662
+ return button;
1663
+ });
1664
+ }
1665
+ /**
1666
+ * Creates the dropdown component containing all resize options.
1667
+ */
1668
+ _registerMediaEmbedResizeDropdown(options) {
1669
+ const editor = this.editor;
1670
+ const t = editor.t;
1671
+ const originalSizeOption = options.find((option) => !option.value);
1672
+ const componentCreator = (locale) => {
1673
+ const command = editor.commands.get("resizeMediaEmbed");
1674
+ const dropdownView = createDropdown(locale, DropdownButtonView);
1675
+ const dropdownButton = dropdownView.buttonView;
1676
+ const accessibleLabel = t("Resize media");
1677
+ dropdownButton.set({
1678
+ tooltip: accessibleLabel,
1679
+ commandValue: originalSizeOption ? originalSizeOption.value : null,
1680
+ icon: RESIZE_ICONS.medium,
1681
+ isToggleable: true,
1682
+ label: originalSizeOption ? this._getOptionLabelValue(originalSizeOption) : "",
1683
+ withText: true,
1684
+ class: "ck-resize-media-embed-button",
1685
+ ariaLabel: accessibleLabel,
1686
+ ariaLabelledBy: void 0
1687
+ });
1688
+ dropdownButton.bind("label").to(command, "value", (commandValue) => {
1689
+ if (commandValue) return commandValue;
1690
+ return originalSizeOption ? this._getOptionLabelValue(originalSizeOption) : "";
1691
+ });
1692
+ dropdownView.bind("isEnabled").to(this);
1693
+ addListToDropdown(dropdownView, () => this._getResizeDropdownListItemDefinitions(options, command), {
1694
+ ariaLabel: t("Media resize list"),
1695
+ role: "menu"
1696
+ });
1697
+ this.listenTo(dropdownView, "execute", (evt) => {
1698
+ if ("onClick" in evt.source) evt.source.onClick();
1699
+ else {
1700
+ editor.execute(evt.source.commandName, { width: evt.source.commandValue });
1701
+ editor.editing.view.focus();
1702
+ }
1703
+ });
1704
+ return dropdownView;
1705
+ };
1706
+ editor.ui.componentFactory.add("resizeMediaEmbed", componentCreator);
1707
+ }
1708
+ /**
1709
+ * Returns a label for the given resize option.
1710
+ */
1711
+ _getOptionLabelValue(option, forTooltip = false) {
1712
+ const t = this.editor.t;
1713
+ if (option.label) return option.label;
1714
+ const isCustom = isCustomMediaEmbedResizeOption(option);
1715
+ if (forTooltip) {
1716
+ if (isCustom) return t("Custom media size");
1717
+ return option.value ? t("Resize media to %0", option.value + this._resizeUnit) : t("Resize media to the original size");
1718
+ }
1719
+ if (isCustom) return t("Custom");
1720
+ return option.value ? option.value + this._resizeUnit : t("Original");
1721
+ }
1722
+ /**
1723
+ * Returns list item definitions for the resize dropdown.
1724
+ */
1725
+ _getResizeDropdownListItemDefinitions(options, command) {
1726
+ const { editor } = this;
1727
+ const itemDefinitions = new Collection();
1728
+ const optionsWithSerializedValues = options.map((option) => {
1729
+ if (isCustomMediaEmbedResizeOption(option)) return {
1730
+ ...option,
1731
+ valueWithUnits: "custom"
1732
+ };
1733
+ if (!option.value) return {
1734
+ ...option,
1735
+ valueWithUnits: null
1736
+ };
1737
+ return {
1738
+ ...option,
1739
+ valueWithUnits: `${option.value}${this._resizeUnit}`
1740
+ };
1741
+ });
1742
+ for (const option of optionsWithSerializedValues) {
1743
+ let definition;
1744
+ if (editor.plugins.has("MediaEmbedCustomResizeUI") && isCustomMediaEmbedResizeOption(option)) {
1745
+ const customResizeUI = editor.plugins.get("MediaEmbedCustomResizeUI");
1746
+ definition = {
1747
+ type: "button",
1748
+ model: new UIModel({
1749
+ label: this._getOptionLabelValue(option),
1750
+ role: "menuitemradio",
1751
+ withText: true,
1752
+ icon: null,
1753
+ onClick: () => {
1754
+ customResizeUI._showForm(this._resizeUnit);
1755
+ }
1756
+ })
1757
+ };
1758
+ const allDropdownValues = Object.values(optionsWithSerializedValues).map((option) => option.valueWithUnits);
1759
+ definition.model.bind("isOn").to(command, "value", command, "isEnabled", getIsOnCustomButtonCallback(allDropdownValues));
1760
+ } else {
1761
+ definition = {
1762
+ type: "button",
1763
+ model: new UIModel({
1764
+ commandName: "resizeMediaEmbed",
1765
+ commandValue: option.valueWithUnits,
1766
+ label: this._getOptionLabelValue(option),
1767
+ role: "menuitemradio",
1768
+ withText: true,
1769
+ icon: null
1770
+ })
1771
+ };
1772
+ definition.model.bind("isOn").to(command, "value", command, "isEnabled", getIsOnButtonCallback(option.valueWithUnits));
1773
+ }
1774
+ definition.model.bind("isEnabled").to(command, "isEnabled");
1775
+ itemDefinitions.add(definition);
1776
+ }
1777
+ return itemDefinitions;
1778
+ }
1779
+ };
1780
+ function isCustomMediaEmbedResizeOption(option) {
1781
+ return option.value === "custom";
1782
+ }
1783
+ function getIsOnButtonCallback(value) {
1784
+ return (commandValue, isEnabled) => {
1785
+ if (commandValue === void 0 || !isEnabled) return false;
1786
+ return commandValue === value;
1787
+ };
1788
+ }
1789
+ function getIsOnCustomButtonCallback(allDropdownValues) {
1790
+ return (commandValue, isEnabled) => !allDropdownValues.some((dropdownValue) => getIsOnButtonCallback(dropdownValue)(commandValue, isEnabled));
816
1791
  }
817
1792
 
818
1793
  /**
819
- * The media form view controller class.
820
- *
821
- * See {@link module:media-embed/ui/mediaformview~MediaFormView}.
822
- */ class MediaFormView extends View {
823
- /**
824
- * Tracks information about the DOM focus in the form.
825
- */ focusTracker;
826
- /**
827
- * An instance of the {@link module:utils/keystrokehandler~KeystrokeHandler}.
828
- */ keystrokes;
829
- /**
830
- * The URL input view.
831
- */ urlInputView;
832
- /**
833
- * An array of form validators used by {@link #isValid}.
834
- */ _validators;
835
- /**
836
- * The default info text for the {@link #urlInputView}.
837
- */ _urlInputViewInfoDefault;
838
- /**
839
- * The info text with an additional tip for the {@link #urlInputView},
840
- * displayed when the input has some value.
841
- */ _urlInputViewInfoTip;
842
- /**
843
- * @param validators Form validators used by {@link #isValid}.
844
- * @param locale The localization services instance.
845
- */ constructor(validators, locale){
846
- super(locale);
847
- this.focusTracker = new FocusTracker();
848
- this.keystrokes = new KeystrokeHandler();
849
- this.set('mediaURLInputValue', '');
850
- this.urlInputView = this._createUrlInput();
851
- this._validators = validators;
852
- this.setTemplate({
853
- tag: 'form',
854
- attributes: {
855
- class: [
856
- 'ck',
857
- 'ck-media-form',
858
- 'ck-responsive-form'
859
- ],
860
- tabindex: '-1'
861
- },
862
- children: [
863
- this.urlInputView
864
- ]
865
- });
866
- }
867
- /**
868
- * @inheritDoc
869
- */ render() {
870
- super.render();
871
- submitHandler({
872
- view: this
873
- });
874
- // Register the view in the focus tracker.
875
- this.focusTracker.add(this.urlInputView.element);
876
- // Start listening for the keystrokes coming from #element.
877
- this.keystrokes.listenTo(this.element);
878
- }
879
- /**
880
- * @inheritDoc
881
- */ destroy() {
882
- super.destroy();
883
- this.focusTracker.destroy();
884
- this.keystrokes.destroy();
885
- }
886
- /**
887
- * Focuses the {@link #urlInputView}.
888
- */ focus() {
889
- this.urlInputView.focus();
890
- }
891
- /**
892
- * The native DOM `value` of the {@link #urlInputView} element.
893
- *
894
- * **Note**: Do not confuse it with the {@link module:ui/inputtext/inputtextview~InputTextView#value}
895
- * which works one way only and may not represent the actual state of the component in the DOM.
896
- */ get url() {
897
- return this.urlInputView.fieldView.element.value.trim();
898
- }
899
- set url(url) {
900
- this.urlInputView.fieldView.value = url.trim();
901
- }
902
- /**
903
- * Validates the form and returns `false` when some fields are invalid.
904
- */ isValid() {
905
- this.resetFormStatus();
906
- for (const validator of this._validators){
907
- const errorText = validator(this);
908
- // One error per field is enough.
909
- if (errorText) {
910
- // Apply updated error.
911
- this.urlInputView.errorText = errorText;
912
- return false;
913
- }
914
- }
915
- return true;
916
- }
917
- /**
918
- * Cleans up the supplementary error and information text of the {@link #urlInputView}
919
- * bringing them back to the state when the form has been displayed for the first time.
920
- *
921
- * See {@link #isValid}.
922
- */ resetFormStatus() {
923
- this.urlInputView.errorText = null;
924
- this.urlInputView.infoText = this._urlInputViewInfoDefault;
925
- }
926
- /**
927
- * Creates a labeled input view.
928
- *
929
- * @returns Labeled input view instance.
930
- */ _createUrlInput() {
931
- const t = this.locale.t;
932
- const labeledInput = new LabeledFieldView(this.locale, createLabeledInputText);
933
- const inputField = labeledInput.fieldView;
934
- this._urlInputViewInfoDefault = t('Paste the media URL in the input.');
935
- this._urlInputViewInfoTip = t('Tip: Paste the URL into the content to embed faster.');
936
- labeledInput.label = t('Media URL');
937
- labeledInput.infoText = this._urlInputViewInfoDefault;
938
- inputField.inputMode = 'url';
939
- inputField.on('input', ()=>{
940
- // Display the tip text only when there is some value. Otherwise fall back to the default info text.
941
- labeledInput.infoText = inputField.element.value ? this._urlInputViewInfoTip : this._urlInputViewInfoDefault;
942
- this.mediaURLInputValue = inputField.element.value.trim();
943
- });
944
- return labeledInput;
945
- }
1794
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1795
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1796
+ */
1797
+ /**
1798
+ * Finds model, view and DOM element for selected media embed element.
1799
+ * Returns `null` if there is no media embed selected.
1800
+ *
1801
+ * @param editor Editor instance.
1802
+ * @internal
1803
+ */
1804
+ function getSelectedMediaEmbedEditorNodes(editor) {
1805
+ const { editing } = editor;
1806
+ const mediaModelElement = getSelectedMediaModelWidget(editor.model.document.selection);
1807
+ if (!mediaModelElement) return null;
1808
+ const mediaViewElement = editing.mapper.toViewElement(mediaModelElement);
1809
+ return {
1810
+ model: mediaModelElement,
1811
+ view: mediaViewElement,
1812
+ dom: editing.view.domConverter.mapViewToDom(mediaViewElement)
1813
+ };
946
1814
  }
947
1815
 
948
1816
  /**
949
- * The media embed UI plugin.
950
- */ class MediaEmbedUI extends Plugin {
951
- /**
952
- * @inheritDoc
953
- */ static get requires() {
954
- return [
955
- MediaEmbedEditing,
956
- Dialog
957
- ];
958
- }
959
- /**
960
- * @inheritDoc
961
- */ static get pluginName() {
962
- return 'MediaEmbedUI';
963
- }
964
- /**
965
- * @inheritDoc
966
- */ static get isOfficialPlugin() {
967
- return true;
968
- }
969
- _formView;
970
- /**
971
- * @inheritDoc
972
- */ init() {
973
- const editor = this.editor;
974
- editor.ui.componentFactory.add('mediaEmbed', ()=>{
975
- const t = this.editor.locale.t;
976
- const button = this._createDialogButton(ButtonView);
977
- button.tooltip = true;
978
- button.label = t('Insert media');
979
- return button;
980
- });
981
- editor.ui.componentFactory.add('menuBar:mediaEmbed', ()=>{
982
- const t = this.editor.locale.t;
983
- const button = this._createDialogButton(MenuBarMenuListItemButtonView);
984
- button.label = t('Media');
985
- return button;
986
- });
987
- }
988
- /**
989
- * Creates a button for menu bar that will show media embed dialog.
990
- */ _createDialogButton(ButtonClass) {
991
- const editor = this.editor;
992
- const buttonView = new ButtonClass(editor.locale);
993
- const command = editor.commands.get('mediaEmbed');
994
- const dialogPlugin = this.editor.plugins.get('Dialog');
995
- buttonView.icon = IconMedia;
996
- buttonView.bind('isEnabled').to(command, 'isEnabled');
997
- buttonView.on('execute', ()=>{
998
- if (dialogPlugin.id === 'mediaEmbed') {
999
- dialogPlugin.hide();
1000
- } else {
1001
- this._showDialog();
1002
- }
1003
- });
1004
- return buttonView;
1005
- }
1006
- _showDialog() {
1007
- const editor = this.editor;
1008
- const dialog = editor.plugins.get('Dialog');
1009
- const command = editor.commands.get('mediaEmbed');
1010
- const t = editor.locale.t;
1011
- const isMediaSelected = command.value !== undefined;
1012
- if (!this._formView) {
1013
- const registry = editor.plugins.get(MediaEmbedEditing).registry;
1014
- this._formView = new (CssTransitionDisablerMixin(MediaFormView))(getFormValidators(editor.t, registry), editor.locale);
1015
- this._formView.on('submit', ()=>this._handleSubmitForm());
1016
- }
1017
- dialog.show({
1018
- id: 'mediaEmbed',
1019
- title: t('Media embed'),
1020
- content: this._formView,
1021
- isModal: true,
1022
- onShow: ()=>{
1023
- this._formView.url = command.value || '';
1024
- this._formView.resetFormStatus();
1025
- this._formView.urlInputView.fieldView.select();
1026
- },
1027
- actionButtons: [
1028
- {
1029
- label: t('Cancel'),
1030
- withText: true,
1031
- onExecute: ()=>dialog.hide()
1032
- },
1033
- {
1034
- label: isMediaSelected ? t('Save') : t('Insert'),
1035
- class: 'ck-button-action',
1036
- withText: true,
1037
- onExecute: ()=>this._handleSubmitForm()
1038
- }
1039
- ]
1040
- });
1041
- }
1042
- _handleSubmitForm() {
1043
- const editor = this.editor;
1044
- const dialog = editor.plugins.get('Dialog');
1045
- if (this._formView.isValid()) {
1046
- editor.execute('mediaEmbed', this._formView.url);
1047
- dialog.hide();
1048
- editor.editing.view.focus();
1049
- }
1050
- }
1817
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1818
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1819
+ */
1820
+ /**
1821
+ * @module media-embed/mediaembedresize/utils/getselectedmediaembedwidthinunits
1822
+ */
1823
+ /**
1824
+ * Returns media embed width in specified units after resize.
1825
+ *
1826
+ * * If no media embed is selected or command is disabled, `null` will be returned.
1827
+ * * If `targetUnit` percentage is passed then it will return width percentage relative to its ancestor.
1828
+ *
1829
+ * @param editor Editor instance.
1830
+ * @param targetUnit Unit in which dimension will be returned.
1831
+ * @returns Parsed media embed width after resize (with unit).
1832
+ * @internal
1833
+ */
1834
+ function getSelectedMediaEmbedWidthInUnits(editor, targetUnit) {
1835
+ const mediaNodes = getSelectedMediaEmbedEditorNodes(editor);
1836
+ if (!mediaNodes) return null;
1837
+ const parsedResizedWidth = _tryParseDimensionWithUnit(mediaNodes.model.getAttribute("resizedWidth") || null);
1838
+ if (!parsedResizedWidth) return null;
1839
+ if (parsedResizedWidth.unit === targetUnit) return parsedResizedWidth;
1840
+ const mediaParentWidthPx = calculateResizeHostAncestorWidth(mediaNodes.dom);
1841
+ const mediaHolderDimension = {
1842
+ unit: "px",
1843
+ value: new Rect(mediaNodes.dom).width
1844
+ };
1845
+ return _tryCastDimensionsToUnit(mediaParentWidthPx, mediaHolderDimension, targetUnit);
1051
1846
  }
1052
- function getFormValidators(t, registry) {
1053
- return [
1054
- (form)=>{
1055
- if (!form.url.length) {
1056
- return t('The URL must not be empty.');
1057
- }
1058
- },
1059
- (form)=>{
1060
- if (!registry.hasMedia(form.url)) {
1061
- return t('This media URL is not supported.');
1062
- }
1063
- }
1064
- ];
1847
+
1848
+ /**
1849
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1850
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1851
+ */
1852
+ /**
1853
+ * Returns the min and max resize values for the selected media embed in the specified unit.
1854
+ *
1855
+ * @param editor Editor instance.
1856
+ * @param targetUnit Unit in which dimension will be returned.
1857
+ * @returns Possible resize range in numeric form.
1858
+ * @internal
1859
+ */
1860
+ function getSelectedMediaEmbedPossibleResizeRange(editor, targetUnit) {
1861
+ const mediaNodes = getSelectedMediaEmbedEditorNodes(editor);
1862
+ if (!mediaNodes) return null;
1863
+ const mediaParentWidthPx = calculateResizeHostAncestorWidth(mediaNodes.dom);
1864
+ const minimumMediaWidth = _tryParseDimensionWithUnit(window.getComputedStyle(mediaNodes.dom).minWidth) || {
1865
+ value: 1,
1866
+ unit: "px"
1867
+ };
1868
+ return {
1869
+ unit: targetUnit,
1870
+ lower: Math.max(.1, _tryCastDimensionsToUnit(mediaParentWidthPx, minimumMediaWidth, targetUnit).value),
1871
+ upper: targetUnit === "px" ? mediaParentWidthPx : 100
1872
+ };
1065
1873
  }
1066
1874
 
1067
1875
  /**
1068
- * The media embed plugin.
1069
- *
1070
- * For a detailed overview, check the {@glink features/media-embed Media Embed feature documentation}.
1071
- *
1072
- * This is a "glue" plugin which loads the following plugins:
1073
- *
1074
- * * The {@link module:media-embed/mediaembedediting~MediaEmbedEditing media embed editing feature},
1075
- * * The {@link module:media-embed/mediaembedui~MediaEmbedUI media embed UI feature} and
1076
- * * The {@link module:media-embed/automediaembed~AutoMediaEmbed auto-media embed feature}.
1077
- */ class MediaEmbed extends Plugin {
1078
- /**
1079
- * @inheritDoc
1080
- */ static get requires() {
1081
- return [
1082
- MediaEmbedEditing,
1083
- MediaEmbedUI,
1084
- AutoMediaEmbed,
1085
- Widget
1086
- ];
1087
- }
1088
- /**
1089
- * @inheritDoc
1090
- */ static get pluginName() {
1091
- return 'MediaEmbed';
1092
- }
1093
- /**
1094
- * @inheritDoc
1095
- */ static get isOfficialPlugin() {
1096
- return true;
1097
- }
1876
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
1877
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
1878
+ */
1879
+ /**
1880
+ * @module media-embed/mediaembedresize/ui/mediaembedcustomresizeformview
1881
+ */
1882
+ /**
1883
+ * The MediaEmbedCustomResizeFormView class.
1884
+ *
1885
+ * @internal
1886
+ */
1887
+ var MediaEmbedCustomResizeFormView = class extends View {
1888
+ /**
1889
+ * Tracks information about the DOM focus in the form.
1890
+ */
1891
+ focusTracker;
1892
+ /**
1893
+ * An instance of the {@link module:utils/keystrokehandler~KeystrokeHandler}.
1894
+ */
1895
+ keystrokes;
1896
+ /**
1897
+ * Resize unit shortcut.
1898
+ */
1899
+ unit;
1900
+ /**
1901
+ * The Back button view displayed in the header.
1902
+ */
1903
+ backButtonView;
1904
+ /**
1905
+ * A button used to submit the form.
1906
+ */
1907
+ saveButtonView;
1908
+ /**
1909
+ * An input with a label.
1910
+ */
1911
+ labeledInput;
1912
+ /**
1913
+ * A collection of child views.
1914
+ */
1915
+ children;
1916
+ /**
1917
+ * A collection of views which can be focused in the form.
1918
+ */
1919
+ _focusables;
1920
+ /**
1921
+ * Helps cycling over {@link #_focusables} in the form.
1922
+ */
1923
+ _focusCycler;
1924
+ /**
1925
+ * An array of form validators used by {@link #isValid}.
1926
+ */
1927
+ _validators;
1928
+ /**
1929
+ * @inheritDoc
1930
+ */
1931
+ constructor(locale, unit, validators) {
1932
+ super(locale);
1933
+ this.focusTracker = new FocusTracker();
1934
+ this.keystrokes = new KeystrokeHandler();
1935
+ this.unit = unit;
1936
+ this.backButtonView = this._createBackButton();
1937
+ this.saveButtonView = this._createSaveButton();
1938
+ this.labeledInput = this._createLabeledInputView();
1939
+ this.children = this.createCollection([this._createHeaderView()]);
1940
+ this.children.add(new FormRowView(locale, {
1941
+ children: [this.labeledInput, this.saveButtonView],
1942
+ class: ["ck-form__row_with-submit", "ck-form__row_large-top-padding"]
1943
+ }));
1944
+ this._focusables = new ViewCollection();
1945
+ this._validators = validators;
1946
+ this.keystrokes.set("Esc", (data, cancel) => {
1947
+ this.fire("cancel");
1948
+ cancel();
1949
+ });
1950
+ this._focusCycler = new FocusCycler({
1951
+ focusables: this._focusables,
1952
+ focusTracker: this.focusTracker,
1953
+ keystrokeHandler: this.keystrokes,
1954
+ actions: {
1955
+ focusPrevious: "shift + tab",
1956
+ focusNext: "tab"
1957
+ }
1958
+ });
1959
+ this.setTemplate({
1960
+ tag: "form",
1961
+ attributes: {
1962
+ class: [
1963
+ "ck",
1964
+ "ck-form",
1965
+ "ck-media-embed-custom-resize-form",
1966
+ "ck-responsive-form"
1967
+ ],
1968
+ tabindex: "-1"
1969
+ },
1970
+ children: this.children
1971
+ });
1972
+ }
1973
+ /**
1974
+ * @inheritDoc
1975
+ */
1976
+ render() {
1977
+ super.render();
1978
+ submitHandler({ view: this });
1979
+ [
1980
+ this.backButtonView,
1981
+ this.labeledInput,
1982
+ this.saveButtonView
1983
+ ].forEach((v) => {
1984
+ this._focusables.add(v);
1985
+ this.focusTracker.add(v.element);
1986
+ });
1987
+ this.keystrokes.listenTo(this.element);
1988
+ }
1989
+ /**
1990
+ * @inheritDoc
1991
+ */
1992
+ destroy() {
1993
+ super.destroy();
1994
+ this.focusTracker.destroy();
1995
+ this.keystrokes.destroy();
1996
+ }
1997
+ _createBackButton() {
1998
+ const t = this.locale.t;
1999
+ const backButton = new ButtonView(this.locale);
2000
+ backButton.set({
2001
+ class: "ck-button-back",
2002
+ label: t("Back"),
2003
+ icon: IconPreviousArrow,
2004
+ tooltip: true
2005
+ });
2006
+ backButton.delegate("execute").to(this, "cancel");
2007
+ return backButton;
2008
+ }
2009
+ _createSaveButton() {
2010
+ const t = this.locale.t;
2011
+ const saveButton = new ButtonView(this.locale);
2012
+ saveButton.set({
2013
+ label: t("Save"),
2014
+ withText: true,
2015
+ type: "submit",
2016
+ class: "ck-button-action"
2017
+ });
2018
+ return saveButton;
2019
+ }
2020
+ _createHeaderView() {
2021
+ const t = this.locale.t;
2022
+ const header = new FormHeaderView(this.locale, { label: t("Media Resize") });
2023
+ header.children.add(this.backButtonView, 0);
2024
+ return header;
2025
+ }
2026
+ _createLabeledInputView() {
2027
+ const t = this.locale.t;
2028
+ const labeledInput = new LabeledFieldView(this.locale, createLabeledInputNumber);
2029
+ labeledInput.label = t("Resize media (in %0)", this.unit);
2030
+ labeledInput.class = "ck-labeled-field-view_full-width";
2031
+ labeledInput.fieldView.set({
2032
+ min: .1,
2033
+ step: .1
2034
+ });
2035
+ return labeledInput;
2036
+ }
2037
+ /**
2038
+ * Validates the form and returns `false` when some fields are invalid.
2039
+ */
2040
+ isValid() {
2041
+ this.resetFormStatus();
2042
+ for (const validator of this._validators) {
2043
+ const errorText = validator(this);
2044
+ if (errorText) {
2045
+ this.labeledInput.errorText = errorText;
2046
+ return false;
2047
+ }
2048
+ }
2049
+ return true;
2050
+ }
2051
+ /**
2052
+ * Cleans up error and information text of {@link #labeledInput}.
2053
+ */
2054
+ resetFormStatus() {
2055
+ this.labeledInput.errorText = null;
2056
+ }
2057
+ /**
2058
+ * The native DOM `value` of the input element of {@link #labeledInput}.
2059
+ */
2060
+ get rawSize() {
2061
+ const { element } = this.labeledInput.fieldView;
2062
+ if (!element) return null;
2063
+ return element.value;
2064
+ }
2065
+ /**
2066
+ * Get numeric value of size. Returns `null` if value is not a number.
2067
+ */
2068
+ get parsedSize() {
2069
+ const { rawSize } = this;
2070
+ if (rawSize === null) return null;
2071
+ const parsed = Number.parseFloat(rawSize);
2072
+ if (Number.isNaN(parsed)) return null;
2073
+ return parsed;
2074
+ }
2075
+ /**
2076
+ * Returns serialized media embed input size with unit.
2077
+ * Returns `null` if value is not a number.
2078
+ */
2079
+ get sizeWithUnits() {
2080
+ const { parsedSize, unit } = this;
2081
+ if (parsedSize === null) return null;
2082
+ return `${parsedSize}${unit}`;
2083
+ }
2084
+ };
2085
+
2086
+ /**
2087
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2088
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2089
+ */
2090
+ /**
2091
+ * @module media-embed/mediaembedresize/mediaembedcustomresizeui
2092
+ */
2093
+ /**
2094
+ * The custom resize media embed UI plugin.
2095
+ *
2096
+ * The plugin uses the {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon}.
2097
+ */
2098
+ var MediaEmbedCustomResizeUI = class extends Plugin {
2099
+ /**
2100
+ * The contextual balloon plugin instance.
2101
+ */
2102
+ _balloon;
2103
+ /**
2104
+ * A form used to set the custom resize width.
2105
+ */
2106
+ _form;
2107
+ /**
2108
+ * @inheritDoc
2109
+ */
2110
+ static get requires() {
2111
+ return [ContextualBalloon];
2112
+ }
2113
+ /**
2114
+ * @inheritDoc
2115
+ */
2116
+ static get pluginName() {
2117
+ return "MediaEmbedCustomResizeUI";
2118
+ }
2119
+ /**
2120
+ * @inheritDoc
2121
+ */
2122
+ static get isOfficialPlugin() {
2123
+ return true;
2124
+ }
2125
+ /**
2126
+ * @inheritDoc
2127
+ */
2128
+ destroy() {
2129
+ super.destroy();
2130
+ if (this._form) this._form.destroy();
2131
+ }
2132
+ /**
2133
+ * Creates the {@link module:media-embed/mediaembedresize/ui/mediaembedcustomresizeformview~MediaEmbedCustomResizeFormView} form.
2134
+ */
2135
+ _createForm(unit) {
2136
+ const editor = this.editor;
2137
+ this._balloon = this.editor.plugins.get("ContextualBalloon");
2138
+ const FormViewClass = CssTransitionDisablerMixin(MediaEmbedCustomResizeFormView);
2139
+ this._form = new FormViewClass(editor.locale, unit, getFormValidators(editor));
2140
+ this._form.render();
2141
+ this.listenTo(this._form, "submit", () => {
2142
+ if (this._form.isValid()) {
2143
+ editor.execute("resizeMediaEmbed", { width: this._form.sizeWithUnits });
2144
+ this._hideForm(true);
2145
+ }
2146
+ });
2147
+ this.listenTo(this._form.labeledInput, "change:errorText", () => {
2148
+ editor.ui.update();
2149
+ });
2150
+ this.listenTo(this._form, "cancel", () => {
2151
+ this._hideForm(true);
2152
+ });
2153
+ clickOutsideHandler({
2154
+ emitter: this._form,
2155
+ activator: () => this._isVisible,
2156
+ contextElements: () => [this._balloon.view.element],
2157
+ callback: () => this._hideForm()
2158
+ });
2159
+ }
2160
+ /**
2161
+ * Shows the {@link #_form} in the {@link #_balloon}.
2162
+ *
2163
+ * @internal
2164
+ */
2165
+ _showForm(unit) {
2166
+ if (this._isVisible) return;
2167
+ if (!this._form) this._createForm(unit);
2168
+ const editor = this.editor;
2169
+ const labeledInput = this._form.labeledInput;
2170
+ this._form.disableCssTransitions();
2171
+ this._form.resetFormStatus();
2172
+ /* v8 ignore else -- @preserve */
2173
+ if (!this._isInBalloon) this._balloon.add({
2174
+ view: this._form,
2175
+ position: getBalloonPositionData(editor)
2176
+ });
2177
+ const currentParsedWidth = getSelectedMediaEmbedWidthInUnits(editor, unit);
2178
+ const initialInputValue = currentParsedWidth ? currentParsedWidth.value.toFixed(1) : "";
2179
+ const possibleRange = getSelectedMediaEmbedPossibleResizeRange(editor, unit);
2180
+ labeledInput.fieldView.value = labeledInput.fieldView.element.value = initialInputValue;
2181
+ if (possibleRange) Object.assign(labeledInput.fieldView, {
2182
+ min: possibleRange.lower.toFixed(1),
2183
+ max: Math.ceil(possibleRange.upper).toFixed(1)
2184
+ });
2185
+ this._form.labeledInput.fieldView.select();
2186
+ this._form.enableCssTransitions();
2187
+ }
2188
+ /**
2189
+ * Removes the {@link #_form} from the {@link #_balloon}.
2190
+ *
2191
+ * @param focusEditable Controls whether the editing view is focused afterwards.
2192
+ */
2193
+ _hideForm(focusEditable = false) {
2194
+ if (!this._isInBalloon) return;
2195
+ if (this._form.focusTracker.isFocused) this._form.saveButtonView.focus();
2196
+ this._balloon.remove(this._form);
2197
+ if (focusEditable) this.editor.editing.view.focus();
2198
+ }
2199
+ /**
2200
+ * Returns `true` when the {@link #_form} is the visible view in the {@link #_balloon}.
2201
+ */
2202
+ get _isVisible() {
2203
+ return !!this._balloon && this._balloon.visibleView === this._form;
2204
+ }
2205
+ /**
2206
+ * Returns `true` when the {@link #_form} is in the {@link #_balloon}.
2207
+ */
2208
+ get _isInBalloon() {
2209
+ return !!this._balloon && this._balloon.hasView(this._form);
2210
+ }
2211
+ };
2212
+ function getBalloonPositionData(editor) {
2213
+ const editingView = editor.editing.view;
2214
+ const defaultPositions = BalloonPanelView.defaultPositions;
2215
+ return {
2216
+ target: editingView.domConverter.mapViewToDom(getSelectedMediaViewWidget(editingView.document.selection)),
2217
+ positions: [
2218
+ defaultPositions.northArrowSouth,
2219
+ defaultPositions.northArrowSouthWest,
2220
+ defaultPositions.northArrowSouthEast,
2221
+ defaultPositions.southArrowNorth,
2222
+ defaultPositions.southArrowNorthWest,
2223
+ defaultPositions.southArrowNorthEast,
2224
+ defaultPositions.viewportStickyNorth
2225
+ ]
2226
+ };
1098
2227
  }
2228
+ function getFormValidators(editor) {
2229
+ const t = editor.t;
2230
+ return [(form) => {
2231
+ if (form.rawSize.trim() === "") return t("The value must not be empty.");
2232
+ if (form.parsedSize === null) return t("The value should be a plain number.");
2233
+ }];
2234
+ }
2235
+
2236
+ /**
2237
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2238
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2239
+ */
2240
+ /**
2241
+ * @module media-embed/mediaembedresize
2242
+ */
2243
+ /**
2244
+ * The media embed resize plugin.
2245
+ *
2246
+ * It adds a possibility to resize each media embed using handles, toolbar buttons,
2247
+ * or a balloon-hosted custom-width input.
2248
+ */
2249
+ var MediaEmbedResize = class extends Plugin {
2250
+ /**
2251
+ * @inheritDoc
2252
+ */
2253
+ static get requires() {
2254
+ return [
2255
+ MediaEmbedResizeEditing,
2256
+ MediaEmbedResizeHandles,
2257
+ MediaEmbedCustomResizeUI,
2258
+ MediaEmbedResizeButtons
2259
+ ];
2260
+ }
2261
+ /**
2262
+ * @inheritDoc
2263
+ */
2264
+ static get pluginName() {
2265
+ return "MediaEmbedResize";
2266
+ }
2267
+ /**
2268
+ * @inheritDoc
2269
+ */
2270
+ static get isOfficialPlugin() {
2271
+ return true;
2272
+ }
2273
+ };
2274
+
2275
+ /**
2276
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2277
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2278
+ */
2279
+ /**
2280
+ * @module media-embed/mediaembedstyle/mediaembedstylecommand
2281
+ */
2282
+ /**
2283
+ * The media embed style command. It is used to apply a style option (e.g. an alignment) to a
2284
+ * selected media embed.
2285
+ *
2286
+ * The set of accepted style values comes from the resolved
2287
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles`}
2288
+ * options. Values not in that set are silently rejected by {@link #execute}.
2289
+ */
2290
+ var MediaEmbedStyleCommand = class extends Command {
2291
+ /**
2292
+ * Resolved styles indexed by `name`. Used to look up the `isDefault` flag at execute time
2293
+ * (any default-marked style clears the attribute) and to validate that a requested style
2294
+ * is part of the resolved options list.
2295
+ */
2296
+ _styles;
2297
+ /**
2298
+ * The `name` of the first style with `isDefault: true` in the resolved options, or `null`
2299
+ * when the integrator did not designate a default. Exposed via {@link #value} when the
2300
+ * selected media has no `mediaStyle` attribute, so the default-state UI button can light up.
2301
+ * Does not gate the "clear attribute" branch in {@link #execute} — that uses the per-style
2302
+ * `isDefault` flag so multi-default configs behave consistently with the downcast.
2303
+ */
2304
+ _defaultStyleName;
2305
+ /**
2306
+ * Creates an instance of the media embed style command.
2307
+ *
2308
+ * @param editor The editor instance.
2309
+ * @param styles The resolved list of style options that this command will accept.
2310
+ */
2311
+ constructor(editor, styles) {
2312
+ super(editor);
2313
+ this._styles = new Map(styles.map((style) => [style.name, style]));
2314
+ const defaultStyle = styles.find((style) => style.isDefault);
2315
+ this._defaultStyleName = defaultStyle ? defaultStyle.name : null;
2316
+ }
2317
+ /**
2318
+ * @inheritDoc
2319
+ */
2320
+ refresh() {
2321
+ const element = getSelectedMediaModelWidget(this.editor.model.document.selection);
2322
+ this.isEnabled = !!element;
2323
+ if (!element) this.value = false;
2324
+ else if (element.hasAttribute("mediaStyle")) {
2325
+ const styleName = element.getAttribute("mediaStyle");
2326
+ this.value = this._styles.has(styleName) ? styleName : this._defaultStyleName ?? false;
2327
+ } else this.value = this._defaultStyleName ?? false;
2328
+ }
2329
+ /**
2330
+ * Executes the command and applies the chosen style to the currently selected media embed.
2331
+ *
2332
+ * ```ts
2333
+ * editor.execute( 'mediaStyle', { value: 'alignLeft' } );
2334
+ * editor.execute( 'mediaStyle', { value: 'alignCenter' } ); // removes the attribute — alignCenter is the built-in default
2335
+ * editor.execute( 'mediaStyle', { value: null } ); // removes the attribute
2336
+ * ```
2337
+ *
2338
+ * The default style is encoded on the model as the absence of the `mediaStyle` attribute.
2339
+ * Passing any `isDefault: true` style name (or `null`) therefore clears the attribute. Values
2340
+ * that are neither falsy, an `isDefault` style, nor present in the resolved options list are
2341
+ * silently rejected.
2342
+ *
2343
+ * @param options
2344
+ * @param options.value The name of the style to apply, or `null` to clear the alignment.
2345
+ * @fires execute
2346
+ */
2347
+ execute(options) {
2348
+ const model = this.editor.model;
2349
+ const element = getSelectedMediaModelWidget(model.document.selection);
2350
+ const requestedStyle = options.value;
2351
+ if (!requestedStyle || this._styles.get(requestedStyle)?.isDefault) {
2352
+ model.change((writer) => {
2353
+ writer.removeAttribute("mediaStyle", element);
2354
+ });
2355
+ return;
2356
+ }
2357
+ if (!this._styles.has(requestedStyle)) return;
2358
+ model.change((writer) => {
2359
+ writer.setAttribute("mediaStyle", requestedStyle, element);
2360
+ });
2361
+ }
2362
+ };
2363
+
2364
+ /**
2365
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2366
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2367
+ */
2368
+ /**
2369
+ * @module media-embed/mediaembedstyle/mediaembedstyleediting
2370
+ */
2371
+ /**
2372
+ * The media embed style engine plugin. It extends the schema with the `mediaStyle` attribute,
2373
+ * registers the {@link module:media-embed/mediaembedstyle/mediaembedstylecommand~MediaEmbedStyleCommand} command,
2374
+ * and adds the converters that apply alignment CSS classes to the figure.
2375
+ */
2376
+ var MediaEmbedStyleEditing = class extends Plugin {
2377
+ /**
2378
+ * The resolved list of media style options. Built once from
2379
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles`}
2380
+ * during {@link #init} and consumed by both the command and the UI plugin (single source of truth).
2381
+ *
2382
+ * @internal
2383
+ * @readonly
2384
+ */
2385
+ normalizedStyles;
2386
+ /**
2387
+ * @inheritDoc
2388
+ */
2389
+ static get requires() {
2390
+ return [MediaEmbedEditing];
2391
+ }
2392
+ /**
2393
+ * @inheritDoc
2394
+ */
2395
+ static get pluginName() {
2396
+ return "MediaEmbedStyleEditing";
2397
+ }
2398
+ /**
2399
+ * @inheritDoc
2400
+ */
2401
+ static get isOfficialPlugin() {
2402
+ return true;
2403
+ }
2404
+ /**
2405
+ * @inheritDoc
2406
+ */
2407
+ init() {
2408
+ const editor = this.editor;
2409
+ const schema = editor.model.schema;
2410
+ editor.config.define("mediaEmbed.styles", { options: Object.keys(DEFAULT_OPTIONS) });
2411
+ this.normalizedStyles = normalizeStyles(editor.config.get("mediaEmbed.styles"));
2412
+ schema.extend("media", { allowAttributes: ["mediaStyle"] });
2413
+ schema.setAttributeProperties("mediaStyle", { isFormatting: true });
2414
+ editor.commands.add("mediaStyle", new MediaEmbedStyleCommand(editor, this.normalizedStyles));
2415
+ this._registerConverters();
2416
+ }
2417
+ /**
2418
+ * Registers the downcast and upcast converters for the `mediaStyle` attribute.
2419
+ */
2420
+ _registerConverters() {
2421
+ const editor = this.editor;
2422
+ const styleClassMap = new Map(this.normalizedStyles.filter((style) => !style.isDefault && style.className).map((style) => [style.name, style.className]));
2423
+ editor.conversion.for("downcast").add((dispatcher) => dispatcher.on("attribute:mediaStyle:media", (evt, data, conversionApi) => {
2424
+ if (!conversionApi.consumable.consume(data.item, evt.name)) return;
2425
+ const figure = conversionApi.mapper.toViewElement(data.item);
2426
+ const viewWriter = conversionApi.writer;
2427
+ const oldClass = styleClassMap.get(data.attributeOldValue);
2428
+ const newClass = styleClassMap.get(data.attributeNewValue);
2429
+ if (oldClass) viewWriter.removeClass(oldClass, figure);
2430
+ if (newClass) viewWriter.addClass(newClass, figure);
2431
+ }));
2432
+ editor.conversion.for("upcast").add((dispatcher) => {
2433
+ dispatcher.on("element:figure", (_evt, data, conversionApi) => {
2434
+ if (!data.modelRange) return;
2435
+ const modelElement = first(data.modelRange.getItems());
2436
+ if (!modelElement || !modelElement.is("element", "media")) return;
2437
+ for (const [styleName, className] of styleClassMap) if (conversionApi.consumable.consume(data.viewItem, { classes: className })) conversionApi.writer.setAttribute("mediaStyle", styleName, modelElement);
2438
+ }, { priority: "low" });
2439
+ });
2440
+ }
2441
+ };
1099
2442
 
1100
2443
  /**
1101
- * The media embed toolbar plugin. It creates a toolbar for media embed that shows up when the media element is selected.
1102
- *
1103
- * Instances of toolbar components (e.g. buttons) are created based on the
1104
- * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#toolbar `media.toolbar` configuration option}.
1105
- */ class MediaEmbedToolbar extends Plugin {
1106
- /**
1107
- * @inheritDoc
1108
- */ static get requires() {
1109
- return [
1110
- WidgetToolbarRepository
1111
- ];
1112
- }
1113
- /**
1114
- * @inheritDoc
1115
- */ static get pluginName() {
1116
- return 'MediaEmbedToolbar';
1117
- }
1118
- /**
1119
- * @inheritDoc
1120
- */ static get isOfficialPlugin() {
1121
- return true;
1122
- }
1123
- /**
1124
- * @inheritDoc
1125
- */ afterInit() {
1126
- const editor = this.editor;
1127
- const t = editor.t;
1128
- const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository);
1129
- widgetToolbarRepository.register('mediaEmbed', {
1130
- ariaLabel: t('Media toolbar'),
1131
- items: editor.config.get('mediaEmbed.toolbar') || [],
1132
- getRelatedElement: getSelectedMediaViewWidget
1133
- });
1134
- }
2444
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2445
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2446
+ */
2447
+ /**
2448
+ * @module media-embed/mediaembedstyle/mediaembedstyleui
2449
+ */
2450
+ /**
2451
+ * The media embed style UI plugin.
2452
+ *
2453
+ * It registers a button for every style in the resolved
2454
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#styles `config.mediaEmbed.styles`}
2455
+ * list, and the default split-button dropdowns (`mediaEmbed:wrapText`, `mediaEmbed:breakText`)
2456
+ * — filtered to the styles that survived configuration. The resulting components can be placed
2457
+ * in the {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#toolbar media embed toolbar}.
2458
+ */
2459
+ var MediaEmbedStyleUI = class extends Plugin {
2460
+ /**
2461
+ * @inheritDoc
2462
+ */
2463
+ static get requires() {
2464
+ return [MediaEmbedStyleEditing];
2465
+ }
2466
+ /**
2467
+ * @inheritDoc
2468
+ */
2469
+ static get pluginName() {
2470
+ return "MediaEmbedStyleUI";
2471
+ }
2472
+ /**
2473
+ * @inheritDoc
2474
+ */
2475
+ static get isOfficialPlugin() {
2476
+ return true;
2477
+ }
2478
+ /**
2479
+ * @inheritDoc
2480
+ */
2481
+ init() {
2482
+ const titles = this._getLocalizedTitles();
2483
+ for (const button of this._getButtonDefinitions(titles)) this._createButton(button);
2484
+ for (const dropdown of this._getDropdownDefinitions(titles)) this._createDropdown(dropdown);
2485
+ }
2486
+ /**
2487
+ * Returns the alignment button definitions sourced from the resolved options list.
2488
+ */
2489
+ _getButtonDefinitions(titles) {
2490
+ return this.editor.plugins.get(MediaEmbedStyleEditing).normalizedStyles.map((option) => ({
2491
+ name: option.name,
2492
+ label: titles[option.title] || option.title,
2493
+ icon: option.icon
2494
+ }));
2495
+ }
2496
+ /**
2497
+ * Returns the localized titles of the built-in styles and dropdowns.
2498
+ */
2499
+ _getLocalizedTitles() {
2500
+ const t = this.editor.t;
2501
+ return {
2502
+ "Left aligned media": t("Left aligned media"),
2503
+ "Centered media": t("Centered media"),
2504
+ "Right aligned media": t("Right aligned media"),
2505
+ "Wrap text": t("Wrap text"),
2506
+ "Break text": t("Break text")
2507
+ };
2508
+ }
2509
+ /**
2510
+ * Returns the split-button dropdown definitions, filtered to the styles present in the
2511
+ * resolved options list. Combines the {@link module:media-embed/mediaembedstyle/constants~DEFAULT_DROPDOWN_DEFINITIONS
2512
+ * built-in dropdowns} with custom dropdowns declared inline in
2513
+ * {@link module:media-embed/mediaembedconfig~MediaEmbedConfig#toolbar `config.mediaEmbed.toolbar`}.
2514
+ *
2515
+ * A dropdown with fewer than two items is skipped — a single-item dropdown carries no value
2516
+ * over the flat button. If the configured `defaultItem` was filtered out, the first surviving
2517
+ * item becomes the default.
2518
+ *
2519
+ * When a *custom* dropdown's items reference styles that are not in the resolved options list,
2520
+ * a console warning is emitted (the integrator's config was not fully honored). Built-in
2521
+ * dropdowns auto-skip silently — they are added by the plugin, not the integrator.
2522
+ */
2523
+ _getDropdownDefinitions(titles) {
2524
+ const editing = this.editor.plugins.get(MediaEmbedStyleEditing);
2525
+ const availableComponentNames = new Set(editing.normalizedStyles.map(({ name }) => `mediaEmbed:${name}`));
2526
+ const dropdowns = [];
2527
+ const resolveDropdown = (definition, warnOnFilter) => {
2528
+ const items = definition.items.filter((itemName) => availableComponentNames.has(itemName));
2529
+ if (warnOnFilter && items.length !== definition.items.length) warnInvalidDropdown({ dropdown: definition });
2530
+ if (items.length < 2) return;
2531
+ const defaultItem = availableComponentNames.has(definition.defaultItem) ? definition.defaultItem : items[0];
2532
+ dropdowns.push({
2533
+ name: definition.name,
2534
+ title: titles[definition.title] || definition.title,
2535
+ items,
2536
+ defaultItem
2537
+ });
2538
+ };
2539
+ for (const definition of DEFAULT_DROPDOWN_DEFINITIONS) resolveDropdown(definition, false);
2540
+ for (const definition of this._collectCustomDropdowns()) resolveDropdown(definition, true);
2541
+ return dropdowns;
2542
+ }
2543
+ /**
2544
+ * Scans `config.mediaEmbed.toolbar` for entries shaped like a dropdown definition
2545
+ * (objects with both `items` and `defaultItem`) and returns the valid ones. `defaultItem`
2546
+ * is the discriminator between our split-button dropdowns and generic toolbar groupings
2547
+ * (which use `items` + `label` and have no `defaultItem`).
2548
+ *
2549
+ * Invalid entries (wrong name prefix, `defaultItem` missing from `items`) are warned and
2550
+ * dropped here. Items that reference filtered-out styles are filtered later by
2551
+ * {@link #_getDropdownDefinitions}, alongside the same logic that applies to built-in
2552
+ * dropdowns.
2553
+ */
2554
+ _collectCustomDropdowns() {
2555
+ return (this.editor.config.get("mediaEmbed.toolbar") || []).filter((item) => isMediaStyleDropdown(item) && isValidCustomDropdown(item));
2556
+ }
2557
+ /**
2558
+ * Registers a single alignment toggle button in the component factory.
2559
+ */
2560
+ _createButton(definition) {
2561
+ const editor = this.editor;
2562
+ const componentName = `mediaEmbed:${definition.name}`;
2563
+ editor.ui.componentFactory.add(componentName, (locale) => {
2564
+ const command = editor.commands.get("mediaStyle");
2565
+ const view = new ButtonView(locale);
2566
+ view.set({
2567
+ label: definition.label,
2568
+ icon: definition.icon,
2569
+ tooltip: true,
2570
+ isToggleable: true
2571
+ });
2572
+ view.bind("isEnabled").to(command, "isEnabled");
2573
+ view.bind("isOn").to(command, "value", (value) => value === definition.name);
2574
+ view.on("execute", () => {
2575
+ editor.execute("mediaStyle", { value: definition.name });
2576
+ editor.editing.view.focus();
2577
+ });
2578
+ return view;
2579
+ });
2580
+ }
2581
+ /**
2582
+ * Registers a split-button dropdown grouping a set of alignment buttons. The action button
2583
+ * reflects whichever child option is currently `isOn`, falling back to the dropdown's
2584
+ * `defaultItem` when nothing is active.
2585
+ */
2586
+ _createDropdown(definition) {
2587
+ const editor = this.editor;
2588
+ const factory = editor.ui.componentFactory;
2589
+ factory.add(definition.name, (locale) => {
2590
+ const buttonViews = definition.items.map((itemName) => factory.create(itemName));
2591
+ const defaultButton = buttonViews[definition.items.indexOf(definition.defaultItem)];
2592
+ const activeOrDefault = (...areOn) => {
2593
+ const index = areOn.findIndex(Boolean);
2594
+ return index < 0 ? defaultButton : buttonViews[index];
2595
+ };
2596
+ const dropdownView = createDropdown(locale, SplitButtonView);
2597
+ const splitButtonView = dropdownView.buttonView;
2598
+ addToolbarToDropdown(dropdownView, buttonViews, { enableActiveItemFocusOnDropdownOpen: true });
2599
+ splitButtonView.set({
2600
+ label: getDropdownButtonTitle(definition.title, defaultButton.label),
2601
+ class: null,
2602
+ tooltip: true
2603
+ });
2604
+ splitButtonView.arrowView.unbind("label");
2605
+ splitButtonView.arrowView.set({ label: definition.title });
2606
+ splitButtonView.bind("icon").toMany(buttonViews, "isOn", (...areOn) => activeOrDefault(...areOn).icon);
2607
+ splitButtonView.bind("label").toMany(buttonViews, "isOn", (...areOn) => getDropdownButtonTitle(definition.title, activeOrDefault(...areOn).label));
2608
+ splitButtonView.bind("isOn").toMany(buttonViews, "isOn", (...areOn) => areOn.some(Boolean));
2609
+ splitButtonView.bind("class").toMany(buttonViews, "isOn", (...areOn) => areOn.some(Boolean) ? "ck-splitbutton_flatten" : void 0);
2610
+ this.listenTo(splitButtonView, "execute", () => {
2611
+ if (buttonViews.some(({ isOn }) => isOn)) dropdownView.isOpen = !dropdownView.isOpen;
2612
+ else defaultButton.fire("execute");
2613
+ });
2614
+ dropdownView.bind("isEnabled").toMany(buttonViews, "isEnabled", (...areEnabled) => areEnabled.some(Boolean));
2615
+ this.listenTo(dropdownView, "execute", () => {
2616
+ editor.editing.view.focus();
2617
+ });
2618
+ return dropdownView;
2619
+ });
2620
+ }
2621
+ };
2622
+ /**
2623
+ * Combines the dropdown title and the default action item label for the split-button label.
2624
+ */
2625
+ function getDropdownButtonTitle(dropdownTitle, buttonTitle) {
2626
+ return `${dropdownTitle}: ${buttonTitle}`;
2627
+ }
2628
+ /**
2629
+ * Validates a user-supplied dropdown definition. Emits a console warning under
2630
+ * `media-style-configuration-definition-invalid` and returns `false` when any of these rules is
2631
+ * broken: `name` must start with `mediaEmbed:`, `title` must be a non-empty string, `items` must
2632
+ * be non-empty and every entry must be a `mediaEmbed:`-prefixed string, and `defaultItem` must be
2633
+ * one of the `items`.
2634
+ *
2635
+ * Item-membership against the resolved styles is checked separately, downstream, alongside the
2636
+ * same logic that applies to built-in dropdowns.
2637
+ */
2638
+ function isValidCustomDropdown(definition) {
2639
+ const valid = definition.name.startsWith("mediaEmbed:") && typeof definition.title === "string" && definition.title.length > 0 && definition.items.length > 0 && definition.items.every((name) => typeof name === "string" && name.startsWith("mediaEmbed:")) && definition.items.includes(definition.defaultItem);
2640
+ if (!valid) warnInvalidDropdown({ dropdown: definition });
2641
+ return valid;
2642
+ }
2643
+ /**
2644
+ * Emits a console warning under `media-style-configuration-definition-invalid` for an invalid
2645
+ * or partially-honored dropdown definition. Called from {@link ~isValidCustomDropdown} for
2646
+ * structural problems and from {@link MediaEmbedStyleUI#_getDropdownDefinitions} when items
2647
+ * reference styles that are not in the resolved options list.
2648
+ */
2649
+ function warnInvalidDropdown(info) {
2650
+ logWarning("media-style-configuration-definition-invalid", info);
1135
2651
  }
1136
2652
 
1137
- export { AutoMediaEmbed, MediaEmbed, MediaEmbedCommand, MediaEmbedEditing, MediaEmbedToolbar, MediaEmbedUI, MediaRegistry, MediaFormView as _MediaFormView, createMediaFigureElement as _createMediaFigureElement, getSelectedMediaModelWidget as _getSelectedMediaModelWidget, getSelectedMediaViewWidget as _getSelectedMediaViewWidget, insertMedia as _insertMedia, isMediaWidget as _isMediaWidget, modelToViewUrlAttributeConverter as _modelToViewUrlAttributeMediaConverter, toMediaWidget as _toMediaWidget };
1138
- //# sourceMappingURL=index.js.map
2653
+ /**
2654
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2655
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2656
+ */
2657
+ /**
2658
+ * @module media-embed/mediaembedstyle
2659
+ */
2660
+ /**
2661
+ * The media embed style plugin.
2662
+ *
2663
+ * This is a "glue" plugin which loads the following plugins:
2664
+ * * {@link module:media-embed/mediaembedstyle/mediaembedstyleediting~MediaEmbedStyleEditing},
2665
+ * * {@link module:media-embed/mediaembedstyle/mediaembedstyleui~MediaEmbedStyleUI}
2666
+ *
2667
+ * For a detailed overview, check the {@glink features/media-embed/media-embed-styles Media embed styles feature documentation}.
2668
+ */
2669
+ var MediaEmbedStyle = class extends Plugin {
2670
+ /**
2671
+ * @inheritDoc
2672
+ */
2673
+ static get requires() {
2674
+ return [MediaEmbedStyleEditing, MediaEmbedStyleUI];
2675
+ }
2676
+ /**
2677
+ * @inheritDoc
2678
+ */
2679
+ static get pluginName() {
2680
+ return "MediaEmbedStyle";
2681
+ }
2682
+ /**
2683
+ * @inheritDoc
2684
+ */
2685
+ static get isOfficialPlugin() {
2686
+ return true;
2687
+ }
2688
+ };
2689
+
2690
+ /**
2691
+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
2692
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
2693
+ */
2694
+
2695
+ export { AutoMediaEmbed, MediaEmbed, MediaEmbedCommand, MediaEmbedCustomResizeUI, MediaEmbedEditing, MediaEmbedResize, MediaEmbedResizeButtons, MediaEmbedResizeEditing, MediaEmbedResizeHandles, MediaEmbedStyle, MediaEmbedStyleCommand, MediaEmbedStyleEditing, MediaEmbedStyleUI, MediaEmbedToolbar, MediaEmbedUI, MediaRegistry, ResizeMediaEmbedCommand, MediaFormView as _MediaFormView, createMediaFigureElement as _createMediaFigureElement, getSelectedMediaModelWidget as _getSelectedMediaModelWidget, getSelectedMediaViewWidget as _getSelectedMediaViewWidget, insertMedia as _insertMedia, isMediaWidget as _isMediaWidget, modelToViewUrlAttributeConverter as _modelToViewUrlAttributeMediaConverter, toMediaWidget as _toMediaWidget };
2696
+ //# sourceMappingURL=index.js.map