File size: 1,281 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import type { DataTType } from '@react-page/editor';
import type { NodeEntry } from 'slate';
import { Editor } from 'slate';
import { useSlate } from 'slate-react';
import type { SlatePluginDefinition } from '../types/slatePluginDefinitions';
export const getCurrentNodeWithPlugin = <T extends DataTType>(
editor: Editor,
plugin: SlatePluginDefinition<T>
): NodeEntry | null => {
if (plugin.pluginType === 'custom') {
return null;
}
const match =
plugin.pluginType === 'component'
? plugin.object === 'mark'
? (elem: any) => Boolean(elem[plugin.type])
: (elem: any) => elem.type === plugin.type
: plugin.pluginType === 'data'
? // search for data
({ data }: any) => {
const matches = plugin.dataMatches(data as T);
return matches;
}
: null;
if (!match) {
return null;
}
try {
const [matchingNode] = Editor.nodes(editor, {
match: match,
mode: 'lowest', // FIXME: whats the best value?
});
return matchingNode;
} catch (e) {
// seems to crash sometimes on redu
return null;
}
};
export default <T extends DataTType>(plugin: SlatePluginDefinition<T>) => {
const editor = useSlate();
return getCurrentNodeWithPlugin(editor, plugin);
};
|