UNPKG

@udecode/plate-core

Version:

The core of Plate – a plugin system for slate

1,535 lines (1,490 loc) 113 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { AstPlugin: () => AstPlugin, BaseParagraphPlugin: () => BaseParagraphPlugin, CARRIAGE_RETURN: () => CARRIAGE_RETURN, DOMPlugin: () => DOMPlugin, DebugPlugin: () => DebugPlugin, ElementStatic: () => ElementStatic, HistoryPlugin: () => HistoryPlugin, Hotkeys: () => Hotkeys, HtmlPlugin: () => HtmlPlugin, InlineVoidPlugin: () => InlineVoidPlugin, LINE_FEED: () => LINE_FEED, LeafStatic: () => LeafStatic, LengthPlugin: () => LengthPlugin, NO_BREAK_SPACE: () => NO_BREAK_SPACE, ParserPlugin: () => ParserPlugin, PlateError: () => PlateError, PlateStatic: () => PlateStatic, SPACE: () => SPACE, SlateElement: () => SlateElement, SlateExtensionPlugin: () => SlateExtensionPlugin, SlateLeaf: () => SlateLeaf, TAB: () => TAB, ZERO_WIDTH_SPACE: () => ZERO_WIDTH_SPACE, applyDeepToNodes: () => applyDeepToNodes, applyPluginsToEditor: () => applyPluginsToEditor2, cleanHtmlBrElements: () => cleanHtmlBrElements, cleanHtmlCrLf: () => cleanHtmlCrLf, cleanHtmlEmptyElements: () => cleanHtmlEmptyElements, cleanHtmlFontElements: () => cleanHtmlFontElements, cleanHtmlLinkElements: () => cleanHtmlLinkElements, cleanHtmlTextNodes: () => cleanHtmlTextNodes, collapseString: () => collapseString, collapseWhiteSpace: () => collapseWhiteSpace, collapseWhiteSpaceChildren: () => collapseWhiteSpaceChildren, collapseWhiteSpaceElement: () => collapseWhiteSpaceElement, collapseWhiteSpaceNode: () => collapseWhiteSpaceNode, collapseWhiteSpaceText: () => collapseWhiteSpaceText, copyBlockMarksToSpanChild: () => copyBlockMarksToSpanChild, createHotkey: () => createHotkey, createSlateEditor: () => createSlateEditor, createSlatePlugin: () => createSlatePlugin, createStaticString: () => createStaticString, createTSlatePlugin: () => createTSlatePlugin, createZustandStore: () => import_zustand_x3.createZustandStore, defaultsDeepToNodes: () => defaultsDeepToNodes, deserializeHtml: () => deserializeHtml, deserializeHtmlElement: () => deserializeHtmlElement, deserializeHtmlNode: () => deserializeHtmlNode, deserializeHtmlNodeChildren: () => deserializeHtmlNodeChildren, endInlineFormattingContext: () => endInlineFormattingContext, findHtmlElement: () => findHtmlElement, getCorePlugins: () => getCorePlugins, getDataNodeProps: () => getDataNodeProps, getEditorDOMFromHtmlString: () => getEditorDOMFromHtmlString, getEditorPlugin: () => getEditorPlugin, getHtmlComments: () => getHtmlComments, getInjectMatch: () => getInjectMatch, getInjectedPlugins: () => getInjectedPlugins, getKeyByType: () => getKeyByType, getKeysByTypes: () => getKeysByTypes, getLeafDataAttributes: () => getLeafDataAttributes, getNodeDataAttributeKeys: () => getNodeDataAttributeKeys, getNodeDataAttributes: () => getNodeDataAttributes, getPluginDataAttributes: () => getPluginDataAttributes, getPluginNodeProps: () => getPluginNodeProps, getPluginType: () => getPluginType, getPluginTypes: () => getPluginTypes, getRenderNodeStaticProps: () => getRenderNodeStaticProps, getSlateClass: () => getSlateClass, getSlateElements: () => getSlateElements, getSlatePlugin: () => getSlatePlugin, htmlBodyToFragment: () => htmlBodyToFragment, htmlBrToNewLine: () => htmlBrToNewLine, htmlElementToElement: () => htmlElementToElement, htmlElementToLeaf: () => htmlElementToLeaf, htmlStringToDOMNode: () => htmlStringToDOMNode, htmlTextNodeToString: () => htmlTextNodeToString, inferWhiteSpaceRule: () => inferWhiteSpaceRule, inlineTagNames: () => inlineTagNames, isHotkey: () => import_is_hotkey2.isHotkey, isHtmlBlockElement: () => isHtmlBlockElement, isHtmlComment: () => isHtmlComment, isHtmlElement: () => isHtmlElement, isHtmlFragmentHref: () => isHtmlFragmentHref, isHtmlInlineElement: () => isHtmlInlineElement, isHtmlTable: () => isHtmlTable, isHtmlText: () => isHtmlText, isLastNonEmptyTextOfInlineFormattingContext: () => isLastNonEmptyTextOfInlineFormattingContext, isOlSymbol: () => isOlSymbol, isSlateEditor: () => isSlateEditor, isSlateElement: () => isSlateElement, isSlateLeaf: () => isSlateLeaf, isSlateNode: () => isSlateNode, isSlatePluginElement: () => isSlatePluginElement, isSlatePluginNode: () => isSlatePluginNode, isSlateString: () => isSlateString, isSlateText: () => isSlateText, isSlateVoid: () => isSlateVoid, isType: () => isType, keyToDataAttribute: () => keyToDataAttribute, mergeDeepToNodes: () => mergeDeepToNodes, nanoid: () => import_nanoid2.nanoid, normalizeDescendantsToDocumentFragment: () => normalizeDescendantsToDocumentFragment, omitPluginContext: () => omitPluginContext, overridePluginsByKey: () => overridePluginsByKey, parseHtmlDocument: () => parseHtmlDocument, parseHtmlElement: () => parseHtmlElement, pipeDecorate: () => pipeDecorate, pipeDeserializeHtmlElement: () => pipeDeserializeHtmlElement, pipeDeserializeHtmlLeaf: () => pipeDeserializeHtmlLeaf, pipeInsertDataQuery: () => pipeInsertDataQuery, pipeRenderElementStatic: () => pipeRenderElementStatic, pipeRenderLeafStatic: () => pipeRenderLeafStatic, pluginDeserializeHtml: () => pluginDeserializeHtml, pluginRenderElementStatic: () => pluginRenderElementStatic, pluginRenderLeafStatic: () => pluginRenderLeafStatic, postCleanHtml: () => postCleanHtml, preCleanHtml: () => preCleanHtml, removeHtmlNodesBetweenComments: () => removeHtmlNodesBetweenComments, removeHtmlSurroundings: () => removeHtmlSurroundings, replaceTagName: () => replaceTagName, resolveAndSortPlugins: () => resolveAndSortPlugins2, resolvePluginOverrides: () => resolvePluginOverrides2, resolvePlugins: () => resolvePlugins2, serializeHtml: () => serializeHtml, someHtmlElement: () => someHtmlElement, stripHtmlClassNames: () => stripHtmlClassNames, stripSlateDataAttributes: () => stripSlateDataAttributes, traverseHtmlComments: () => traverseHtmlComments, traverseHtmlElements: () => traverseHtmlElements, traverseHtmlNode: () => traverseHtmlNode, traverseHtmlTexts: () => traverseHtmlTexts, unwrapHtmlElement: () => unwrapHtmlElement, upsertInlineFormattingContext: () => upsertInlineFormattingContext, withInlineVoid: () => withInlineVoid, withPlateHistory: () => withPlateHistory, withSlate: () => withSlate }); module.exports = __toCommonJS(index_exports); // src/lib/editor/withSlate.ts var import_slate10 = require("@udecode/slate"); var import_nanoid = require("nanoid"); // src/internal/utils/isFunction.ts function isFunction(value) { return typeof value === "function"; } // src/internal/utils/mergePlugins.ts var import_mergeWith = __toESM(require("lodash/mergeWith.js")); function mergePlugins(basePlugin, ...sourcePlugins) { return (0, import_mergeWith.default)( {}, basePlugin, ...sourcePlugins, (objValue, srcValue, key) => { if (Array.isArray(srcValue)) { return srcValue; } if (key === "options") { return { ...objValue, ...srcValue }; } } ); } // src/lib/plugin/createSlatePlugin.ts function createSlatePlugin(config = {}) { let baseConfig; let initialExtension; if (isFunction(config)) { baseConfig = { key: "" }; initialExtension = (editor) => config(editor); } else { baseConfig = config; } const key = baseConfig.key ?? ""; const plugin = mergePlugins( { key, __apiExtensions: [], __configuration: null, __extensions: initialExtension ? [initialExtension] : [], __selectorExtensions: [], api: {}, dependencies: [], editor: {}, handlers: {}, inject: {}, node: { type: key }, options: {}, override: {}, parser: {}, parsers: {}, plugins: [], priority: 100, render: {}, shortcuts: {}, transforms: {} }, config ); plugin.configure = (config2) => { const newPlugin = { ...plugin }; newPlugin.__configuration = (ctx) => isFunction(config2) ? config2(ctx) : config2; return createSlatePlugin(newPlugin); }; plugin.configurePlugin = (p, config2) => { const newPlugin = { ...plugin }; const configureNestedPlugin = (plugins) => { let found = false; const updatedPlugins = plugins.map((nestedPlugin) => { if (nestedPlugin.key === p.key) { found = true; return createSlatePlugin({ ...nestedPlugin, __configuration: (ctx) => isFunction(config2) ? config2(ctx) : config2 }); } if (nestedPlugin.plugins && nestedPlugin.plugins.length > 0) { const result2 = configureNestedPlugin(nestedPlugin.plugins); if (result2.found) { found = true; return { ...nestedPlugin, plugins: result2.plugins }; } } return nestedPlugin; }); return { found, plugins: updatedPlugins }; }; const result = configureNestedPlugin(newPlugin.plugins); newPlugin.plugins = result.plugins; return createSlatePlugin(newPlugin); }; plugin.extendEditorApi = (extension) => { const newPlugin = { ...plugin }; newPlugin.__apiExtensions = [ ...newPlugin.__apiExtensions, { extension, isPluginSpecific: false } ]; return createSlatePlugin(newPlugin); }; plugin.extendSelectors = (extension) => { const newPlugin = { ...plugin }; newPlugin.__selectorExtensions = [ ...newPlugin.__selectorExtensions, extension ]; return createSlatePlugin(newPlugin); }; plugin.extendApi = (extension) => { const newPlugin = { ...plugin }; newPlugin.__apiExtensions = [ ...newPlugin.__apiExtensions, { extension, isPluginSpecific: true } ]; return createSlatePlugin(newPlugin); }; plugin.extendEditorTransforms = (extension) => { const newPlugin = { ...plugin }; newPlugin.__apiExtensions = [ ...newPlugin.__apiExtensions, { extension, isPluginSpecific: false, isTransform: true } ]; return createSlatePlugin(newPlugin); }; plugin.extendTransforms = (extension) => { const newPlugin = { ...plugin }; newPlugin.__apiExtensions = [ ...newPlugin.__apiExtensions, { extension, isPluginSpecific: true, isTransform: true } ]; return createSlatePlugin(newPlugin); }; plugin.overrideEditor = (extension) => { const newPlugin = { ...plugin }; newPlugin.__apiExtensions = [ ...newPlugin.__apiExtensions, { extension, isOverride: true, isPluginSpecific: false, isTransform: true } ]; return createSlatePlugin(newPlugin); }; plugin.extend = (extendConfig) => { let newPlugin = { ...plugin }; if (isFunction(extendConfig)) { newPlugin.__extensions = [ ...newPlugin.__extensions, extendConfig ]; } else { newPlugin = mergePlugins(newPlugin, extendConfig); } return createSlatePlugin(newPlugin); }; plugin.clone = () => mergePlugins(plugin); plugin.extendPlugin = (p, extendConfig) => { const newPlugin = { ...plugin }; const extendNestedPlugin = (plugins) => { let found = false; const updatedPlugins = plugins.map((nestedPlugin) => { if (nestedPlugin.key === p.key) { found = true; return createSlatePlugin({ ...nestedPlugin, __extensions: [ ...nestedPlugin.__extensions, (ctx) => isFunction(extendConfig) ? extendConfig(ctx) : extendConfig ] }); } if (nestedPlugin.plugins && nestedPlugin.plugins.length > 0) { const result2 = extendNestedPlugin(nestedPlugin.plugins); if (result2.found) { found = true; return { ...nestedPlugin, plugins: result2.plugins }; } } return nestedPlugin; }); return { found, plugins: updatedPlugins }; }; const result = extendNestedPlugin(newPlugin.plugins); newPlugin.plugins = result.plugins; if (!result.found) { newPlugin.plugins.push( createSlatePlugin({ key: p.key, __extensions: [ (ctx) => isFunction(extendConfig) ? extendConfig(ctx) : extendConfig ] }) ); } return createSlatePlugin(newPlugin); }; return plugin; } function createTSlatePlugin(config = {}) { return createSlatePlugin(config); } // src/lib/plugin/getEditorPlugin.ts function getEditorPlugin(editor, p) { const plugin = editor.getPlugin(p); return { api: editor.api, editor, plugin, setOption: (keyOrOptions, value) => editor.setOption(plugin, keyOrOptions, value), setOptions: (options) => editor.setOptions(plugin, options), tf: editor.transforms, type: plugin.node.type, getOption: (key, ...args) => editor.getOption(plugin, key, ...args), getOptions: () => editor.getOptions(plugin) }; } // src/internal/plugin/resolvePlugin.ts var import_merge = __toESM(require("lodash/merge.js")); var resolvePlugin = (editor, _plugin) => { let plugin = mergePlugins({}, _plugin); plugin.__resolved = true; if (plugin.__configuration) { const configResult = plugin.__configuration( getEditorPlugin(editor, plugin) ); plugin = mergePlugins(plugin, configResult); delete plugin.__configuration; } if (plugin.__extensions && plugin.__extensions.length > 0) { plugin.__extensions.forEach((extension) => { plugin = mergePlugins( plugin, extension(getEditorPlugin(editor, plugin)) ); }); plugin.__extensions = []; } const targetPluginToInject = plugin.inject?.targetPluginToInject; const targetPlugins = plugin.inject?.targetPlugins; if (targetPluginToInject && targetPlugins && targetPlugins.length > 0) { plugin.inject = plugin.inject || {}; plugin.inject.plugins = (0, import_merge.default)( {}, plugin.inject.plugins, Object.fromEntries( targetPlugins.map((targetPlugin) => { const injectedPlugin = targetPluginToInject({ ...getEditorPlugin(editor, plugin), targetPlugin }); return [targetPlugin, injectedPlugin]; }) ) ); } if (plugin.node?.component) { plugin.render.node = plugin.node.component; } if (plugin.render?.node) { plugin.node.component = plugin.render.node; } validatePlugin(editor, plugin); return plugin; }; var validatePlugin = (editor, plugin) => { if (!plugin.__extensions) { editor.api.debug.error( `Invalid plugin '${plugin.key}', you should use createSlatePlugin.`, "USE_CREATE_PLUGIN" ); } if (plugin.node.isElement && plugin.node.isLeaf) { editor.api.debug.error( `Plugin ${plugin.key} cannot be both an element and a leaf.`, "PLUGIN_NODE_TYPE" ); } }; // src/lib/plugin/getSlatePlugin.ts function getSlatePlugin(editor, p) { let plugin = p; const editorPlugin = editor.plugins[p.key]; if (!editorPlugin) { if (!plugin.node) { plugin = createSlatePlugin(plugin); } return plugin.__resolved ? plugin : resolvePlugin(editor, plugin); } return editorPlugin; } function getPluginType(editor, plugin) { const p = editor.getPlugin(plugin); return p.node.type ?? p.key ?? ""; } var getPluginTypes = (editor, plugins) => plugins.map((plugin) => editor.getType(plugin)); // src/internal/plugin/pipeNormalizeInitialValue.ts var pipeNormalizeInitialValue = (editor) => { editor.pluginList.forEach((p) => { p.normalizeInitialValue?.({ ...getEditorPlugin(editor, p), value: editor.children }); }); }; // src/internal/plugin/resolvePlugins.ts var import_slate = require("@udecode/slate"); var import_utils = require("@udecode/utils"); var import_merge2 = __toESM(require("lodash/merge.js")); var import_zustand_x = require("zustand-x"); var resolvePlugins = (editor, plugins = []) => { editor.pluginList = []; editor.plugins = {}; editor.shortcuts = {}; const resolvedPlugins = resolveAndSortPlugins(editor, plugins); applyPluginsToEditor(editor, resolvedPlugins); resolvePluginOverrides(editor); resolvePluginStores(editor); editor.pluginList.forEach((plugin) => { if (plugin.extendEditor) { editor = plugin.extendEditor(getEditorPlugin(editor, plugin)); (0, import_slate.syncLegacyMethods)(editor); } resolvePluginMethods(editor, plugin); }); resolvePluginShortcuts(editor); return editor; }; var resolvePluginStores = (editor) => { editor.pluginList.forEach((plugin) => { let store = (0, import_zustand_x.createZustandStore)(plugin.options, { mutative: true, name: plugin.key }); if (plugin.__selectorExtensions && plugin.__selectorExtensions.length > 0) { plugin.__selectorExtensions.forEach((extension) => { const extendedOptions = extension(getEditorPlugin(editor, plugin)); store = store.extendSelectors(() => extendedOptions); }); } plugin.optionsStore = store; }); }; var resolvePluginMethods = (editor, plugin) => { Object.entries(plugin.api).forEach(([apiKey, apiFunction]) => { editor.api[apiKey] = apiFunction; }); if (plugin.__apiExtensions && plugin.__apiExtensions.length > 0) { plugin.__apiExtensions.forEach( ({ extension, isOverride, isPluginSpecific, isTransform }) => { const newExtensions = extension(getEditorPlugin(editor, plugin)); if (isOverride) { if (newExtensions.api) { (0, import_merge2.default)(editor.api, newExtensions.api); (0, import_merge2.default)(plugin.api, newExtensions.api); (0, import_slate.assignLegacyApi)(editor, editor.api); } if (newExtensions.transforms) { (0, import_merge2.default)(editor.transforms, newExtensions.transforms); (0, import_merge2.default)(plugin.transforms, newExtensions.transforms); (0, import_slate.assignLegacyTransforms)(editor, newExtensions.transforms); } } else if (isTransform) { if (isPluginSpecific) { if (!editor.transforms[plugin.key]) { editor.transforms[plugin.key] = {}; } if (!plugin.transforms[plugin.key]) { plugin.transforms[plugin.key] = {}; } (0, import_merge2.default)(editor.transforms[plugin.key], newExtensions); (0, import_merge2.default)(plugin.transforms[plugin.key], newExtensions); } else { (0, import_merge2.default)(editor.transforms, newExtensions); (0, import_merge2.default)(plugin.transforms, newExtensions); (0, import_slate.assignLegacyTransforms)(editor, newExtensions); } } else { if (isPluginSpecific) { if (!editor.api[plugin.key]) { editor.api[plugin.key] = {}; } if (!plugin.api[plugin.key]) { plugin.api[plugin.key] = {}; } (0, import_merge2.default)(editor.api[plugin.key], newExtensions); (0, import_merge2.default)(plugin.api[plugin.key], newExtensions); } else { (0, import_merge2.default)(editor.api, newExtensions); (0, import_merge2.default)(plugin.api, newExtensions); (0, import_slate.assignLegacyApi)(editor, editor.api); } } } ); delete plugin.__apiExtensions; } }; var resolvePluginShortcuts = (editor) => { const shortcutsByPriority = []; editor.pluginList.forEach((plugin) => { Object.entries(plugin.shortcuts).forEach(([key, hotkey]) => { if (hotkey === null) { const index = shortcutsByPriority.findIndex((item) => item.key === key); if (index !== -1) { shortcutsByPriority.splice(index, 1); } } else { const priority = hotkey.priority ?? plugin.priority; const existingIndex = shortcutsByPriority.findIndex( (item) => item.key === key ); if (existingIndex === -1 || priority >= shortcutsByPriority[existingIndex].priority) { if (existingIndex !== -1) { shortcutsByPriority.splice(existingIndex, 1); } shortcutsByPriority.push({ key, hotkey, priority }); } } }); }); shortcutsByPriority.sort((a, b) => b.hotkey.priority - a.hotkey.priority); editor.shortcuts = Object.fromEntries( shortcutsByPriority.map(({ key, hotkey }) => { const { priority, ...hotkeyWithoutPriority } = hotkey; return [key, hotkeyWithoutPriority]; }) ); }; var flattenAndResolvePlugins = (editor, plugins) => { const pluginMap = /* @__PURE__ */ new Map(); const processPlugin = (plugin) => { const resolvedPlugin = resolvePlugin(editor, plugin); const existingPlugin = pluginMap.get(resolvedPlugin.key); if (existingPlugin) { pluginMap.set( resolvedPlugin.key, mergePlugins(existingPlugin, resolvedPlugin) ); } else { pluginMap.set(resolvedPlugin.key, resolvedPlugin); } if (resolvedPlugin.plugins && resolvedPlugin.plugins.length > 0) { resolvedPlugin.plugins.forEach(processPlugin); } }; plugins.forEach(processPlugin); return pluginMap; }; var resolveAndSortPlugins = (editor, plugins) => { const pluginMap = flattenAndResolvePlugins(editor, plugins); const enabledPlugins = Array.from(pluginMap.values()).filter( (plugin) => plugin.enabled !== false ); enabledPlugins.sort((a, b) => b.priority - a.priority); const orderedPlugins = []; const visited = /* @__PURE__ */ new Set(); const visit = (plugin) => { if (visited.has(plugin.key)) return; visited.add(plugin.key); plugin.dependencies?.forEach((depKey) => { const depPlugin = pluginMap.get(depKey); if (depPlugin) { visit(depPlugin); } else { editor.api.debug.warn( `Plugin "${plugin.key}" depends on missing plugin "${depKey}"`, "PLUGIN_DEPENDENCY_MISSING" ); } }); orderedPlugins.push(plugin); }; enabledPlugins.forEach(visit); return orderedPlugins; }; var applyPluginsToEditor = (editor, plugins) => { editor.pluginList = plugins; editor.plugins = Object.fromEntries( plugins.map((plugin) => [plugin.key, plugin]) ); }; var resolvePluginOverrides = (editor) => { const applyOverrides = (plugins) => { let overriddenPlugins = [...plugins]; const enabledOverrides = {}; const componentOverrides = {}; const pluginOverrides = {}; for (const plugin of plugins) { if (plugin.override.enabled) { Object.assign(enabledOverrides, plugin.override.enabled); } if (plugin.override.components) { Object.entries(plugin.override.components).forEach( ([key, component]) => { if (!componentOverrides[key] || plugin.priority > componentOverrides[key].priority) { componentOverrides[key] = { component, priority: plugin.priority }; } } ); } if (plugin.override.plugins) { Object.entries(plugin.override.plugins).forEach(([key, value]) => { pluginOverrides[key] = mergePlugins(pluginOverrides[key], value); if (value.enabled !== void 0) { enabledOverrides[key] = value.enabled; } }); } } overriddenPlugins = overriddenPlugins.map((p) => { let updatedPlugin = { ...p }; if (pluginOverrides[p.key]) { updatedPlugin = mergePlugins(updatedPlugin, pluginOverrides[p.key]); } if (componentOverrides[p.key] && (!p.render.node && !p.node.component || componentOverrides[p.key].priority > p.priority)) { updatedPlugin.render.node = componentOverrides[p.key].component; updatedPlugin.node.component = componentOverrides[p.key].component; } const enabled = enabledOverrides[p.key] ?? updatedPlugin.enabled; if ((0, import_utils.isDefined)(enabled)) { updatedPlugin.enabled = enabled; } return updatedPlugin; }); return overriddenPlugins.filter((p) => p.enabled !== false).map((plugin) => ({ ...plugin, plugins: applyOverrides(plugin.plugins || []) })); }; editor.pluginList = applyOverrides(editor.pluginList); editor.plugins = Object.fromEntries( editor.pluginList.map((plugin) => [plugin.key, plugin]) ); }; // src/lib/plugins/AstPlugin.ts var AstPlugin = createSlatePlugin({ key: "ast", parser: { format: "application/x-slate-fragment", deserialize: ({ data }) => { const decoded = decodeURIComponent(window.atob(data)); let parsed; try { parsed = JSON.parse(decoded); } catch { } return parsed; } } }); // src/lib/plugins/DOMPlugin.ts var DOMPlugin = createSlatePlugin({ key: "dom" }); // src/lib/plugins/HistoryPlugin.ts var import_slate2 = require("@udecode/slate"); var withPlateHistory = ({ editor }) => (0, import_slate2.withHistory)(editor); var HistoryPlugin = createSlatePlugin({ key: "history", extendEditor: withPlateHistory }); // src/lib/plugins/InlineVoidPlugin.ts var withInlineVoid = ({ api: { isInline, isSelectable, isVoid, markableVoid }, editor }) => { const voidTypes = []; const inlineTypes = []; const markableVoidTypes = []; const nonSelectableTypes = []; editor.pluginList.forEach((plugin) => { if (plugin.node.isInline) { inlineTypes.push(plugin.node.type); } if (plugin.node.isVoid) { voidTypes.push(plugin.node.type); } if (plugin.node.isMarkableVoid) { markableVoidTypes.push(plugin.node.type); } if (plugin.node.isSelectable === false) { nonSelectableTypes.push(plugin.node.type); } }); return { api: { isInline(element) { return inlineTypes.includes(element.type) ? true : isInline(element); }, isSelectable(element) { return nonSelectableTypes.includes(element.type) ? false : isSelectable(element); }, isVoid(element) { return voidTypes.includes(element.type) ? true : isVoid(element); }, markableVoid(element) { return markableVoidTypes.includes(element.type) ? true : markableVoid(element); } } }; }; var InlineVoidPlugin = createSlatePlugin({ key: "inlineVoid" }).overrideEditor(withInlineVoid); // src/internal/plugin/pipeInsertFragment.ts var pipeInsertFragment = (editor, injectedPlugins, { fragment, ...options }) => { editor.tf.withoutNormalizing(() => { injectedPlugins.some((p) => { return p.parser?.preInsert?.({ ...getEditorPlugin(editor, p), fragment, ...options }) === true; }); editor.tf.insertFragment(fragment); }); }; // src/internal/plugin/pipeTransformData.ts var pipeTransformData = (editor, plugins, { data, dataTransfer }) => { plugins.forEach((p) => { const transformData = p.parser?.transformData; if (!transformData) return; data = transformData({ ...getEditorPlugin(editor, p), data, dataTransfer }); }); return data; }; // src/internal/plugin/pipeTransformFragment.ts var pipeTransformFragment = (editor, plugins, { fragment, ...options }) => { plugins.forEach((p) => { const transformFragment = p.parser?.transformFragment; if (!transformFragment) return; fragment = transformFragment({ fragment, ...options, ...getEditorPlugin(editor, p) }); }); return fragment; }; // src/lib/utils/applyDeepToNodes.ts var import_slate3 = require("@udecode/slate"); var applyDeepToNodes = ({ apply, node, path = [], query, source }) => { const entry = [node, path]; if ((0, import_slate3.queryNode)(entry, query)) { if (source instanceof Function) { apply(node, source()); } else { apply(node, source); } } if (!import_slate3.NodeApi.isAncestor(node)) return; node.children.forEach((child, index) => { applyDeepToNodes({ apply, node: child, path: path.concat([index]), query, source }); }); }; // src/lib/utils/defaultsDeepToNodes.ts var import_defaults = __toESM(require("lodash/defaults.js")); var defaultsDeepToNodes = (options) => { applyDeepToNodes({ ...options, apply: import_defaults.default }); }; // src/lib/utils/getInjectMatch.ts var import_slate4 = require("@udecode/slate"); // src/lib/utils/getKeysByTypes.ts var getKeysByTypes = (editor, types) => { return Object.values(editor.plugins).filter((plugin) => types.includes(plugin.node.type)).map((plugin) => plugin.key); }; var getKeyByType = (editor, type) => { const plugin = Object.values(editor.plugins).find( (plugin2) => plugin2.node.type === type ); return plugin?.key ?? type; }; // src/lib/utils/getInjectMatch.ts var getInjectMatch = (editor, plugin) => { return (node, path) => { const { inject: { excludeBelowPlugins, excludePlugins, isBlock: _isBlock, isElement: _isElement, isLeaf, maxLevel, targetPlugins } } = plugin; const element = import_slate4.ElementApi.isElement(node) ? node : void 0; if (_isElement && !element) return false; if (_isBlock && (!element || !editor.api.isBlock(element))) return false; if (isLeaf && element) return false; if (element?.type) { if (excludePlugins?.includes(getKeyByType(editor, element.type))) { return false; } if (targetPlugins && !targetPlugins.includes(getKeyByType(editor, element.type))) { return false; } } if (excludeBelowPlugins || maxLevel) { if (maxLevel && path.length > maxLevel) { return false; } if (excludeBelowPlugins) { const excludeTypes = getKeysByTypes(editor, excludeBelowPlugins); const isBelow = editor.api.above({ at: path, match: (n) => import_slate4.ElementApi.isElement(n) && excludeTypes.includes(n.type) }); if (isBelow) return false; } } return true; }; }; // src/lib/utils/getInjectedPlugins.ts var getInjectedPlugins = (editor, plugin) => { const injectedPlugins = []; [...editor.pluginList].reverse().forEach((p) => { const injectedPlugin = p.inject.plugins?.[plugin.key]; if (injectedPlugin) injectedPlugins.push(injectedPlugin); }); return [plugin, ...injectedPlugins]; }; // src/lib/utils/getPluginNodeProps.ts var import_pick = __toESM(require("lodash/pick.js")); // src/lib/static/pipeRenderElementStatic.tsx var import_react4 = __toESM(require("react")); // src/lib/static/components/SlateElement.tsx var import_react = __toESM(require("react")); var import_clsx = __toESM(require("clsx")); var SlateElement = (props) => { const { as, attributes, element, elementToAttributes, nodeProps, ...rest } = omitPluginContext(props); const block = !!element.id && props.editor.api.isBlock(element); const rootProps = { ...attributes, ...rest, ...nodeProps, ...elementToAttributes?.(element), className: (0, import_clsx.default)(props.className, nodeProps?.className), "data-block-id": block ? element.id : void 0, style: { position: "relative", ...props.style, ...nodeProps?.style } }; const Element = as ?? "div"; return /* @__PURE__ */ import_react.default.createElement(Element, { ...rootProps, ref: attributes.ref }); }; // src/lib/static/pluginRenderElementStatic.tsx var import_react3 = __toESM(require("react")); // src/lib/static/utils/createStaticString.ts var import_react2 = __toESM(require("react")); function createStaticString({ text }) { return import_react2.default.createElement( "span", { "data-slate-string": true }, text === "" ? "\uFEFF" : text ); } // src/lib/static/utils/getNodeDataAttributes.ts var import_slate5 = require("@udecode/slate"); var import_kebabCase = __toESM(require("lodash/kebabCase.js")); var getNodeDataAttributes = (node, { isElement, isLeaf }) => { const dataAttributes = Object.keys(node).reduce((acc, key) => { if (typeof node[key] === "object") return acc; if (isElement && key === "children") return acc; if (isLeaf && key === "text") return acc; const attributeName = keyToDataAttribute(key); return { ...acc, [attributeName]: node[key] }; }, {}); return dataAttributes; }; var getPluginDataAttributes = (editor, plugin, node) => { const isElement = plugin.node.isElement; const isLeaf = plugin.node.isLeaf; const dataAttributes = getNodeDataAttributes(node, { isElement, isLeaf }); const customAttributes = plugin.node.toDataAttributes?.({ ...plugin ? getEditorPlugin(editor, plugin) : {}, node }) ?? {}; return { ...dataAttributes, ...customAttributes }; }; var getLeafDataAttributes = (leaf) => getNodeDataAttributes(leaf, { isElement: false, isLeaf: true }); var getNodeDataAttributeKeys = (node) => { return Object.keys(node).filter( (key) => typeof node[key] !== "object" && (!import_slate5.TextApi.isText(node) || key !== "text") ).map((key) => keyToDataAttribute(key)); }; var keyToDataAttribute = (key) => { return `data-slate-${(0, import_kebabCase.default)(key)}`; }; // src/lib/static/utils/getRenderNodeStaticProps.ts var import_clsx3 = __toESM(require("clsx")); // src/internal/plugin/pipeInjectNodeProps.tsx var import_clsx2 = __toESM(require("clsx")); // src/internal/plugin/pluginInjectNodeProps.ts var import_utils3 = require("@udecode/utils"); var pluginInjectNodeProps = (editor, plugin, nodeProps, getElementPath) => { const { key, inject: { nodeProps: injectNodeProps } } = plugin; const { element, text } = nodeProps; const node = element ?? text; if (!node) return; if (!injectNodeProps) return; const { classNames, defaultNodeValue, nodeKey = key, query, styleKey = nodeKey, transformClassName, transformNodeValue, transformProps, transformStyle, validNodeValues } = injectNodeProps; const injectMatch = getInjectMatch(editor, plugin); if (!injectMatch(node, getElementPath(node))) return; const queryResult = query?.({ ...injectNodeProps, ...getEditorPlugin(editor, plugin), nodeProps }); if (query && !queryResult) { return; } const nodeValue = node[nodeKey]; if (!transformProps && (!(0, import_utils3.isDefined)(nodeValue) || validNodeValues && !validNodeValues.includes(nodeValue) || nodeValue === defaultNodeValue)) { return; } const transformOptions = { ...nodeProps, ...getEditorPlugin(editor, plugin), nodeValue }; const value = transformNodeValue?.(transformOptions) ?? nodeValue; transformOptions.value = value; let newProps = {}; if (element && nodeKey) { newProps.className = `slate-${nodeKey}-${nodeValue}`; } if (classNames?.[nodeValue] || transformClassName) { newProps.className = transformClassName?.(transformOptions) ?? classNames?.[value]; } if (styleKey) { newProps.style = transformStyle?.(transformOptions) ?? { [styleKey]: value }; } if (transformProps) { newProps = transformProps({ ...transformOptions, props: newProps }) ?? newProps; } return newProps; }; // src/internal/plugin/pipeInjectNodeProps.tsx var pipeInjectNodeProps = (editor, nodeProps, getElementPath) => { editor.pluginList.forEach((plugin) => { if (plugin.inject.nodeProps) { const newProps = pluginInjectNodeProps( editor, plugin, nodeProps, getElementPath ); if (!newProps) return; nodeProps = { ...nodeProps, ...newProps, className: (0, import_clsx2.default)(nodeProps.className, newProps.className), style: { ...nodeProps.style, ...newProps.style } }; } }); return nodeProps; }; // src/lib/static/utils/getRenderNodeStaticProps.ts var getRenderNodeStaticProps = ({ attributes, editor, node, plugin, props }) => { let nodeProps = { ...props, ...plugin ? getEditorPlugin(editor, plugin) : {} }; const { className } = props; nodeProps = { ...getPluginNodeProps({ attributes, node, plugin, props: nodeProps }), className: (0, import_clsx3.default)(getSlateClass(plugin?.node.type), className) }; nodeProps = pipeInjectNodeProps( editor, nodeProps, (node2) => editor.api.findPath(node2) ); if (nodeProps.style && Object.keys(nodeProps.style).length === 0) { delete nodeProps.style; } return nodeProps; }; // src/lib/static/utils/pipeDecorate.ts var pipeDecorate = (editor, decorateProp) => { const relevantPlugins = editor.pluginList.filter((plugin) => plugin.decorate); if (relevantPlugins.length === 0 && !decorateProp) return; return (entry) => { let ranges = []; const addRanges = (newRanges) => { if (newRanges?.length) ranges = [...ranges, ...newRanges]; }; relevantPlugins.forEach((plugin) => { addRanges( plugin.decorate({ ...getEditorPlugin(editor, plugin), entry }) ); }); if (decorateProp) { addRanges( decorateProp({ editor, entry }) ); } return ranges; }; }; // src/lib/static/utils/stripHtmlClassNames.ts var classAttrRegExp = / class="([^"]*)"/g; var stripHtmlClassNames = (html, { preserveClassNames = ["slate-"] }) => { if (preserveClassNames.length === 0) { return html.replaceAll(classAttrRegExp, ""); } const preserveRegExp = new RegExp( preserveClassNames.map((cn) => `^${cn}`).join("|") ); return html.replaceAll( classAttrRegExp, (match, className) => { const classesToKeep = className.split(/\s+/).filter((cn) => preserveRegExp.test(cn)); return classesToKeep.length === 0 ? "" : ` class="${classesToKeep.join(" ")}"`; } ); }; // src/lib/static/utils/stripSlateDataAttributes.ts var stripSlateDataAttributes = (rawHtml) => rawHtml.replaceAll(/ data-slate(?:-node|-type|-leaf|-string)="[^"]+"/g, "").replaceAll(/ data-testid="[^"]+"/g, ""); // src/lib/static/pluginRenderElementStatic.tsx var pluginRenderElementStatic = (editor, plugin, components) => function render(nodeProps) { if (nodeProps.element.type === plugin.node.type) { const element = nodeProps.element; const key = plugin.key; const Element = components?.[plugin.key] ?? SlateElement; let { children } = nodeProps; const aboveNodes = editor.pluginList.flatMap( (o) => o.render?.aboveNodes ?? [] ); const belowNodes = editor.pluginList.flatMap( (o) => o.render?.belowNodes ?? [] ); const dataAttributes = getPluginDataAttributes(editor, plugin, element); nodeProps = getRenderNodeStaticProps({ attributes: { ...element.attributes, ...dataAttributes }, editor, node: element, plugin, props: nodeProps }); belowNodes.forEach((withHOC) => { const hoc = withHOC({ ...nodeProps, key }); if (hoc) { children = hoc({ ...nodeProps, children }); } }); let component = /* @__PURE__ */ import_react3.default.createElement(Element, { ...nodeProps }, children); aboveNodes.forEach((withHOC) => { const hoc = withHOC({ ...nodeProps, key }); if (hoc) { component = hoc({ ...nodeProps, children: component }); } }); return component; } }; // src/lib/static/pipeRenderElementStatic.tsx var pipeRenderElementStatic = (editor, { components, renderElement: renderElementProp }) => { const renderElements = []; editor.pluginList.forEach((plugin) => { if (plugin.node.isElement) { renderElements.push( pluginRenderElementStatic(editor, plugin, components) ); } }); return function render(props) { let element; renderElements.some((renderElement) => { element = renderElement(props); return !!element; }); if (element) return element; if (renderElementProp) { return renderElementProp(props); } return /* @__PURE__ */ import_react4.default.createElement( SlateElement, { attributes: props.attributes, element: props.element, ...{} }, props.children ); }; }; // src/lib/static/pluginRenderLeafStatic.tsx var import_react6 = __toESM(require("react")); // src/lib/static/components/SlateLeaf.tsx var import_react5 = __toESM(require("react")); var import_clsx4 = __toESM(require("clsx")); function SlateLeaf(props) { const { as, attributes, leaf, leafToAttributes, nodeProps, text, ...rest } = omitPluginContext(props); const rootProps = { ...attributes, ...rest, ...nodeProps, ...leafToAttributes?.(leaf), className: (0, import_clsx4.default)(props.className, nodeProps?.className) }; const Leaf = as ?? "span"; return /* @__PURE__ */ import_react5.default.createElement(Leaf, { ...rootProps }); } // src/lib/static/pluginRenderLeafStatic.tsx var pluginRenderLeafStatic = (editor, plugin, components) => function render(nodeProps) { const { children, leaf } = nodeProps; if (leaf[plugin.node.type ?? plugin.key]) { const Leaf = components?.[plugin.key] ?? SlateLeaf; const dataAttributes = getPluginDataAttributes(editor, plugin, leaf); const ctxProps = getRenderNodeStaticProps({ attributes: { ...leaf.attributes, ...dataAttributes }, editor, node: leaf, plugin, props: nodeProps }); return /* @__PURE__ */ import_react6.default.createElement(Leaf, { ...ctxProps }, children); } return children; }; var pipeRenderLeafStatic = (editor, { components, renderLeaf: renderLeafProp }) => { const renderLeafs = []; editor.pluginList.forEach((plugin) => { if (plugin.node.isLeaf && plugin.key) { renderLeafs.push(pluginRenderLeafStatic(editor, plugin, components)); } }); return function render(props) { renderLeafs.forEach((renderLeaf) => { const newChildren = renderLeaf(props); if (newChildren !== void 0) { props.children = newChildren; } }); if (renderLeafProp) { return renderLeafProp(props); } const ctxProps = getRenderNodeStaticProps({ attributes: props.attributes, editor, props }); const leaf = ctxProps.leaf; const dataAttributes = getLeafDataAttributes(leaf); return /* @__PURE__ */ import_react6.default.createElement(SlateLeaf, { ...ctxProps, ...dataAttributes }); }; }; // src/lib/static/serializeHtml.tsx var import_react8 = __toESM(require("react")); var import_html_entities = require("html-entities"); // src/lib/static/components/PlateStatic.tsx var import_react7 = __toESM(require("react")); var import_slate6 = require("@udecode/slate"); var import_clsx5 = __toESM(require("clsx")); function BaseElementStatic({ components, decorate, decorations, editor, element = { children: [], type: "" } }) { const renderElement = pipeRenderElementStatic(editor, { components }); const attributes = { "data-slate-node": "element", ref: null }; let children = /* @__PURE__ */ import_react7.default.createElement( Children, { components, decorate, decorations, editor }, element.children ); if (editor.api.isVoid(element)) { attributes["data-slate-void"] = true; children = /* @__PURE__ */ import_react7.default.createElement( "span", { style: { color: "transparent", height: "0", outline: "none", position: "absolute" }, "data-slate-spacer": true }, /* @__PURE__ */ import_react7.default.createElement( Children, { components, decorate, decorations, editor }, element.children ) ); } if (editor.api.isInline(element)) { attributes["data-slate-inline"] = true; } return /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, renderElement?.({ attributes, children, element })); } var ElementStatic = import_react7.default.memo(BaseElementStatic, (prev, next) => { return (prev.element === next.element || prev.element._memo !== void 0 && prev.element._memo === next.element._memo) && (0, import_slate6.isElementDecorationsEqual)(prev.decorations, next.decorations); }); function BaseLeafStatic({ components, decorations, editor, leaf = { text: "" } }) { const renderLeaf = pipeRenderLeafStatic(editor, { components }); const leaves = import_slate6.TextApi.decorations(leaf, decorations); return /* @__PURE__ */ import_react7.default.createElement("span", { "data-slate-node": "text" }, leaves.map((l, index) => { const leafElement = renderLeaf({ attributes: { "data-slate-leaf": true }, children: /* @__PURE__ */ import_react7.default.createElement("span", { "data-slate-string": true }, l.text === "" ? "\uFEFF" : l.text), leaf: l, text: l }); return /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, { key: index }, leafElement); })); } var LeafStatic = import_react7.default.memo(BaseLeafStatic, (prev, next) => { return ( // prev.leaf === next.leaf && import_slate6.TextApi.equals(next.leaf, prev.leaf) && (0, import_slate6.isTextDecorationsEqual)(next.decorations, prev.decorations) ); }); var defaultDecorate = () => []; function Children({ children = [], components, decorate = defaultDecorate, decorations = [], editor }) { return /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, children.map((child, i) => { const p = editor.api.findPath(child); let ds = []; if (p) { const range = editor.api.range(p); ds = decorate([child, p]); for (const dec of decorations) { const d = import_slate6.RangeApi.intersection(dec, range); if (d) { ds.push(d); } } } return import_slate6.ElementApi.isElement(child) ? /* @__PURE__ */ import_react7.default.createElement( ElementStatic, { key: i, components, decorate, decorations: ds, editor, element: child } ) : /* @__PURE__ */ import_react7.default.createElement( LeafStatic, { key: i, components, decorations: ds, editor, leaf: child } ); })); } function PlateStatic(props) { const { className, components, editor, value, ...rest } = props; if (value) { editor.children = value; } const decorate = pipeDecorate(editor); let afterEditable = null; let beforeEditable = null; editor.pluginList.forEach((plugin) => { const { render: { afterEditable: AfterEditable, beforeEditable: BeforeEditable } } = plugin; if (AfterEditable) { afterEditable = /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, afterEditable, /* @__PURE__ */ import_react7.default.createElement(AfterEditable, null)); } if (BeforeEditable) { beforeEditable = /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, beforeEditable, /* @__PURE__ */ import_react7.default.createElement(BeforeEditable, null)); } }); const content = /* @__PURE__ */ import_react7.default.createElement( "div", { className: (0, import_clsx5.default)("slate-editor", className), "data-slate-editor": true, "data-slate-node": "value", ...rest }, /* @__PURE__ */ import_react7.default.createElement( Children, { components, decorate, decorations: [], editor }, editor.children ) ); let aboveEditable = /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, beforeEditable, content, afterEditable); editor.pluginList.forEach((plugin) => { const { render: { aboveEditable: AboveEditable } } = plugin; if (AboveEditable) { aboveEditable = /* @__PURE__ */ import_react7.default.createElement(AboveEditable, null, aboveEditable); } }); return aboveEditable; } // src/lib/static/serializeHtml.tsx var getReactDOMServer = async () => { const Reac