UNPKG

@lexical/react

Version:

This package provides Lexical components and hooks for React applications.

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