8
0

unlinkcommand.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/unlinkcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import findLinkRange from './findlinkrange';
  10. /**
  11. * The unlink command. It is used by the {@link module:link/link~Link link plugin}.
  12. *
  13. * @extends module:core/command~Command
  14. */
  15. export default class UnlinkCommand extends Command {
  16. /**
  17. * @inheritDoc
  18. */
  19. refresh() {
  20. this.isEnabled = this.editor.model.document.selection.hasAttribute( 'linkHref' );
  21. }
  22. /**
  23. * Executes the command.
  24. *
  25. * When the selection is collapsed, it removes the `linkHref` attribute from each node with the same `linkHref` attribute value.
  26. * When the selection is non-collapsed, it removes the `linkHref` attribute from each node in selected ranges.
  27. *
  28. * # Decorators
  29. *
  30. * If {@link module:link/link~LinkConfig#decorators `config.link.decorators`} is specified,
  31. * all configured decorators are removed together with the `linkHref` attribute.
  32. *
  33. * @fires execute
  34. */
  35. execute() {
  36. const editor = this.editor;
  37. const model = this.editor.model;
  38. const selection = model.document.selection;
  39. const linkCommand = editor.commands.get( 'link' );
  40. model.change( writer => {
  41. // Get ranges to unlink.
  42. const rangesToUnlink = selection.isCollapsed ?
  43. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ), model ) ] : selection.getRanges();
  44. // Remove `linkHref` attribute from specified ranges.
  45. for ( const range of rangesToUnlink ) {
  46. writer.removeAttribute( 'linkHref', range );
  47. // If there are registered custom attributes, then remove them during unlink.
  48. if ( linkCommand ) {
  49. for ( const manualDecorator of linkCommand.manualDecorators ) {
  50. writer.removeAttribute( manualDecorator.id, range );
  51. }
  52. }
  53. }
  54. } );
  55. }
  56. }