8
0

utils.js 18 KB

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