8
0

utils.js 13 KB

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