@lexical/utils
Version:
This package contains misc utilities for Lexical.
10 lines (8 loc) • 10.5 kB
JavaScript
/**
* 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.
*
*/
import{isHTMLElement as t,$getSelection as e,$isRangeSelection as n,$isElementNode as o,getDOMTextNode as r,$getAdjacentSiblingOrParentSiblingCaret as i,$getSiblingCaret as l,$getChildCaretOrSelf as u,$findMatchingParent as s,$cloneWithProperties as c,$setSelection as a,$getPreviousSelection as f,$caretFromPoint as d,$getChildCaret as g,$getRoot as p,$createParagraphNode as m,$getAdjacentChildCaret as h,$isChildCaret as v,$normalizeCaret as y,$setSelectionFromCaretRange as w,$getCollapsedCaretRange as x,$getCaretInDirection as E,$splitAtPointCaretNext as S,$isTextPointCaret as A,$rewindSiblingCaret as C,$getState as b,$setState as L,makeStepwiseIterator as P,$isSiblingCaret as N}from"lexical";export{$findMatchingParent,$getAdjacentSiblingOrParentSiblingCaret,$splitNode,isBlockDomNode,isHTMLAnchorElement,isHTMLElement,isInlineDomNode}from"lexical";import{createRectsFromDOMRange as M}from"@lexical/selection";function R(t,...e){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",t);for(const t of e)o.append("v",t);throw n.search=o.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}const T="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,B=T&&"documentMode"in document?document.documentMode:null,_=T&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),k=T&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),$=!(!T||!("InputEvent"in window)||B)&&"getTargetRanges"in new window.InputEvent("input"),K=T&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),O=T&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,H=T&&/Android/.test(navigator.userAgent),j=T&&/^(?=.*Chrome).*/i.test(navigator.userAgent),D=T&&H&&j,I=T&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&_&&!j;function F(...t){const e=[];for(const n of t)if(n&&"string"==typeof n)for(const[t]of n.matchAll(/\S+/g))e.push(t);return e}function U(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function z(t){return`${t}px`}const V={attributes:!0,characterData:!0,childList:!0,subtree:!0};function W(e,n,o){let r=null,i=null,l=null,u=[];const s=document.createElement("div");function c(){null===r&&R(182),null===i&&R(183);const{left:t,top:l}=i.getBoundingClientRect(),c=M(e,n);var a,f;s.isConnected||(f=s,(a=i).insertBefore(f,a.firstChild));let d=!1;for(let e=0;e<c.length;e++){const n=c[e],o=u[e]||document.createElement("div"),r=o.style;"absolute"!==r.position&&(r.position="absolute",d=!0);const i=z(n.left-t);r.left!==i&&(r.left=i,d=!0);const a=z(n.top-l);r.top!==a&&(o.style.top=a,d=!0);const f=z(n.width);r.width!==f&&(o.style.width=f,d=!0);const g=z(n.height);r.height!==g&&(o.style.height=g,d=!0),o.parentNode!==s&&(s.append(o),d=!0),u[e]=o}for(;u.length>c.length;)u.pop();d&&o(u)}function a(){i=null,r=null,null!==l&&l.disconnect(),l=null,s.remove();for(const t of u)t.remove();u=[]}s.style.position="relative";const f=e.registerRootListener(function n(){const o=e.getRootElement();if(null===o)return a();const u=o.parentElement;if(!t(u))return a();a(),r=o,i=u,l=new MutationObserver(t=>{const o=e.getRootElement(),l=o&&o.parentElement;if(o!==r||l!==i)return n();for(const e of t)if(!s.contains(e.target))return c()}),l.observe(u,V),c()});return()=>{f(),a()}}function G(t,e,n){if("text"!==t.type&&o(e)){const o=e.getDOMSlot(n);return[o.element,o.getFirstChildOffset()+t.offset]}return[r(n)||n,t.offset]}function q(t,o){let r=null,i=null,l=null,u=null,s=null,c=null,a=()=>{};function f(f){f.read(()=>{const f=e();if(!n(f))return r=null,l=null,u=null,c=null,a(),void(a=()=>{});const[d,g]=function(t){const e=t.getStartEndPoints();return t.isBackward()?[e[1],e[0]]:e}(f),p=d.getNode(),m=p.getKey(),h=d.offset,v=g.getNode(),y=v.getKey(),w=g.offset,x=t.getElementByKey(m),E=t.getElementByKey(y),S=null===r||x!==i||h!==l||m!==r.getKey(),A=null===u||E!==s||w!==c||y!==u.getKey();if((S||A)&&null!==x&&null!==E){const e=function(t,e,n,o,r,i,l){const u=(t._window?t._window.document:document).createRange();return u.setStart(...G(e,n,o)),u.setEnd(...G(r,i,l)),u}(t,d,p,x,g,v,E);a(),a=W(t,e,t=>{if(void 0===o)for(const e of t){const t=e.style;"Highlight"!==t.background&&(t.background="Highlight"),"HighlightText"!==t.color&&(t.color="HighlightText"),t.marginTop!==z(-1.5)&&(t.marginTop=z(-1.5)),t.paddingTop!==z(4)&&(t.paddingTop=z(4)),t.paddingBottom!==z(0)&&(t.paddingBottom=z(0))}else o(t)})}r=p,i=x,l=h,u=v,s=E,c=w})}return f(t.getEditorState()),U(t.registerUpdateListener(({editorState:t})=>f(t)),()=>{a()})}function J(t){let e=null;const n=()=>{const n=getSelection(),o=n&&n.anchorNode,r=t.getRootElement();null!==o&&null!==r&&r.contains(o)?null!==e&&(e(),e=null):null===e&&(e=q(t))};return document.addEventListener("selectionchange",n),()=>{null!==e&&e(),document.removeEventListener("selectionchange",n)}}const Q=$,X=T,Y=H,Z=D,tt=_,et=I,nt=j,ot=k,rt=O,it=K;function lt(t,...e){const n=F(...e);n.length>0&&t.classList.add(...n)}function ut(t,...e){const n=F(...e);n.length>0&&t.classList.remove(...n)}function st(t,e){for(const n of e)if(t.type.startsWith(n))return!0;return!1}function ct(t,e){const n=t[Symbol.iterator]();return new Promise((t,o)=>{const r=[],i=()=>{const{done:l,value:u}=n.next();if(l)return t(r);const s=new FileReader;s.addEventListener("error",o),s.addEventListener("load",()=>{const t=s.result;"string"==typeof t&&r.push({file:u,result:t}),i()}),st(u,e)?s.readAsDataURL(u):i()};i()})}function at(t,e){return Array.from(gt(t,e))}function ft(t){return t?t.getAdjacentCaret():null}function dt(t,e){return Array.from(wt(t,e))}function gt(t,e){return mt("next",t,e)}function pt(t,e){const n=i(l(t,e));return n&&n[0]}function mt(t,e,n){const r=p(),s=e||r,c=o(s)?g(s,t):l(s,t),a=vt(s),f=n?h(u(l(n,t)))||pt(n,t):pt(s,t);let d=a;return P({hasNext:t=>null!==t,initial:c,map:t=>({depth:d,node:t.origin}),step:t=>{if(t.isSameNodeCaret(f))return null;v(t)&&d++;const e=i(t);return!e||e[0].isSameNodeCaret(f)?null:(d+=e[1],e[0])}})}function ht(t){const e=i(l(t,"next"));return e&&[e[0].origin,e[1]]}function vt(t){let e=-1;for(let n=t;null!==n;n=n.getParent())e++;return e}function yt(t){const e=u(l(t,"previous")),n=i(e,"root");return n&&n[0].origin}function wt(t,e){return mt("previous",t,e)}function xt(t,e){let n=t;for(;null!=n;){if(n instanceof e)return n;n=n.getParent()}return null}function Et(t){const e=s(t,t=>o(t)&&!t.isInline());return o(e)||R(4,t.__key),e}function St(t,e,n,o){const r=t=>t instanceof e;return t.registerNodeTransform(e,t=>{const e=(t=>{const e=t.getChildren();for(let t=0;t<e.length;t++){const n=e[t];if(r(n))return null}let n=t,o=t;for(;null!==n;)if(o=n,n=n.getParent(),r(n))return{child:o,parent:n};return null})(t);if(null!==e){const{child:r,parent:i}=e;if(r.is(t)){o(i,t);const e=r.getNextSiblings(),l=e.length;if(i.insertAfter(r),0!==l){const t=n(i);r.insertAfter(t);for(let n=0;n<l;n++)t.append(e[n])}i.canBeEmpty()||0!==i.getChildrenSize()||i.remove()}}})}function At(t,e){const n=new Map,o=t._pendingEditorState;for(const[t,o]of e._nodeMap)n.set(t,c(o));o&&(o._nodeMap=n),t._dirtyType=2;const r=e._selection;a(null===r?null:r.clone())}function Ct(t){const o=e()||f();let r;if(n(o))r=d(o.focus,"next");else{if(null!=o){const t=o.getNodes(),e=t[t.length-1];e&&(r=l(e,"next"))}r=r||g(p(),"previous").getFlipped().insert(m())}const i=bt(t,r),u=h(i),s=v(u)?y(u):i;return w(x(s)),t.getLatest()}function bt(t,e,n){let o=E(e,"next");for(let t=o;t;t=S(t,n))o=t;return A(o)&&R(283),o.insert(t.isInline()?m().append(t):t),E(l(t.getLatest(),"next"),e.direction)}function Lt(t,e){const n=e();return t.replace(n),n.append(t),n}function Pt(t,e){return null!==t&&Object.getPrototypeOf(t).constructor.name===e.name}function Nt(t,e){const n=[];for(let o=0;o<t.length;o++){const r=e(t[o]);null!==r&&n.push(r)}return n}function Mt(t,e){g(t,"next").insert(e)}let Rt=!(ot||!X)&&void 0;function Tt(t){let e=1;if(function(){if(void 0===Rt){const t=document.createElement("div");t.style.cssText="position: absolute; opacity: 0; width: 100px; left: -1000px;",document.body.appendChild(t);const e=t.getBoundingClientRect();t.style.setProperty("zoom","2"),Rt=t.getBoundingClientRect().width===e.width,document.body.removeChild(t)}return Rt}())for(;t;)e*=Number(window.getComputedStyle(t).getPropertyValue("zoom")),t=t.parentElement;return e}function Bt(t){return null!==t._parentEditor}function _t(t,e){return kt(t,e,null)}function kt(t,e,n){let r=!1;for(const i of Ot(t))e(i)?null!==n&&n(i):(r=!0,o(i)&&kt(i,e,n||(t=>i.insertAfter(t))),i.remove());return r}function $t(t,e){const n=[],r=Array.from(t).reverse();for(let t=r.pop();void 0!==t;t=r.pop())if(e(t))n.push(t);else if(o(t))for(const e of Ot(t))r.push(e);return n}function Kt(t){return Ht(g(t,"next"))}function Ot(t){return Ht(g(t,"previous"))}function Ht(t){return P({hasNext:N,initial:t.getAdjacentCaret(),map:t=>t.origin.getLatest(),step:t=>t.getAdjacentCaret()})}function jt(t){C(l(t,"next")).splice(1,t.getChildren())}function Dt(t){const e=e=>b(e,t),n=(e,n)=>L(e,t,n);return{$get:e,$set:n,accessors:[e,n],makeGetterMethod:()=>function(){return e(this)},makeSetterMethod:()=>function(t){return n(this,t)},stateConfig:t}}export{$t as $descendantsMatching,at as $dfs,gt as $dfsIterator,Nt as $filter,Kt as $firstToLastIterator,ft as $getAdjacentCaret,vt as $getDepth,Et as $getNearestBlockElementAncestorOrThrow,xt as $getNearestNodeOfType,yt as $getNextRightPreorderNode,ht as $getNextSiblingOrParentSibling,Mt as $insertFirst,Ct as $insertNodeToNearestRoot,bt as $insertNodeToNearestRootAtCaret,Bt as $isEditorIsNestedEditor,Ot as $lastToFirstIterator,At as $restoreEditorState,dt as $reverseDfs,wt as $reverseDfsIterator,_t as $unwrapAndFilterDescendants,jt as $unwrapNode,Lt as $wrapNodeInElement,Q as CAN_USE_BEFORE_INPUT,X as CAN_USE_DOM,Y as IS_ANDROID,Z as IS_ANDROID_CHROME,tt as IS_APPLE,et as IS_APPLE_WEBKIT,nt as IS_CHROME,ot as IS_FIREFOX,rt as IS_IOS,it as IS_SAFARI,lt as addClassNamesToElement,Tt as calculateZoomLevel,st as isMimeType,Dt as makeStateWrapper,q as markSelection,ct as mediaFileReader,U as mergeRegister,Pt as objectKlassEquals,W as positionNodeOnRange,St as registerNestedElementResolver,ut as removeClassNamesFromElement,J as selectionAlwaysOnDisplay};