8
0

linkcommand.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 link/linkcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import findLinkRange from './findlinkrange';
  10. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  11. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  12. import first from '@ckeditor/ckeditor5-utils/src/first';
  13. /**
  14. * The link command. It is used by the {@link module:link/link~Link link feature}.
  15. *
  16. * @extends module:core/command~Command
  17. */
  18. export default class LinkCommand extends Command {
  19. /**
  20. * The value of the `'linkHref'` attribute if the start of the selection is located in a node with this attribute.
  21. *
  22. * @observable
  23. * @readonly
  24. * @member {Object|undefined} #value
  25. */
  26. constructor( editor ) {
  27. super( editor );
  28. /**
  29. * A collection of {@link module:link/utils~ManualDecorator manual decorators}
  30. * corresponding to the {@link module:link/link~LinkConfig#decorators decorator configuration}.
  31. *
  32. * You can consider it a model with states of manual decorators added to the currently selected link.
  33. *
  34. * @readonly
  35. * @type {module:utils/collection~Collection}
  36. */
  37. this.manualDecorators = new Collection();
  38. }
  39. /**
  40. * Synchronizes the state of {@link #manualDecorators} with the currently present elements in the model.
  41. */
  42. restoreManualDecoratorStates() {
  43. for ( const manualDecorator of this.manualDecorators ) {
  44. manualDecorator.value = this._getDecoratorStateFromModel( manualDecorator.id );
  45. }
  46. }
  47. /**
  48. * @inheritDoc
  49. */
  50. refresh() {
  51. const model = this.editor.model;
  52. const doc = model.document;
  53. const selectedElement = first( doc.selection.getSelectedBlocks() );
  54. // A check for the `LinkImage` plugin. If the selection contains an element, get values from the element.
  55. // Currently the selection reads attributes from text nodes only. See #7429 and #7465.
  56. if ( selectedElement && selectedElement.is( 'image' ) && model.schema.checkAttribute( 'image', 'linkHref' ) ) {
  57. this.value = selectedElement.getAttribute( 'linkHref' );
  58. this.isEnabled = model.schema.checkAttribute( selectedElement, 'linkHref' );
  59. } else {
  60. this.value = doc.selection.getAttribute( 'linkHref' );
  61. this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, 'linkHref' );
  62. }
  63. for ( const manualDecorator of this.manualDecorators ) {
  64. manualDecorator.value = this._getDecoratorStateFromModel( manualDecorator.id );
  65. }
  66. }
  67. /**
  68. * Executes the command.
  69. *
  70. * When the selection is non-collapsed, the `linkHref` attribute will be applied to nodes inside the selection, but only to
  71. * those nodes where the `linkHref` attribute is allowed (disallowed nodes will be omitted).
  72. *
  73. * When the selection is collapsed and is not inside the text with the `linkHref` attribute, a
  74. * new {@link module:engine/model/text~Text text node} with the `linkHref` attribute will be inserted in place of the caret, but
  75. * only if such element is allowed in this place. The `_data` of the inserted text will equal the `href` parameter.
  76. * The selection will be updated to wrap the just inserted text node.
  77. *
  78. * When the selection is collapsed and inside the text with the `linkHref` attribute, the attribute value will be updated.
  79. *
  80. * # Decorators and model attribute management
  81. *
  82. * There is an optional argument to this command that applies or removes model
  83. * {@glink framework/guides/architecture/editing-engine#text-attributes text attributes} brought by
  84. * {@link module:link/utils~ManualDecorator manual link decorators}.
  85. *
  86. * Text attribute names in the model correspond to the entries in the {@link module:link/link~LinkConfig#decorators configuration}.
  87. * For every decorator configured, a model text attribute exists with the "link" prefix. For example, a `'linkMyDecorator'` attribute
  88. * corresponds to `'myDecorator'` in the configuration.
  89. *
  90. * To learn more about link decorators, check out the {@link module:link/link~LinkConfig#decorators `config.link.decorators`}
  91. * documentation.
  92. *
  93. * Here is how to manage decorator attributes with the link command:
  94. *
  95. * const linkCommand = editor.commands.get( 'link' );
  96. *
  97. * // Adding a new decorator attribute.
  98. * linkCommand.execute( 'http://example.com', {
  99. * linkIsExternal: true
  100. * } );
  101. *
  102. * // Removing a decorator attribute from the selection.
  103. * linkCommand.execute( 'http://example.com', {
  104. * linkIsExternal: false
  105. * } );
  106. *
  107. * // Adding multiple decorator attributes at the same time.
  108. * linkCommand.execute( 'http://example.com', {
  109. * linkIsExternal: true,
  110. * linkIsDownloadable: true,
  111. * } );
  112. *
  113. * // Removing and adding decorator attributes at the same time.
  114. * linkCommand.execute( 'http://example.com', {
  115. * linkIsExternal: false,
  116. * linkFoo: true,
  117. * linkIsDownloadable: false,
  118. * } );
  119. *
  120. * **Note**: If the decorator attribute name is not specified, its state remains untouched.
  121. *
  122. * **Note**: {@link module:link/unlinkcommand~UnlinkCommand#execute `UnlinkCommand#execute()`} removes all
  123. * decorator attributes.
  124. *
  125. * @fires execute
  126. * @param {String} href Link destination.
  127. * @param {Object} [manualDecoratorIds={}] The information about manual decorator attributes to be applied or removed upon execution.
  128. */
  129. execute( href, manualDecoratorIds = {} ) {
  130. const model = this.editor.model;
  131. const selection = model.document.selection;
  132. // Stores information about manual decorators to turn them on/off when command is applied.
  133. const truthyManualDecorators = [];
  134. const falsyManualDecorators = [];
  135. for ( const name in manualDecoratorIds ) {
  136. if ( manualDecoratorIds[ name ] ) {
  137. truthyManualDecorators.push( name );
  138. } else {
  139. falsyManualDecorators.push( name );
  140. }
  141. }
  142. model.change( writer => {
  143. // If selection is collapsed then update selected link or insert new one at the place of caret.
  144. if ( selection.isCollapsed ) {
  145. const position = selection.getFirstPosition();
  146. // When selection is inside text with `linkHref` attribute.
  147. if ( selection.hasAttribute( 'linkHref' ) ) {
  148. // Then update `linkHref` value.
  149. const linkRange = findLinkRange( position, selection.getAttribute( 'linkHref' ), model );
  150. writer.setAttribute( 'linkHref', href, linkRange );
  151. truthyManualDecorators.forEach( item => {
  152. writer.setAttribute( item, true, linkRange );
  153. } );
  154. falsyManualDecorators.forEach( item => {
  155. writer.removeAttribute( item, linkRange );
  156. } );
  157. // Put the selection at the end of the updated link.
  158. writer.setSelection( writer.createPositionAfter( linkRange.end.nodeBefore ) );
  159. }
  160. // If not then insert text node with `linkHref` attribute in place of caret.
  161. // However, since selection in collapsed, attribute value will be used as data for text node.
  162. // So, if `href` is empty, do not create text node.
  163. else if ( href !== '' ) {
  164. const attributes = toMap( selection.getAttributes() );
  165. attributes.set( 'linkHref', href );
  166. truthyManualDecorators.forEach( item => {
  167. attributes.set( item, true );
  168. } );
  169. const node = writer.createText( href, attributes );
  170. model.insertContent( node, position );
  171. // Put the selection at the end of the inserted link.
  172. writer.setSelection( writer.createPositionAfter( node ) );
  173. }
  174. // Remove the `linkHref` attribute and all link decorators from the selection.
  175. // It stops adding a new content into the link element.
  176. [ 'linkHref', ...truthyManualDecorators, ...falsyManualDecorators ].forEach( item => {
  177. writer.removeSelectionAttribute( item );
  178. } );
  179. } else {
  180. // If selection has non-collapsed ranges, we change attribute on nodes inside those ranges
  181. // omitting nodes where the `linkHref` attribute is disallowed.
  182. const ranges = model.schema.getValidRanges( selection.getRanges(), 'linkHref' );
  183. // But for the first, check whether the `linkHref` attribute is allowed on selected blocks (e.g. the "image" element).
  184. const allowedRanges = [];
  185. for ( const element of selection.getSelectedBlocks() ) {
  186. if ( model.schema.checkAttribute( element, 'linkHref' ) ) {
  187. allowedRanges.push( writer.createRangeOn( element ) );
  188. }
  189. }
  190. // Ranges that accept the `linkHref` attribute. Since we will iterate over `allowedRanges`, let's clone it.
  191. const rangesToUpdate = allowedRanges.slice();
  192. // For all selection ranges we want to check whether given range is inside an element that accepts the `linkHref` attribute.
  193. // If so, we don't want to propagate applying the attribute to its children.
  194. for ( const range of ranges ) {
  195. if ( this._isRangeToUpdate( range, allowedRanges ) ) {
  196. rangesToUpdate.push( range );
  197. }
  198. }
  199. for ( const range of rangesToUpdate ) {
  200. writer.setAttribute( 'linkHref', href, range );
  201. truthyManualDecorators.forEach( item => {
  202. writer.setAttribute( item, true, range );
  203. } );
  204. falsyManualDecorators.forEach( item => {
  205. writer.removeAttribute( item, range );
  206. } );
  207. }
  208. }
  209. } );
  210. }
  211. /**
  212. * Provides information whether a decorator with a given name is present in the currently processed selection.
  213. *
  214. * @private
  215. * @param {String} decoratorName The name of the manual decorator used in the model
  216. * @returns {Boolean} The information whether a given decorator is currently present in the selection.
  217. */
  218. _getDecoratorStateFromModel( decoratorName ) {
  219. const doc = this.editor.model.document;
  220. return doc.selection.getAttribute( decoratorName );
  221. }
  222. /**
  223. * Checks whether specified `range` is inside an element that accepts the `linkHref` attribute.
  224. *
  225. * @private
  226. * @param {module:engine/view/range~Range} range A range to check.
  227. * @param {Array.<module:engine/view/range~Range>} allowedRanges An array of ranges created on elements where the attribute is accepted.
  228. * @returns {Boolean}
  229. */
  230. _isRangeToUpdate( range, allowedRanges ) {
  231. for ( const allowedRange of allowedRanges ) {
  232. // A range is inside an element that will have the `linkHref` attribute. Do not modify its nodes.
  233. if ( allowedRange.containsRange( range ) ) {
  234. return false;
  235. }
  236. }
  237. return true;
  238. }
  239. }