utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module widget/utils
  7. */
  8. import HighlightStack from './highlightstack';
  9. import IconView from '@ckeditor/ckeditor5-ui/src/icon/iconview';
  10. import env from '@ckeditor/ckeditor5-utils/src/env';
  11. import dragHandlerIcon from '../theme/icons/drag-handler.svg';
  12. const widgetSymbol = Symbol( 'isWidget' );
  13. const labelSymbol = Symbol( 'label' );
  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( widgetSymbol );
  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.hasSelectionHandler=false] If `true`, the widget will have a selection handler 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. // The selection on Edge behaves better when the whole editor contents is in a single contenteditable element.
  88. // https://github.com/ckeditor/ckeditor5/issues/1079
  89. if ( !env.isEdge ) {
  90. writer.setAttribute( 'contenteditable', 'false', element );
  91. }
  92. writer.addClass( WIDGET_CLASS_NAME, element );
  93. writer.setCustomProperty( widgetSymbol, true, element );
  94. element.getFillerOffset = getFillerOffset;
  95. if ( options.label ) {
  96. setLabel( element, options.label, writer );
  97. }
  98. if ( options.hasSelectionHandler ) {
  99. addSelectionHandler( element, writer );
  100. }
  101. setHighlightHandling(
  102. element,
  103. writer,
  104. ( element, descriptor, writer ) => writer.addClass( normalizeToArray( descriptor.classes ), element ),
  105. ( element, descriptor, writer ) => writer.removeClass( normalizeToArray( descriptor.classes ), element )
  106. );
  107. return element;
  108. // Normalizes CSS class in descriptor that can be provided in form of an array or a string.
  109. function normalizeToArray( classes ) {
  110. return Array.isArray( classes ) ? classes : [ classes ];
  111. }
  112. }
  113. /**
  114. * Sets highlight handling methods. Uses {@link module:widget/highlightstack~HighlightStack} to
  115. * properly determine which highlight descriptor should be used at given time.
  116. *
  117. * @param {module:engine/view/element~Element} element
  118. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  119. * @param {Function} add
  120. * @param {Function} remove
  121. */
  122. export function setHighlightHandling( element, writer, add, remove ) {
  123. const stack = new HighlightStack();
  124. stack.on( 'change:top', ( evt, data ) => {
  125. if ( data.oldDescriptor ) {
  126. remove( element, data.oldDescriptor, data.writer );
  127. }
  128. if ( data.newDescriptor ) {
  129. add( element, data.newDescriptor, data.writer );
  130. }
  131. } );
  132. writer.setCustomProperty( 'addHighlight', ( element, descriptor, writer ) => stack.add( descriptor, writer ), element );
  133. writer.setCustomProperty( 'removeHighlight', ( element, id, writer ) => stack.remove( id, writer ), element );
  134. }
  135. /**
  136. * Sets label for given element.
  137. * It can be passed as a plain string or a function returning a string. Function will be called each time label is retrieved by
  138. * {@link ~getLabel `getLabel()`}.
  139. *
  140. * @param {module:engine/view/element~Element} element
  141. * @param {String|Function} labelOrCreator
  142. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  143. */
  144. export function setLabel( element, labelOrCreator, writer ) {
  145. writer.setCustomProperty( labelSymbol, labelOrCreator, element );
  146. }
  147. /**
  148. * Returns the label of the provided element.
  149. *
  150. * @param {module:engine/view/element~Element} element
  151. * @returns {String}
  152. */
  153. export function getLabel( element ) {
  154. const labelCreator = element.getCustomProperty( labelSymbol );
  155. if ( !labelCreator ) {
  156. return '';
  157. }
  158. return typeof labelCreator == 'function' ? labelCreator() : labelCreator;
  159. }
  160. /**
  161. * Adds functionality to the provided {@link module:engine/view/editableelement~EditableElement} to act as a widget's editable:
  162. *
  163. * * sets the `contenteditable` attribute to `true` when {@link module:engine/view/editableelement~EditableElement#isReadOnly} is `false`,
  164. * otherwise sets it to `false`,
  165. * * adds the `ck-editor__editable` and `ck-editor__nested-editable` CSS classes,
  166. * * adds the `ck-editor__nested-editable_focused` CSS class when the editable is focused and removes it when it is blurred.
  167. *
  168. * Similarly to {@link ~toWidget `toWidget()`} this function should be used in `dataDowncast` only and it is usually
  169. * used together with {@link module:engine/conversion/downcasthelpers~DowncastHelpers#elementToElement `elementToElement()`}.
  170. *
  171. * For example, in order to convert a `<nested>` model element to `<div class="nested">` in the view, you can define
  172. * such converters:
  173. *
  174. * editor.conversion.for( 'editingDowncast' )
  175. * .elementToElement( {
  176. * model: 'nested',
  177. * view: ( modelItem, writer ) => {
  178. * const div = writer.createEditableElement( 'div', { class: 'nested' } );
  179. *
  180. * return toWidgetEditable( nested, writer );
  181. * }
  182. * } );
  183. *
  184. * editor.conversion.for( 'dataDowncast' )
  185. * .elementToElement( {
  186. * model: 'nested',
  187. * view: ( modelItem, writer ) => {
  188. * return writer.createContainerElement( 'div', { class: 'nested' } );
  189. * }
  190. * } );
  191. *
  192. * See the full source code of the widget (with nested editable) schema definition and converters in
  193. * [this sample](https://github.com/ckeditor/ckeditor5-widget/blob/master/tests/manual/widget-with-nestededitable.js).
  194. *
  195. * @param {module:engine/view/editableelement~EditableElement} editable
  196. * @param {module:engine/view/downcastwriter~DowncastWriter} writer
  197. * @returns {module:engine/view/editableelement~EditableElement} Returns the same element that was provided in the `editable` parameter
  198. */
  199. export function toWidgetEditable( editable, writer ) {
  200. writer.addClass( [ 'ck-editor__editable', 'ck-editor__nested-editable' ], editable );
  201. // The selection on Edge behaves better when the whole editor contents is in a single contentedible element.
  202. // https://github.com/ckeditor/ckeditor5/issues/1079
  203. if ( !env.isEdge ) {
  204. // Set initial contenteditable value.
  205. writer.setAttribute( 'contenteditable', editable.isReadOnly ? 'false' : 'true', editable );
  206. // Bind the contenteditable property to element#isReadOnly.
  207. editable.on( 'change:isReadOnly', ( evt, property, is ) => {
  208. writer.setAttribute( 'contenteditable', is ? 'false' : 'true', editable );
  209. } );
  210. }
  211. editable.on( 'change:isFocused', ( evt, property, is ) => {
  212. if ( is ) {
  213. writer.addClass( 'ck-editor__nested-editable_focused', editable );
  214. } else {
  215. writer.removeClass( 'ck-editor__nested-editable_focused', editable );
  216. }
  217. } );
  218. return editable;
  219. }
  220. /**
  221. * Returns a model position which is optimal (in terms of UX) for inserting a widget block.
  222. *
  223. * For instance, if a selection is in the middle of a paragraph, the position before this paragraph
  224. * will be returned so that it is not split. If the selection is at the end of a paragraph,
  225. * the position after this paragraph will be returned.
  226. *
  227. * Note: If the selection is placed in an empty block, that block will be returned. If that position
  228. * is then passed to {@link module:engine/model/model~Model#insertContent},
  229. * the block will be fully replaced by the image.
  230. *
  231. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  232. * The selection based on which the insertion position should be calculated.
  233. * @param {module:engine/model/model~Model} model Model instance.
  234. * @returns {module:engine/model/position~Position} The optimal position.
  235. */
  236. export function findOptimalInsertionPosition( selection, model ) {
  237. const selectedElement = selection.getSelectedElement();
  238. if ( selectedElement && !model.schema.isInline( selectedElement ) ) {
  239. return model.createPositionAfter( selectedElement );
  240. }
  241. const firstBlock = selection.getSelectedBlocks().next().value;
  242. if ( firstBlock ) {
  243. // If inserting into an empty block – return position in that block. It will get
  244. // replaced with the image by insertContent(). #42.
  245. if ( firstBlock.isEmpty ) {
  246. return model.createPositionAt( firstBlock, 0 );
  247. }
  248. const positionAfter = model.createPositionAfter( firstBlock );
  249. // If selection is at the end of the block - return position after the block.
  250. if ( selection.focus.isTouching( positionAfter ) ) {
  251. return positionAfter;
  252. }
  253. // Otherwise return position before the block.
  254. return model.createPositionBefore( firstBlock );
  255. }
  256. return selection.focus;
  257. }
  258. // Default filler offset function applied to all widget elements.
  259. //
  260. // @returns {null}
  261. function getFillerOffset() {
  262. return null;
  263. }
  264. // Adds a drag handler to the editable element.
  265. //
  266. // @param {module:engine/view/editableelement~EditableElement}
  267. // @param {module:engine/view/downcastwriter~DowncastWriter} writer
  268. function addSelectionHandler( editable, writer ) {
  269. const selectionHandler = writer.createUIElement( 'div', { class: 'ck ck-widget__selection-handler' }, function( domDocument ) {
  270. const domElement = this.toDomElement( domDocument );
  271. // Use the IconView from the ui library.
  272. const icon = new IconView();
  273. icon.set( 'content', dragHandlerIcon );
  274. // Render the icon view right away to append its #element to the selectionHandler DOM element.
  275. icon.render();
  276. domElement.appendChild( icon.element );
  277. return domElement;
  278. } );
  279. // Append the selection handler into the widget wrapper.
  280. writer.insert( writer.createPositionAt( editable, 0 ), selectionHandler );
  281. writer.addClass( [ 'ck-widget_with-selection-handler' ], editable );
  282. }