8
0

utils.js 17 KB

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