@lexical/react
Version:
This package provides Lexical components and hooks for React applications.
10 lines (8 loc) • 957 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,$getNodeByKey as n,$createNodeSelection as l,$setSelection as o}from"lexical";import{useState as c,useEffect as i,useCallback as a}from"react";function u(e,t){return e.read("latest",()=>{const e=n(t);return null!==e&&e.isSelected()})}function s(s){const[d]=e(),[p,f]=c(()=>u(d,s));i(()=>{let e=!0;const t=d.registerUpdateListener(()=>{e&&f(u(d,s))});return()=>{e=!1,t()}},[d,s]);return[p,a(e=>{d.update(()=>{let c=t();if(!r(c)){const t=e?null:n(s);if(null!==t&&!t.isSelected())return;c=l(),o(c)}r(c)&&(e?c.add(s):c.delete(s))})},[d,s]),a(()=>{d.update(()=>{const e=t();r(e)&&e.clear()})},[d])]}export{s as useLexicalNodeSelection};