lexical-vue
Version:
An extensible Vue 3 web text-editor based on Lexical.
84 lines (83 loc) • 3.61 kB
JavaScript
import { defineComponent, inject, onMounted, provide, renderSlot } from "vue";
import { CAN_USE_DOM } from "@lexical/utils";
import { $createParagraphNode, $getRoot, $getSelection, HISTORY_MERGE_TAG, createEditor } from "lexical";
import tiny_invariant from "tiny-invariant";
const lexicalEditorKey = Symbol('LexicalEditor');
const LexicalComposer = (()=>{
const __vine = defineComponent({
name: 'LexicalComposer',
props: {
initialConfig: {
required: true
}
},
emits: [
'error'
],
setup (__props, param) {
let { emit: __emit, expose: __expose } = param;
const emit = __emit;
__expose();
const props = __props;
const HISTORY_MERGE_OPTIONS = {
tag: HISTORY_MERGE_TAG
};
const { theme, namespace, nodes, onError, editorState: initialEditorState, html } = props.initialConfig;
const editor = createEditor({
editable: props.initialConfig.editable,
html,
namespace,
nodes,
theme,
onError (error) {
emit('error', error, editor);
null == onError || onError(error, editor);
}
});
initializeEditor(editor, initialEditorState);
function initializeEditor(editor, initialEditorState) {
if (null === initialEditorState) return;
if (void 0 === initialEditorState) editor.update(()=>{
const root = $getRoot();
if (root.isEmpty()) {
const paragraph = $createParagraphNode();
root.append(paragraph);
const activeElement = CAN_USE_DOM ? document.activeElement : null;
if (null !== $getSelection() || null !== activeElement && activeElement === editor.getRootElement()) paragraph.select();
}
}, HISTORY_MERGE_OPTIONS);
else if (null !== initialEditorState) switch(typeof initialEditorState){
case 'string':
{
const parsedEditorState = editor.parseEditorState(initialEditorState);
editor.setEditorState(parsedEditorState, HISTORY_MERGE_OPTIONS);
break;
}
case 'object':
editor.setEditorState(initialEditorState, HISTORY_MERGE_OPTIONS);
break;
case 'function':
editor.update(()=>{
const root = $getRoot();
if (root.isEmpty()) initialEditorState(editor);
}, HISTORY_MERGE_OPTIONS);
break;
}
}
provide(lexicalEditorKey, editor);
onMounted(()=>{
const isEditable = props.initialConfig.editable;
editor.setEditable(void 0 !== isEditable ? isEditable : true);
});
return (_ctx, _cache)=>renderSlot(_ctx.$slots, "default");
}
});
__vine.__vue_vine = true;
return __vine;
})();
function useLexicalComposer() {
const editor = inject(lexicalEditorKey, null);
if (!editor) tiny_invariant(false, 'useLexicalComposer: cannot find a LexicalComposer');
return editor;
}
export { LexicalComposer, useLexicalComposer };