unlinkcommand.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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, 'changesDone', () => {
  24. this.refreshState();
  25. } );
  26. }
  27. /**
  28. * Executes the command.
  29. *
  30. * When the selection is collapsed, removes `linkHref` attribute from each node with the same `linkHref` attribute value.
  31. * When the selection is non-collapsed, removes `linkHref` from each node in selected ranges.
  32. *
  33. * @protected
  34. */
  35. _doExecute() {
  36. const document = this.editor.document;
  37. const selection = document.selection;
  38. document.enqueueChanges( () => {
  39. // Get ranges to unlink.
  40. const rangesToUnlink = selection.isCollapsed ?
  41. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ) ) ] : selection.getRanges();
  42. // Keep it as one undo step.
  43. const batch = document.batch();
  44. // Remove `linkHref` attribute from specified ranges.
  45. for ( let range of rangesToUnlink ) {
  46. batch.removeAttribute( range, 'linkHref' );
  47. }
  48. } );
  49. }
  50. /**
  51. * Checks if selection has `linkHref` attribute.
  52. *
  53. * @protected
  54. * @returns {Boolean}
  55. */
  56. _checkEnabled() {
  57. return this.editor.document.selection.hasAttribute( 'linkHref' );
  58. }
  59. }