utils.js 15 KB

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