@lexical/react 0.1.6 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/DEPRECATED_useLexical.dev.js +49 -0
  2. package/DEPRECATED_useLexical.js +9 -2
  3. package/DEPRECATED_useLexical.prod.js +7 -0
  4. package/DEPRECATED_useLexicalAutoFormatter.dev.js +729 -0
  5. package/DEPRECATED_useLexicalAutoFormatter.js +9 -11
  6. package/DEPRECATED_useLexicalAutoFormatter.prod.js +26 -0
  7. package/DEPRECATED_useLexicalCanShowPlaceholder.dev.js +136 -0
  8. package/DEPRECATED_useLexicalCanShowPlaceholder.js +9 -3
  9. package/DEPRECATED_useLexicalCanShowPlaceholder.prod.js +8 -0
  10. package/DEPRECATED_useLexicalCharacterLimit.dev.js +293 -0
  11. package/DEPRECATED_useLexicalCharacterLimit.js +9 -9
  12. package/DEPRECATED_useLexicalCharacterLimit.prod.js +14 -0
  13. package/DEPRECATED_useLexicalDecorators.dev.js +82 -0
  14. package/DEPRECATED_useLexicalDecorators.js +9 -2
  15. package/DEPRECATED_useLexicalDecorators.prod.js +8 -0
  16. package/DEPRECATED_useLexicalEditor.dev.js +28 -0
  17. package/DEPRECATED_useLexicalEditor.js +9 -1
  18. package/DEPRECATED_useLexicalEditor.prod.js +7 -0
  19. package/DEPRECATED_useLexicalEditorEvents.dev.js +96 -0
  20. package/DEPRECATED_useLexicalEditorEvents.js +9 -2
  21. package/DEPRECATED_useLexicalEditorEvents.prod.js +8 -0
  22. package/DEPRECATED_useLexicalHistory.dev.js +342 -0
  23. package/DEPRECATED_useLexicalHistory.js +9 -7
  24. package/DEPRECATED_useLexicalHistory.prod.js +13 -0
  25. package/DEPRECATED_useLexicalList.dev.js +64 -0
  26. package/DEPRECATED_useLexicalList.js +9 -12
  27. package/DEPRECATED_useLexicalList.prod.js +7 -0
  28. package/DEPRECATED_useLexicalPlainText.dev.js +761 -0
  29. package/DEPRECATED_useLexicalPlainText.js +9 -17
  30. package/DEPRECATED_useLexicalPlainText.prod.js +21 -0
  31. package/DEPRECATED_useLexicalRichText.dev.js +1197 -0
  32. package/DEPRECATED_useLexicalRichText.js +9 -31
  33. package/DEPRECATED_useLexicalRichText.prod.js +32 -0
  34. package/LexicalAutoFormatterPlugin.dev.js +732 -0
  35. package/LexicalAutoFormatterPlugin.js +9 -12
  36. package/LexicalAutoFormatterPlugin.prod.js +26 -0
  37. package/LexicalAutoLinkPlugin.dev.js +227 -0
  38. package/LexicalAutoLinkPlugin.js +9 -5
  39. package/LexicalAutoLinkPlugin.prod.js +12 -0
  40. package/LexicalBootstrapPlugin.dev.js +122 -0
  41. package/LexicalBootstrapPlugin.js +9 -0
  42. package/LexicalBootstrapPlugin.prod.js +8 -0
  43. package/LexicalCharacterLimitPlugin.dev.js +351 -0
  44. package/LexicalCharacterLimitPlugin.js +9 -10
  45. package/LexicalCharacterLimitPlugin.prod.js +14 -0
  46. package/LexicalCollaborationPlugin.dev.js +220 -0
  47. package/LexicalCollaborationPlugin.js +9 -8
  48. package/LexicalCollaborationPlugin.prod.js +13 -0
  49. package/LexicalComposer.dev.js +71 -0
  50. package/LexicalComposer.js +9 -2
  51. package/LexicalComposer.prod.js +8 -0
  52. package/LexicalComposerContext.dev.js +53 -0
  53. package/LexicalComposerContext.js +9 -1
  54. package/LexicalComposerContext.prod.js +7 -0
  55. package/LexicalContentEditable.dev.js +71 -0
  56. package/LexicalContentEditable.js +9 -3
  57. package/LexicalContentEditable.prod.js +9 -0
  58. package/LexicalHashtagPlugin.dev.js +152 -0
  59. package/LexicalHashtagPlugin.js +9 -4
  60. package/LexicalHashtagPlugin.prod.js +10 -0
  61. package/LexicalHistoryPlugin.dev.js +347 -0
  62. package/LexicalHistoryPlugin.js +9 -7
  63. package/LexicalHistoryPlugin.prod.js +13 -0
  64. package/LexicalHorizontalRuleNode.dev.js +66 -0
  65. package/LexicalHorizontalRuleNode.js +9 -0
  66. package/LexicalHorizontalRuleNode.prod.js +8 -0
  67. package/LexicalLinkPlugin.dev.js +136 -0
  68. package/LexicalLinkPlugin.js +9 -3
  69. package/LexicalLinkPlugin.prod.js +9 -0
  70. package/LexicalListPlugin.dev.js +67 -0
  71. package/LexicalListPlugin.js +9 -12
  72. package/LexicalListPlugin.prod.js +8 -0
  73. package/LexicalNestedComposer.dev.js +60 -0
  74. package/LexicalNestedComposer.js +9 -1
  75. package/LexicalNestedComposer.prod.js +8 -0
  76. package/LexicalOnChangePlugin.dev.js +57 -0
  77. package/LexicalOnChangePlugin.js +9 -1
  78. package/LexicalOnChangePlugin.prod.js +7 -0
  79. package/LexicalPlainTextPlugin.dev.js +589 -0
  80. package/LexicalPlainTextPlugin.js +9 -13
  81. package/LexicalPlainTextPlugin.prod.js +18 -0
  82. package/LexicalRichTextPlugin.dev.js +1025 -0
  83. package/LexicalRichTextPlugin.js +9 -27
  84. package/LexicalRichTextPlugin.prod.js +28 -0
  85. package/LexicalTablePlugin.dev.js +77 -0
  86. package/LexicalTablePlugin.js +9 -3
  87. package/LexicalTablePlugin.prod.js +9 -0
  88. package/LexicalTreeView.dev.js +348 -0
  89. package/LexicalTreeView.js +9 -12
  90. package/LexicalTreeView.prod.js +20 -0
  91. package/README.md +10 -5
  92. package/package.json +5 -4
  93. package/useLexicalDecoratorMap.dev.js +83 -0
  94. package/useLexicalDecoratorMap.js +9 -2
  95. package/useLexicalDecoratorMap.prod.js +8 -0
  96. package/useLexicalIsTextContentEmpty.dev.js +84 -0
  97. package/useLexicalIsTextContentEmpty.js +9 -2
  98. package/useLexicalIsTextContentEmpty.prod.js +8 -0
  99. package/useLexicalNodeSelection.dev.js +70 -0
  100. package/useLexicalNodeSelection.js +9 -0
  101. package/useLexicalNodeSelection.prod.js +8 -0
  102. package/withSubscriptions.dev.js +23 -0
  103. package/withSubscriptions.js +9 -1
  104. package/withSubscriptions.prod.js +7 -0
  105. package/LexicalHorizontalRulePlugin.js +0 -1
@@ -1,27 +1,9 @@
1
- 'use strict';var g=require("react"),v=require("@lexical/react/LexicalComposerContext"),x=require("lexical"),z=require("lexical/HeadingNode"),A=require("lexical/ListNode"),B=require("lexical/QuoteNode"),C=require("lexical/CodeNode"),D=require("lexical/ListItemNode"),E=require("lexical/LinkNode"),F=require("@lexical/react/withSubscriptions"),G=require("react-dom");
2
- function H(a){g.useEffect(()=>{const c=e=>{var f=a.getRootElement();if(document.activeElement===f&&(f=e.data,"string"===typeof f)){try{var d=JSON.parse(f)}catch(b){return}if(d&&"nuanria_messaging"===d.protocol&&"request"===d.type&&(d=d.payload)&&"makeChanges"===d.functionId&&(d=d.args)){const [b,k,h,l,q]=d;a.update(()=>{x.$log("useLexicalDragonSupport");const m=x.$getSelection();if(null!==m){var n=m.anchor;let r=n.getNode(),p=0,t=0;x.$isTextNode(r)&&0<=b&&0<=k&&(p=b,t=b+k,m.setTextNodeRange(r,p,r,
3
- t));if(p!==t||""!==h)m.insertRawText(h),r=n.getNode();x.$isTextNode(r)&&(p=l,t=l+q,n=r.getTextContentSize(),p=p>n?n:p,t=t>n?n:t,m.setTextNodeRange(r,p,r,t));e.stopImmediatePropagation()}})}}};window.addEventListener("message",c,!0);return()=>{window.removeEventListener("message",c,!0)}},[a])}
4
- function I(a){a=a.getLatest();const c=a.constructor.clone(a);c.__parent=a.__parent;x.$isElementNode(a)&&x.$isElementNode(c)?(c.__children=Array.from(a.__children),c.__format=a.__format,c.__indent=a.__indent,c.__dir=a.__dir):x.$isTextNode(a)&&x.$isTextNode(c)?(c.__format=a.__format,c.__style=a.__style,c.__mode=a.__mode,c.__detail=a.__detail):x.$isDecoratorNode(a)&&x.$isDecoratorNode(c)&&(c.__state=a.__state);return c}
5
- function J(a,c,e,f,d){for(var b=c;null!==a;){for(c=a.getParent();null!==c&&c.excludeFromCopy();)c=c.getParent();if(null===c)break;if(!x.$isElementNode(a)||!a.excludeFromCopy()){const k=a.getKey();let h=d.get(k);const l=void 0===h;l&&(h=I(a),d.set(k,h));!x.$isTextNode(h)||h.isSegmented()||h.isToken()?x.$isElementNode(h)&&(h.__children=h.__children.slice(e?b:0,e?void 0:b+1)):h.__text=h.__text.slice(e?b:0,e?void 0:b);if(x.$isRootNode(c)){l&&f.push(k);break}}b=d.get(c.getKey());b=x.$isElementNode(b)?
6
- b.__children.indexOf(a.getKey()):a.getIndexWithinParent();a=c}}
7
- const K={ul:()=>({node:A.$createListNode("ul")}),ol:()=>({node:A.$createListNode("ol")}),li:()=>({node:D.$createListItemNode()}),h1:()=>({node:z.$createHeadingNode("h1")}),h2:()=>({node:z.$createHeadingNode("h2")}),h3:()=>({node:z.$createHeadingNode("h3")}),h4:()=>({node:z.$createHeadingNode("h4")}),h5:()=>({node:z.$createHeadingNode("h5")}),p:()=>({node:x.$createParagraphNode()}),br:()=>({node:x.$createLineBreakNode()}),a:a=>({node:a instanceof HTMLAnchorElement?E.$createLinkNode(a.href):x.$createTextNode(a.textContent)}),
8
- u:()=>({node:null,forChild:a=>{x.$isTextNode(a)&&a.toggleFormat("underline")}}),b:a=>{const c="normal"===a.style.fontWeight;return{node:null,forChild:e=>{x.$isTextNode(e)&&!c&&e.toggleFormat("bold")}}},strong:()=>({node:null,forChild:a=>{x.$isTextNode(a)&&a.toggleFormat("bold")}}),i:()=>({node:null,forChild:a=>{x.$isTextNode(a)&&a.toggleFormat("italic")}}),em:()=>({node:null,forChild:a=>{x.$isTextNode(a)&&a.toggleFormat("italic")}}),td:a=>{const c=a.classList.contains("js-file-line");return{node:null,
9
- after:e=>{c&&a.parentNode&&a.parentNode.nextSibling&&e.push(x.$createLineBreakNode());return e}}},table:a=>({node:a.classList.contains("js-file-line-container")?C.$createCodeNode():null}),span:a=>{const c="700"===a.style.fontWeight;return{node:null,forChild:e=>{x.$isTextNode(e)&&c&&e.toggleFormat("bold")}}},"#text":a=>({node:x.$createTextNode(a.textContent)}),pre:()=>({node:C.$createCodeNode()}),div:a=>({node:null!==a.style.fontFamily.match("monospace")?C.$createCodeNode():null,after:c=>{const e=
10
- a.parentNode;null!=e&&a!==e.lastChild&&c.push(x.$createLineBreakNode());return c}})};
11
- function L(a,c,e,f=new Map){let d=[],b=null;var k=a.nodeName.toLowerCase(),h=(e._config.htmlTransforms||{})[k]||c[k],l=h?h(a):null;h=null;if(null!==l){h=l.after;b=l.node;if(null!==b){d.push(b);const q=Array.from(f.values());for(let m=0;m<q.length;m++)q[m](b)}null!=l.forChild&&f.set(k,l.forChild)}a=a.childNodes;k=[];for(l=0;l<a.length;l++)k.push(...L(a[l],c,e,f));null!=h&&(k=h(k));null==b?d=d.concat(k):x.$isElementNode(b)&&b.append(...k);return d}
12
- function M(a,c,e){var f=a.getData("application/x-lexical-editor");if(f){var d=e._config.namespace;try{const l=JSON.parse(f);if(l.namespace===d){const {range:q,nodeMap:m}=l.state;var b=new Map(m);f=[];for(d=0;d<q.length;d++){var k=b.get(q[d]);if(void 0!==k){var h=x.$createNodeFromParse(k,b);f.push(h)}}c.insertNodes(f);return}}catch(l){}}if(b=a.getData("text/html")){b=(new DOMParser).parseFromString(b,"text/html");a=[];b=b.body?Array.from(b.body.childNodes):[];k=b.length;for(h=0;h<k;h++)f=L(b[h],K,
13
- e),null!==f&&(a=a.concat(f));e=a;a=[];b=null;for(k=0;k<e.length;k++)h=e[k],!x.$isElementNode(h)||h.isInline()?(null===b&&(b=x.$createParagraphNode(),a.push(b)),null!==b&&b.append(h)):(a.push(h),b=null);c.insertNodes(a)}else e=a.getData("text/plain"),null!=e&&c.insertRawText(e)}
14
- function N(a,c){var e=a.focus;a=e.offset;"element"===e.type?c=e.getNode().getChildAtIndex(c?a-1:a):(e=e.getNode(),c=c&&0===a||!c&&a===e.getTextContentSize()?c?e.getPreviousSibling():e.getNextSibling():null);return x.$isDecoratorNode(c)}function O(a,c){a.preventDefault();c.update(()=>{x.$log("onPasteForRichText");const e=x.$getSelection(),f=a.clipboardData;null!=f&&null!==e&&M(f,e,c)})}
15
- function P(a,c){Q(a,c);c.update(()=>{x.$log("onCutForRichText");const e=x.$getSelection();null!==e&&e.removeText()})}
16
- function Q(a,c){a.preventDefault();c.update(()=>{x.$log("onCopyForRichText");const e=a.clipboardData;var f=x.$getSelection();if(null!==f&&null!=e){var d=window.getSelection();if(!d.isCollapsed){var b=d.getRangeAt(0);b&&(d=document.createElement("div"),b=b.cloneContents(),d.appendChild(b),e.setData("text/html",d.innerHTML));e.setData("text/plain",f.getTextContent());d=c._config.namespace;b=e.setData;var k=JSON,h=k.stringify;{var l=f.anchor,q=f.focus;var m=l.getCharacterOffset();const y=q.getCharacterOffset();
17
- var n=l.getNode(),r=q.getNode(),p=n.getParentOrThrow();if(n===r&&x.$isTextNode(n)&&(p.canBeEmpty()||1<p.getChildrenSize()))f=I(n),n=y>m,f.__text=f.__text.slice(n?m:y,n?y:m),m=f.getKey(),m={range:[m],nodeMap:[[m,f]]};else if(f=f.getNodes(),0===f.length)m={range:[],nodeMap:[]};else{n=f.length;r=f[0];p=r.getParent();if(null!==p&&!p.canBeEmpty()){var t=p.__children;if(t.length===n){var u=!0;for(var w=0;w<t.length;w++)if(t[w]!==f[w].__key){u=!1;break}u&&(n++,f.push(p))}}p=f[n-1];l=l.isBefore(q);q=new Map;
18
- t=[];J(r,l?m:y,!0,t,q);for(r=0;r<n;r++)if(u=f[r],w=u.getKey(),!(q.has(w)||x.$isElementNode(u)&&u.excludeFromCopy())){const U=I(u);x.$isRootNode(u.getParent())&&t.push(u.getKey());q.set(w,U)}J(p,l?y:m,!1,t,q);m={range:t,nodeMap:Array.from(q.entries())}}}b.call(e,"application/x-lexical-editor",h.call(k,{namespace:d,state:m}))}}})}var R="undefined"!==typeof window&&"undefined"!==typeof window.document&&"undefined"!==typeof window.document.createElement?g.useLayoutEffect:g.useEffect;
19
- function S(a,c){const e=x.$createParagraphNode();a.append(e);a=document.activeElement;(null!==x.$getSelection()||null!==a&&a===c.getRootElement())&&e.select()}function T(a){a.update(()=>{x.$log("initEditor");const c=x.$getRoot();null===c.getFirstChild()&&S(c,a)})}function V(a,c){a.update(()=>{x.$log("clearEditor");const e=x.$getRoot();e.clear();S(e,a)},{onUpdate:c})}
20
- function W(a,c){R(()=>{const e=F(a.registerNodes([z.HeadingNode,A.ListNode,B.QuoteNode,C.CodeNode,D.ListItemNode]),a.addListener("command",(f,d)=>{var b=x.$getSelection();if(null===b)return!1;switch(f){case "deleteCharacter":return b.deleteCharacter(d),!0;case "deleteWord":return b.deleteWord(d),!0;case "deleteLine":return b.deleteLine(d),!0;case "insertText":return"string"===typeof d?b.insertText(d):(f=d.dataTransfer,null!=f?M(f,b,a):(d=d.data)&&b.insertText(d)),!0;case "removeText":return b.removeText(),
21
- !0;case "formatText":return b.formatText(d),!0;case "formatElement":return b=b.anchor.getNode(),(x.$isElementNode(b)?b:b.getParentOrThrow()).setFormat(d),!0;case "insertLineBreak":return b.insertLineBreak(d),!0;case "insertParagraph":return b.insertParagraph(),!0;case "indentContent":return b=b.anchor,b="element"===b.type?b.getNode():b.getNode().getParentOrThrow(),b.canInsertTab()?a.execCommand("insertText","\t"):10!==b.getIndent()&&b.setIndent(b.getIndent()+1),!0;case "outdentContent":return b=b.anchor,
22
- d=b.getNode(),f="element"===b.type?b.getNode():b.getNode().getParentOrThrow(),f.canInsertTab()?"\t"===d.getTextContent()[b.offset-1]&&a.execCommand("deleteCharacter",!0):0!==f.getIndent()&&f.setIndent(f.getIndent()-1),!0;case "keyArrowLeft":f=d.shiftKey;if(N(b,!0))return d.preventDefault(),d=f,f="rtl"===b.anchor.getNode().getParentOrThrow().getDirection(),b.modify(d?"extend":"move",!f,"character"),!0;break;case "keyArrowRight":f=d.shiftKey;if(N(b,!1))return d.preventDefault(),d=f,f="rtl"===b.anchor.getNode().getParentOrThrow().getDirection(),
23
- b.modify(d?"extend":"move",f,"character"),!0;break;case "keyBackspace":return d.preventDefault(),{anchor:d}=b,b.isCollapsed()&&0===d.offset&&0<("element"===d.type?d.getNode():d.getNode().getParentOrThrow()).getIndent()?a.execCommand("outdentContent"):a.execCommand("deleteCharacter",!0);case "keyDelete":return d.preventDefault(),a.execCommand("deleteCharacter",!1);case "keyEnter":return d.preventDefault(),d.shiftKey?a.execCommand("insertLineBreak"):a.execCommand("insertParagraph");case "keyTab":return d.preventDefault(),
24
- a.execCommand(d.shiftKey?"outdentContent":"indentContent");case "keyEscape":return a.blur(),!0;case "clearEditor":V(a);break;case "copy":return Q(d,a),!0;case "cut":return P(d,a),!0;case "paste":return O(d,a),!0;case "drop":case "dragstart":return d.preventDefault(),!0}return!1},0));c&&T(a);return e},[a,c]);H(a)}
25
- function X(a){const [c,e]=g.useState(()=>a.getDecorators());R(()=>a.addListener("decorator",f=>{G.flushSync(()=>{e(f)})}),[a]);return g.useMemo(()=>{const f=[],d=Object.keys(c);for(let k=0;k<d.length;k++){var b=d[k];const h=c[b];b=a.getElementByKey(b);null!==b&&f.push(G.createPortal(h,b))}return f},[c,a])}function Y(a,c=!0){if(a)return!1;a=x.$getRoot().getTextContent();c&&(a=a.trim());return""===a}
26
- function aa(a){if(!Y(a,!1))return!1;a=x.$getRoot().getChildren();const c=a.length;if(1<c)return!1;for(let f=0;f<c;f++){var e=a[f];if(x.$isElementNode(e)){if("paragraph"!==e.__type||0!==e.__indent)return!1;e=e.getChildren();const d=e.length;for(let b=0;b<d;b++)if(!x.$isTextNode(e[f]))return!1}}return!0}function Z(a){return()=>aa(a)}
27
- function ba(a){const [c,e]=g.useState(a.getEditorState().read(Z(a.isComposing())));R(()=>a.addListener("update",({editorState:f})=>{const d=a.isComposing();f=f.read(Z(d));e(f)}),[a]);return c}function ca(a){throw a;}module.exports=function({contentEditable:a,placeholder:c,skipInit:e,onError:f}){const [d]=v.useLexicalComposerContext(),b=ba(d);W(d,!e);e=X(d);R(()=>d.addListener("error",f||ca),[d,f]);return g.createElement(g.Fragment,null,a,b&&c,e)};
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict'
8
+ const LexicalRichTextPlugin = process.env.NODE_ENV === 'development' ? require('./LexicalRichTextPlugin.dev.js') : require('./LexicalRichTextPlugin.prod.js')
9
+ module.exports = LexicalRichTextPlugin;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ var g=require("@lexical/react/LexicalComposerContext"),u=require("react"),y=require("lexical"),z=require("react-dom");function A(a,e=!0){if(a)return!1;a=y.$getRoot().getTextContent();e&&(a=a.trim());return""===a}
8
+ function B(a){if(!A(a,!1))return!1;a=y.$getRoot().getChildren();const e=a.length;if(1<e)return!1;for(let b=0;b<e;b++){var d=a[b];if(y.$isElementNode(d)){if("paragraph"!==d.__type||0!==d.__indent)return!1;d=d.getChildren();const c=d.length;for(let f=0;f<c;f++)if(!y.$isTextNode(d[b]))return!1}}return!0}function C(a){return()=>B(a)}var D="undefined"!==typeof window&&"undefined"!==typeof window.document&&"undefined"!==typeof window.document.createElement?u.useLayoutEffect:u.useEffect;
9
+ function E(a){const [e,d]=u.useState(a.getEditorState().read(C(a.isComposing())));D(()=>a.addListener("update",({editorState:b})=>{const c=a.isComposing();b=b.read(C(c));d(b)}),[a]);return e}function F(a){const [e,d]=u.useState(()=>a.getDecorators());D(()=>a.addListener("decorator",b=>{z.flushSync(()=>{d(b)})}),[a]);return u.useMemo(()=>{const b=[],c=Object.keys(e);for(let k=0;k<c.length;k++){var f=c[k];const h=e[f];f=a.getElementByKey(f);null!==f&&b.push(z.createPortal(h,f))}return b},[e,a])}
10
+ function G(a){a=a.getLatest();const e=a.constructor.clone(a);e.__parent=a.__parent;y.$isElementNode(a)&&y.$isElementNode(e)?(e.__children=Array.from(a.__children),e.__format=a.__format,e.__indent=a.__indent,e.__dir=a.__dir):y.$isTextNode(a)&&y.$isTextNode(e)?(e.__format=a.__format,e.__style=a.__style,e.__mode=a.__mode,e.__detail=a.__detail):y.$isDecoratorNode(a)&&y.$isDecoratorNode(e)&&(e.__state=a.__state);return e}
11
+ function H(a,e,d,b,c){for(var f=e;null!==a;){for(e=a.getParent();null!==e&&e.excludeFromCopy();)e=e.getParent();if(null===e)break;if(!y.$isElementNode(a)||!a.excludeFromCopy()){const k=a.getKey();let h=c.get(k);const l=void 0===h;l&&(h=G(a),c.set(k,h));!y.$isTextNode(h)||h.isSegmented()||h.isToken()?y.$isElementNode(h)&&(h.__children=h.__children.slice(d?f:0,d?void 0:f+1)):h.__text=h.__text.slice(d?f:0,d?void 0:f);if(y.$isRootNode(e)){l&&b.push(k);break}}f=c.get(e.getKey());f=y.$isElementNode(f)?
12
+ f.__children.indexOf(a.getKey()):a.getIndexWithinParent();a=e}}function I(a){a=a.anchor.getNode();return"rtl"===(y.$isRootNode(a)?a:a.getParentOrThrow()).getDirection()}function J(a,e,d){const b=a.getParent();let c=d;null!==b&&(e&&0===d?(c=a.getIndexWithinParent(),a=b):e||d!==a.getChildrenSize()||(c=a.getIndexWithinParent()+1,a=b));return a.getChildAtIndex(e?c-1:c)}
13
+ function K(a,e){const {nodeName:d}=a;e=e._htmlConversions.get(d.toLowerCase());let b=null;void 0!==e&&e.forEach(c=>{c=c(a);null!==c&&(null===b||b.priority<c.priority)&&(b=c)});return null!==b?b.conversion:null}
14
+ function L(a,e,d=new Map){let b=[],c=null;var f=K(a,e),k=f?f(a):null;f=null;if(null!==k){f=k.after;c=k.node;if(null!==c){b.push(c);var h=Array.from(d.values());for(let l=0;l<h.length;l++)h[l](c)}null!=k.forChild&&d.set(a.nodeName,k.forChild)}a=a.childNodes;k=[];for(h=0;h<a.length;h++)k.push(...L(a[h],e,d));null!=f&&(k=f(k));null==c?b=b.concat(k):y.$isElementNode(c)&&c.append(...k);return b}
15
+ function M(a,e,d){var b=a.getData("application/x-lexical-editor");if(b){var c=d._config.namespace;try{const l=JSON.parse(b);if(l.namespace===c){const {range:t,nodeMap:m}=l.state;var f=new Map(m);b=[];for(c=0;c<t.length;c++){var k=f.get(t[c]);if(void 0!==k){var h=y.$createNodeFromParse(k,f);b.push(h)}}e.insertNodes(b);return}}catch(l){}}if(f=a.getData("text/html")){f=(new DOMParser).parseFromString(f,"text/html");a=[];f=f.body?Array.from(f.body.childNodes):[];k=f.length;for(h=0;h<k;h++)b=L(f[h],d),
16
+ null!==b&&(a=a.concat(b));d=a;a=[];f=null;for(k=0;k<d.length;k++)h=d[k],!y.$isElementNode(h)||h.isInline()?(null===f&&(f=y.$createParagraphNode(),a.push(f)),null!==f&&f.append(h)):(a.push(h),f=null);e.insertNodes(a)}else d=a.getData("text/plain"),null!=d&&e.insertRawText(d)}
17
+ function N(a,e){var d=a.focus;a=d.offset;"element"===d.type?(d=d.getNode(),e=J(d,e,a)):(d=d.getNode(),e&&0===a||!e&&a===d.getTextContentSize()?(a=e?d.getPreviousSibling():d.getNextSibling(),e=null===a?J(d.getParentOrThrow(),e,d.getIndexWithinParent()+(e?0:1)):a):e=null);return y.$isDecoratorNode(e)&&!e.isIsolated()}function O(a,e){a.preventDefault();e.update(()=>{const d=y.$getSelection(),b=a.clipboardData;null!=b&&y.$isRangeSelection(d)&&M(b,d,e)})}
18
+ function P(a,e){Q(a,e);e.update(()=>{const d=y.$getSelection();y.$isRangeSelection(d)&&d.removeText()})}
19
+ function Q(a,e){a.preventDefault();e.update(()=>{const d=a.clipboardData;var b=y.$getSelection();if(null!==b&&null!=d){var c=window.getSelection();if(!c.isCollapsed){var f=c.getRangeAt(0);f&&(c=document.createElement("div"),f=f.cloneContents(),c.appendChild(f),d.setData("text/html",c.innerHTML));d.setData("text/plain",b.getTextContent());c=e._config.namespace;f=d.setData;var k=JSON,h=k.stringify;{if(!y.$isRangeSelection(b))throw Error("Minified Lexical error #68; see codes.json for the full message or use the non-minified dev environment for full errors and additional helpful warnings.");
20
+ var l=b.anchor,t=b.focus;var m=l.getCharacterOffset();const x=t.getCharacterOffset();var n=l.getNode(),q=t.getNode(),p=n.getParentOrThrow();if(n===q&&y.$isTextNode(n)&&(p.canBeEmpty()||1<p.getChildrenSize()))b=G(n),n=x>m,b.__text=b.__text.slice(n?m:x,n?x:m),m=b.getKey(),m={nodeMap:[[m,b]],range:[m]};else if(b=b.getNodes(),0===b.length)m={nodeMap:[],range:[]};else{n=b.length;q=b[0];p=q.getParent();if(null!==p&&(!p.canBeEmpty()||y.$isRootNode(p))){var r=p.__children;if(r.length===n){var v=!0;for(var w=
21
+ 0;w<r.length;w++)if(r[w]!==b[w].__key){v=!1;break}v&&(n++,b.push(p))}}p=b[n-1];l=l.isBefore(t);t=new Map;r=[];H(q,l?m:x,!0,r,t);for(q=0;q<n;q++)if(v=b[q],w=v.getKey(),!(t.has(w)||y.$isElementNode(v)&&v.excludeFromCopy())){const R=G(v);y.$isRootNode(v.getParent())&&r.push(v.getKey());t.set(w,R)}H(p,l?x:m,!1,r,t);m={nodeMap:Array.from(t.entries()),range:r}}}f.call(d,"application/x-lexical-editor",h.call(k,{namespace:c,state:m}))}}})}
22
+ function S(a){u.useEffect(()=>{const e=d=>{var b=a.getRootElement();if(document.activeElement===b&&(b=d.data,"string"===typeof b)){try{var c=JSON.parse(b)}catch(f){return}if(c&&"nuanria_messaging"===c.protocol&&"request"===c.type&&(c=c.payload)&&"makeChanges"===c.functionId&&(c=c.args)){const [f,k,h,l,t]=c;a.update(()=>{const m=y.$getSelection();if(y.$isRangeSelection(m)){var n=m.anchor;let q=n.getNode(),p=0,r=0;y.$isTextNode(q)&&0<=f&&0<=k&&(p=f,r=f+k,m.setTextNodeRange(q,p,q,r));if(p!==r||""!==
23
+ h)m.insertRawText(h),q=n.getNode();y.$isTextNode(q)&&(p=l,r=l+t,n=q.getTextContentSize(),p=p>n?n:p,r=r>n?n:r,m.setTextNodeRange(q,p,q,r));d.stopImmediatePropagation()}})}}};window.addEventListener("message",e,!0);return()=>{window.removeEventListener("message",e,!0)}},[a])}
24
+ function T(a){u.useEffect(()=>{const e=a.addListener("command",(d,b)=>{var c=y.$getSelection();if("click"===d&&y.$isNodeSelection(c))return c.clear(),!0;if(!y.$isRangeSelection(c))return!1;switch(d){case "deleteCharacter":return c.deleteCharacter(b),!0;case "deleteWord":return c.deleteWord(b),!0;case "deleteLine":return c.deleteLine(b),!0;case "insertText":return"string"===typeof b?c.insertText(b):(d=b.dataTransfer,null!=d?M(d,c,a):(b=b.data)&&c.insertText(b)),!0;case "removeText":return c.removeText(),
25
+ !0;case "formatText":return c.formatText(b),!0;case "formatElement":return c=c.anchor.getNode(),(y.$isElementNode(c)?c:c.getParentOrThrow()).setFormat(b),!0;case "insertLineBreak":return c.insertLineBreak(b),!0;case "insertParagraph":return c.insertParagraph(),!0;case "indentContent":return c=c.anchor,c="element"===c.type?c.getNode():c.getNode().getParentOrThrow(),c.canInsertTab()?a.execCommand("insertText","\t"):10!==c.getIndent()&&c.setIndent(c.getIndent()+1),!0;case "outdentContent":return c=c.anchor,
26
+ b=c.getNode(),d="element"===c.type?c.getNode():c.getNode().getParentOrThrow(),d.canInsertTab()?"\t"===b.getTextContent()[c.offset-1]&&a.execCommand("deleteCharacter",!0):0!==d.getIndent()&&d.setIndent(d.getIndent()-1),!0;case "keyArrowLeft":d=b.shiftKey;if(N(c,!0))return b.preventDefault(),b=d,d=I(c),c.modify(b?"extend":"move",!d,"character"),!0;break;case "keyArrowRight":d=b.shiftKey;if(N(c,!1))return b.preventDefault(),b=d,d=I(c),c.modify(b?"extend":"move",d,"character"),!0;break;case "keyBackspace":return b.preventDefault(),
27
+ {anchor:b}=c,c.isCollapsed()&&0===b.offset&&0<("element"===b.type?b.getNode():b.getNode().getParentOrThrow()).getIndent()?a.execCommand("outdentContent"):a.execCommand("deleteCharacter",!0);case "keyDelete":return b.preventDefault(),a.execCommand("deleteCharacter",!1);case "keyEnter":return b.preventDefault(),b.shiftKey?a.execCommand("insertLineBreak"):a.execCommand("insertParagraph");case "keyTab":return b.preventDefault(),a.execCommand(b.shiftKey?"outdentContent":"indentContent");case "keyEscape":return a.blur(),
28
+ !0;case "copy":return Q(b,a),!0;case "cut":return P(b,a),!0;case "paste":return O(b,a),!0;case "drop":case "dragstart":return b.preventDefault(),!0}return!1},0);a.execCommand("bootstrapEditor");return e},[a]);S(a)}module.exports=function({contentEditable:a,placeholder:e}){var [d]=g.useLexicalComposerContext();const b=E(d);T(d);d=F(d);return u.createElement(u.Fragment,null,a,b&&e,d)};
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict';
8
+
9
+ var LexicalComposerContext = require('@lexical/react/LexicalComposerContext');
10
+ var table = require('@lexical/table');
11
+ var lexical = require('lexical');
12
+ var react = require('react');
13
+
14
+ /**
15
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
16
+ *
17
+ * This source code is licensed under the MIT license found in the
18
+ * LICENSE file in the root directory of this source tree.
19
+ *
20
+ *
21
+ */
22
+ const EditorPriority = 0;
23
+ function TablePlugin() {
24
+ const [editor] = LexicalComposerContext.useLexicalComposerContext();
25
+ react.useEffect(() => {
26
+ if (!editor.hasNodes([table.TableNode, table.TableCellNode, table.TableRowNode])) {
27
+ {
28
+ throw Error(`TablePlugin: TableNode, TableCellNode or TableRowNode not registered on editor`);
29
+ }
30
+ }
31
+
32
+ return editor.addListener('command', (type, payload) => {
33
+ if (type === 'insertTable') {
34
+ const {
35
+ columns,
36
+ rows
37
+ } = payload;
38
+ const selection = lexical.$getSelection();
39
+
40
+ if (!lexical.$isRangeSelection(selection)) {
41
+ return true;
42
+ }
43
+
44
+ const focus = selection.focus;
45
+ const focusNode = focus.getNode();
46
+
47
+ if (focusNode !== null) {
48
+ const tableNode = table.$createTableNodeWithDimensions(rows, columns);
49
+
50
+ if (lexical.$isRootNode(focusNode)) {
51
+ const target = focusNode.getChildAtIndex(focus.offset);
52
+
53
+ if (target !== null) {
54
+ target.insertBefore(tableNode);
55
+ } else {
56
+ focusNode.append(tableNode);
57
+ }
58
+ } else {
59
+ const topLevelNode = focusNode.getTopLevelElementOrThrow();
60
+ topLevelNode.insertAfter(tableNode);
61
+ }
62
+
63
+ tableNode.insertAfter(lexical.$createParagraphNode());
64
+ const firstCell = tableNode.getFirstChildOrThrow().getFirstChildOrThrow();
65
+ firstCell.select();
66
+ }
67
+
68
+ return true;
69
+ }
70
+
71
+ return false;
72
+ }, EditorPriority);
73
+ }, [editor]);
74
+ return null;
75
+ }
76
+
77
+ module.exports = TablePlugin;
@@ -1,3 +1,9 @@
1
- 'use strict';var c=require("react"),k=require("@lexical/react/LexicalComposerContext"),l=require("lexical"),m=require("lexical/TableNode"),q=require("lexical/TableCellNode"),r=require("lexical/TableRowNode");function t(d,g,h=!0){const a=m.$createTableNode();for(let b=0;b<d;b++){const e=r.$createTableRowNode();for(let f=0;f<g;f++){const n=q.$createTableCellNode(0===b&&h),p=l.$createParagraphNode();p.append(l.$createTextNode());n.append(p);e.append(n)}a.append(e)}return a}
2
- module.exports=function(){const [d]=k.useLexicalComposerContext();c.useEffect(()=>{const g=d.addListener("command",(a,b)=>{if("insertTable"===a){const {columns:e,rows:f}=b;l.$log("handleAddTable");a=l.$getSelection();if(null===a)return!0;a=a.focus.getNode();null!==a&&(a=a.getTopLevelElementOrThrow(),b=t(f,e),a.insertAfter(b),b.insertAfter(l.$createParagraphNode()),b.getFirstChildOrThrow().getFirstChildOrThrow().select());return!0}return!1},0),h=d.registerNodes([m.TableNode,q.TableCellNode,r.TableRowNode]);
3
- return()=>{g();h()}},[d]);return null};
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict'
8
+ const LexicalTablePlugin = process.env.NODE_ENV === 'development' ? require('./LexicalTablePlugin.dev.js') : require('./LexicalTablePlugin.prod.js')
9
+ module.exports = LexicalTablePlugin;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ var d=require("@lexical/react/LexicalComposerContext"),e=require("@lexical/table"),g=require("lexical"),h=require("react");
8
+ module.exports=function(){const [f]=d.useLexicalComposerContext();h.useEffect(()=>{if(!f.hasNodes([e.TableNode,e.TableCellNode,e.TableRowNode]))throw Error("Minified Lexical error #54; see codes.json for the full message or use the non-minified dev environment for full errors and additional helpful warnings.");return f.addListener("command",(a,b)=>{if("insertTable"===a){const {columns:k,rows:l}=b;a=g.$getSelection();if(!g.$isRangeSelection(a))return!0;var c=a.focus;a=c.getNode();null!==a&&(b=e.$createTableNodeWithDimensions(l,
9
+ k),g.$isRootNode(a)?(c=a.getChildAtIndex(c.offset),null!==c?c.insertBefore(b):a.append(b)):a.getTopLevelElementOrThrow().insertAfter(b),b.insertAfter(g.$createParagraphNode()),b.getFirstChildOrThrow().getFirstChildOrThrow().select());return!0}return!1},0)},[f]);return null};
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict';
8
+
9
+ var lexical = require('lexical');
10
+ var React = require('react');
11
+
12
+ /**
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ *
18
+ *
19
+ */
20
+ const NON_SINGLE_WIDTH_CHARS_REPLACEMENT = Object.freeze({
21
+ '\t': '\\t',
22
+ '\n': '\\n'
23
+ });
24
+ const NON_SINGLE_WIDTH_CHARS_REGEX = new RegExp(Object.keys(NON_SINGLE_WIDTH_CHARS_REPLACEMENT).join('|'), 'g');
25
+ const SYMBOLS = Object.freeze({
26
+ ancestorHasNextSibling: '|',
27
+ ancestorIsLastChild: ' ',
28
+ hasNextSibling: '├',
29
+ isLastChild: '└',
30
+ selectedChar: '^',
31
+ selectedLine: '>'
32
+ });
33
+ function TreeView({
34
+ timeTravelButtonClassName,
35
+ timeTravelPanelSliderClassName,
36
+ timeTravelPanelButtonClassName,
37
+ viewClassName,
38
+ timeTravelPanelClassName,
39
+ editor
40
+ }) {
41
+ const [timeStampedEditorStates, setTimeStampedEditorStates] = React.useState([]);
42
+ const [content, setContent] = React.useState('');
43
+ const [timeTravelEnabled, setTimeTravelEnabled] = React.useState(false);
44
+ const playingIndexRef = React.useRef(0);
45
+ const treeElementRef = React.useRef(null);
46
+ const inputRef = React.useRef(null);
47
+ const [isPlaying, setIsPlaying] = React.useState(false);
48
+ React.useEffect(() => {
49
+ setContent(generateContent(editor.getEditorState()));
50
+ return editor.addListener('update', ({
51
+ editorState
52
+ }) => {
53
+ const compositionKey = editor._compositionKey;
54
+ const treeText = generateContent(editor.getEditorState());
55
+ const compositionText = compositionKey !== null && `Composition key: ${compositionKey}`;
56
+ setContent([treeText, compositionText].filter(Boolean).join('\n\n'));
57
+
58
+ if (!timeTravelEnabled) {
59
+ setTimeStampedEditorStates(currentEditorStates => [...currentEditorStates, [Date.now(), editorState]]);
60
+ }
61
+ });
62
+ }, [timeTravelEnabled, editor]);
63
+ const totalEditorStates = timeStampedEditorStates.length;
64
+ React.useEffect(() => {
65
+ if (isPlaying) {
66
+ let timeoutId;
67
+
68
+ const play = () => {
69
+ const currentIndex = playingIndexRef.current;
70
+
71
+ if (currentIndex === totalEditorStates - 1) {
72
+ setIsPlaying(false);
73
+ return;
74
+ }
75
+
76
+ const currentTime = timeStampedEditorStates[currentIndex][0];
77
+ const nextTime = timeStampedEditorStates[currentIndex + 1][0];
78
+ const timeDiff = nextTime - currentTime;
79
+ timeoutId = setTimeout(() => {
80
+ playingIndexRef.current++;
81
+ const index = playingIndexRef.current;
82
+ const input = inputRef.current;
83
+
84
+ if (input !== null) {
85
+ input.value = String(index);
86
+ }
87
+
88
+ editor.setEditorState(timeStampedEditorStates[index][1]);
89
+ play();
90
+ }, timeDiff);
91
+ };
92
+
93
+ play();
94
+ return () => {
95
+ window.clearTimeout(timeoutId);
96
+ };
97
+ }
98
+ }, [timeStampedEditorStates, isPlaying, editor, totalEditorStates]);
99
+ React.useEffect(() => {
100
+ const element = treeElementRef.current;
101
+
102
+ if (element !== null) {
103
+ // $FlowExpectedError[prop-missing] Internal field
104
+ element.__lexicalEditor = editor;
105
+ return () => {
106
+ // $FlowExpectedError[prop-missing] Internal field
107
+ element.__lexicalEditor = null;
108
+ };
109
+ }
110
+ }, [editor]);
111
+ return /*#__PURE__*/React.createElement("div", {
112
+ className: viewClassName
113
+ }, !timeTravelEnabled && totalEditorStates > 2 && /*#__PURE__*/React.createElement("button", {
114
+ onClick: () => {
115
+ const rootElement = editor.getRootElement();
116
+
117
+ if (rootElement !== null) {
118
+ rootElement.contentEditable = 'false';
119
+ playingIndexRef.current = totalEditorStates - 1;
120
+ setTimeTravelEnabled(true);
121
+ }
122
+ },
123
+ className: timeTravelButtonClassName
124
+ }, "Time Travel"), /*#__PURE__*/React.createElement("pre", {
125
+ ref: treeElementRef
126
+ }, content), timeTravelEnabled && /*#__PURE__*/React.createElement("div", {
127
+ className: timeTravelPanelClassName
128
+ }, /*#__PURE__*/React.createElement("button", {
129
+ className: timeTravelPanelButtonClassName,
130
+ onClick: () => {
131
+ setIsPlaying(!isPlaying);
132
+ }
133
+ }, isPlaying ? 'Pause' : 'Play'), /*#__PURE__*/React.createElement("input", {
134
+ className: timeTravelPanelSliderClassName,
135
+ ref: inputRef,
136
+ onChange: event => {
137
+ const editorStateIndex = Number(event.target.value);
138
+ const timeStampedEditorState = timeStampedEditorStates[editorStateIndex];
139
+
140
+ if (timeStampedEditorState) {
141
+ playingIndexRef.current = editorStateIndex;
142
+ editor.setEditorState(timeStampedEditorState[1]);
143
+ }
144
+ },
145
+ type: "range",
146
+ min: "1",
147
+ max: totalEditorStates - 1
148
+ }), /*#__PURE__*/React.createElement("button", {
149
+ className: timeTravelPanelButtonClassName,
150
+ onClick: () => {
151
+ const rootElement = editor.getRootElement();
152
+
153
+ if (rootElement !== null) {
154
+ rootElement.contentEditable = 'true';
155
+ const index = timeStampedEditorStates.length - 1;
156
+ const timeStampedEditorState = timeStampedEditorStates[index];
157
+ editor.setEditorState(timeStampedEditorState[1]);
158
+ const input = inputRef.current;
159
+
160
+ if (input !== null) {
161
+ input.value = String(index);
162
+ }
163
+
164
+ setTimeTravelEnabled(false);
165
+ setIsPlaying(false);
166
+ }
167
+ }
168
+ }, "Exit")));
169
+ }
170
+
171
+ function printRangeSelection(selection) {
172
+ let res = '';
173
+ const formatText = printFormatProperties(selection);
174
+ res += `: range ${formatText !== '' ? `{ ${formatText} }` : ''}`;
175
+ const anchor = selection.anchor;
176
+ const focus = selection.focus;
177
+ const anchorOffset = anchor.offset;
178
+ const focusOffset = focus.offset;
179
+ res += `\n ├ anchor { key: ${anchor.key}, offset: ${anchorOffset === null ? 'null' : anchorOffset}, type: ${anchor.type} }`;
180
+ res += `\n └ focus { key: ${focus.key}, offset: ${focusOffset === null ? 'null' : focusOffset}, type: ${focus.type} }`;
181
+ return res;
182
+ }
183
+
184
+ function printObjectSelection(selection) {
185
+ return `: node\n └ [${Array.from(selection._nodes).join(', ')}]`;
186
+ }
187
+
188
+ function printGridSelection(selection) {
189
+ return `: grid\n └ { grid: ${selection.gridKey}, anchorCell: ${selection.anchorCellKey}, focusCell: ${selection.focusCellKey} }`;
190
+ }
191
+
192
+ function generateContent(editorState) {
193
+ let res = ' root\n';
194
+ const selectionString = editorState.read(() => {
195
+ const selection = lexical.$getSelection();
196
+ visitTree(lexical.$getRoot(), (node, indent) => {
197
+ const nodeKey = node.getKey();
198
+ const nodeKeyDisplay = `(${nodeKey})`;
199
+ const typeDisplay = node.getType() || '';
200
+ const isSelected = node.isSelected();
201
+ res += `${isSelected ? SYMBOLS.selectedLine : ' '} ${indent.join(' ')} ${nodeKeyDisplay} ${typeDisplay} ${printNode(node)}\n`;
202
+ res += printSelectedCharsLine({
203
+ indent,
204
+ isSelected,
205
+ node,
206
+ nodeKeyDisplay,
207
+ selection,
208
+ typeDisplay
209
+ });
210
+ });
211
+ return selection === null ? ': null' : lexical.$isRangeSelection(selection) ? printRangeSelection(selection) : lexical.$isGridSelection(selection) ? printGridSelection(selection) : printObjectSelection(selection);
212
+ });
213
+ return res + '\n selection' + selectionString;
214
+ }
215
+
216
+ function visitTree(currentNode, visitor, indent = []) {
217
+ const childNodes = currentNode.getChildren();
218
+ const childNodesLength = childNodes.length;
219
+ childNodes.forEach((childNode, i) => {
220
+ visitor(childNode, indent.concat(i === childNodesLength - 1 ? SYMBOLS.isLastChild : SYMBOLS.hasNextSibling));
221
+
222
+ if (lexical.$isElementNode(childNode)) {
223
+ visitTree(childNode, visitor, indent.concat(i === childNodesLength - 1 ? SYMBOLS.ancestorIsLastChild : SYMBOLS.ancestorHasNextSibling));
224
+ }
225
+ });
226
+ }
227
+
228
+ function normalize(text) {
229
+ return Object.entries(NON_SINGLE_WIDTH_CHARS_REPLACEMENT).reduce((acc, [key, value]) => acc.replace(new RegExp(key, 'g'), String(value)), text);
230
+ }
231
+
232
+ function printNode(node) {
233
+ if (lexical.$isTextNode(node)) {
234
+ const text = node.getTextContent(true);
235
+ const title = text.length === 0 ? '(empty)' : `"${normalize(text)}"`;
236
+ const properties = printAllProperties(node);
237
+ return [title, properties.length !== 0 ? `{ ${properties} }` : null].filter(Boolean).join(' ').trim();
238
+ }
239
+
240
+ return '';
241
+ }
242
+
243
+ const FORMAT_PREDICATES = [node => node.hasFormat('bold') && 'Bold', node => node.hasFormat('code') && 'Code', node => node.hasFormat('italic') && 'Italic', node => node.hasFormat('strikethrough') && 'Strikethrough', node => node.hasFormat('underline') && 'Underline'];
244
+ const DETAIL_PREDICATES = [node => node.isDirectionless() && 'Directionless', node => node.isUnmergeable() && 'Unmergeable'];
245
+ const MODE_PREDICATES = [node => node.isToken() && 'Token', node => node.isSegmented() && 'Segmented', node => node.isInert() && 'Inert'];
246
+
247
+ function printAllProperties(node) {
248
+ return [printFormatProperties(node), printDetailProperties(node), printModeProperties(node)].filter(Boolean).join(', ');
249
+ }
250
+
251
+ function printDetailProperties(nodeOrSelection) {
252
+ let str = DETAIL_PREDICATES.map(predicate => predicate(nodeOrSelection)).filter(Boolean).join(', ').toLocaleLowerCase();
253
+
254
+ if (str !== '') {
255
+ str = 'detail: ' + str;
256
+ }
257
+
258
+ return str;
259
+ }
260
+
261
+ function printModeProperties(nodeOrSelection) {
262
+ let str = MODE_PREDICATES.map(predicate => predicate(nodeOrSelection)).filter(Boolean).join(', ').toLocaleLowerCase();
263
+
264
+ if (str !== '') {
265
+ str = 'mode: ' + str;
266
+ }
267
+
268
+ return str;
269
+ }
270
+
271
+ function printFormatProperties(nodeOrSelection) {
272
+ let str = FORMAT_PREDICATES.map(predicate => predicate(nodeOrSelection)).filter(Boolean).join(', ').toLocaleLowerCase();
273
+
274
+ if (str !== '') {
275
+ str = 'format: ' + str;
276
+ }
277
+
278
+ return str;
279
+ }
280
+
281
+ function printSelectedCharsLine({
282
+ indent,
283
+ isSelected,
284
+ node,
285
+ nodeKeyDisplay,
286
+ selection,
287
+ typeDisplay
288
+ }) {
289
+ // No selection or node is not selected.
290
+ if (!lexical.$isTextNode(node) || !lexical.$isRangeSelection(selection) || !isSelected || lexical.$isElementNode(node)) {
291
+ return '';
292
+ } // No selected characters.
293
+
294
+
295
+ const anchor = selection.anchor;
296
+ const focus = selection.focus;
297
+
298
+ if (node.getTextContent() === '' || anchor.getNode() === selection.focus.getNode() && anchor.offset === focus.offset) {
299
+ return '';
300
+ }
301
+
302
+ const [start, end] = $getSelectionStartEnd(node, selection);
303
+
304
+ if (start === end) {
305
+ return '';
306
+ }
307
+
308
+ const selectionLastIndent = indent[indent.length - 1] === SYMBOLS.hasNextSibling ? SYMBOLS.ancestorHasNextSibling : SYMBOLS.ancestorIsLastChild;
309
+ const indentionChars = [...indent.slice(0, indent.length - 1), selectionLastIndent];
310
+ const unselectedChars = Array(start).fill(' ');
311
+ const selectedChars = Array(end - start).fill(SYMBOLS.selectedChar);
312
+ const paddingLength = typeDisplay.length + 3; // 2 for the spaces around + 1 for the double quote.
313
+
314
+ const nodePrintSpaces = Array(nodeKeyDisplay.length + paddingLength).fill(' ');
315
+ return [SYMBOLS.selectedLine, indentionChars.join(' '), [...nodePrintSpaces, ...unselectedChars, ...selectedChars].join('')].join(' ') + '\n';
316
+ }
317
+
318
+ function $getSelectionStartEnd(node, selection) {
319
+ const anchor = selection.anchor;
320
+ const focus = selection.focus;
321
+ const textContent = node.getTextContent(true);
322
+ const textLength = textContent.length;
323
+ let start = -1;
324
+ let end = -1; // Only one node is being selected.
325
+
326
+ if (anchor.type === 'text' && focus.type === 'text') {
327
+ const anchorNode = anchor.getNode();
328
+ const focusNode = focus.getNode();
329
+
330
+ if (anchorNode === focusNode && node === anchorNode && anchor.offset !== focus.offset) {
331
+ [start, end] = anchor.offset < focus.offset ? [anchor.offset, focus.offset] : [focus.offset, anchor.offset];
332
+ } else if (node === anchorNode) {
333
+ [start, end] = anchorNode.isBefore(focusNode) ? [anchor.offset, textLength] : [0, anchor.offset];
334
+ } else if (node === focusNode) {
335
+ [start, end] = focusNode.isBefore(anchorNode) ? [focus.offset, textLength] : [0, focus.offset];
336
+ } else {
337
+ // Node is within selection but not the anchor nor focus.
338
+ [start, end] = [0, textLength];
339
+ }
340
+ } // Account for non-single width characters.
341
+
342
+
343
+ const numNonSingleWidthCharBeforeSelection = (textContent.slice(0, start).match(NON_SINGLE_WIDTH_CHARS_REGEX) || []).length;
344
+ const numNonSingleWidthCharInSelection = (textContent.slice(start, end).match(NON_SINGLE_WIDTH_CHARS_REGEX) || []).length;
345
+ return [start + numNonSingleWidthCharBeforeSelection, end + numNonSingleWidthCharBeforeSelection + numNonSingleWidthCharInSelection];
346
+ }
347
+
348
+ module.exports = TreeView;
@@ -1,12 +1,9 @@
1
- 'use strict';var k=require("lexical"),q=require("react");const w=Object.freeze({"\n":"\\n","\t":"\\t"}),D=new RegExp(Object.keys(w).join("|"),"g"),E=Object.freeze({hasNextSibling:"\u251c",isLastChild:"\u2514",ancestorHasNextSibling:"|",ancestorIsLastChild:" ",selectedChar:"^",selectedLine:">"});
2
- function F(a){let b="";const c=G(a),g=a.anchor;a=a.focus;const d=g.offset,e=a.offset;b=b+`${""!==c?" - "+c:""}`+`\n \u251c anchor { key: ${g.key}, offset: ${null===d?"null":d}, type: ${g.type} }`;return b+=`\n \u2514 focus { key: ${a.key}, offset: ${null===e?"null":e}, type: ${a.type} }`}
3
- function H(a){let b=" root\n";a=a.read(()=>{const c=k.$getSelection();J(k.$getRoot(),(g,d)=>{const e=`(${g.getKey()})`,f=g.getType()||"",m=g.isSelected();var v=b,t=m?E.selectedLine:" ",r=d.join(" ");if(k.$isTextNode(g)){var n=g.getTextContent(!0);n=0===n.length?"(empty)":`"${K(n)}"`;const l=L(g);n=[n,0!==l.length?`- ${l}`:null].filter(Boolean).join(" ").trim()}else n="";b=v+`${t} ${r} ${e} ${f} ${n}\n`;b+=M({isSelected:m,indent:d,node:g,nodeKeyDisplay:e,selection:c,typeDisplay:f})});return null===
4
- c?": null":F(c)});return b+"\n selection"+a}function J(a,b,c=[]){a=a.getChildren();const g=a.length;a.forEach((d,e)=>{b(d,c.concat(e===g-1?E.isLastChild:E.hasNextSibling));k.$isElementNode(d)&&J(d,b,c.concat(e===g-1?E.ancestorIsLastChild:E.ancestorHasNextSibling))})}function K(a){return Object.entries(w).reduce((b,[c,g])=>b.replace(new RegExp(c,"g"),String(g)),a)}
5
- const N=[a=>a.hasFormat("bold")&&"Bold",a=>a.hasFormat("code")&&"Code",a=>a.hasFormat("italic")&&"Italic",a=>a.hasFormat("strikethrough")&&"Strikethrough",a=>a.hasFormat("underline")&&"Underline"],O=[a=>a.isToken()&&"Token",a=>a.isSegmented()&&"Segmented",a=>a.isInert()&&"Inert",a=>a.isDirectionless()&&"Directionless",a=>a.isUnmergeable()&&"Unmergeable"];function L(a){return[...N,...O].map(b=>b(a)).filter(Boolean).join(", ")}function G(a){return N.map(b=>b(a)).filter(Boolean).join(", ")}
6
- function M({indent:a,isSelected:b,node:c,nodeKeyDisplay:g,selection:d,typeDisplay:e}){if(!k.$isTextNode(c)||null===d||!b||k.$isElementNode(c))return"";b=d.anchor;var f=d.focus;if(""===c.getTextContent()||b.getNode()===d.focus.getNode()&&b.offset===f.offset)return"";f=d.anchor;const m=d.focus,v=c.getTextContent(!0),t=v.length;b=d=-1;if("text"===f.type&&"text"===m.type){const l=f.getNode(),u=m.getNode();l===u&&c===l&&f.offset!==m.offset?[d,b]=f.offset<m.offset?[f.offset,m.offset]:[m.offset,f.offset]:
7
- c===l?[d,b]=l.isBefore(u)?[f.offset,t]:[0,f.offset]:c===u?[d,b]=u.isBefore(l)?[m.offset,t]:[0,m.offset]:[d,b]=[0,t]}c=(v.slice(0,d).match(D)||[]).length;f=(v.slice(d,b).match(D)||[]).length;const [r,n]=[d+c,b+c+f];if(r===n)return"";c=a[a.length-1]===E.hasNextSibling?E.ancestorHasNextSibling:E.ancestorIsLastChild;a=[...a.slice(0,a.length-1),c];c=Array(r).fill(" ");d=Array(n-r).fill(E.selectedChar);g=Array(g.length+(e.length+3)).fill(" ");return[E.selectedLine,a.join(" "),[...g,...c,...d].join("")].join(" ")+
8
- "\n"}
9
- module.exports=function({timeTravelButtonClassName:a,timeTravelPanelSliderClassName:b,timeTravelPanelButtonClassName:c,viewClassName:g,timeTravelPanelClassName:d,editor:e}){const [f,m]=q.useState([]),[v,t]=q.useState(""),[r,n]=q.useState(!1),l=q.useRef(0),u=q.useRef(null),B=q.useRef(null),[z,C]=q.useState(!1);q.useEffect(()=>{t(H(e.getEditorState()));return e.addListener("update",({editorState:h})=>{const p=e._compositionKey,x=H(e.getEditorState());t([x,null!==p&&`Composition key: ${p}`].filter(Boolean).join("\n\n"));r||
10
- m(A=>[...A,[Date.now(),h]])})},[r,e]);const y=f.length;q.useEffect(()=>{if(z){let h;const p=()=>{const x=l.current;x===y-1?C(!1):h=setTimeout(()=>{l.current++;const A=l.current,I=B.current;null!==I&&(I.value=String(A));e.setEditorState(f[A][1]);p()},f[x+1][0]-f[x][0])};p();return()=>{window.clearTimeout(h)}}},[f,z,e,y]);q.useEffect(()=>{u.current&&(u.current.__lexicalEditor=e)},[e]);return q.createElement("div",{className:g},!r&&2<y&&q.createElement("button",{onClick:()=>{const h=e.getRootElement();
11
- null!==h&&(h.contentEditable="false",l.current=y-1,n(!0))},className:a},"Time Travel"),q.createElement("pre",{ref:u},v),r&&q.createElement("div",{className:d},q.createElement("button",{className:c,onClick:()=>{C(!z)}},z?"Pause":"Play"),q.createElement("input",{className:b,ref:B,onChange:h=>{h=Number(h.target.value);const p=f[h];p&&(l.current=h,e.setEditorState(p[1]))},type:"range",min:"1",max:y-1}),q.createElement("button",{className:c,onClick:()=>{var h=e.getRootElement();if(null!==h){h.contentEditable=
12
- "true";h=f.length-1;e.setEditorState(f[h][1]);const p=B.current;null!==p&&(p.value=String(h));n(!1);C(!1)}}},"Exit")))};
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ 'use strict'
8
+ const LexicalTreeView = process.env.NODE_ENV === 'development' ? require('./LexicalTreeView.dev.js') : require('./LexicalTreeView.prod.js')
9
+ module.exports = LexicalTreeView;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ var k=require("lexical"),q=require("react");const t=Object.freeze({"\t":"\\t","\n":"\\n"}),D=new RegExp(Object.keys(t).join("|"),"g"),E=Object.freeze({ancestorHasNextSibling:"|",ancestorIsLastChild:" ",hasNextSibling:"\u251c",isLastChild:"\u2514",selectedChar:"^",selectedLine:">"});
8
+ function F(a){let b="";const c=G(a),e=a.anchor;a=a.focus;const d=e.offset,f=a.offset;b=b+`: range ${""!==c?`{ ${c} }`:""}`+`\n \u251c anchor { key: ${e.key}, offset: ${null===d?"null":d}, type: ${e.type} }`;return b+=`\n \u2514 focus { key: ${a.key}, offset: ${null===f?"null":f}, type: ${a.type} }`}
9
+ function H(a){let b=" root\n";a=a.read(()=>{const c=k.$getSelection();J(k.$getRoot(),(e,d)=>{const f=`(${e.getKey()})`,g=e.getType()||"",m=e.isSelected();var v=b,u=m?E.selectedLine:" ",r=d.join(" ");if(k.$isTextNode(e)){var l=e.getTextContent(!0);const n=0===l.length?"(empty)":`"${K(l)}"`;l=[G(e),L(e),M(e)].filter(Boolean).join(", ");l=[n,0!==l.length?`{ ${l} }`:null].filter(Boolean).join(" ").trim()}else l="";b=v+`${u} ${r} ${f} ${g} ${l}\n`;b+=N({indent:d,isSelected:m,node:e,nodeKeyDisplay:f,selection:c,
10
+ typeDisplay:g})});return null===c?": null":k.$isRangeSelection(c)?F(c):k.$isGridSelection(c)?`: grid\n \u2514 { grid: ${c.gridKey}, anchorCell: ${c.anchorCellKey}, focusCell: ${c.focusCellKey} }`:`: node\n \u2514 [${Array.from(c._nodes).join(", ")}]`});return b+"\n selection"+a}
11
+ function J(a,b,c=[]){a=a.getChildren();const e=a.length;a.forEach((d,f)=>{b(d,c.concat(f===e-1?E.isLastChild:E.hasNextSibling));k.$isElementNode(d)&&J(d,b,c.concat(f===e-1?E.ancestorIsLastChild:E.ancestorHasNextSibling))})}function K(a){return Object.entries(t).reduce((b,[c,e])=>b.replace(new RegExp(c,"g"),String(e)),a)}
12
+ const O=[a=>a.hasFormat("bold")&&"Bold",a=>a.hasFormat("code")&&"Code",a=>a.hasFormat("italic")&&"Italic",a=>a.hasFormat("strikethrough")&&"Strikethrough",a=>a.hasFormat("underline")&&"Underline"],P=[a=>a.isDirectionless()&&"Directionless",a=>a.isUnmergeable()&&"Unmergeable"],Q=[a=>a.isToken()&&"Token",a=>a.isSegmented()&&"Segmented",a=>a.isInert()&&"Inert"];function L(a){let b=P.map(c=>c(a)).filter(Boolean).join(", ").toLocaleLowerCase();""!==b&&(b="detail: "+b);return b}
13
+ function M(a){let b=Q.map(c=>c(a)).filter(Boolean).join(", ").toLocaleLowerCase();""!==b&&(b="mode: "+b);return b}function G(a){let b=O.map(c=>c(a)).filter(Boolean).join(", ").toLocaleLowerCase();""!==b&&(b="format: "+b);return b}
14
+ function N({indent:a,isSelected:b,node:c,nodeKeyDisplay:e,selection:d,typeDisplay:f}){if(!k.$isTextNode(c)||!k.$isRangeSelection(d)||!b||k.$isElementNode(c))return"";b=d.anchor;var g=d.focus;if(""===c.getTextContent()||b.getNode()===d.focus.getNode()&&b.offset===g.offset)return"";g=d.anchor;const m=d.focus,v=c.getTextContent(!0),u=v.length;b=d=-1;if("text"===g.type&&"text"===m.type){const n=g.getNode(),w=m.getNode();n===w&&c===n&&g.offset!==m.offset?[d,b]=g.offset<m.offset?[g.offset,m.offset]:[m.offset,
15
+ g.offset]:c===n?[d,b]=n.isBefore(w)?[g.offset,u]:[0,g.offset]:c===w?[d,b]=w.isBefore(n)?[m.offset,u]:[0,m.offset]:[d,b]=[0,u]}c=(v.slice(0,d).match(D)||[]).length;g=(v.slice(d,b).match(D)||[]).length;const [r,l]=[d+c,b+c+g];if(r===l)return"";c=a[a.length-1]===E.hasNextSibling?E.ancestorHasNextSibling:E.ancestorIsLastChild;a=[...a.slice(0,a.length-1),c];c=Array(r).fill(" ");d=Array(l-r).fill(E.selectedChar);e=Array(e.length+(f.length+3)).fill(" ");return[E.selectedLine,a.join(" "),[...e,...c,...d].join("")].join(" ")+
16
+ "\n"}
17
+ module.exports=function({timeTravelButtonClassName:a,timeTravelPanelSliderClassName:b,timeTravelPanelButtonClassName:c,viewClassName:e,timeTravelPanelClassName:d,editor:f}){const [g,m]=q.useState([]),[v,u]=q.useState(""),[r,l]=q.useState(!1),n=q.useRef(0),w=q.useRef(null),B=q.useRef(null),[z,C]=q.useState(!1);q.useEffect(()=>{u(H(f.getEditorState()));return f.addListener("update",({editorState:h})=>{const p=f._compositionKey,x=H(f.getEditorState());u([x,null!==p&&`Composition key: ${p}`].filter(Boolean).join("\n\n"));r||
18
+ m(A=>[...A,[Date.now(),h]])})},[r,f]);const y=g.length;q.useEffect(()=>{if(z){let h;const p=()=>{const x=n.current;x===y-1?C(!1):h=setTimeout(()=>{n.current++;const A=n.current,I=B.current;null!==I&&(I.value=String(A));f.setEditorState(g[A][1]);p()},g[x+1][0]-g[x][0])};p();return()=>{window.clearTimeout(h)}}},[g,z,f,y]);q.useEffect(()=>{const h=w.current;if(null!==h)return h.__lexicalEditor=f,()=>{h.__lexicalEditor=null}},[f]);return q.createElement("div",{className:e},!r&&2<y&&q.createElement("button",
19
+ {onClick:()=>{const h=f.getRootElement();null!==h&&(h.contentEditable="false",n.current=y-1,l(!0))},className:a},"Time Travel"),q.createElement("pre",{ref:w},v),r&&q.createElement("div",{className:d},q.createElement("button",{className:c,onClick:()=>{C(!z)}},z?"Pause":"Play"),q.createElement("input",{className:b,ref:B,onChange:h=>{h=Number(h.target.value);const p=g[h];p&&(n.current=h,f.setEditorState(p[1]))},type:"range",min:"1",max:y-1}),q.createElement("button",{className:c,onClick:()=>{var h=f.getRootElement();
20
+ if(null!==h){h.contentEditable="true";h=g.length-1;f.setEditorState(g[h][1]);const p=B.current;null!==p&&(p.value=String(h));l(!1);C(!1)}}},"Exit")))};
package/README.md CHANGED
@@ -63,17 +63,22 @@ function onError(error) {
63
63
  }
64
64
 
65
65
  function Editor() {
66
+ const initialConfig = {
67
+ theme,
68
+ onError,
69
+ };
70
+
66
71
  return (
67
- <LexicalComposer theme={theme}>
72
+ <LexicalComposer initialConfig={initialConfig}>
73
+ <LexicalBootstrapPlugin />
68
74
  <LexicalPlainTextPlugin
69
- contentEditable={<LexicalContentEditable className="editor-input" />}
75
+ contentEditable={<LexicalContentEditable />}
70
76
  placeholder={<div>Enter some text...</div>}
71
- onError={onError}
72
77
  />
73
78
  <LexicalOnChangePlugin onChange={onChange} />
74
- <LexicalHistoryPlugin />
79
+ <HistoryPlugin />
75
80
  <MyCustomAutoFocusPlugin />
76
81
  </LexicalComposer>
77
82
  );
78
83
  }
79
- ```
84
+ ```