removeformatcommand.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module removeformat/removeformat
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import DocumentSelection from '@ckeditor/ckeditor5-engine/src/model/documentselection';
  10. const removedAttributes = [
  11. 'bold',
  12. 'italic',
  13. 'underline',
  14. 'highlight'
  15. ];
  16. /**
  17. * The removeformat command. It is used by the {@link module:removeformat/removeformatediting~HighlightEditing removeformat feature}
  18. * to apply the text removeformating.
  19. *
  20. * editor.execute( 'removeformat', { value: 'greenMarker' } );
  21. *
  22. * **Note**: Executing the command without a value removes the attribute from the model. If the selection is collapsed
  23. * inside a text with the removeformat attribute, the command will remove the attribute from the entire range
  24. * of that text.
  25. *
  26. * @extends module:core/command~Command
  27. */
  28. export default class RemoveFormatCommand extends Command {
  29. /**
  30. * @inheritDoc
  31. */
  32. refresh() {
  33. const selection = this.editor.model.document.selection;
  34. this.isEnabled = !this._getStylableElements( selection ).next().done;
  35. }
  36. /**
  37. * @inheritdoc
  38. */
  39. execute() {
  40. const model = this.editor.model;
  41. model.change( writer => {
  42. for ( const item of this._getStylableElements( model.document.selection ) ) {
  43. for ( const attributeName of removedAttributes ) {
  44. if ( item instanceof DocumentSelection ) {
  45. writer.removeSelectionAttribute( attributeName );
  46. } else {
  47. writer.removeAttribute( attributeName, item );
  48. }
  49. }
  50. }
  51. } );
  52. }
  53. /**
  54. * Executes the command.
  55. *
  56. * @protected
  57. * @fires execute
  58. */
  59. * _getStylableElements( selection ) {
  60. for ( const curRange of selection.getRanges() ) {
  61. for ( const item of curRange.getItems() ) {
  62. if ( itemHasRemovableFormatting( item ) ) {
  63. yield item;
  64. }
  65. }
  66. }
  67. // Finally the selection might be styles as well, so make sure to check it.
  68. if ( itemHasRemovableFormatting( selection ) ) {
  69. yield selection;
  70. }
  71. function itemHasRemovableFormatting( item ) {
  72. for ( const attributeName of removedAttributes ) {
  73. if ( item.hasAttribute( attributeName ) ) {
  74. return true;
  75. }
  76. }
  77. }
  78. }
  79. }