plugincollection.js 15 KB

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