8
0

linkediting.js 12 KB

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