UNPKG

@lexical/utils

Version:

This package contains misc utilities for Lexical.

10 lines (8 loc) 11.1 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"),t=require("@lexical/selection");function n(e,...t){const n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",e);for(const e of t)r.append("v",e);throw n.search=r.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.`)}const r="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,o=r&&"documentMode"in document?document.documentMode:null,i=r&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),s=r&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),l=!(!r||!("InputEvent"in window)||o)&&"getTargetRanges"in new window.InputEvent("input"),a=r&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),c=r&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,u=r&&/Android/.test(navigator.userAgent),d=r&&/^(?=.*Chrome).*/i.test(navigator.userAgent),g=r&&u&&d,f=r&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&i&&!d;function p(...e){const t=[];for(const n of e)if(n&&"string"==typeof n)for(const[e]of n.matchAll(/\S+/g))t.push(e);return t}function m(...e){return()=>{for(let t=e.length-1;t>=0;t--)e[t]();e.length=0}}function h(e){return`${e}px`}const $={attributes:!0,characterData:!0,childList:!0,subtree:!0};function x(r,o,i){let s=null,l=null,a=null,c=[];const u=document.createElement("div");function d(){null===s&&n(182),null===l&&n(183);const{left:e,top:a}=l.getBoundingClientRect(),d=t.createRectsFromDOMRange(r,o);var g,f;u.isConnected||(f=u,(g=l).insertBefore(f,g.firstChild));let p=!1;for(let t=0;t<d.length;t++){const n=d[t],r=c[t]||document.createElement("div"),o=r.style;"absolute"!==o.position&&(o.position="absolute",p=!0);const i=h(n.left-e);o.left!==i&&(o.left=i,p=!0);const s=h(n.top-a);o.top!==s&&(r.style.top=s,p=!0);const l=h(n.width);o.width!==l&&(r.style.width=l,p=!0);const g=h(n.height);o.height!==g&&(r.style.height=g,p=!0),r.parentNode!==u&&(u.append(r),p=!0),c[t]=r}for(;c.length>d.length;)c.pop();p&&i(c)}function g(){l=null,s=null,null!==a&&a.disconnect(),a=null,u.remove();for(const e of c)e.remove();c=[]}u.style.position="relative";const f=r.registerRootListener(function t(){const n=r.getRootElement();if(null===n)return g();const o=n.parentElement;if(!e.isHTMLElement(o))return g();g(),s=n,l=o,a=new MutationObserver(e=>{const n=r.getRootElement(),o=n&&n.parentElement;if(n!==s||o!==l)return t();for(const t of e)if(!u.contains(t.target))return d()}),a.observe(o,$),d()});return()=>{f(),g()}}function S(t,n,r){if("text"!==t.type&&e.$isElementNode(n)){const e=n.getDOMSlot(r);return[e.element,e.getFirstChildOffset()+t.offset]}return[e.getDOMTextNode(r)||r,t.offset]}function C(t,n){let r=null,o=null,i=null,s=null,l=null,a=null,c=()=>{};function u(u){u.read(()=>{const u=e.$getSelection();if(!e.$isRangeSelection(u))return r=null,i=null,s=null,a=null,c(),void(c=()=>{});const[d,g]=function(e){const t=e.getStartEndPoints();return e.isBackward()?[t[1],t[0]]:t}(u),f=d.getNode(),p=f.getKey(),m=d.offset,$=g.getNode(),C=$.getKey(),E=g.offset,v=t.getElementByKey(p),N=t.getElementByKey(C),A=null===r||v!==o||m!==i||p!==r.getKey(),w=null===s||N!==l||E!==a||C!==s.getKey();if((A||w)&&null!==v&&null!==N){const e=function(e,t,n,r,o,i,s){const l=(e._window?e._window.document:document).createRange();return l.setStart(...S(t,n,r)),l.setEnd(...S(o,i,s)),l}(t,d,f,v,g,$,N);c(),c=x(t,e,e=>{if(void 0===n)for(const t of e){const e=t.style;"Highlight"!==e.background&&(e.background="Highlight"),"HighlightText"!==e.color&&(e.color="HighlightText"),e.marginTop!==h(-1.5)&&(e.marginTop=h(-1.5)),e.paddingTop!==h(4)&&(e.paddingTop=h(4)),e.paddingBottom!==h(0)&&(e.paddingBottom=h(0))}else n(e)})}r=f,o=v,i=m,s=$,l=N,a=E})}return u(t.getEditorState()),m(t.registerUpdateListener(({editorState:e})=>u(e)),()=>{c()})}const E=l,v=r,N=u,A=g,w=i,b=f,y=d,P=s,R=c,I=a;function O(e,t){for(const n of t)if(e.type.startsWith(n))return!0;return!1}function M(e,t){return L("next",e,t)}function T(t,n){const r=e.$getAdjacentSiblingOrParentSiblingCaret(e.$getSiblingCaret(t,n));return r&&r[0]}function L(t,n,r){const o=e.$getRoot(),i=n||o,s=e.$isElementNode(i)?e.$getChildCaret(i,t):e.$getSiblingCaret(i,t),l=_(i),a=r?e.$getAdjacentChildCaret(e.$getChildCaretOrSelf(e.$getSiblingCaret(r,t)))||T(r,t):T(i,t);let c=l;return e.makeStepwiseIterator({hasNext:e=>null!==e,initial:s,map:e=>({depth:c,node:e.origin}),step:t=>{if(t.isSameNodeCaret(a))return null;e.$isChildCaret(t)&&c++;const n=e.$getAdjacentSiblingOrParentSiblingCaret(t);return!n||n[0].isSameNodeCaret(a)?null:(c+=n[1],n[0])}})}function _(e){let t=-1;for(let n=e;null!==n;n=n.getParent())t++;return t}function D(e,t){return L("previous",e,t)}function F(t,r,o){let i=e.$getCaretInDirection(r,"next");for(let t=i;t;t=e.$splitAtPointCaretNext(t,o))i=t;return e.$isTextPointCaret(i)&&n(283),i.insert(t.isInline()?e.$createParagraphNode().append(t):t),e.$getCaretInDirection(e.$getSiblingCaret(t.getLatest(),"next"),r.direction)}let B=!(P||!v)&&void 0;function j(t,n,r){let o=!1;for(const i of k(t))n(i)?null!==r&&r(i):(o=!0,e.$isElementNode(i)&&j(i,n,r||(e=>i.insertAfter(e))),i.remove());return o}function k(t){return H(e.$getChildCaret(t,"previous"))}function H(t){return e.makeStepwiseIterator({hasNext:e.$isSiblingCaret,initial:t.getAdjacentCaret(),map:e=>e.origin.getLatest(),step:e=>e.getAdjacentCaret()})}exports.$findMatchingParent=e.$findMatchingParent,exports.$getAdjacentSiblingOrParentSiblingCaret=e.$getAdjacentSiblingOrParentSiblingCaret,exports.$splitNode=e.$splitNode,exports.isBlockDomNode=e.isBlockDomNode,exports.isHTMLAnchorElement=e.isHTMLAnchorElement,exports.isHTMLElement=e.isHTMLElement,exports.isInlineDomNode=e.isInlineDomNode,exports.$descendantsMatching=function(t,n){const r=[],o=Array.from(t).reverse();for(let t=o.pop();void 0!==t;t=o.pop())if(n(t))r.push(t);else if(e.$isElementNode(t))for(const e of k(t))o.push(e);return r},exports.$dfs=function(e,t){return Array.from(M(e,t))},exports.$dfsIterator=M,exports.$filter=function(e,t){const n=[];for(let r=0;r<e.length;r++){const o=t(e[r]);null!==o&&n.push(o)}return n},exports.$firstToLastIterator=function(t){return H(e.$getChildCaret(t,"next"))},exports.$getAdjacentCaret=function(e){return e?e.getAdjacentCaret():null},exports.$getDepth=_,exports.$getNearestBlockElementAncestorOrThrow=function(t){const r=e.$findMatchingParent(t,t=>e.$isElementNode(t)&&!t.isInline());return e.$isElementNode(r)||n(4,t.__key),r},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(t){const n=e.$getChildCaretOrSelf(e.$getSiblingCaret(t,"previous")),r=e.$getAdjacentSiblingOrParentSiblingCaret(n,"root");return r&&r[0].origin},exports.$getNextSiblingOrParentSibling=function(t){const n=e.$getAdjacentSiblingOrParentSiblingCaret(e.$getSiblingCaret(t,"next"));return n&&[n[0].origin,n[1]]},exports.$insertFirst=function(t,n){e.$getChildCaret(t,"next").insert(n)},exports.$insertNodeToNearestRoot=function(t){const n=e.$getSelection()||e.$getPreviousSelection();let r;if(e.$isRangeSelection(n))r=e.$caretFromPoint(n.focus,"next");else{if(null!=n){const t=n.getNodes(),o=t[t.length-1];o&&(r=e.$getSiblingCaret(o,"next"))}r=r||e.$getChildCaret(e.$getRoot(),"previous").getFlipped().insert(e.$createParagraphNode())}const o=F(t,r),i=e.$getAdjacentChildCaret(o),s=e.$isChildCaret(i)?e.$normalizeCaret(i):o;return e.$setSelectionFromCaretRange(e.$getCollapsedCaretRange(s)),t.getLatest()},exports.$insertNodeToNearestRootAtCaret=F,exports.$isEditorIsNestedEditor=function(e){return null!==e._parentEditor},exports.$lastToFirstIterator=k,exports.$restoreEditorState=function(t,n){const r=new Map,o=t._pendingEditorState;for(const[t,o]of n._nodeMap)r.set(t,e.$cloneWithProperties(o));o&&(o._nodeMap=r),t._dirtyType=2;const i=n._selection;e.$setSelection(null===i?null:i.clone())},exports.$reverseDfs=function(e,t){return Array.from(D(e,t))},exports.$reverseDfsIterator=D,exports.$unwrapAndFilterDescendants=function(e,t){return j(e,t,null)},exports.$unwrapNode=function(t){e.$rewindSiblingCaret(e.$getSiblingCaret(t,"next")).splice(1,t.getChildren())},exports.$wrapNodeInElement=function(e,t){const n=t();return e.replace(n),n.append(e),n},exports.CAN_USE_BEFORE_INPUT=E,exports.CAN_USE_DOM=v,exports.IS_ANDROID=N,exports.IS_ANDROID_CHROME=A,exports.IS_APPLE=w,exports.IS_APPLE_WEBKIT=b,exports.IS_CHROME=y,exports.IS_FIREFOX=P,exports.IS_IOS=R,exports.IS_SAFARI=I,exports.addClassNamesToElement=function(e,...t){const n=p(...t);n.length>0&&e.classList.add(...n)},exports.calculateZoomLevel=function(e){let t=1;if(function(){if(void 0===B){const e=document.createElement("div");e.style.cssText="position: absolute; opacity: 0; width: 100px; left: -1000px;",document.body.appendChild(e);const t=e.getBoundingClientRect();e.style.setProperty("zoom","2"),B=e.getBoundingClientRect().width===t.width,document.body.removeChild(e)}return B}())for(;e;)t*=Number(window.getComputedStyle(e).getPropertyValue("zoom")),e=e.parentElement;return t},exports.isMimeType=O,exports.makeStateWrapper=function(t){const n=n=>e.$getState(n,t),r=(n,r)=>e.$setState(n,t,r);return{$get:n,$set:r,accessors:[n,r],makeGetterMethod:()=>function(){return n(this)},makeSetterMethod:()=>function(e){return r(this,e)},stateConfig:t}},exports.markSelection=C,exports.mediaFileReader=function(e,t){const n=e[Symbol.iterator]();return new Promise((e,r)=>{const o=[],i=()=>{const{done:s,value:l}=n.next();if(s)return e(o);const a=new FileReader;a.addEventListener("error",r),a.addEventListener("load",()=>{const e=a.result;"string"==typeof e&&o.push({file:l,result:e}),i()}),O(l,t)?a.readAsDataURL(l):i()};i()})},exports.mergeRegister=m,exports.objectKlassEquals=function(e,t){return null!==e&&Object.getPrototypeOf(e).constructor.name===t.name},exports.positionNodeOnRange=x,exports.registerNestedElementResolver=function(e,t,n,r){const o=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(o(n))return null}let n=e,r=e;for(;null!==n;)if(r=n,n=n.getParent(),o(n))return{child:r,parent:n};return null})(e);if(null!==t){const{child:o,parent:i}=t;if(o.is(e)){r(i,e);const t=o.getNextSiblings(),s=t.length;if(i.insertAfter(o),0!==s){const e=n(i);o.insertAfter(e);for(let n=0;n<s;n++)e.append(t[n])}i.canBeEmpty()||0!==i.getChildrenSize()||i.remove()}}})},exports.removeClassNamesFromElement=function(e,...t){const n=p(...t);n.length>0&&e.classList.remove(...n)},exports.selectionAlwaysOnDisplay=function(e){let t=null;const n=()=>{const n=getSelection(),r=n&&n.anchorNode,o=e.getRootElement();null!==r&&null!==o&&o.contains(r)?null!==t&&(t(),t=null):null===t&&(t=C(e))};return document.addEventListener("selectionchange",n),()=>{null!==t&&t(),document.removeEventListener("selectionchange",n)}};