plugincollection.js 13 KB

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