componentfactory.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import CKEditorError from '../utils/ckeditorerror.js';
  6. /**
  7. * Class implementing the UI component factory.
  8. *
  9. * Factories of specific UI components can be registered under their unique names. Registered
  10. * components can be later instantiated by providing the name of the component. The model is shared between all
  11. * instances of that component and has to be provided upon registering its factory.
  12. *
  13. * The main use case for the component factory is the {@link ui.editorUI.EditorUI#featureComponents} factory.
  14. *
  15. * @memberOf ui
  16. */
  17. export default class ComponentFactory {
  18. /**
  19. * Creates ComponentFactory instance.
  20. *
  21. * @constructor
  22. * @param {ckeditor5.Editor} editor The editor instance.
  23. */
  24. constructor( editor ) {
  25. /**
  26. * @readonly
  27. * @member {ckeditor5.Editor} ui.ComponentFactory#editor
  28. */
  29. this.editor = editor;
  30. /**
  31. * Registered component factories.
  32. *
  33. * @private
  34. * @member {Map} ui.ComponentFactory#_components
  35. */
  36. this._components = new Map();
  37. }
  38. /**
  39. * Registers a component factory.
  40. *
  41. * @param {String} name The name of the component.
  42. * @param {Function} ControllerClass The component controller constructor.
  43. * @param {Function} ViewClass The component view constructor.
  44. * @param {ui.Model} model The model of the component.
  45. */
  46. add( name, ControllerClass, ViewClass, model ) {
  47. if ( this._components.get( name ) ) {
  48. throw new CKEditorError(
  49. 'componentfactory-item-exists: The item already exists in the component factory.', { name }
  50. );
  51. }
  52. this._components.set( name, {
  53. ControllerClass,
  54. ViewClass,
  55. model
  56. } );
  57. }
  58. /**
  59. * Creates a component instance.
  60. *
  61. * @param {String} name The name of the component.
  62. * @returns {ui.Controller} The instantiated component.
  63. */
  64. create( name ) {
  65. const component = this._components.get( name );
  66. const model = component.model;
  67. const view = new component.ViewClass( model, this.editor.locale );
  68. const controller = new component.ControllerClass( model, view, this.editor );
  69. return controller;
  70. }
  71. }