UNPKG

lexical-vue

Version:

An extensible Vue 3 web text-editor based on Lexical.

44 lines (43 loc) 1.56 kB
import { $createNodeSelection, $getNodeByKey, $getSelection, $isNodeSelection, $setSelection } from "lexical"; import { readonly, ref, toValue, watchEffect } from "vue"; import { useLexicalComposer } from "./LexicalComposer.vine.js"; function isNodeSelected(editor, key) { return editor.getEditorState().read(()=>{ const node = $getNodeByKey(key); if (null === node) return false; return node.isSelected(); }); } function useLexicalNodeSelection(key) { const editor = useLexicalComposer(); const isSelected = ref(isNodeSelected(editor, toValue(key))); watchEffect((onInvalidate)=>{ const unregister = editor.registerUpdateListener(()=>{ isSelected.value = isNodeSelected(editor, toValue(key)); }); onInvalidate(unregister); }); const setSelected = (selected)=>{ editor.update(()=>{ let selection = $getSelection(); if (!$isNodeSelection(selection)) { selection = $createNodeSelection(); $setSelection(selection); } if ($isNodeSelection(selection)) if (selected) selection.add(toValue(key)); else selection.delete(toValue(key)); }); }; const clearSelection = ()=>{ editor.update(()=>{ const selection = $getSelection(); if ($isNodeSelection(selection)) selection.clear(); }); }; return [ readonly(isSelected), setSelected, clearSelection ]; } export { useLexicalNodeSelection };