utils.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module widget/utils
  7. */
  8. import HighlightStack from './highlightstack';
  9. import IconView from '@ckeditor/ckeditor5-ui/src/icon/iconview';
  10. import Rect from '@ckeditor/ckeditor5-utils/src/dom/rect';
  11. import BalloonPanelView from '@ckeditor/ckeditor5-ui/src/panel/balloon/balloonpanelview';
  12. import global from '@ckeditor/ckeditor5-utils/src/dom/global';
  13. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  14. import dragHandleIcon from '../theme/icons/drag-handle.svg';
  15. import { getTypeAroundFakeCaretPosition } from './widgettypearound/utils';
  16. /**
  17. * CSS class added to each widget element.
  18. *
  19. * @const {String}
  20. */
  21. export const WIDGET_CLASS_NAME = 'ck-widget';
  22. /**
  23. * CSS class added to currently selected widget element.
  24. *
  25. * @const {String}
  26. */
  27. export const WIDGET_SELECTED_CLASS_NAME = 'ck-widget_selected';
  28. /**
  29. * Returns `true` if given {@link module:engine/view/node~Node} is an {@link module:engine/view/element~Element} and a widget.
  30. *
  31. * @param {module:engine/view/node~Node} node
  32. * @returns {Boolean}
  33. */
  34. export function isWidget( node ) {
  35. if ( !node.is( 'element' ) ) {
  36. return false;
  37. }
  38. return !!node.getCustomProperty( 'widget' );
  39. }
  40. /**
  41. * Converts the given {@link module:engine/view/element~Element} to a widget in the following way:
  42. *
  43. * * sets the `contenteditable` attribute to `"false"`,
  44. * * adds the `ck-widget` CSS class,
  45. * * adds a custom {@link module:engine/view/element~Element#getFillerOffset `getFillerOffset()`} method returning `null`,
  46. * * adds a custom property allowing to recognize widget elements by using {@link ~isWidget `isWidget()`},
  47. * * implements the {@link ~setHighlightHandling view highlight on widgets}.
  48. *
  49. * This function needs to be used in conjunction with
  50. * {@link module:engine/conversion/downcasthelpers~DowncastHelpers downcast conversion helpers}
  51. * like {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToElement `elementToElement()`}.
  52. * Moreover, typically you will want to use `toWidget()` only for `editingDowncast`, while keeping the `dataDowncast` clean.
  53. *
  54. * For example, in order to convert a `<widget>` model element to `<div class="widget">` in the view, you can define
  55. * such converters:
  56. *
  57. * editor.conversion.for( 'editingDowncast' )
  58. * .elementToElement( {
  59. * model: 'widget',
  60. * view: ( modelItem, { writer } ) => {
  61. * const div = writer.createContainerElement( 'div', { class: 'widget' } );
  62. *
  63. * return toWidget( div, writer, { label: 'some widget' } );
  64. * }
  65. * } );
  66. *
  67. * editor.conversion.for( 'dataDowncast' )
  68. * .elementToElement( {
  69. * model: 'widget',
  70. * view: ( modelItem, { writer } ) => {
  71. * return writer.createContainerElement( 'div', { class: 'widget' } );
  72. * }
  73. * } );
  74. *
  75. * See the full source code of the widget (with a nested editable) schema definition and converters in
  76. * [this sample](https://github.com/ckeditor/ckeditor5-widget/blob/master/tests/manual/widget-with-nestededitable.js).
  77. *
  78. * @param {module:engine/view/element~Element} element
  79. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  80. * @param {Object} [options={}]
  81. * @param {String|Function} [options.label] Element's label provided to the {@link ~setLabel} function. It can be passed as
  82. * a plain string or a function returning a string. It represents the widget for assistive technologies (like screen readers).
  83. * @param {Boolean} [options.hasSelectionHandle=false] If `true`, the widget will have a selection handle added.
  84. * @returns {module:engine/view/element~Element} Returns the same element.
  85. */
  86. export function toWidget( element, writer, options = {} ) {
  87. if ( !element.is( 'containerElement' ) ) {
  88. /**
  89. * The element passed to `toWidget()` must be a {@link module:engine/view/containerelement~ContainerElement}
  90. * instance.
  91. *
  92. * @error widget-to-widget-wrong-element-type
  93. * @param {String} element The view element passed to `toWidget()`.
  94. */
  95. throw new CKEditorError(
  96. 'widget-to-widget-wrong-element-type',
  97. null,
  98. { element }
  99. );
  100. }
  101. writer.setAttribute( 'contenteditable', 'false', element );
  102. writer.addClass( WIDGET_CLASS_NAME, element );
  103. writer.setCustomProperty( 'widget', true, element );
  104. element.getFillerOffset = getFillerOffset;
  105. if ( options.label ) {
  106. setLabel( element, options.label, writer );
  107. }
  108. if ( options.hasSelectionHandle ) {
  109. addSelectionHandle( element, writer );
  110. }
  111. setHighlightHandling(
  112. element,
  113. writer,
  114. ( element, descriptor, writer ) => writer.addClass( normalizeToArray( descriptor.classes ), element ),
  115. ( element, descriptor, writer ) => writer.removeClass( normalizeToArray( descriptor.classes ), element )
  116. );
  117. return element;
  118. // Normalizes CSS class in descriptor that can be provided in form of an array or a string.
  119. function normalizeToArray( classes ) {
  120. return Array.isArray( classes ) ? classes : [ classes ];
  121. }
  122. }
  123. /**
  124. * Sets highlight handling methods. Uses {@link module:widget/highlightstack~HighlightStack} to
  125. * properly determine which highlight descriptor should be used at given time.
  126. *
  127. * @param {module:engine/view/element~Element} element
  128. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  129. * @param {Function} add
  130. * @param {Function} remove
  131. */
  132. export function setHighlightHandling( element, writer, add, remove ) {
  133. const stack = new HighlightStack();
  134. stack.on( 'change:top', ( evt, data ) => {
  135. if ( data.oldDescriptor ) {
  136. remove( element, data.oldDescriptor, data.writer );
  137. }
  138. if ( data.newDescriptor ) {
  139. add( element, data.newDescriptor, data.writer );
  140. }
  141. } );
  142. writer.setCustomProperty( 'addHighlight', ( element, descriptor, writer ) => stack.add( descriptor, writer ), element );
  143. writer.setCustomProperty( 'removeHighlight', ( element, id, writer ) => stack.remove( id, writer ), element );
  144. }
  145. /**
  146. * Sets label for given element.
  147. * It can be passed as a plain string or a function returning a string. Function will be called each time label is retrieved by
  148. * {@link ~getLabel `getLabel()`}.
  149. *
  150. * @param {module:engine/view/element~Element} element
  151. * @param {String|Function} labelOrCreator
  152. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  153. */
  154. export function setLabel( element, labelOrCreator, writer ) {
  155. writer.setCustomProperty( 'widgetLabel', labelOrCreator, element );
  156. }
  157. /**
  158. * Returns the label of the provided element.
  159. *
  160. * @param {module:engine/view/element~Element} element
  161. * @returns {String}
  162. */
  163. export function getLabel( element ) {
  164. const labelCreator = element.getCustomProperty( 'widgetLabel' );
  165. if ( !labelCreator ) {
  166. return '';
  167. }
  168. return typeof labelCreator == 'function' ? labelCreator() : labelCreator;
  169. }
  170. /**
  171. * Adds functionality to the provided {@link module:engine/view/editableelement~EditableElement} to act as a widget's editable:
  172. *
  173. * * sets the `contenteditable` attribute to `true` when {@link module:engine/view/editableelement~EditableElement#isReadOnly} is `false`,
  174. * otherwise sets it to `false`,
  175. * * adds the `ck-editor__editable` and `ck-editor__nested-editable` CSS classes,
  176. * * adds the `ck-editor__nested-editable_focused` CSS class when the editable is focused and removes it when it is blurred.
  177. *
  178. * Similarly to {@link ~toWidget `toWidget()`} this function should be used in `editingDowncast` only and it is usually
  179. * used together with {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToElement `elementToElement()`}.
  180. *
  181. * For example, in order to convert a `<nested>` model element to `<div class="nested">` in the view, you can define
  182. * such converters:
  183. *
  184. * editor.conversion.for( 'editingDowncast' )
  185. * .elementToElement( {
  186. * model: 'nested',
  187. * view: ( modelItem, { writer } ) => {
  188. * const div = writer.createEditableElement( 'div', { class: 'nested' } );
  189. *
  190. * return toWidgetEditable( nested, writer );
  191. * }
  192. * } );
  193. *
  194. * editor.conversion.for( 'dataDowncast' )
  195. * .elementToElement( {
  196. * model: 'nested',
  197. * view: ( modelItem, { writer } ) => {
  198. * return writer.createContainerElement( 'div', { class: 'nested' } );
  199. * }
  200. * } );
  201. *
  202. * See the full source code of the widget (with nested editable) schema definition and converters in
  203. * [this sample](https://github.com/ckeditor/ckeditor5-widget/blob/master/tests/manual/widget-with-nestededitable.js).
  204. *
  205. * @param {module:engine/view/editableelement~EditableElement} editable
  206. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  207. * @returns {module:engine/view/editableelement~EditableElement} Returns the same element that was provided in the `editable` parameter
  208. */
  209. export function toWidgetEditable( editable, writer ) {
  210. writer.addClass( [ 'ck-editor__editable', 'ck-editor__nested-editable' ], editable );
  211. // Set initial contenteditable value.
  212. writer.setAttribute( 'contenteditable', editable.isReadOnly ? 'false' : 'true', editable );
  213. // Bind the contenteditable property to element#isReadOnly.
  214. editable.on( 'change:isReadOnly', ( evt, property, is ) => {
  215. writer.setAttribute( 'contenteditable', is ? 'false' : 'true', editable );
  216. } );
  217. editable.on( 'change:isFocused', ( evt, property, is ) => {
  218. if ( is ) {
  219. writer.addClass( 'ck-editor__nested-editable_focused', editable );
  220. } else {
  221. writer.removeClass( 'ck-editor__nested-editable_focused', editable );
  222. }
  223. } );
  224. return editable;
  225. }
  226. /**
  227. * Returns a model position which is optimal (in terms of UX) for inserting a widget block.
  228. *
  229. * For instance, if a selection is in the middle of a paragraph, the position before this paragraph
  230. * will be returned so that it is not split. If the selection is at the end of a paragraph,
  231. * the position after this paragraph will be returned.
  232. *
  233. * Note: If the selection is placed in an empty block, that block will be returned. If that position
  234. * is then passed to {@link module:engine/model/model~Model#insertContent},
  235. * the block will be fully replaced by the image.
  236. *
  237. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  238. * The selection based on which the insertion position should be calculated.
  239. * @param {module:engine/model/model~Model} model Model instance.
  240. * @returns {module:engine/model/position~Position} The optimal position.
  241. */
  242. export function findOptimalInsertionPosition( selection, model ) {
  243. const selectedElement = selection.getSelectedElement();
  244. if ( selectedElement ) {
  245. const typeAroundFakeCaretPosition = getTypeAroundFakeCaretPosition( selection );
  246. // If the WidgetTypeAround "fake caret" is displayed, use its position for the insertion
  247. // to provide the most predictable UX (https://github.com/ckeditor/ckeditor5/issues/7438).
  248. if ( typeAroundFakeCaretPosition ) {
  249. return model.createPositionAt( selectedElement, typeAroundFakeCaretPosition );
  250. }
  251. if ( model.schema.isBlock( selectedElement ) ) {
  252. return model.createPositionAfter( selectedElement );
  253. }
  254. }
  255. const firstBlock = selection.getSelectedBlocks().next().value;
  256. if ( firstBlock ) {
  257. // If inserting into an empty block – return position in that block. It will get
  258. // replaced with the image by insertContent(). #42.
  259. if ( firstBlock.isEmpty ) {
  260. return model.createPositionAt( firstBlock, 0 );
  261. }
  262. const positionAfter = model.createPositionAfter( firstBlock );
  263. // If selection is at the end of the block - return position after the block.
  264. if ( selection.focus.isTouching( positionAfter ) ) {
  265. return positionAfter;
  266. }
  267. // Otherwise return position before the block.
  268. return model.createPositionBefore( firstBlock );
  269. }
  270. return selection.focus;
  271. }
  272. /**
  273. * A util to be used in order to map view positions to correct model positions when implementing a widget
  274. * which renders non-empty view element for an empty model element.
  275. *
  276. * For example:
  277. *
  278. * // Model:
  279. * <placeholder type="name"></placeholder>
  280. *
  281. * // View:
  282. * <span class="placeholder">name</span>
  283. *
  284. * In such case, view positions inside `<span>` cannot be correct mapped to the model (because the model element is empty).
  285. * To handle mapping positions inside `<span class="placeholder">` to the model use this util as follows:
  286. *
  287. * editor.editing.mapper.on(
  288. * 'viewToModelPosition',
  289. * viewToModelPositionOutsideModelElement( model, viewElement => viewElement.hasClass( 'placeholder' ) )
  290. * );
  291. *
  292. * The callback will try to map the view offset of selection to an expected model position.
  293. *
  294. * 1. When the position is at the end (or in the middle) of the inline widget:
  295. *
  296. * // View:
  297. * <p>foo <span class="placeholder">name|</span> bar</p>
  298. *
  299. * // Model:
  300. * <paragraph>foo <placeholder type="name"></placeholder>| bar</paragraph>
  301. *
  302. * 2. When the position is at the beginning of the inline widget:
  303. *
  304. * // View:
  305. * <p>foo <span class="placeholder">|name</span> bar</p>
  306. *
  307. * // Model:
  308. * <paragraph>foo |<placeholder type="name"></placeholder> bar</paragraph>
  309. *
  310. * @param {module:engine/model/model~Model} model Model instance on which the callback operates.
  311. * @param {Function} viewElementMatcher Function that is passed a view element and should return `true` if the custom mapping
  312. * should be applied to the given view element.
  313. * @return {Function}
  314. */
  315. export function viewToModelPositionOutsideModelElement( model, viewElementMatcher ) {
  316. return ( evt, data ) => {
  317. const { mapper, viewPosition } = data;
  318. const viewParent = mapper.findMappedViewAncestor( viewPosition );
  319. if ( !viewElementMatcher( viewParent ) ) {
  320. return;
  321. }
  322. const modelParent = mapper.toModelElement( viewParent );
  323. data.modelPosition = model.createPositionAt( modelParent, viewPosition.isAtStart ? 'before' : 'after' );
  324. };
  325. }
  326. /**
  327. * A positioning function passed to the {@link module:utils/dom/position~getOptimalPosition} helper as a last resort
  328. * when attaching {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView balloon UI} to widgets.
  329. * It comes in handy when a widget is longer than the visual viewport of the web browser and/or upper/lower boundaries
  330. * of a widget are off screen because of the web page scroll.
  331. *
  332. * ┌─┄┄┄┄┄┄┄┄┄Widget┄┄┄┄┄┄┄┄┄┐
  333. * ┊ ┊
  334. * ┌────────────Viewport───────────┐ ┌──╁─────────Viewport────────╁──┐
  335. * │ ┏━━━━━━━━━━Widget━━━━━━━━━┓ │ │ ┃ ^ ┃ │
  336. * │ ┃ ^ ┃ │ │ ┃ ╭───────/ \───────╮ ┃ │
  337. * │ ┃ ╭───────/ \───────╮ ┃ │ │ ┃ │ Balloon │ ┃ │
  338. * │ ┃ │ Balloon │ ┃ │ │ ┃ ╰─────────────────╯ ┃ │
  339. * │ ┃ ╰─────────────────╯ ┃ │ │ ┃ ┃ │
  340. * │ ┃ ┃ │ │ ┃ ┃ │
  341. * │ ┃ ┃ │ │ ┃ ┃ │
  342. * │ ┃ ┃ │ │ ┃ ┃ │
  343. * │ ┃ ┃ │ │ ┃ ┃ │
  344. * │ ┃ ┃ │ │ ┃ ┃ │
  345. * │ ┃ ┃ │ │ ┃ ┃ │
  346. * └──╀─────────────────────────╀──┘ └──╀─────────────────────────╀──┘
  347. * ┊ ┊ ┊ ┊
  348. * ┊ ┊ └┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
  349. * ┊ ┊
  350. * └┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
  351. *
  352. * **Note**: Works best if used together with
  353. * {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions default `BalloonPanelView` positions}
  354. * like `northArrowSouth` and `southArrowNorth`; the transition between these two and this position is smooth.
  355. *
  356. * @param {module:utils/dom/rect~Rect} widgetRect A rect of the widget.
  357. * @param {module:utils/dom/rect~Rect} balloonRect A rect of the balloon.
  358. * @returns {module:utils/dom/position~Position|null}
  359. */
  360. export function centeredBalloonPositionForLongWidgets( widgetRect, balloonRect ) {
  361. const viewportRect = new Rect( global.window );
  362. const viewportWidgetInsersectionRect = viewportRect.getIntersection( widgetRect );
  363. const balloonTotalHeight = balloonRect.height + BalloonPanelView.arrowVerticalOffset;
  364. // If there is enough space above or below the widget then this position should not be used.
  365. if ( widgetRect.top - balloonTotalHeight > viewportRect.top || widgetRect.bottom + balloonTotalHeight < viewportRect.bottom ) {
  366. return null;
  367. }
  368. // Because this is a last resort positioning, to keep things simple we're not playing with positions of the arrow
  369. // like, for instance, "south west" or whatever. Just try to keep the balloon in the middle of the visible area of
  370. // the widget for as long as it is possible. If the widgets becomes invisible (because cropped by the viewport),
  371. // just... place the balloon in the middle of it (because why not?).
  372. const targetRect = viewportWidgetInsersectionRect || widgetRect;
  373. const left = targetRect.left + targetRect.width / 2 - balloonRect.width / 2;
  374. return {
  375. top: Math.max( widgetRect.top, 0 ) + BalloonPanelView.arrowVerticalOffset,
  376. left,
  377. name: 'arrow_n'
  378. };
  379. }
  380. // Default filler offset function applied to all widget elements.
  381. //
  382. // @returns {null}
  383. function getFillerOffset() {
  384. return null;
  385. }
  386. // Adds a drag handle to the widget.
  387. //
  388. // @param {module:engine/view/containerelement~ContainerElement}
  389. // @param {module:engine/view/downcastwriter~DowncastWriter} writer
  390. function addSelectionHandle( widgetElement, writer ) {
  391. const selectionHandle = writer.createUIElement( 'div', { class: 'ck ck-widget__selection-handle' }, function( domDocument ) {
  392. const domElement = this.toDomElement( domDocument );
  393. // Use the IconView from the ui library.
  394. const icon = new IconView();
  395. icon.set( 'content', dragHandleIcon );
  396. // Render the icon view right away to append its #element to the selectionHandle DOM element.
  397. icon.render();
  398. domElement.appendChild( icon.element );
  399. return domElement;
  400. } );
  401. // Append the selection handle into the widget wrapper.
  402. writer.insert( writer.createPositionAt( widgetElement, 0 ), selectionHandle );
  403. writer.addClass( [ 'ck-widget_with-selection-handle' ], widgetElement );
  404. }