unlinkcommand.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Command from '../core/command/command.js';
  6. import findLinkRange from './findlinkrange.js';
  7. /**
  8. * The unlink command. It is used by the {@link Link.Link link feature}.
  9. *
  10. * @memberOf link
  11. * @extends core.command.Command
  12. */
  13. export default class UnlinkCommand extends Command {
  14. /**
  15. * @see core.command.Command
  16. * @param {core.editor.Editor} editor
  17. */
  18. constructor( editor ) {
  19. super( editor );
  20. /**
  21. * Flag indicating whether command is active. For collapsed selection it means that typed characters will have
  22. * the command's attribute set. For range selection it means that all nodes inside have the attribute applied.
  23. *
  24. * @observable
  25. * @member {Boolean} core.command.ToggleAttributeCommand#hasValue
  26. */
  27. this.set( 'hasValue', undefined );
  28. this.listenTo( this.editor.document.selection, 'change:attribute', () => {
  29. this.hasValue = this.editor.document.selection.hasAttribute( 'linkHref' );
  30. } );
  31. }
  32. /**
  33. * Executes the command.
  34. *
  35. * When selection is collapsed then remove `linkHref` attribute from each stick node with the same `linkHref` attribute value.
  36. *
  37. * When selection is non-collapsed then remove `linkHref` from each node in selected ranges.
  38. *
  39. * @protected
  40. */
  41. _doExecute() {
  42. const document = this.editor.document;
  43. const selection = document.selection;
  44. document.enqueueChanges( () => {
  45. // Get ranges to unlink.
  46. const rangesToUnlink = selection.isCollapsed ?
  47. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ) ) ] : selection.getRanges();
  48. // Keep it as one undo step.
  49. const batch = document.batch();
  50. // Remove `linkHref` attribute from specified ranges.
  51. for ( let range of rangesToUnlink ) {
  52. batch.removeAttribute( range, 'linkHref' );
  53. }
  54. } );
  55. }
  56. }