@lexical/react
Version:
This package provides Lexical components and hooks for React applications.
10 lines (8 loc) • 907 B
JavaScript
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import{useLexicalComposerContext as e}from"@lexical/react/LexicalComposerContext";import{$getSelection as t,$isNodeSelection as r,$createNodeSelection as o,$setSelection as n,$getNodeByKey as c}from"lexical";import{useState as a,useEffect as i,useCallback as l}from"react";function d(e,t){return e.getEditorState().read(()=>{const e=c(t);return null!==e&&e.isSelected()})}function u(c){const[u]=e(),[p,s]=a(()=>d(u,c));i(()=>{let e=!0;const t=u.registerUpdateListener(()=>{e&&s(d(u,c))});return()=>{e=!1,t()}},[u,c]);return[p,l(e=>{u.update(()=>{let a=t();r(a)||(a=o(),n(a)),r(a)&&(e?a.add(c):a.delete(c))})},[u,c]),l(()=>{u.update(()=>{const e=t();r(e)&&e.clear()})},[u])]}export{u as useLexicalNodeSelection};