UNPKG

@lexical/utils

Version:

This package contains misc utilities for Lexical.

10 lines (8 loc) 11.2 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"),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.`)}const o="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,r=o&&"documentMode"in document?document.documentMode:null,i=o&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),s=o&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),l=!(!o||!("InputEvent"in window)||r)&&"getTargetRanges"in new window.InputEvent("input"),a=o&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),c=o&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,u=o&&/Android/.test(navigator.userAgent),d=o&&/^(?=.*Chrome).*/i.test(navigator.userAgent),g=o&&u&&d,f=o&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!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(o,r,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(o,r);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],o=c[t]||document.createElement("div"),r=o.style;"absolute"!==r.position&&(r.position="absolute",p=!0);const i=h(n.left-e);r.left!==i&&(r.left=i,p=!0);const s=h(n.top-a);r.top!==s&&(o.style.top=s,p=!0);const l=h(n.width);r.width!==l&&(o.style.width=l,p=!0);const g=h(n.height);r.height!==g&&(o.style.height=g,p=!0),o.parentNode!==u&&(u.append(o),p=!0),c[t]=o}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=o.registerRootListener((function t(){const n=o.getRootElement();if(null===n)return g();const r=n.parentElement;if(!e.isHTMLElement(r))return g();g(),s=n,l=r,a=new MutationObserver((e=>{const n=o.getRootElement(),r=n&&n.parentElement;if(n!==s||r!==l)return t();for(const t of e)if(!u.contains(t.target))return d()})),a.observe(r,$),d()}));return()=>{f(),g()}}function C(t,n,o){if("text"!==t.type&&e.$isElementNode(n)){const e=n.getDOMSlot(o);return[e.element,e.getFirstChildOffset()+t.offset]}return[e.getDOMTextNode(o)||o,t.offset]}function S(t,n){let o=null,r=null,i=null,s=null,l=null,a=null,c=()=>{};function u(u){u.read((()=>{const u=e.$getSelection();if(!e.$isRangeSelection(u))return o=null,i=null,s=null,a=null,c(),void(c=()=>{});const{anchor:d,focus:g}=u,f=d.getNode(),p=f.getKey(),m=d.offset,$=g.getNode(),S=$.getKey(),E=g.offset,v=t.getElementByKey(p),N=t.getElementByKey(S),w=null===o||v!==r||m!==i||p!==o.getKey(),y=null===s||N!==l||E!==a||S!==s.getKey();if((w||y)&&null!==v&&null!==N){const e=function(e,t,n,o,r,i,s){const l=(e._window?e._window.document:document).createRange();return i.isBefore(n)?(l.setStart(...C(r,i,s)),l.setEnd(...C(t,n,o))):(l.setStart(...C(t,n,o)),l.setEnd(...C(r,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)}))}o=f,r=v,i=m,s=$,l=N,a=E}))}return u(t.getEditorState()),m(t.registerUpdateListener((({editorState:e})=>u(e))),(()=>{c()}))}const E=l,v=o,N=u,w=g,y=i,A=f,R=d,P=s,b=c,I=a;function T(e,t){for(const n of t)if(e.type.startsWith(n))return!0;return!1}function L(e,t){return M("next",e,t)}function M(t,n,o){const r=e.$getRoot(),i=n||r,s=e.$isElementNode(i)?e.$getChildCaret(i,t):e.$getSiblingCaret(i,t),l=_(i),a=o?e.$getAdjacentChildCaret(e.$getChildCaretOrSelf(e.$getSiblingCaret(o,t))):function(t,n){const o=K(e.$getSiblingCaret(t,n));return o&&o[0]}(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=K(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 O(e,t){return M("previous",e,t)}const D=(t,n)=>{let o=t;for(;o!==e.$getRoot()&&null!=o;){if(n(o))return o;o=o.getParent()}return null};function F(t,o,r){let i=e.$getCaretInDirection(o,"next");for(let t=i;t;t=e.$splitAtPointCaretNext(t,r))i=t;return e.$isTextPointCaret(i)&&n(283),i.insert(t.isInline()?e.$createParagraphNode().append(t):t),e.$getCaretInDirection(e.$getSiblingCaret(t.getLatest(),"next"),o.direction)}let B=!(P||!v)&&void 0;function k(t,n,o){let r=!1;for(const i of j(t))n(i)?null!==o&&o(i):(r=!0,e.$isElementNode(i)&&k(i,n,o||(e=>i.insertAfter(e))),i.remove());return r}function j(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()})}function K(t,n="root"){let o=0,r=t,i=e.$getAdjacentChildCaret(r);for(;null===i;){if(o--,i=r.getParentCaret(n),!i)return null;r=i,i=e.$getAdjacentChildCaret(r)}return i&&[i,o]}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 o=[],r=Array.from(t).reverse();for(let t=r.pop();void 0!==t;t=r.pop())if(n(t))o.push(t);else if(e.$isElementNode(t))for(const e of j(t))r.push(e);return o},exports.$dfs=function(e,t){return Array.from(L(e,t))},exports.$dfsIterator=L,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.$findMatchingParent=D,exports.$firstToLastIterator=function(t){return H(e.$getChildCaret(t,"next"))},exports.$getAdjacentCaret=function(e){return e?e.getAdjacentCaret():null},exports.$getAdjacentSiblingOrParentSiblingCaret=K,exports.$getDepth=_,exports.$getNearestBlockElementAncestorOrThrow=function(t){const o=D(t,(t=>e.$isElementNode(t)&&!t.isInline()));return e.$isElementNode(o)||n(4,t.__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(t){const n=K(e.$getChildCaretOrSelf(e.$getSiblingCaret(t,"previous")),"root");return n&&n[0].origin},exports.$getNextSiblingOrParentSibling=function(t){const n=K(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 o;if(e.$isRangeSelection(n))o=e.$caretFromPoint(n.focus,"next");else{if(null!=n){const t=n.getNodes(),r=t[t.length-1];r&&(o=e.$getSiblingCaret(r,"next"))}o=o||e.$getChildCaret(e.$getRoot(),"previous").getFlipped().insert(e.$createParagraphNode())}const r=F(t,o),i=e.$getAdjacentChildCaret(r),s=e.$isChildCaret(i)?e.$normalizeCaret(i):r;return e.$setSelectionFromCaretRange(e.$getCollapsedCaretRange(s)),t.getLatest()},exports.$insertNodeToNearestRootAtCaret=F,exports.$isEditorIsNestedEditor=function(e){return null!==e._parentEditor},exports.$lastToFirstIterator=j,exports.$restoreEditorState=function(t,n){const o=new Map,r=t._pendingEditorState;for(const[t,r]of n._nodeMap)o.set(t,e.$cloneWithProperties(r));r&&(r._nodeMap=o),t._dirtyType=2;const i=n._selection;e.$setSelection(null===i?null:i.clone())},exports.$reverseDfs=function(e,t){return Array.from(O(e,t))},exports.$reverseDfsIterator=O,exports.$unwrapAndFilterDescendants=function(e,t){return k(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=w,exports.IS_APPLE=y,exports.IS_APPLE_WEBKIT=A,exports.IS_CHROME=R,exports.IS_FIREFOX=P,exports.IS_IOS=b,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=T,exports.makeStateWrapper=function(t){const n=n=>e.$getState(n,t),o=(n,o)=>e.$setState(n,t,o);return{$get:n,$set:o,accessors:[n,o],makeGetterMethod:()=>function(){return n(this)},makeSetterMethod:()=>function(e){return o(this,e)},stateConfig:t}},exports.markSelection=S,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()})),T(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,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.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(),o=n&&n.anchorNode,r=e.getRootElement();null!==o&&null!==r&&r.contains(o)?null!==t&&(t(),t=null):null===t&&(t=S(e))};return document.addEventListener("selectionchange",n),()=>{null!==t&&t(),document.removeEventListener("selectionchange",n)}};