UNPKG

@lexical/react

Version:

This package provides Lexical components and hooks for React applications.

10 lines (8 loc) 2.32 kB
/** * 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 t}from"@lexical/react/LexicalComposerContext";import{HeadingNode as e,$isHeadingNode as n}from"@lexical/rich-text";import{$getNextRightPreorderNode as r}from"@lexical/utils";import{$getRoot as o,$isElementNode as i,$getNodeByKey as s,TextNode as f}from"lexical";import{useState as c,useEffect as l}from"react";function u(t){return[t.getKey(),t.getTextContent(),t.getTag()]}function a(t,e,n){if(null===e)return n;const r=u(e);let o=[];if(null===t){if(n.length>0&&n[0][0]===e.__key)return n;o=[r,...n]}else for(let i=0;i<n.length;i++){const s=n[i][0];if(o.push(n[i]),s===t.getKey()&&s!==e.getKey()){if(i+1<n.length&&n[i+1][0]===e.__key)return n;o.push(r)}}return o}function g(t,e){const n=[];for(const r of e)r[0]!==t&&n.push(r);return n}function d(t,e){const n=[];for(const r of e)r[0]===t.getKey()?n.push(u(t)):n.push(r);return n}function p(t,e,n){const r=[],o=u(e);t||r.push(o);for(const i of n)i[0]!==e.getKey()&&(r.push(i),t&&i[0]===t.getKey()&&r.push(o));return r}function h(t){let e=r(t);for(;null!==e&&!n(e);)e=r(e);return e}function m({children:r}){const[u,m]=c([]),[y]=t();return l((()=>{let t=[];y.getEditorState().read((()=>{const e=r=>{for(const o of r.getChildren())n(o)?t.push([o.getKey(),o.getTextContent(),o.getTag()]):i(o)&&e(o)};e(o()),m(t)}));const r=y.registerUpdateListener((({editorState:e,dirtyElements:r})=>{e.read((()=>{const e=r=>{for(const o of r.getChildren())if(n(o)){const e=h(o);t=p(e,o,t),m(t)}else i(o)&&e(o)};o().getChildren().forEach((t=>{i(t)&&r.get(t.__key)&&e(t)}))}))})),c=y.registerMutationListener(e,(e=>{y.getEditorState().read((()=>{for(const[n,r]of e)if("created"===r){const e=s(n);if(null!==e){const n=h(e);t=a(n,e,t)}}else if("destroyed"===r)t=g(n,t);else if("updated"===r){const e=s(n);if(null!==e){const n=h(e);t=p(n,e,t)}}m(t)}))}),{skipInitialization:!0}),l=y.registerMutationListener(f,(e=>{y.getEditorState().read((()=>{for(const[r,o]of e)if("updated"===o){const e=s(r);if(null!==e){const r=e.getParentOrThrow();n(r)&&(t=d(r,t),m(t))}}}))}),{skipInitialization:!0});return()=>{c(),l(),r()}}),[y]),r(u,y)}export{m as TableOfContentsPlugin};