diff --git a/src/editor/config/config.ts b/src/editor/config/config.ts index a3923dfa7..d2411d3e3 100644 --- a/src/editor/config/config.ts +++ b/src/editor/config/config.ts @@ -45,7 +45,7 @@ export interface EditorConfig { * Array of plugins to execute on start. * @default [] */ - plugins?: (string | Plugin)[]; + plugins?: (string | Plugin)[]; /** * Custom options for plugins diff --git a/src/index.ts b/src/index.ts index 23e97d767..1863f365a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,9 @@ -import { isElement, isFunction } from 'underscore'; +import { isElement, isFunction, isString } from 'underscore'; import $ from './utils/cash-dom'; import Editor from './editor'; import polyfills from './utils/polyfills'; import { getGlobal } from './utils/mixins'; -import PluginManager from './plugin_manager'; +import PluginManager, { Plugin, getPlugin, logPluginWarn } from './plugin_manager'; import { EditorConfig } from './editor/config/config'; interface InitEditorConfig extends EditorConfig { @@ -15,6 +15,18 @@ polyfills(); const plugins = new PluginManager(); const editors: Editor[] = []; +export const usePlugin =

| string>(plugin: P, opts?: P extends Plugin ? C : {}) => { + let pluginResult = getPlugin(plugin, plugins); + + return (editor: Editor) => { + if (pluginResult) { + pluginResult(editor, opts || {}); + } else { + logPluginWarn(editor, plugin as string); + } + }; +}; + const GrapesJS = { $, diff --git a/src/plugin_manager/index.ts b/src/plugin_manager/index.ts index f506405bc..bfafbe2c5 100644 --- a/src/plugin_manager/index.ts +++ b/src/plugin_manager/index.ts @@ -1,9 +1,34 @@ +import { isString } from 'underscore'; import Editor from '../editor'; +import { getGlobal } from '../utils/mixins'; type PluginOptions = Record; export type Plugin = (editor: Editor, config: T) => void; +const getPluginById = (pluginId: string, plugins: PluginManager) => { + let result = plugins.get(pluginId); + + // Try to search in global context + if (!result) { + const wplg = (getGlobal() as any)[pluginId]; + result = wplg?.default || wplg; + } + + return result; +}; + +export const getPlugin = (plugin: string | Plugin, plugins: PluginManager) => { + return isString(plugin) ? getPluginById(plugin, plugins) : plugin; +}; + +export const logPluginWarn = (editor: Editor, plugin: string) => { + editor.getModel().logWarning(`Plugin ${plugin} not found`, { + context: 'plugins', + plugin, + }); +}; + export default class PluginManager { plugins: Record = {};