8
0

fontcommand.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 font/fontcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * The base font command.
  11. *
  12. * @extends module:core/command~Command
  13. */
  14. export default class FontCommand extends Command {
  15. /**
  16. * Creates an instance of the command.
  17. *
  18. * @param {module:core/editor/editor~Editor} editor Editor instance.
  19. * @param {String} attributeKey The name of a model attribute on which this command operates.
  20. */
  21. constructor( editor, attributeKey ) {
  22. super( editor );
  23. /**
  24. * When set, it reflects the {@link #attributeKey} value of the selection.
  25. *
  26. * @observable
  27. * @readonly
  28. * @member {String} module:font/fontcommand~FontCommand#value
  29. */
  30. /**
  31. * A model attribute on which this command operates.
  32. *
  33. * @readonly
  34. * @member {Boolean} module:font/fontcommand~FontCommand#attributeKey
  35. */
  36. this.attributeKey = attributeKey;
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. refresh() {
  42. const model = this.editor.model;
  43. const doc = model.document;
  44. this.value = doc.selection.getAttribute( this.attributeKey );
  45. this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, this.attributeKey );
  46. }
  47. /**
  48. * Executes the command. Applies the `value` of the {@link #attributeKey} to the selection.
  49. * If no `value` is passed, it removes the attribute from the selection.
  50. *
  51. * @protected
  52. * @param {Object} [options] Options for the executed command.
  53. * @param {String} [options.value] The value to apply.
  54. * @fires execute
  55. */
  56. execute( options = {} ) {
  57. const model = this.editor.model;
  58. const document = model.document;
  59. const selection = document.selection;
  60. const value = options.value;
  61. model.change( writer => {
  62. if ( selection.isCollapsed ) {
  63. if ( value ) {
  64. writer.setSelectionAttribute( this.attributeKey, value );
  65. } else {
  66. writer.removeSelectionAttribute( this.attributeKey );
  67. }
  68. } else {
  69. const ranges = model.schema.getValidRanges( selection.getRanges(), this.attributeKey );
  70. for ( const range of ranges ) {
  71. if ( value ) {
  72. writer.setAttribute( this.attributeKey, value, range );
  73. } else {
  74. writer.removeAttribute( this.attributeKey, range );
  75. }
  76. }
  77. }
  78. } );
  79. }
  80. }