8
0

commandcollection.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  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. */
  48. execute( commandName, ...args ) {
  49. const command = this.get( commandName );
  50. if ( !command ) {
  51. /**
  52. * Command does not exist.
  53. *
  54. * @error commandcollection-command-not-found
  55. * @param {String} commandName Name of the command.
  56. */
  57. throw new CKEditorError( 'commandcollection-command-not-found: Command does not exist.', { commandName } );
  58. }
  59. command.execute( ...args );
  60. }
  61. /**
  62. * Returns iterator of command names.
  63. *
  64. * @returns {Iterator.<String>}
  65. */
  66. * names() {
  67. yield* this._commands.keys();
  68. }
  69. /**
  70. * Returns iterator of command instances.
  71. *
  72. * @returns {Iterator.<module:core/command~Command>}
  73. */
  74. * commands() {
  75. yield* this._commands.values();
  76. }
  77. /**
  78. * Collection iterator.
  79. */
  80. [ Symbol.iterator ]() {
  81. return this._commands[ Symbol.iterator ]();
  82. }
  83. /**
  84. * Destroys all collection commands.
  85. */
  86. destroy() {
  87. for ( const command of this.commands() ) {
  88. command.destroy();
  89. }
  90. }
  91. }