unlinkcommand.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module link/unlinkcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command/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~Command
  14. */
  15. export default class UnlinkCommand extends Command {
  16. /**
  17. * @see module:core/command/command~Command
  18. * @param {module:core/editor/editor~Editor} editor
  19. */
  20. constructor( editor ) {
  21. super( editor );
  22. // Checks when command should be enabled or disabled.
  23. this.listenTo( editor.document.selection, 'change:attribute', () => this.refreshState() );
  24. }
  25. /**
  26. * Executes the command.
  27. *
  28. * When the selection is collapsed, removes `linkHref` attribute from each node with the same `linkHref` attribute value.
  29. * When the selection is non-collapsed, removes `linkHref` from each node in selected ranges.
  30. *
  31. * @protected
  32. */
  33. _doExecute() {
  34. const document = this.editor.document;
  35. const selection = document.selection;
  36. document.enqueueChanges( () => {
  37. // Get ranges to unlink.
  38. const rangesToUnlink = selection.isCollapsed ?
  39. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ) ) ] : selection.getRanges();
  40. // Keep it as one undo step.
  41. const batch = document.batch();
  42. // Remove `linkHref` attribute from specified ranges.
  43. for ( let range of rangesToUnlink ) {
  44. batch.removeAttribute( range, 'linkHref' );
  45. }
  46. } );
  47. }
  48. /**
  49. * Checks if selection has `linkHref` attribute.
  50. *
  51. * @protected
  52. * @returns {Boolean}
  53. */
  54. _checkEnabled() {
  55. return this.editor.document.selection.hasAttribute( 'linkHref' );
  56. }
  57. }