8
0

utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /**
  2. * @license Copyright (c) 2003-2018, 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 ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
  10. import ModelPosition from '@ckeditor/ckeditor5-engine/src/model/position';
  11. import IconView from '@ckeditor/ckeditor5-ui/src/icon/iconview';
  12. import env from '@ckeditor/ckeditor5-utils/src/env';
  13. import dragHandlerIcon from '../theme/icons/drag-handler.svg';
  14. const widgetSymbol = Symbol( 'isWidget' );
  15. const labelSymbol = Symbol( 'label' );
  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/element~Element} is a widget.
  30. *
  31. * @param {module:engine/view/element~Element} element
  32. * @returns {Boolean}
  33. */
  34. export function isWidget( element ) {
  35. return !!element.getCustomProperty( widgetSymbol );
  36. }
  37. /**
  38. * Converts given {@link module:engine/view/element~Element} to widget in following way:
  39. *
  40. * * sets `contenteditable` attribute to `"true"`,
  41. * * adds `ck-widget` CSS class,
  42. * * adds custom {@link module:engine/view/element~Element#getFillerOffset `getFillerOffset()`} method returning `null`,
  43. * * adds custom property allowing to recognize widget elements by using {@link ~isWidget `isWidget()`},
  44. * * implements {@link ~setHighlightHandling view highlight on widgets}.
  45. *
  46. * This function needs to be used in conjuction with {@link module:engine/conversion/downcast-converters downcast converters}
  47. * like {@link module:engine/conversion/downcast-converters~downcastElementToElement `downcastElementToElement()`}.
  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. * .add( downcastElementToElement( {
  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. * .add( downcastElementToElement( {
  65. * model: 'widget',
  66. * view: ( modelItem, writer ) => {
  67. * return writer.createContainerElement( 'div', { class: 'widget' } );
  68. * }
  69. * } ) );
  70. *
  71. * See a full source code of a widget (with 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 {@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.hasSelectionHandler=false] If `true`, the widget will have a selection handler added.
  80. * @returns {module:engine/view/element~Element} Returns same element.
  81. */
  82. export function toWidget( element, writer, options = {} ) {
  83. // The selection on Edge behaves better when the whole editor contents is in a single contentedible element.
  84. // https://github.com/ckeditor/ckeditor5/issues/1079
  85. if ( !env.isEdge ) {
  86. writer.setAttribute( 'contenteditable', 'false', element );
  87. }
  88. writer.addClass( WIDGET_CLASS_NAME, element );
  89. writer.setCustomProperty( widgetSymbol, true, element );
  90. element.getFillerOffset = getFillerOffset;
  91. if ( options.label ) {
  92. setLabel( element, options.label, writer );
  93. }
  94. if ( options.hasSelectionHandler ) {
  95. addSelectionHandler( 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( labelSymbol, 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( labelSymbol );
  151. if ( !labelCreator ) {
  152. return '';
  153. }
  154. return typeof labelCreator == 'function' ? labelCreator() : labelCreator;
  155. }
  156. /**
  157. * Adds functionality to a provided {@link module:engine/view/editableelement~EditableElement} to act as a widget's editable:
  158. *
  159. * * sets `contenteditable` as `true` when {@link module:engine/view/editableelement~EditableElement#isReadOnly} is `false`
  160. * otherwise set `false`,
  161. * * adds `ck-editor__editable` and `ck-editor__nested-editable` CSS classes,
  162. * * adds `ck-editor__nested-editable_focused` CSS class when 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/downcast-converters~downcastElementToElement `downcastElementToElement()`}.
  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. * .add( downcastElementToElement( {
  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. * .add( downcastElementToElement( {
  182. * model: 'nested',
  183. * view: ( modelItem, writer ) => {
  184. * return writer.createContainerElement( 'div', { class: 'nested' } );
  185. * }
  186. * } ) );
  187. *
  188. * See a full source code of a 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 same element that was provided in `editable` param.
  194. */
  195. export function toWidgetEditable( editable, writer ) {
  196. writer.addClass( [ 'ck-editor__editable', 'ck-editor__nested-editable' ], editable );
  197. // The selection on Edge behaves better when the whole editor contents is in a single contentedible element.
  198. // https://github.com/ckeditor/ckeditor5/issues/1079
  199. if ( !env.isEdge ) {
  200. // Set initial contenteditable value.
  201. writer.setAttribute( 'contenteditable', editable.isReadOnly ? 'false' : 'true', editable );
  202. // Bind the contenteditable property to element#isReadOnly.
  203. editable.on( 'change:isReadOnly', ( evt, property, is ) => {
  204. writer.setAttribute( 'contenteditable', is ? 'false' : 'true', editable );
  205. } );
  206. }
  207. editable.on( 'change:isFocused', ( evt, property, is ) => {
  208. if ( is ) {
  209. writer.addClass( 'ck-editor__nested-editable_focused', editable );
  210. } else {
  211. writer.removeClass( 'ck-editor__nested-editable_focused', editable );
  212. }
  213. } );
  214. return editable;
  215. }
  216. /**
  217. * Returns a model position which is optimal (in terms of UX) for inserting a widget block.
  218. *
  219. * For instance, if a selection is in the middle of a paragraph, the position before this paragraph
  220. * will be returned so that it is not split. If the selection is at the end of a paragraph,
  221. * the position after this paragraph will be returned.
  222. *
  223. * Note: If the selection is placed in an empty block, that block will be returned. If that position
  224. * is then passed to {@link module:engine/model/model~Model#insertContent},
  225. * the block will be fully replaced by the image.
  226. *
  227. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  228. * The selection based on which the insertion position should be calculated.
  229. * @returns {module:engine/model/position~Position} The optimal position.
  230. */
  231. export function findOptimalInsertionPosition( selection ) {
  232. const selectedElement = selection.getSelectedElement();
  233. if ( selectedElement ) {
  234. return ModelPosition.createAfter( selectedElement );
  235. }
  236. const firstBlock = selection.getSelectedBlocks().next().value;
  237. if ( firstBlock ) {
  238. // If inserting into an empty block – return position in that block. It will get
  239. // replaced with the image by insertContent(). #42.
  240. if ( firstBlock.isEmpty ) {
  241. return ModelPosition.createAt( firstBlock );
  242. }
  243. const positionAfter = ModelPosition.createAfter( firstBlock );
  244. // If selection is at the end of the block - return position after the block.
  245. if ( selection.focus.isTouching( positionAfter ) ) {
  246. return positionAfter;
  247. }
  248. // Otherwise return position before the block.
  249. return ModelPosition.createBefore( firstBlock );
  250. }
  251. return selection.focus;
  252. }
  253. // Default filler offset function applied to all widget elements.
  254. //
  255. // @returns {null}
  256. function getFillerOffset() {
  257. return null;
  258. }
  259. // Adds a drag handler to the editable element.
  260. //
  261. // @param {module:engine/view/editableelement~EditableElement}
  262. // @param {module:engine/view/downcastwriter~DowncastWriter} writer
  263. function addSelectionHandler( editable, writer ) {
  264. const selectionHandler = writer.createUIElement( 'div', { class: 'ck ck-widget__selection-handler' }, function( domDocument ) {
  265. const domElement = this.toDomElement( domDocument );
  266. // Use the IconView from the ui library.
  267. const icon = new IconView();
  268. icon.set( 'content', dragHandlerIcon );
  269. // Render the icon view right away to append its #element to the selectionHandler DOM element.
  270. icon.render();
  271. domElement.appendChild( icon.element );
  272. return domElement;
  273. } );
  274. // Append the selection handler into the widget wrapper.
  275. writer.insert( ViewPosition.createAt( editable ), selectionHandler );
  276. writer.addClass( [ 'ck-widget_selectable' ], editable );
  277. }