UNPKG

@lexical/utils

Version:

This package contains misc utilities for Lexical.

10 lines (8 loc) • 14.8 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/selection"),t=require("lexical");function n(e,...t){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(const e of t)o.append("v",e);throw n.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function o(e){const t=(e,t)=>t.left>=e.left-1&&t.top>=e.top-1&&t.right<=e.right+1&&t.bottom<=e.bottom+1,n=[];for(const o of Array.from(e))if(!(o.width<.5||o.height<.5||n.some(e=>t(o,e)))){for(let e=n.length-1;e>=0;e--)t(n[e],o)&&n.splice(e,1);n.push(o)}return n}function r(e){return`${e}px`}const i={attributes:!0,characterData:!0,childList:!0,subtree:!0};function s(s,l,a){let c=null,u=null,d=null,g=[];const f=t.getRootOwnerDocument(s.getRootElement()).createElement("div");function p(){null===c&&n(182),null===u&&n(183);const{left:i,top:d}=u.getBoundingClientRect(),p=o(e.createRectsFromDOMRange(s,l));var $,m;f.isConnected||(m=f,($=u).insertBefore(m,$.firstChild));let h=!1;for(let e=0;e<p.length;e++){const n=p[e],o=g[e]||t.getRootOwnerDocument(c).createElement("div"),s=o.style;"absolute"!==s.position&&(s.position="absolute",h=!0);const l=r(n.left-i);s.left!==l&&(s.left=l,h=!0);const a=r(n.top-d);s.top!==a&&(o.style.top=a,h=!0);const u=r(n.width);s.width!==u&&(o.style.width=u,h=!0);const $=r(n.height);s.height!==$&&(o.style.height=$,h=!0),o.parentNode!==f&&(f.append(o),h=!0),g[e]=o}for(;g.length>p.length;){const e=g.pop();null!=e&&e.remove()}h&&a(g)}function $(){u=null,c=null,null!==d&&d.disconnect(),d=null,f.remove();for(const e of g)e.remove();g=[]}f.style.position="relative";const m=s.registerRootListener(function e(){const n=s.getRootElement();if(null===n)return $();const o=n.parentElement;if(!t.isHTMLElement(o))return $();$(),c=n,u=o,d=new MutationObserver(t=>{const n=s.getRootElement(),o=n&&n.parentElement;if(n!==c||o!==u)return e();for(const e of t)if(!f.contains(e.target))return p()}),d.observe(o,i),p()});return()=>{m(),$()}}function l(e,n,o,r){if("text"!==n.type&&t.$isElementNode(o)){const i=t.$getDOMSlot(o,r,e);return[i.element,i.getFirstChildOffset()+n.offset]}return[(t.$isTextNode(o)?t.$getDOMTextNode(o,r,e):t.getDOMTextNode(r))||r,n.offset]}function a(e){for(const t of e){const e=t.style;"Highlight"!==e.background&&(e.background="Highlight"),"HighlightText"!==e.color&&(e.color="HighlightText"),e.marginTop!==r(-1.5)&&(e.marginTop=r(-1.5)),e.paddingTop!==r(4)&&(e.paddingTop=r(4)),e.paddingBottom!==r(0)&&(e.paddingBottom=r(0))}}function c(e,n=a){let o=null,r=null,i=null,c=null,u=null,d=null,g=()=>{};function f(a){a.read(()=>{const a=t.$getSelection();if(!t.$isRangeSelection(a))return o=null,i=null,c=null,d=null,g(),void(g=()=>{});const[f,p]=function(e){const t=e.getStartEndPoints();return e.isBackward()?[t[1],t[0]]:t}(a),$=f.getNode(),m=$.getKey(),h=f.offset,S=p.getNode(),x=S.getKey(),C=p.offset,E=e.getElementByKey(m),N=e.getElementByKey(x),R=null===o||E!==r||h!==i||m!==o.getKey(),y=null===c||N!==u||C!==d||x!==c.getKey();if((R||y)&&null!==E&&null!==N){const t=function(e,t,n,o,r,i,s){const a=(e._window?e._window.document:document).createRange();return a.setStart(...l(e,t,n,o)),a.setEnd(...l(e,r,i,s)),a}(e,f,$,E,p,S,N);g(),g=s(e,t,n)}o=$,r=E,i=h,c=S,u=N,d=C},{editor:e})}return f(e.getEditorState()),t.mergeRegister(e.registerUpdateListener(({editorState:e})=>f(e)),()=>{g()})}function u(e,t){for(const n of t)if(e.type.startsWith(n))return!0;return!1}function d(e,t){return $("next",e,t)}function*g(e,n){for(const o of $("next",e,n)){yield o;const{node:e,depth:r}=o;if(t.$isSlotHost(e)&&!e.is(n))for(const n of t.$getSlotNames(e)){const o=t.$getSlot(e,n);null!==o&&(yield*f(o,r+1))}}}function*f(e,n){yield{depth:n,node:e};const o=n+1;if(t.$isSlotHost(e))for(const n of t.$getSlotNames(e)){const r=t.$getSlot(e,n);null!==r&&(yield*f(r,o))}if(t.$isElementNode(e))for(const t of e.getChildren())yield*f(t,o)}function p(e,n){const o=t.$getAdjacentSiblingOrParentSiblingCaret(t.$getSiblingCaret(e,n));return o&&o[0]}function $(e,n,o){const r=t.$getRoot(),i=n||r,s=t.$isElementNode(i)?t.$getChildCaret(i,e):t.$getSiblingCaret(i,e),l=m(i),a=o?t.$getAdjacentChildCaret(t.$getChildCaretOrSelf(t.$getSiblingCaret(o,e)))||p(o,e):p(i,e);let c=l;return t.makeStepwiseIterator({hasNext:e=>null!==e,initial:s,map:e=>({depth:c,node:e.origin}),step:e=>{if(e.isSameNodeCaret(a))return null;t.$isChildCaret(e)&&c++;const n=t.$getAdjacentSiblingOrParentSiblingCaret(e);return!n||n[0].isSameNodeCaret(a)?null:(c+=n[1],n[0])}})}function m(e){let n=-1;for(let o=e;null!==o;o=o.getParent()??t.$getSlotHost(o))n++;return n}function h(e,t){return $("previous",e,t)}function*S(e,n){const o=[];for(const r of $("previous",e,n)){for(;o.length>0&&r.depth<=o[o.length-1].depth;){const e=o.pop();yield*x(e.node,e.depth+1)}yield r;const{node:e,depth:i}=r;t.$isSlotHost(e)&&t.$getSlotNames(e).length>0&&!e.is(n)&&o.push({depth:i,node:e})}for(;o.length>0;){const e=o.pop();yield*x(e.node,e.depth+1)}}function*x(e,n){const o=t.$getSlotNames(e);for(let r=o.length-1;r>=0;r--){const i=t.$getSlot(e,o[r]);null!==i&&(yield*C(i,n))}}function*C(e,n){yield{depth:n,node:e};const o=n+1;if(t.$isElementNode(e)){const t=e.getChildren();for(let e=t.length-1;e>=0;e--)yield*C(t[e],o)}t.$isSlotHost(e)&&(yield*x(e,o))}function E(e,t){return null!==e&&Object.getPrototypeOf(e).constructor.name===t.name}let N=!(t.IS_FIREFOX||!t.CAN_USE_DOM)&&void 0;function R(e,n,o){let r=!1;for(const i of y(e))n(i)?null!==o&&o(i):(r=!0,t.$isElementNode(i)&&R(i,n,o||(e=>i.insertAfter(e))),i.remove());return r}function y(e){return A(t.$getChildCaret(e,"previous"))}function A(e){return t.makeStepwiseIterator({hasNext:t.$isSiblingCaret,initial:e.getAdjacentCaret(),map:e=>e.origin.getLatest(),step:e=>e.getAdjacentCaret()})}function v(t,n){return e.$isAtEdgeOfElement(t,n,"previous")}function I(t,n){return e.$isAtEdgeOfElement(t,n,"next")}exports.$findMatchingParent=t.$findMatchingParent,exports.$getAdjacentSiblingOrParentSiblingCaret=t.$getAdjacentSiblingOrParentSiblingCaret,exports.$insertNodeToNearestRootAtCaret=t.$insertNodeToNearestRootAtCaret,exports.$splitNode=t.$splitNode,exports.CAN_USE_BEFORE_INPUT=t.CAN_USE_BEFORE_INPUT,exports.CAN_USE_DOM=t.CAN_USE_DOM,exports.IS_ANDROID=t.IS_ANDROID,exports.IS_ANDROID_CHROME=t.IS_ANDROID_CHROME,exports.IS_APPLE=t.IS_APPLE,exports.IS_APPLE_WEBKIT=t.IS_APPLE_WEBKIT,exports.IS_CHROME=t.IS_CHROME,exports.IS_FIREFOX=t.IS_FIREFOX,exports.IS_IOS=t.IS_IOS,exports.IS_SAFARI=t.IS_SAFARI,exports.addClassNamesToElement=t.addClassNamesToElement,exports.isBlockDomNode=t.isBlockDomNode,exports.isHTMLAnchorElement=t.isHTMLAnchorElement,exports.isHTMLElement=t.isHTMLElement,exports.isInlineDomNode=t.isInlineDomNode,exports.mergeRegister=t.mergeRegister,exports.removeClassNamesFromElement=t.removeClassNamesFromElement,exports.$descendantsMatching=function(e,n){const o=[],r=Array.from(e).reverse();for(let e=r.pop();void 0!==e;e=r.pop())if(n(e))o.push(e);else if(t.$isElementNode(e))for(const t of y(e))r.push(t);return o},exports.$dfs=function(e,t){return Array.from(d(e,t))},exports.$dfsIterator=d,exports.$dfsWithSlots=function(e,t){return Array.from(g(e,t))},exports.$dfsWithSlotsIterator=g,exports.$filter=function(e,t){const n=[];for(let o=0;o<e.length;o++){const r=t(e[o]);null!==r&&n.push(r)}return n},exports.$firstToLastIterator=function(e){return A(t.$getChildCaret(e,"next"))},exports.$getAdjacentCaret=function(e){return e?e.getAdjacentCaret():null},exports.$getDepth=m,exports.$getNearestBlockElementAncestorOrThrow=function(e){const o=t.$findMatchingParent(e,e=>t.$isElementNode(e)&&!e.isInline());return t.$isElementNode(o)||n(4,e.__key),o},exports.$getNearestNodeOfType=function(e,t){let n=e;for(;null!=n;){if(n instanceof t)return n;n=n.getParent()}return null},exports.$getNextRightPreorderNode=function(e){const n=t.$getChildCaretOrSelf(t.$getSiblingCaret(e,"previous")),o=t.$getAdjacentSiblingOrParentSiblingCaret(n,"root");return o&&o[0].origin},exports.$getNextSiblingOrParentSibling=function(e){const n=t.$getAdjacentSiblingOrParentSiblingCaret(t.$getSiblingCaret(e,"next"));return n&&[n[0].origin,n[1]]},exports.$handleIndentAndOutdent=function(e){const n=t.$getSelection();if(!t.$isRangeSelection(n))return!1;const o=new Set,r=n.getNodes();for(let n=0;n<r.length;n++){const i=r[n],s=i.getKey();if(o.has(s))continue;const l=t.$findMatchingParent(i,e=>t.$isElementNode(e)&&!e.isInline());if(null===l)continue;const a=l.getKey();l.canIndent()&&!o.has(a)&&(o.add(a),e(l))}return o.size>0},exports.$insertFirst=function(e,n){t.$getChildCaret(e,"next").insert(n)},exports.$insertNodeIntoLeaf=function(e){const n=t.$getSelection();if(!t.$isRangeSelection(n))return void(n&&n.insertNodes([e]));const o=t.$caretRangeFromSelection(n);let r=t.$getCaretRangeInDirection(t.$removeTextFromCaretRange(o),"next").anchor;if(t.$isTextPointCaret(r)){const e=t.$splitAtPointCaretNext(r);if(!e)return;r=e}const i=r.getFlipped();i.insert(e),t.$setSelectionFromCaretRange(t.$getCaretRange(i,i))},exports.$insertNodeToNearestRoot=function(e){const n=t.$getSelection()||t.$getPreviousSelection();let o;if(t.$isRangeSelection(n))o=t.$caretFromPoint(n.focus,"next");else{if(null!=n){const e=n.getNodes(),r=e[e.length-1];r&&(o=t.$getSiblingCaret(r,"next"))}o=o||t.$getChildCaret(t.$getRoot(),"previous").getFlipped().insert(t.$createParagraphNode())}const r=t.$insertNodeToNearestRootAtCaret(e,o),i=t.$getAdjacentChildCaret(r),s=t.$isChildCaret(i)?t.$normalizeCaret(i):r;return t.$setSelectionFromCaretRange(t.$getCollapsedCaretRange(s)),e.getLatest()},exports.$isAtEndOfNode=I,exports.$isAtStartOfNode=v,exports.$isBlockFullySelected=function(e,n){const o=t.$getCaretRangeInDirection(t.$isRangeSelection(n)?t.$caretRangeFromSelection(n):n,"next"),r=t.$getSlotFrame(o.anchor.origin),i=t.$getSlotFrame(e.getLatest());if(null===r?null!==i:!r.is(i))return!1;const s=t.$normalizeCaret(t.$getChildCaret(e,"next")),l=t.$getCaretInDirection(t.$normalizeCaret(t.$getChildCaret(e,"previous")),"next");return t.$comparePointCaretNext(o.anchor,s)<=0&&t.$comparePointCaretNext(o.focus,l)>=0},exports.$isEditorIsNestedEditor=function(e){return null!==e._parentEditor},exports.$lastToFirstIterator=y,exports.$onEscapeDown=function(e,n){const o=t.$getSelection();if(t.$isRangeSelection(o)&&o.isCollapsed()){const r=t.$findMatchingParent(o.anchor.getNode(),e);if(r){const e=r.getParent();if(null!==e&&e.getLastChild()===r&&I(o.anchor,r))return r.insertAfter(t.$createParagraphNode()).selectEnd(),n&&n.preventDefault(),!0}}return!1},exports.$onEscapeUp=function(e,n){const o=t.$getSelection();if(t.$isRangeSelection(o)&&o.isCollapsed()){const r=t.$findMatchingParent(o.anchor.getNode(),e);if(r){const e=r.getParent();if(null!==e&&e.getFirstChild()===r&&v(o.anchor,r))return r.insertBefore(t.$createParagraphNode()).selectEnd(),n&&n.preventDefault(),!0}}return!1},exports.$restoreEditorState=function(e,n){const o=new Map,r=e._pendingEditorState;for(const[e,r]of n._nodeMap)o.set(e,t.$cloneWithProperties(r));r&&(r._nodeMap=o),t.$fullReconcile();const i=n._selection;t.$setSelection(null===i?null:i.clone())},exports.$reverseDfs=function(e,t){return Array.from(h(e,t))},exports.$reverseDfsIterator=h,exports.$reverseDfsWithSlots=function(e,t){return Array.from(S(e,t))},exports.$reverseDfsWithSlotsIterator=S,exports.$unwrapAndFilterDescendants=function(e,t){return R(e,t,null)},exports.$unwrapNode=function(e){t.$rewindSiblingCaret(t.$getSiblingCaret(e,"next")).splice(1,e.getChildren())},exports.$wrapNodeInElement=function(e,t){const n=t();return e.replace(n),n.append(e),n},exports.calculateZoomLevel=function(e,n=!1){let o=1;if(function(){if(void 0===N){const e=document.createElement("div");e.style.position="absolute",e.style.opacity="0",e.style.width="100px",e.style.left="-1000px",document.body.appendChild(e);const t=e.getBoundingClientRect();e.style.setProperty("zoom","2"),N=e.getBoundingClientRect().width===t.width,document.body.removeChild(e)}return N}()||n){const n=e&&e.ownerDocument.defaultView||window;for(;e;)o*=Number(n.getComputedStyle(e).getPropertyValue("zoom")),e=t.getParentElement(e)}return o},exports.dedupeSelectionRects=o,exports.eventFiles=function(e){let t=null;if(E(e,DragEvent)?t=e.dataTransfer:E(e,ClipboardEvent)&&(t=e.clipboardData),null===t)return[!1,[],!1];const n=t.types,o=n.includes("Files"),r=n.includes("text/html")||n.includes("text/plain");return[o,Array.from(t.files),r]},exports.getScrollParent=function(e,n){const o=e.ownerDocument,r=o.defaultView||window;let i=r.getComputedStyle(e);const s="absolute"===i.position,l=n?/(auto|scroll|hidden)/:/(auto|scroll)/;if("fixed"===i.position)return o.body;for(let n=e;n=t.getParentElement(n);)if(i=r.getComputedStyle(n),(!s||"static"!==i.position)&&l.test(i.overflow+i.overflowY+i.overflowX))return n;return o.body},exports.isMimeType=u,exports.makeStateWrapper=function(e){const n=n=>t.$getState(n,e),o=(n,o)=>t.$setState(n,e,o);return{$get:n,$set:o,accessors:[n,o],makeGetterMethod:()=>function(){return n(this)},makeSetterMethod:()=>function(e){return o(this,e)},stateConfig:e}},exports.markSelection=c,exports.mediaFileReader=function(e,t){const n=e[Symbol.iterator]();return new Promise((e,o)=>{const r=[],i=()=>{const{done:s,value:l}=n.next();if(s)return e(r);const a=new FileReader;a.addEventListener("error",o),a.addEventListener("load",()=>{const e=a.result;"string"==typeof e&&r.push({file:l,result:e}),i()}),u(l,t)?a.readAsDataURL(l):i()};i()})},exports.objectKlassEquals=E,exports.positionNodeOnRange=s,exports.registerNestedElementResolver=function(e,t,n,o){const r=e=>e instanceof t;return e.registerNodeTransform(t,e=>{const t=(e=>{const t=e.getChildren();for(let e=0;e<t.length;e++){const n=t[e];if(r(n))return null}let n=e,o=e;for(;null!==n;)if(o=n,n=n.getParent(),r(n))return{child:o,parent:n};return null})(e);if(null!==t){const{child:r,parent:i}=t;if(r.is(e)){o(i,e);const t=r.getNextSiblings(),s=t.length;if(i.insertAfter(r),0!==s){const e=n(i);r.insertAfter(e);for(let n=0;n<s;n++)e.append(t[n])}i.canBeEmpty()||0!==i.getChildrenSize()||i.remove()}}})},exports.selectionAlwaysOnDisplay=function(e,n){let o=null;const r=()=>{const r=e.getRootElement(),i=null!==r?r.ownerDocument.defaultView:null,s=null!==i?i.getSelection():null,l=null!==s?t.getDOMSelectionPoints(s,r).anchorNode:null;null!==l&&null!==r&&r.contains(l)?null!==o&&(o(),o=null):null===o&&(o=c(e,n))};return e.registerRootListener(e=>{if(e){const n=e.ownerDocument,i=t.mergeRegister(t.registerEventListener(n,"selectionchange",r),()=>{null!==o&&o()});return r(),i}})};