linkediting.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 bindTwoStepCaretToAttribute from '@ckeditor/ckeditor5-engine/src/utils/bindtwostepcarettoattribute';
  11. import LinkCommand from './linkcommand';
  12. import UnlinkCommand from './unlinkcommand';
  13. import AutomaticDecorators from './utils/automaticdecorators';
  14. import ManualDecorator from './utils/manualdecorator';
  15. import findLinkRange from './findlinkrange';
  16. import { createLinkElement, ensureSafeUrl, getLocalizedDecorators, normalizeDecorators } from './utils';
  17. import '../theme/link.css';
  18. const HIGHLIGHT_CLASS = 'ck-link_selected';
  19. const DECORATOR_AUTOMATIC = 'automatic';
  20. const DECORATOR_MANUAL = 'manual';
  21. const EXTERNAL_LINKS_REGEXP = /^(https?:)?\/\//;
  22. /**
  23. * The link engine feature.
  24. *
  25. * It introduces the `linkHref="url"` attribute in the model which renders to the view as a `<a href="url">` element
  26. * as well as `'link'` and `'unlink'` commands.
  27. *
  28. * @extends module:core/plugin~Plugin
  29. */
  30. export default class LinkEditing extends Plugin {
  31. /**
  32. * @inheritDoc
  33. */
  34. static get pluginName() {
  35. return 'LinkEditing';
  36. }
  37. /**
  38. * @inheritDoc
  39. */
  40. constructor( editor ) {
  41. super( editor );
  42. editor.config.define( 'link', {
  43. addTargetToExternalLinks: false
  44. } );
  45. }
  46. /**
  47. * @inheritDoc
  48. */
  49. init() {
  50. const editor = this.editor;
  51. const locale = editor.locale;
  52. // Allow link attribute on all inline nodes.
  53. editor.model.schema.extend( '$text', { allowAttributes: 'linkHref' } );
  54. editor.conversion.for( 'dataDowncast' )
  55. .attributeToElement( { model: 'linkHref', view: createLinkElement } );
  56. editor.conversion.for( 'editingDowncast' )
  57. .attributeToElement( { model: 'linkHref', view: ( href, writer ) => {
  58. return createLinkElement( ensureSafeUrl( href ), writer );
  59. } } );
  60. editor.conversion.for( 'upcast' )
  61. .elementToAttribute( {
  62. view: {
  63. name: 'a',
  64. attributes: {
  65. href: true
  66. }
  67. },
  68. model: {
  69. key: 'linkHref',
  70. value: viewElement => viewElement.getAttribute( 'href' )
  71. }
  72. } );
  73. // Create linking commands.
  74. editor.commands.add( 'link', new LinkCommand( editor ) );
  75. editor.commands.add( 'unlink', new UnlinkCommand( editor ) );
  76. const linkDecorators = getLocalizedDecorators( editor.t, normalizeDecorators( editor.config.get( 'link.decorators' ) ) );
  77. this._enableAutomaticDecorators( linkDecorators.filter( item => item.mode === DECORATOR_AUTOMATIC ) );
  78. this._enableManualDecorators( linkDecorators.filter( item => item.mode === DECORATOR_MANUAL ) );
  79. // Enable two-step caret movement for `linkHref` attribute.
  80. bindTwoStepCaretToAttribute( {
  81. view: editor.editing.view,
  82. model: editor.model,
  83. emitter: this,
  84. attribute: 'linkHref',
  85. locale
  86. } );
  87. // Setup highlight over selected link.
  88. this._setupLinkHighlight();
  89. // Change the attributes of the selection in certain situations after the link was inserted into the document.
  90. this._enableInsertContentSelectionAttributesFixer();
  91. // Handle a click at the beginning/end of a link element.
  92. this._enableClickingAfterLink();
  93. }
  94. /**
  95. * Processes an array of configured {@link module:link/link~LinkDecoratorAutomaticDefinition automatic decorators}
  96. * and registers a {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher downcast dispatcher}
  97. * for each one of them. Downcast dispatchers are obtained using the
  98. * {@link module:link/utils~AutomaticDecorators#getDispatcher} method.
  99. *
  100. * **Note**: This method also activates the automatic external link decorator if enabled with
  101. * {@link module:link/link~LinkConfig#addTargetToExternalLinks `config.link.addTargetToExternalLinks`}.
  102. *
  103. * @private
  104. * @param {Array.<module:link/link~LinkDecoratorAutomaticDefinition>} automaticDecoratorDefinitions
  105. */
  106. _enableAutomaticDecorators( automaticDecoratorDefinitions ) {
  107. const editor = this.editor;
  108. const automaticDecorators = new AutomaticDecorators();
  109. // Adds a default decorator for external links.
  110. if ( editor.config.get( 'link.addTargetToExternalLinks' ) ) {
  111. automaticDecorators.add( {
  112. id: 'linkIsExternal',
  113. mode: DECORATOR_AUTOMATIC,
  114. callback: url => EXTERNAL_LINKS_REGEXP.test( url ),
  115. attributes: {
  116. target: '_blank',
  117. rel: 'noopener noreferrer'
  118. }
  119. } );
  120. }
  121. automaticDecorators.add( automaticDecoratorDefinitions );
  122. if ( automaticDecorators.length ) {
  123. editor.conversion.for( 'downcast' ).add( automaticDecorators.getDispatcher() );
  124. }
  125. }
  126. /**
  127. * Processes an array of configured {@link module:link/link~LinkDecoratorManualDefinition manual decorators},
  128. * transforms them into {@link module:link/utils~ManualDecorator} instances and stores them in the
  129. * {@link module:link/linkcommand~LinkCommand#manualDecorators} collection (a model for manual decorators state).
  130. *
  131. * Also registers an {@link module:engine/conversion/downcasthelpers~DowncastHelpers#attributeToElement attribute-to-element}
  132. * converter for each manual decorator and extends the {@link module:engine/model/schema~Schema model's schema}
  133. * with adequate model attributes.
  134. *
  135. * @private
  136. * @param {Array.<module:link/link~LinkDecoratorManualDefinition>} manualDecoratorDefinitions
  137. */
  138. _enableManualDecorators( manualDecoratorDefinitions ) {
  139. if ( !manualDecoratorDefinitions.length ) {
  140. return;
  141. }
  142. const editor = this.editor;
  143. const command = editor.commands.get( 'link' );
  144. const manualDecorators = command.manualDecorators;
  145. manualDecoratorDefinitions.forEach( decorator => {
  146. editor.model.schema.extend( '$text', { allowAttributes: decorator.id } );
  147. // Keeps reference to manual decorator to decode its name to attributes during downcast.
  148. manualDecorators.add( new ManualDecorator( decorator ) );
  149. editor.conversion.for( 'downcast' ).attributeToElement( {
  150. model: decorator.id,
  151. view: ( manualDecoratorName, writer ) => {
  152. if ( manualDecoratorName ) {
  153. const attributes = manualDecorators.get( decorator.id ).attributes;
  154. const element = writer.createAttributeElement( 'a', attributes, { priority: 5 } );
  155. writer.setCustomProperty( 'link', true, element );
  156. return element;
  157. }
  158. } } );
  159. editor.conversion.for( 'upcast' ).elementToAttribute( {
  160. view: {
  161. name: 'a',
  162. attributes: manualDecorators.get( decorator.id ).attributes
  163. },
  164. model: {
  165. key: decorator.id
  166. }
  167. } );
  168. } );
  169. }
  170. /**
  171. * Adds a visual highlight style to a link in which the selection is anchored.
  172. * Together with two-step caret movement, they indicate that the user is typing inside the link.
  173. *
  174. * Highlight is turned on by adding the `.ck-link_selected` class to the link in the view:
  175. *
  176. * * The class is removed before the conversion has started, as callbacks added with the `'highest'` priority
  177. * to {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher} events.
  178. * * The class is added in the view post fixer, after other changes in the model tree were converted to the view.
  179. *
  180. * This way, adding and removing the highlight does not interfere with conversion.
  181. *
  182. * @private
  183. */
  184. _setupLinkHighlight() {
  185. const editor = this.editor;
  186. const view = editor.editing.view;
  187. const highlightedLinks = new Set();
  188. // Adding the class.
  189. view.document.registerPostFixer( writer => {
  190. const selection = editor.model.document.selection;
  191. let changed = false;
  192. if ( selection.hasAttribute( 'linkHref' ) ) {
  193. const modelRange = findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ), editor.model );
  194. const viewRange = editor.editing.mapper.toViewRange( modelRange );
  195. // There might be multiple `a` elements in the `viewRange`, for example, when the `a` element is
  196. // broken by a UIElement.
  197. for ( const item of viewRange.getItems() ) {
  198. if ( item.is( 'a' ) && !item.hasClass( HIGHLIGHT_CLASS ) ) {
  199. writer.addClass( HIGHLIGHT_CLASS, item );
  200. highlightedLinks.add( item );
  201. changed = true;
  202. }
  203. }
  204. }
  205. return changed;
  206. } );
  207. // Removing the class.
  208. editor.conversion.for( 'editingDowncast' ).add( dispatcher => {
  209. // Make sure the highlight is removed on every possible event, before conversion is started.
  210. dispatcher.on( 'insert', removeHighlight, { priority: 'highest' } );
  211. dispatcher.on( 'remove', removeHighlight, { priority: 'highest' } );
  212. dispatcher.on( 'attribute', removeHighlight, { priority: 'highest' } );
  213. dispatcher.on( 'selection', removeHighlight, { priority: 'highest' } );
  214. function removeHighlight() {
  215. view.change( writer => {
  216. for ( const item of highlightedLinks.values() ) {
  217. writer.removeClass( HIGHLIGHT_CLASS, item );
  218. highlightedLinks.delete( item );
  219. }
  220. } );
  221. }
  222. } );
  223. }
  224. /**
  225. * Starts listening to {@link module:engine/model/model~Model#event:insertContent} and corrects the model
  226. * selection attributes if the selection is at the end of a link after inserting the content.
  227. *
  228. * The purpose of this action is to improve the overall UX because the user is no longer "trapped" by the
  229. * `linkHref` attribute of the selection and they can type a "clean" (`linkHref`–less) text right away.
  230. *
  231. * See https://github.com/ckeditor/ckeditor5/issues/6053.
  232. *
  233. * @private
  234. */
  235. _enableInsertContentSelectionAttributesFixer() {
  236. const editor = this.editor;
  237. const model = editor.model;
  238. const selection = model.document.selection;
  239. model.on( 'insertContent', () => {
  240. const nodeBefore = selection.anchor.nodeBefore;
  241. const nodeAfter = selection.anchor.nodeAfter;
  242. // NOTE: ↰ and ↱ represent the gravity of the selection.
  243. // The only truly valid case is:
  244. //
  245. // ↰
  246. // ...<$text linkHref="foo">INSERTED[]</$text>
  247. //
  248. // If the selection is not "trapped" by the `linkHref` attribute after inserting, there's nothing
  249. // to fix there.
  250. if ( !selection.hasAttribute( 'linkHref' ) ) {
  251. return;
  252. }
  253. // Filter out the following case where a link with the same href (e.g. <a href="foo">INSERTED</a>) is inserted
  254. // in the middle of an existing link:
  255. //
  256. // Before insertion:
  257. // ↰
  258. // <$text linkHref="foo">l[]ink</$text>
  259. //
  260. // Expected after insertion:
  261. // ↰
  262. // <$text linkHref="foo">lINSERTED[]ink</$text>
  263. //
  264. if ( !nodeBefore ) {
  265. return;
  266. }
  267. // Filter out the following case where the selection has the "linkHref" attribute because the
  268. // gravity is overridden and some text with another attribute (e.g. <b>INSERTED</b>) is inserted:
  269. //
  270. // Before insertion:
  271. //
  272. // ↱
  273. // <$text linkHref="foo">[]link</$text>
  274. //
  275. // Expected after insertion:
  276. //
  277. // ↱
  278. // <$text bold="true">INSERTED</$text><$text linkHref="foo">[]link</$text>
  279. //
  280. if ( !nodeBefore.hasAttribute( 'linkHref' ) ) {
  281. return;
  282. }
  283. // Filter out the following case where a link is a inserted in the middle (or before) another link
  284. // (different URLs, so they will not merge). In this (let's say weird) case, we can leave the selection
  285. // attributes as they are because the user will end up writing in one link or another anyway.
  286. //
  287. // Before insertion:
  288. //
  289. // ↰
  290. // <$text linkHref="foo">l[]ink</$text>
  291. //
  292. // Expected after insertion:
  293. //
  294. // ↰
  295. // <$text linkHref="foo">l</$text><$text linkHref="bar">INSERTED[]</$text><$text linkHref="foo">ink</$text>
  296. //
  297. if ( nodeAfter && nodeAfter.hasAttribute( 'linkHref' ) ) {
  298. return;
  299. }
  300. // Make the selection free of link-related model attributes.
  301. // All link-related model attributes start with "link". That includes not only "linkHref"
  302. // but also all decorator attributes (they have dynamic names).
  303. model.change( writer => {
  304. [ ...model.document.selection.getAttributeKeys() ]
  305. .filter( name => name.startsWith( 'link' ) )
  306. .forEach( name => writer.removeSelectionAttribute( name ) );
  307. } );
  308. }, { priority: 'low' } );
  309. }
  310. /**
  311. * Starts listening to {@link module:engine/view/document~Document#event:mousedown} and
  312. * {@link module:engine/view/document~Document#event:selectionChange} and puts the selection before/after a link node
  313. * if clicked at the beginning/ending of the link.
  314. *
  315. * The purpose of this action is to allow typing around the link node directly after a click.
  316. *
  317. * See https://github.com/ckeditor/ckeditor5/issues/1016.
  318. *
  319. * @private
  320. */
  321. _enableClickingAfterLink() {
  322. const editor = this.editor;
  323. editor.editing.view.addObserver( MouseObserver );
  324. let clicked = false;
  325. // Detect the click.
  326. this.listenTo( editor.editing.view.document, 'mousedown', () => {
  327. clicked = true;
  328. } );
  329. // When the selection has changed...
  330. this.listenTo( editor.editing.view.document, 'selectionChange', () => {
  331. if ( !clicked ) {
  332. return;
  333. }
  334. // ...and it was caused by the click...
  335. clicked = false;
  336. const selection = editor.model.document.selection;
  337. // ...and no text is selected...
  338. if ( !selection.isCollapsed ) {
  339. return;
  340. }
  341. // ...and clicked text is the link...
  342. if ( !selection.hasAttribute( 'linkHref' ) ) {
  343. return;
  344. }
  345. const position = selection.getFirstPosition();
  346. const linkRange = findLinkRange( position, selection.getAttribute( 'linkHref' ), editor.model );
  347. // ...check whether clicked start/end boundary of the link.
  348. // If so, remove the `linkHref` attribute.
  349. if ( position.isTouching( linkRange.start ) || position.isTouching( linkRange.end ) ) {
  350. editor.model.change( writer => {
  351. writer.removeSelectionAttribute( 'linkHref' );
  352. for ( const manualDecorator of editor.commands.get( 'link' ).manualDecorators ) {
  353. writer.removeSelectionAttribute( manualDecorator.id );
  354. }
  355. } );
  356. }
  357. } );
  358. }
  359. }