linkediting.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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/linkediting
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import MouseObserver from '@ckeditor/ckeditor5-engine/src/view/observer/mouseobserver';
  10. import TwoStepCaretMovement from '@ckeditor/ckeditor5-typing/src/twostepcaretmovement';
  11. import inlineHighlight from '@ckeditor/ckeditor5-typing/src/utils/inlinehighlight';
  12. import Input from '@ckeditor/ckeditor5-typing/src/input';
  13. import Clipboard from '@ckeditor/ckeditor5-clipboard/src/clipboard';
  14. import LinkCommand from './linkcommand';
  15. import UnlinkCommand from './unlinkcommand';
  16. import ManualDecorator from './utils/manualdecorator';
  17. import findAttributeRange from '@ckeditor/ckeditor5-typing/src/utils/findattributerange';
  18. import { keyCodes } from '@ckeditor/ckeditor5-utils/src/keyboard';
  19. import { createLinkElement, ensureSafeUrl, getLocalizedDecorators, normalizeDecorators } from './utils';
  20. import '../theme/link.css';
  21. const HIGHLIGHT_CLASS = 'ck-link_selected';
  22. const DECORATOR_AUTOMATIC = 'automatic';
  23. const DECORATOR_MANUAL = 'manual';
  24. const EXTERNAL_LINKS_REGEXP = /^(https?:)?\/\//;
  25. /**
  26. * The link engine feature.
  27. *
  28. * It introduces the `linkHref="url"` attribute in the model which renders to the view as a `<a href="url">` element
  29. * as well as `'link'` and `'unlink'` commands.
  30. *
  31. * @extends module:core/plugin~Plugin
  32. */
  33. export default class LinkEditing extends Plugin {
  34. /**
  35. * @inheritDoc
  36. */
  37. static get pluginName() {
  38. return 'LinkEditing';
  39. }
  40. /**
  41. * @inheritDoc
  42. */
  43. static get requires() {
  44. // Clipboard is required for handling cut and paste events while typing over the link.
  45. return [ TwoStepCaretMovement, Input, Clipboard ];
  46. }
  47. /**
  48. * @inheritDoc
  49. */
  50. constructor( editor ) {
  51. super( editor );
  52. editor.config.define( 'link', {
  53. addTargetToExternalLinks: false
  54. } );
  55. }
  56. /**
  57. * @inheritDoc
  58. */
  59. init() {
  60. const editor = this.editor;
  61. // Allow link attribute on all inline nodes.
  62. editor.model.schema.extend( '$text', { allowAttributes: 'linkHref' } );
  63. editor.conversion.for( 'dataDowncast' )
  64. .attributeToElement( { model: 'linkHref', view: createLinkElement } );
  65. editor.conversion.for( 'editingDowncast' )
  66. .attributeToElement( { model: 'linkHref', view: ( href, conversionApi ) => {
  67. return createLinkElement( ensureSafeUrl( href ), conversionApi );
  68. } } );
  69. editor.conversion.for( 'upcast' )
  70. .elementToAttribute( {
  71. view: {
  72. name: 'a',
  73. attributes: {
  74. href: true
  75. }
  76. },
  77. model: {
  78. key: 'linkHref',
  79. value: viewElement => viewElement.getAttribute( 'href' )
  80. }
  81. } );
  82. // Create linking commands.
  83. editor.commands.add( 'link', new LinkCommand( editor ) );
  84. editor.commands.add( 'unlink', new UnlinkCommand( editor ) );
  85. const linkDecorators = getLocalizedDecorators( editor.t, normalizeDecorators( editor.config.get( 'link.decorators' ) ) );
  86. this._enableAutomaticDecorators( linkDecorators.filter( item => item.mode === DECORATOR_AUTOMATIC ) );
  87. this._enableManualDecorators( linkDecorators.filter( item => item.mode === DECORATOR_MANUAL ) );
  88. // Enable two-step caret movement for `linkHref` attribute.
  89. const twoStepCaretMovementPlugin = editor.plugins.get( TwoStepCaretMovement );
  90. twoStepCaretMovementPlugin.registerAttribute( 'linkHref' );
  91. // Setup highlight over selected link.
  92. inlineHighlight( editor, 'linkHref', 'a', HIGHLIGHT_CLASS );
  93. // Change the attributes of the selection in certain situations after the link was inserted into the document.
  94. this._enableInsertContentSelectionAttributesFixer();
  95. // Handle a click at the beginning/end of a link element.
  96. this._enableClickingAfterLink();
  97. // Handle typing over the link.
  98. this._enableTypingOverLink();
  99. // Handle removing the content after the link element.
  100. this._handleDeleteContentAfterLink();
  101. }
  102. /**
  103. * Processes an array of configured {@link module:link/link~LinkDecoratorAutomaticDefinition automatic decorators}
  104. * and registers a {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher downcast dispatcher}
  105. * for each one of them. Downcast dispatchers are obtained using the
  106. * {@link module:link/utils~AutomaticDecorators#getDispatcher} method.
  107. *
  108. * **Note**: This method also activates the automatic external link decorator if enabled with
  109. * {@link module:link/link~LinkConfig#addTargetToExternalLinks `config.link.addTargetToExternalLinks`}.
  110. *
  111. * @private
  112. * @param {Array.<module:link/link~LinkDecoratorAutomaticDefinition>} automaticDecoratorDefinitions
  113. */
  114. _enableAutomaticDecorators( automaticDecoratorDefinitions ) {
  115. const editor = this.editor;
  116. // Store automatic decorators in the command instance as we do the same with manual decorators.
  117. // Thanks to that, `LinkImageEditing` plugin can re-use the same definitions.
  118. const command = editor.commands.get( 'link' );
  119. const automaticDecorators = command.automaticDecorators;
  120. // Adds a default decorator for external links.
  121. if ( editor.config.get( 'link.addTargetToExternalLinks' ) ) {
  122. automaticDecorators.add( {
  123. id: 'linkIsExternal',
  124. mode: DECORATOR_AUTOMATIC,
  125. callback: url => EXTERNAL_LINKS_REGEXP.test( url ),
  126. attributes: {
  127. target: '_blank',
  128. rel: 'noopener noreferrer'
  129. }
  130. } );
  131. }
  132. automaticDecorators.add( automaticDecoratorDefinitions );
  133. if ( automaticDecorators.length ) {
  134. editor.conversion.for( 'downcast' ).add( automaticDecorators.getDispatcher() );
  135. }
  136. }
  137. /**
  138. * Processes an array of configured {@link module:link/link~LinkDecoratorManualDefinition manual decorators},
  139. * transforms them into {@link module:link/utils~ManualDecorator} instances and stores them in the
  140. * {@link module:link/linkcommand~LinkCommand#manualDecorators} collection (a model for manual decorators state).
  141. *
  142. * Also registers an {@link module:engine/conversion/downcasthelpers~DowncastHelpers#attributeToElement attribute-to-element}
  143. * converter for each manual decorator and extends the {@link module:engine/model/schema~Schema model's schema}
  144. * with adequate model attributes.
  145. *
  146. * @private
  147. * @param {Array.<module:link/link~LinkDecoratorManualDefinition>} manualDecoratorDefinitions
  148. */
  149. _enableManualDecorators( manualDecoratorDefinitions ) {
  150. if ( !manualDecoratorDefinitions.length ) {
  151. return;
  152. }
  153. const editor = this.editor;
  154. const command = editor.commands.get( 'link' );
  155. const manualDecorators = command.manualDecorators;
  156. manualDecoratorDefinitions.forEach( decorator => {
  157. editor.model.schema.extend( '$text', { allowAttributes: decorator.id } );
  158. // Keeps reference to manual decorator to decode its name to attributes during downcast.
  159. manualDecorators.add( new ManualDecorator( decorator ) );
  160. editor.conversion.for( 'downcast' ).attributeToElement( {
  161. model: decorator.id,
  162. view: ( manualDecoratorName, { writer } ) => {
  163. if ( manualDecoratorName ) {
  164. const attributes = manualDecorators.get( decorator.id ).attributes;
  165. const element = writer.createAttributeElement( 'a', attributes, { priority: 5 } );
  166. writer.setCustomProperty( 'link', true, element );
  167. return element;
  168. }
  169. } } );
  170. editor.conversion.for( 'upcast' ).elementToAttribute( {
  171. view: {
  172. name: 'a',
  173. attributes: manualDecorators.get( decorator.id ).attributes
  174. },
  175. model: {
  176. key: decorator.id
  177. }
  178. } );
  179. } );
  180. }
  181. /**
  182. * Starts listening to {@link module:engine/model/model~Model#event:insertContent} and corrects the model
  183. * selection attributes if the selection is at the end of a link after inserting the content.
  184. *
  185. * The purpose of this action is to improve the overall UX because the user is no longer "trapped" by the
  186. * `linkHref` attribute of the selection and they can type a "clean" (`linkHref`–less) text right away.
  187. *
  188. * See https://github.com/ckeditor/ckeditor5/issues/6053.
  189. *
  190. * @private
  191. */
  192. _enableInsertContentSelectionAttributesFixer() {
  193. const editor = this.editor;
  194. const model = editor.model;
  195. const selection = model.document.selection;
  196. const linkCommand = editor.commands.get( 'link' );
  197. this.listenTo( model, 'insertContent', () => {
  198. const nodeBefore = selection.anchor.nodeBefore;
  199. const nodeAfter = selection.anchor.nodeAfter;
  200. // NOTE: ↰ and ↱ represent the gravity of the selection.
  201. // The only truly valid case is:
  202. //
  203. // ↰
  204. // ...<$text linkHref="foo">INSERTED[]</$text>
  205. //
  206. // If the selection is not "trapped" by the `linkHref` attribute after inserting, there's nothing
  207. // to fix there.
  208. if ( !selection.hasAttribute( 'linkHref' ) ) {
  209. return;
  210. }
  211. // Filter out the following case where a link with the same href (e.g. <a href="foo">INSERTED</a>) is inserted
  212. // in the middle of an existing link:
  213. //
  214. // Before insertion:
  215. // ↰
  216. // <$text linkHref="foo">l[]ink</$text>
  217. //
  218. // Expected after insertion:
  219. // ↰
  220. // <$text linkHref="foo">lINSERTED[]ink</$text>
  221. //
  222. if ( !nodeBefore ) {
  223. return;
  224. }
  225. // Filter out the following case where the selection has the "linkHref" attribute because the
  226. // gravity is overridden and some text with another attribute (e.g. <b>INSERTED</b>) is inserted:
  227. //
  228. // Before insertion:
  229. //
  230. // ↱
  231. // <$text linkHref="foo">[]link</$text>
  232. //
  233. // Expected after insertion:
  234. //
  235. // ↱
  236. // <$text bold="true">INSERTED</$text><$text linkHref="foo">[]link</$text>
  237. //
  238. if ( !nodeBefore.hasAttribute( 'linkHref' ) ) {
  239. return;
  240. }
  241. // Filter out the following case where a link is a inserted in the middle (or before) another link
  242. // (different URLs, so they will not merge). In this (let's say weird) case, we can leave the selection
  243. // attributes as they are because the user will end up writing in one link or another anyway.
  244. //
  245. // Before insertion:
  246. //
  247. // ↰
  248. // <$text linkHref="foo">l[]ink</$text>
  249. //
  250. // Expected after insertion:
  251. //
  252. // ↰
  253. // <$text linkHref="foo">l</$text><$text linkHref="bar">INSERTED[]</$text><$text linkHref="foo">ink</$text>
  254. //
  255. if ( nodeAfter && nodeAfter.hasAttribute( 'linkHref' ) ) {
  256. return;
  257. }
  258. model.change( writer => {
  259. removeLinkAttributesFromSelection( writer, linkCommand.manualDecorators );
  260. } );
  261. }, { priority: 'low' } );
  262. }
  263. /**
  264. * Starts listening to {@link module:engine/view/document~Document#event:mousedown} and
  265. * {@link module:engine/view/document~Document#event:selectionChange} and puts the selection before/after a link node
  266. * if clicked at the beginning/ending of the link.
  267. *
  268. * The purpose of this action is to allow typing around the link node directly after a click.
  269. *
  270. * See https://github.com/ckeditor/ckeditor5/issues/1016.
  271. *
  272. * @private
  273. */
  274. _enableClickingAfterLink() {
  275. const editor = this.editor;
  276. const linkCommand = editor.commands.get( 'link' );
  277. editor.editing.view.addObserver( MouseObserver );
  278. let clicked = false;
  279. // Detect the click.
  280. this.listenTo( editor.editing.view.document, 'mousedown', () => {
  281. clicked = true;
  282. } );
  283. // When the selection has changed...
  284. this.listenTo( editor.editing.view.document, 'selectionChange', () => {
  285. if ( !clicked ) {
  286. return;
  287. }
  288. // ...and it was caused by the click...
  289. clicked = false;
  290. const selection = editor.model.document.selection;
  291. // ...and no text is selected...
  292. if ( !selection.isCollapsed ) {
  293. return;
  294. }
  295. // ...and clicked text is the link...
  296. if ( !selection.hasAttribute( 'linkHref' ) ) {
  297. return;
  298. }
  299. const position = selection.getFirstPosition();
  300. const linkRange = findAttributeRange( position, 'linkHref', selection.getAttribute( 'linkHref' ), editor.model );
  301. // ...check whether clicked start/end boundary of the link.
  302. // If so, remove the `linkHref` attribute.
  303. if ( position.isTouching( linkRange.start ) || position.isTouching( linkRange.end ) ) {
  304. editor.model.change( writer => {
  305. removeLinkAttributesFromSelection( writer, linkCommand.manualDecorators );
  306. } );
  307. }
  308. } );
  309. }
  310. /**
  311. * Starts listening to {@link module:engine/model/model~Model#deleteContent} and {@link module:engine/model/model~Model#insertContent}
  312. * and checks whether typing over the link. If so, attributes of removed text are preserved and applied to the inserted text.
  313. *
  314. * The purpose of this action is to allow modifying a text without loosing the `linkHref` attribute (and other).
  315. *
  316. * See https://github.com/ckeditor/ckeditor5/issues/4762.
  317. *
  318. * @private
  319. */
  320. _enableTypingOverLink() {
  321. const editor = this.editor;
  322. const view = editor.editing.view;
  323. // Selection attributes when started typing over the link.
  324. let selectionAttributes;
  325. // Whether pressed `Backspace` or `Delete`. If so, attributes should not be preserved.
  326. let deletedContent;
  327. // Detect pressing `Backspace` / `Delete`.
  328. this.listenTo( view.document, 'delete', () => {
  329. deletedContent = true;
  330. }, { priority: 'high' } );
  331. // Listening to `model#deleteContent` allows detecting whether selected content was a link.
  332. // If so, before removing the element, we will copy its attributes.
  333. this.listenTo( editor.model, 'deleteContent', () => {
  334. const selection = editor.model.document.selection;
  335. // Copy attributes only if anything is selected.
  336. if ( selection.isCollapsed ) {
  337. return;
  338. }
  339. // When the content was deleted, do not preserve attributes.
  340. if ( deletedContent ) {
  341. deletedContent = false;
  342. return;
  343. }
  344. // Enabled only when typing.
  345. if ( !isTyping( editor ) ) {
  346. return;
  347. }
  348. if ( shouldCopyAttributes( editor.model ) ) {
  349. selectionAttributes = selection.getAttributes();
  350. }
  351. }, { priority: 'high' } );
  352. // Listening to `model#insertContent` allows detecting the content insertion.
  353. // We want to apply attributes that were removed while typing over the link.
  354. this.listenTo( editor.model, 'insertContent', ( evt, [ element ] ) => {
  355. deletedContent = false;
  356. // Enabled only when typing.
  357. if ( !isTyping( editor ) ) {
  358. return;
  359. }
  360. if ( !selectionAttributes ) {
  361. return;
  362. }
  363. editor.model.change( writer => {
  364. for ( const [ attribute, value ] of selectionAttributes ) {
  365. writer.setAttribute( attribute, value, element );
  366. }
  367. } );
  368. selectionAttributes = null;
  369. }, { priority: 'high' } );
  370. }
  371. /**
  372. * Starts listening to {@link module:engine/model/model~Model#deleteContent} and checks whether
  373. * removing a content right after the "linkHref" attribute.
  374. *
  375. * If so, the selection should not preserve the `linkHref` attribute. However, if
  376. * the {@link module:typing/twostepcaretmovement~TwoStepCaretMovement} plugin is active and
  377. * the selection has the "linkHref" attribute due to overriden gravity (at the end), the `linkHref` attribute should stay untouched.
  378. *
  379. * The purpose of this action is to allow removing the link text and keep the selection outside the link.
  380. *
  381. * See https://github.com/ckeditor/ckeditor5/issues/7521.
  382. *
  383. * @private
  384. */
  385. _handleDeleteContentAfterLink() {
  386. const editor = this.editor;
  387. const model = editor.model;
  388. const selection = model.document.selection;
  389. const view = editor.editing.view;
  390. const linkCommand = editor.commands.get( 'link' );
  391. // A flag whether attributes `linkHref` attribute should be preserved.
  392. let shouldPreserveAttributes = false;
  393. // A flag whether the `Backspace` key was pressed.
  394. let hasBackspacePressed = false;
  395. // Detect pressing `Backspace`.
  396. this.listenTo( view.document, 'delete', ( evt, data ) => {
  397. hasBackspacePressed = data.domEvent.keyCode === keyCodes.backspace;
  398. }, { priority: 'high' } );
  399. // Before removing the content, check whether the selection is inside a link or at the end of link but with 2-SCM enabled.
  400. // If so, we want to preserve link attributes.
  401. this.listenTo( model, 'deleteContent', () => {
  402. // Reset the state.
  403. shouldPreserveAttributes = false;
  404. const position = selection.getFirstPosition();
  405. const linkHref = selection.getAttribute( 'linkHref' );
  406. if ( !linkHref ) {
  407. return;
  408. }
  409. const linkRange = findAttributeRange( position, 'linkHref', linkHref, model );
  410. // Preserve `linkHref` attribute if the selection is in the middle of the link or
  411. // the selection is at the end of the link and 2-SCM is activated.
  412. shouldPreserveAttributes = linkRange.containsPosition( position ) || linkRange.end.isEqual( position );
  413. }, { priority: 'high' } );
  414. // After removing the content, check whether the current selection should preserve the `linkHref` attribute.
  415. this.listenTo( model, 'deleteContent', () => {
  416. // If didn't press `Backspace`.
  417. if ( !hasBackspacePressed ) {
  418. return;
  419. }
  420. hasBackspacePressed = false;
  421. // Disable the mechanism if inside a link (`<$text url="foo">F[]oo</$text>` or <$text url="foo">Foo[]</$text>`).
  422. if ( shouldPreserveAttributes ) {
  423. return;
  424. }
  425. // Use `model.enqueueChange()` in order to execute the callback at the end of the changes process.
  426. editor.model.enqueueChange( writer => {
  427. removeLinkAttributesFromSelection( writer, linkCommand.manualDecorators );
  428. } );
  429. }, { priority: 'low' } );
  430. }
  431. }
  432. // Make the selection free of link-related model attributes.
  433. // All link-related model attributes start with "link". That includes not only "linkHref"
  434. // but also all decorator attributes (they have dynamic names).
  435. //
  436. // @param {module:engine/model/writer~Writer} writer
  437. // @param {module:utils/collection~Collection} manualDecorators
  438. function removeLinkAttributesFromSelection( writer, manualDecorators ) {
  439. writer.removeSelectionAttribute( 'linkHref' );
  440. for ( const decorator of manualDecorators ) {
  441. writer.removeSelectionAttribute( decorator.id );
  442. }
  443. }
  444. // Checks whether selection's attributes should be copied to the new inserted text.
  445. //
  446. // @param {module:engine/model/model~Model} model
  447. // @returns {Boolean}
  448. function shouldCopyAttributes( model ) {
  449. const selection = model.document.selection;
  450. const firstPosition = selection.getFirstPosition();
  451. const lastPosition = selection.getLastPosition();
  452. const nodeAtFirstPosition = firstPosition.nodeAfter;
  453. // The text link node does not exist...
  454. if ( !nodeAtFirstPosition ) {
  455. return false;
  456. }
  457. // ...or it isn't the text node...
  458. if ( !nodeAtFirstPosition.is( '$text' ) ) {
  459. return false;
  460. }
  461. // ...or isn't the link.
  462. if ( !nodeAtFirstPosition.hasAttribute( 'linkHref' ) ) {
  463. return false;
  464. }
  465. // `textNode` = the position is inside the link element.
  466. // `nodeBefore` = the position is at the end of the link element.
  467. const nodeAtLastPosition = lastPosition.textNode || lastPosition.nodeBefore;
  468. // If both references the same node selection contains a single text node.
  469. if ( nodeAtFirstPosition === nodeAtLastPosition ) {
  470. return true;
  471. }
  472. // If nodes are not equal, maybe the link nodes has defined additional attributes inside.
  473. // First, we need to find the entire link range.
  474. const linkRange = findAttributeRange( firstPosition, 'linkHref', nodeAtFirstPosition.getAttribute( 'linkHref' ), model );
  475. // Then we can check whether selected range is inside the found link range. If so, attributes should be preserved.
  476. return linkRange.containsRange( model.createRange( firstPosition, lastPosition ), true );
  477. }
  478. // Checks whether provided changes were caused by typing.
  479. //
  480. // @params {module:core/editor/editor~Editor} editor
  481. // @returns {Boolean}
  482. function isTyping( editor ) {
  483. const input = editor.plugins.get( 'Input' );
  484. return input.isInput( editor.model.change( writer => writer.batch ) );
  485. }