plugincollection.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module core/plugincollection
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import log from '@ckeditor/ckeditor5-utils/src/log';
  10. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  11. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  12. /**
  13. * Manages a list of CKEditor plugins, including loading, resolving dependencies and initialization.
  14. *
  15. * @mixes module:utils/emittermixin~EmitterMixin
  16. */
  17. export default class PluginCollection {
  18. /**
  19. * Creates an instance of the PluginCollection class.
  20. * Allows loading and initializing plugins and their dependencies.
  21. *
  22. * @param {module:core/editor/editor~Editor} editor
  23. * @param {Array.<Function>} [availablePlugins] Plugins (constructors) which the collection will be able to use
  24. * when {@link module:core/plugincollection~PluginCollection#init} is used with plugin names (strings, instead of constructors).
  25. * Usually, the editor will pass its built-in plugins to the collection so they can later be
  26. * used in `config.plugins` or `config.removePlugins` by names.
  27. */
  28. constructor( editor, availablePlugins = [] ) {
  29. /**
  30. * @protected
  31. * @member {module:core/editor/editor~Editor} module:core/plugin~PluginCollection#_editor
  32. */
  33. this._editor = editor;
  34. /**
  35. * Map of plugin constructors which can be retrieved by their names.
  36. *
  37. * @protected
  38. * @member {Map.<String|Function,Function>} module:core/plugin~PluginCollection#_availablePlugins
  39. */
  40. this._availablePlugins = new Map();
  41. /**
  42. * @protected
  43. * @member {Map} module:core/plugin~PluginCollection#_plugins
  44. */
  45. this._plugins = new Map();
  46. for ( const PluginConstructor of availablePlugins ) {
  47. this._availablePlugins.set( PluginConstructor, PluginConstructor );
  48. if ( PluginConstructor.pluginName ) {
  49. this._availablePlugins.set( PluginConstructor.pluginName, PluginConstructor );
  50. }
  51. }
  52. }
  53. /**
  54. * Iterable interface.
  55. *
  56. * Returns `[ PluginConstructor, pluginInstance ]` pairs.
  57. *
  58. * @returns {Iterable.<Array>}
  59. */
  60. * [ Symbol.iterator ]() {
  61. for ( const entry of this._plugins ) {
  62. if ( typeof entry[ 0 ] == 'function' ) {
  63. yield entry;
  64. }
  65. }
  66. }
  67. /**
  68. * Gets the plugin instance by its constructor or name.
  69. *
  70. * // Check if 'Clipboard' plugin was loaded.
  71. * if ( editor.plugins.has( 'Clipboard' ) ) {
  72. * // Get clipboard plugin instance
  73. * const clipboard = editor.plugins.get( 'Clipboard' );
  74. *
  75. * this.listenTo( clipboard, 'inputTransformation', ( evt, data ) => {
  76. * // Do something on clipboard input.
  77. * } );
  78. * }
  79. *
  80. * **Note**: This method will throw error if plugin is not loaded. Use `{@link #has editor.plugins.has()}`
  81. * to check if plugin is available.
  82. *
  83. * @param {Function|String} key The plugin constructor or {@link module:core/plugin~PluginInterface.pluginName name}.
  84. * @returns {module:core/plugin~PluginInterface}
  85. */
  86. get( key ) {
  87. const plugin = this._plugins.get( key );
  88. if ( !plugin ) {
  89. /**
  90. * The plugin is not loaded and could not be obtained.
  91. *
  92. * Plugin classes (constructors) need to be provided to the editor and must be loaded before they can be obtained from
  93. * the plugin collection.
  94. * This is usually done in CKEditor 5 builds by setting the {@link module:core/editor/editor~Editor.builtinPlugins}
  95. * property.
  96. *
  97. * **Note**: You can use `{@link module:core/plugincollection~PluginCollection#has editor.plugins.has()}`
  98. * to check if plugin was loaded.
  99. *
  100. * @error plugincollection-plugin-not-loaded
  101. * @param {String} plugin The name of the plugin which is not loaded.
  102. */
  103. const errorMsg = 'plugincollection-plugin-not-loaded: The requested plugin is not loaded.';
  104. let pluginName = key;
  105. if ( typeof key == 'function' ) {
  106. pluginName = key.pluginName || key.name;
  107. }
  108. throw new CKEditorError( errorMsg, { plugin: pluginName } );
  109. }
  110. return plugin;
  111. }
  112. /**
  113. * Checks if plugin is loaded.
  114. *
  115. * // Check if 'Clipboard' plugin was loaded.
  116. * if ( editor.plugins.has( 'Clipboard' ) ) {
  117. * // Now use clipboard plugin instance:
  118. * const clipboard = editor.plugins.get( 'Clipboard' );
  119. *
  120. * // ...
  121. * }
  122. *
  123. * @param {Function|String} key The plugin constructor or {@link module:core/plugin~PluginInterface.pluginName name}.
  124. * @returns {Boolean}
  125. */
  126. has( key ) {
  127. return this._plugins.has( key );
  128. }
  129. /**
  130. * Initializes a set of plugins and adds them to the collection.
  131. *
  132. * @param {Array.<Function|String>} plugins An array of {@link module:core/plugin~PluginInterface plugin constructors}
  133. * or {@link module:core/plugin~PluginInterface.pluginName plugin names}. The second option (names) works only if
  134. * `availablePlugins` were passed to the {@link #constructor}.
  135. * @param {Array.<String|Function>} [removePlugins] Names of plugins or plugin constructors
  136. * that should not be loaded (despite being specified in the `plugins` array).
  137. * @returns {Promise.<module:core/plugin~LoadedPlugins>} A promise which gets resolved once all plugins are loaded
  138. * and available in the collection.
  139. */
  140. init( plugins, removePlugins = [] ) {
  141. const that = this;
  142. const editor = this._editor;
  143. const loading = new Set();
  144. const loaded = [];
  145. const pluginConstructors = mapToAvailableConstructors( plugins );
  146. const removePluginConstructors = mapToAvailableConstructors( removePlugins );
  147. const missingPlugins = getMissingPluginNames( plugins );
  148. if ( missingPlugins ) {
  149. /**
  150. * Some plugins are not available and could not be loaded.
  151. *
  152. * Plugin classes (constructors) need to be provided to the editor before they can be loaded by name.
  153. * This is usually done in CKEditor 5 builds by setting the {@link module:core/editor/editor~Editor.builtinPlugins}
  154. * property.
  155. *
  156. * **If you see this warning when using one of the {@glink builds/index CKEditor 5 Builds}**, it means
  157. * that you try to enable a plugin which was not included in that build. This may be due to a typo
  158. * in the plugin name or simply because that plugin is not a part of this build. In the latter scenario,
  159. * read more about {@glink builds/guides/development/custom-builds custom builds}.
  160. *
  161. * **If you see this warning when using one of the editor creators directly** (not a build), then it means
  162. * that you tried loading plugins by name. However, unlike CKEditor 4, CKEditor 5 does not implement a "plugin loader".
  163. * This means that CKEditor 5 does not know where to load the plugin modules from. Therefore, you need to
  164. * provide each plugin through reference (as a constructor function). Check out the examples in
  165. * {@glink builds/guides/integration/advanced-setup#scenario-2-building-from-source "Building from source"}.
  166. *
  167. * @error plugincollection-plugin-not-found
  168. * @param {Array.<String>} plugins The name of the plugins which could not be loaded.
  169. */
  170. const errorMsg = 'plugincollection-plugin-not-found: Some plugins are not available and could not be loaded.';
  171. // Log the error so it's more visible on the console. Hopefully, for better DX.
  172. log.error( errorMsg, { plugins: missingPlugins } );
  173. return Promise.reject( new CKEditorError( errorMsg, { plugins: missingPlugins } ) );
  174. }
  175. return Promise.all( pluginConstructors.map( loadPlugin ) )
  176. .then( () => initPlugins( loaded, 'init' ) )
  177. .then( () => initPlugins( loaded, 'afterInit' ) )
  178. .then( () => loaded );
  179. function loadPlugin( PluginConstructor ) {
  180. if ( removePluginConstructors.includes( PluginConstructor ) ) {
  181. return;
  182. }
  183. // The plugin is already loaded or being loaded - do nothing.
  184. if ( that._plugins.has( PluginConstructor ) || loading.has( PluginConstructor ) ) {
  185. return;
  186. }
  187. return instantiatePlugin( PluginConstructor )
  188. .catch( err => {
  189. /**
  190. * It was not possible to load the plugin.
  191. *
  192. * This is a generic error logged to the console when a JavaSript error is thrown during the initialization
  193. * of one of the plugins.
  194. *
  195. * If you correctly handled the promise returned by the editor's `create()` method (like shown below)
  196. * you will find the original error logged to the console, too:
  197. *
  198. * ClassicEditor.create( document.getElementById( 'editor' ) )
  199. * .then( editor => {
  200. * // ...
  201. * } )
  202. * .catch( error => {
  203. * console.error( error );
  204. * } );
  205. *
  206. * @error plugincollection-load
  207. * @param {String} plugin The name of the plugin that could not be loaded.
  208. */
  209. log.error( 'plugincollection-load: It was not possible to load the plugin.', { plugin: PluginConstructor } );
  210. throw err;
  211. } );
  212. }
  213. function initPlugins( loadedPlugins, method ) {
  214. return loadedPlugins.reduce( ( promise, plugin ) => {
  215. if ( !plugin[ method ] ) {
  216. return promise;
  217. }
  218. return promise.then( plugin[ method ].bind( plugin ) );
  219. }, Promise.resolve() );
  220. }
  221. function instantiatePlugin( PluginConstructor ) {
  222. return new Promise( resolve => {
  223. loading.add( PluginConstructor );
  224. if ( PluginConstructor.requires ) {
  225. PluginConstructor.requires.forEach( RequiredPluginConstructorOrName => {
  226. const RequiredPluginConstructor = getPluginConstructor( RequiredPluginConstructorOrName );
  227. if ( removePlugins.includes( RequiredPluginConstructor ) ) {
  228. /**
  229. * Cannot load a plugin because one of its dependencies is listed in the `removePlugins` option.
  230. *
  231. * @error plugincollection-required
  232. * @param {Function} plugin The required plugin.
  233. * @param {Function} requiredBy The parent plugin.
  234. */
  235. throw new CKEditorError(
  236. 'plugincollection-required: Cannot load a plugin because one of its dependencies is listed in' +
  237. 'the `removePlugins` option.',
  238. { plugin: RequiredPluginConstructor, requiredBy: PluginConstructor }
  239. );
  240. }
  241. loadPlugin( RequiredPluginConstructor );
  242. } );
  243. }
  244. const plugin = new PluginConstructor( editor );
  245. that._add( PluginConstructor, plugin );
  246. loaded.push( plugin );
  247. resolve();
  248. } );
  249. }
  250. function getPluginConstructor( PluginConstructorOrName ) {
  251. if ( typeof PluginConstructorOrName == 'function' ) {
  252. return PluginConstructorOrName;
  253. }
  254. return that._availablePlugins.get( PluginConstructorOrName );
  255. }
  256. function getMissingPluginNames( plugins ) {
  257. const missingPlugins = [];
  258. for ( const pluginNameOrConstructor of plugins ) {
  259. if ( !getPluginConstructor( pluginNameOrConstructor ) ) {
  260. missingPlugins.push( pluginNameOrConstructor );
  261. }
  262. }
  263. return missingPlugins.length ? missingPlugins : null;
  264. }
  265. function mapToAvailableConstructors( plugins ) {
  266. return plugins
  267. .map( pluginNameOrConstructor => getPluginConstructor( pluginNameOrConstructor ) )
  268. .filter( PluginConstructor => !!PluginConstructor );
  269. }
  270. }
  271. /**
  272. * Destroys all loaded plugins.
  273. *
  274. * @returns {Promise}
  275. */
  276. destroy() {
  277. const promises = Array.from( this )
  278. .map( ( [ , pluginInstance ] ) => pluginInstance )
  279. .filter( pluginInstance => typeof pluginInstance.destroy == 'function' )
  280. .map( pluginInstance => pluginInstance.destroy() );
  281. return Promise.all( promises );
  282. }
  283. /**
  284. * Adds the plugin to the collection. Exposed mainly for testing purposes.
  285. *
  286. * @protected
  287. * @param {Function} PluginConstructor The plugin constructor.
  288. * @param {module:core/plugin~PluginInterface} plugin The instance of the plugin.
  289. */
  290. _add( PluginConstructor, plugin ) {
  291. this._plugins.set( PluginConstructor, plugin );
  292. const pluginName = PluginConstructor.pluginName;
  293. if ( !pluginName ) {
  294. return;
  295. }
  296. if ( this._plugins.has( pluginName ) ) {
  297. /**
  298. * Two plugins with the same {@link module:core/plugin~PluginInterface.pluginName} were loaded.
  299. * This will lead to runtime conflicts between these plugins.
  300. *
  301. * In practice, this warning usually means that new plugins were added to an existing CKEditor 5 build.
  302. * Plugins should always be added to a source version of the editor (`@ckeditor/ckeditor5-editor-*`),
  303. * not to an editor imported from one of the `@ckeditor/ckeditor5-build-*` packages.
  304. *
  305. * Check your import paths and the list of plugins passed to
  306. * {@link module:core/editor/editor~Editor.create `Editor.create()`}
  307. * or specified in {@link module:core/editor/editor~Editor.builtinPlugins `Editor.builtinPlugins`}.
  308. *
  309. * The second option is that your `node_modules/` directory contains duplicated versions of the same
  310. * CKEditor 5 packages. Normally, on clean installations, npm deduplicates packages in `node_modules/`, so
  311. * it may be enough to call `rm -rf node_modules && npm i`. However, if you installed conflicting versions
  312. * of packages, their dependencies may need to be installed in more than one version which may lead to this
  313. * warning.
  314. *
  315. * Technically speaking, this error occurs because after adding a plugin to an existing editor build
  316. * dependencies of this plugin are being duplicated.
  317. * They are already built into that editor build and now get added for the second time as dependencies
  318. * of the plugin you are installing.
  319. *
  320. * Read more about {@glink builds/guides/integration/installing-plugins installing plugins}.
  321. *
  322. * @error plugincollection-plugin-name-conflict
  323. * @param {String} pluginName The duplicated plugin name.
  324. * @param {Function} plugin1 The first plugin constructor.
  325. * @param {Function} plugin2 The second plugin constructor.
  326. */
  327. log.warn(
  328. 'plugincollection-plugin-name-conflict: Two plugins with the same name were loaded.',
  329. { pluginName, plugin1: this._plugins.get( pluginName ).constructor, plugin2: PluginConstructor }
  330. );
  331. } else {
  332. this._plugins.set( pluginName, plugin );
  333. }
  334. }
  335. }
  336. mix( PluginCollection, EmitterMixin );