plugincollection.js 15 KB

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