plugincollection.js 16 KB

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