unlinkcommand.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license Copyright (c) 2003-2019, 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, removes the `linkHref` attribute from each node with the same `linkHref` attribute value.
  26. * When the selection is non-collapsed, removes the `linkHref` attribute from each node in selected ranges.
  27. *
  28. * @fires execute
  29. */
  30. execute() {
  31. const editor = this.editor;
  32. const model = this.editor.model;
  33. const selection = model.document.selection;
  34. const linkCommand = editor.commands.get( 'link' );
  35. model.change( writer => {
  36. // Get ranges to unlink.
  37. const rangesToUnlink = selection.isCollapsed ?
  38. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ), model ) ] : selection.getRanges();
  39. // Remove `linkHref` attribute from specified ranges.
  40. for ( const range of rangesToUnlink ) {
  41. writer.removeAttribute( 'linkHref', range );
  42. // If there are registered custom attributes, then remove them during unlink.
  43. if ( linkCommand ) {
  44. linkCommand.customAttributes.forEach( ( val, key ) => {
  45. writer.removeAttribute( key, range );
  46. } );
  47. }
  48. }
  49. } );
  50. }
  51. }