8
0

commandcollection.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module core/commandcollection
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. /**
  10. * Collection of commands. Its instance is available in {@link module:core/editor/editor~Editor#commands `editor.commands`}.
  11. */
  12. export default class CommandCollection {
  13. /**
  14. * Creates collection instance.
  15. */
  16. constructor() {
  17. /**
  18. * Command map.
  19. *
  20. * @private
  21. * @member {Map}
  22. */
  23. this._commands = new Map();
  24. }
  25. /**
  26. * Registers a new command.
  27. *
  28. * @param {String} commandName The name of the command.
  29. * @param {module:core/command~Command} command
  30. */
  31. add( commandName, command ) {
  32. this._commands.set( commandName, command );
  33. }
  34. /**
  35. * Retrieves a command from the collection.
  36. *
  37. * @param {String} commandName The name of the command.
  38. * @returns {module:core/command~Command}
  39. */
  40. get( commandName ) {
  41. return this._commands.get( commandName );
  42. }
  43. /**
  44. * Executes a command.
  45. *
  46. * @param {String} commandName The name of the command.
  47. * @param {*} [...commandParams] Command parameters.
  48. */
  49. execute( commandName, ...args ) {
  50. const command = this.get( commandName );
  51. if ( !command ) {
  52. /**
  53. * Command does not exist.
  54. *
  55. * @error commandcollection-command-not-found
  56. * @param {String} commandName Name of the command.
  57. */
  58. throw new CKEditorError( 'commandcollection-command-not-found: Command does not exist.', this, { commandName } );
  59. }
  60. command.execute( ...args );
  61. }
  62. /**
  63. * Returns iterator of command names.
  64. *
  65. * @returns {Iterable.<String>}
  66. */
  67. * names() {
  68. yield* this._commands.keys();
  69. }
  70. /**
  71. * Returns iterator of command instances.
  72. *
  73. * @returns {Iterable.<module:core/command~Command>}
  74. */
  75. * commands() {
  76. yield* this._commands.values();
  77. }
  78. /**
  79. * Iterable interface.
  80. *
  81. * Returns `[ commandName, commandInstance ]` pairs.
  82. *
  83. * @returns {Iterable.<Array>}
  84. */
  85. [ Symbol.iterator ]() {
  86. return this._commands[ Symbol.iterator ]();
  87. }
  88. /**
  89. * Destroys all collection commands.
  90. */
  91. destroy() {
  92. for ( const command of this.commands() ) {
  93. command.destroy();
  94. }
  95. }
  96. }