8
0

unlinkcommand.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 first from '@ckeditor/ckeditor5-utils/src/first';
  10. import findLinkRange from './findlinkrange';
  11. import { isImageAllowed } from './utils';
  12. /**
  13. * The unlink command. It is used by the {@link module:link/link~Link link plugin}.
  14. *
  15. * @extends module:core/command~Command
  16. */
  17. export default class UnlinkCommand extends Command {
  18. /**
  19. * @inheritDoc
  20. */
  21. refresh() {
  22. const model = this.editor.model;
  23. const doc = model.document;
  24. const selectedElement = first( doc.selection.getSelectedBlocks() );
  25. // A check for the `LinkImage` plugin. If the selection contains an image element, get values from the element.
  26. // Currently the selection reads attributes from text nodes only. See #7429 and #7465.
  27. if ( isImageAllowed( selectedElement, model.schema ) ) {
  28. this.isEnabled = model.schema.checkAttribute( selectedElement, 'linkHref' );
  29. } else {
  30. this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, 'linkHref' );
  31. }
  32. }
  33. /**
  34. * Executes the command.
  35. *
  36. * When the selection is collapsed, it removes the `linkHref` attribute from each node with the same `linkHref` attribute value.
  37. * When the selection is non-collapsed, it removes the `linkHref` attribute from each node in selected ranges.
  38. *
  39. * # Decorators
  40. *
  41. * If {@link module:link/link~LinkConfig#decorators `config.link.decorators`} is specified,
  42. * all configured decorators are removed together with the `linkHref` attribute.
  43. *
  44. * @fires execute
  45. */
  46. execute() {
  47. const editor = this.editor;
  48. const model = this.editor.model;
  49. const selection = model.document.selection;
  50. const linkCommand = editor.commands.get( 'link' );
  51. model.change( writer => {
  52. // Get ranges to unlink.
  53. const rangesToUnlink = selection.isCollapsed ?
  54. [ findLinkRange( selection.getFirstPosition(), selection.getAttribute( 'linkHref' ), model ) ] : selection.getRanges();
  55. // Remove `linkHref` attribute from specified ranges.
  56. for ( const range of rangesToUnlink ) {
  57. writer.removeAttribute( 'linkHref', range );
  58. // If there are registered custom attributes, then remove them during unlink.
  59. if ( linkCommand ) {
  60. for ( const manualDecorator of linkCommand.manualDecorators ) {
  61. writer.removeAttribute( manualDecorator.id, range );
  62. }
  63. }
  64. }
  65. } );
  66. }
  67. }