UNPKG

@lexical/utils

Version:

This package contains misc utilities for Lexical.

10 lines (8 loc) 10.7 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. * */ import{isHTMLElement as t,$getSelection as e,$isRangeSelection as n,$isElementNode as o,getDOMTextNode as r,$getRoot as i,$getChildCaret as l,$getSiblingCaret as u,$getAdjacentChildCaret as s,$getChildCaretOrSelf as c,makeStepwiseIterator as f,$isChildCaret as a,$cloneWithProperties as d,$setSelection as g,$getPreviousSelection as p,$caretFromPoint as m,$createParagraphNode as h,$normalizeCaret as v,$setSelectionFromCaretRange as y,$getCollapsedCaretRange as w,$getCaretInDirection as x,$splitAtPointCaretNext as E,$isTextPointCaret as S,$isSiblingCaret as A,$rewindSiblingCaret as C,$getState as L,$setState as b}from"lexical";export{$splitNode,isBlockDomNode,isHTMLAnchorElement,isHTMLElement,isInlineDomNode}from"lexical";import{createRectsFromDOMRange as N}from"@lexical/selection";function P(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 M="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,R=M&&"documentMode"in document?document.documentMode:null,T=M&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),B=M&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),_=!(!M||!("InputEvent"in window)||R)&&"getTargetRanges"in new window.InputEvent("input"),k=M&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),K=M&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,H=M&&/Android/.test(navigator.userAgent),O=M&&/^(?=.*Chrome).*/i.test(navigator.userAgent),$=M&&H&&O,D=M&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!O;function I(...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 j(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function F(t){return`${t}px`}const U={attributes:!0,characterData:!0,childList:!0,subtree:!0};function z(e,n,o){let r=null,i=null,l=null,u=[];const s=document.createElement("div");function c(){null===r&&P(182),null===i&&P(183);const{left:t,top:l}=i.getBoundingClientRect(),c=N(e,n);var f,a;s.isConnected||(a=s,(f=i).insertBefore(a,f.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=F(n.left-t);r.left!==i&&(r.left=i,d=!0);const f=F(n.top-l);r.top!==f&&(o.style.top=f,d=!0);const a=F(n.width);r.width!==a&&(o.style.width=a,d=!0);const g=F(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 f(){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 a=e.registerRootListener((function n(){const o=e.getRootElement();if(null===o)return f();const u=o.parentElement;if(!t(u))return f();f(),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,U),c()}));return()=>{a(),f()}}function V(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 W(t,o){let r=null,i=null,l=null,u=null,s=null,c=null,f=()=>{};function a(a){a.read((()=>{const a=e();if(!n(a))return r=null,l=null,u=null,c=null,f(),void(f=()=>{});const{anchor:d,focus:g}=a,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 i.isBefore(n)?(u.setStart(...V(r,i,l)),u.setEnd(...V(e,n,o))):(u.setStart(...V(e,n,o)),u.setEnd(...V(r,i,l))),u}(t,d,p,x,g,v,E);f(),f=z(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!==F(-1.5)&&(t.marginTop=F(-1.5)),t.paddingTop!==F(4)&&(t.paddingTop=F(4)),t.paddingBottom!==F(0)&&(t.paddingBottom=F(0))}else o(t)}))}r=p,i=x,l=h,u=v,s=E,c=w}))}return a(t.getEditorState()),j(t.registerUpdateListener((({editorState:t})=>a(t))),(()=>{f()}))}function G(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=W(t))};return document.addEventListener("selectionchange",n),()=>{null!==e&&e(),document.removeEventListener("selectionchange",n)}}const q=_,J=M,Q=H,X=$,Y=T,Z=D,tt=O,et=B,nt=K,ot=k;function rt(t,...e){const n=I(...e);n.length>0&&t.classList.add(...n)}function it(t,...e){const n=I(...e);n.length>0&&t.classList.remove(...n)}function lt(t,e){for(const n of e)if(t.type.startsWith(n))return!0;return!1}function ut(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()})),lt(u,e)?s.readAsDataURL(u):i()};i()}))}function st(t,e){return Array.from(at(t,e))}function ct(t){return t?t.getAdjacentCaret():null}function ft(t,e){return Array.from(ht(t,e))}function at(t,e){return dt("next",t,e)}function dt(t,e,n){const r=i(),d=e||r,g=o(d)?l(d,t):u(d,t),p=pt(d),m=n?s(c(u(n,t))):function(t,e){const n=$t(u(t,e));return n&&n[0]}(d,t);let h=p;return f({hasNext:t=>null!==t,initial:g,map:t=>({depth:h,node:t.origin}),step:t=>{if(t.isSameNodeCaret(m))return null;a(t)&&h++;const e=$t(t);return!e||e[0].isSameNodeCaret(m)?null:(h+=e[1],e[0])}})}function gt(t){const e=$t(u(t,"next"));return e&&[e[0].origin,e[1]]}function pt(t){let e=-1;for(let n=t;null!==n;n=n.getParent())e++;return e}function mt(t){const e=$t(c(u(t,"previous")),"root");return e&&e[0].origin}function ht(t,e){return dt("previous",t,e)}function vt(t,e){let n=t;for(;null!=n;){if(n instanceof e)return n;n=n.getParent()}return null}function yt(t){const e=wt(t,(t=>o(t)&&!t.isInline()));return o(e)||P(4,t.__key),e}const wt=(t,e)=>{let n=t;for(;n!==i()&&null!=n;){if(e(n))return n;n=n.getParent()}return null};function xt(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 Et(t,e){const n=new Map,o=t._pendingEditorState;for(const[t,o]of e._nodeMap)n.set(t,d(o));o&&(o._nodeMap=n),t._dirtyType=2;const r=e._selection;g(null===r?null:r.clone())}function St(t){const o=e()||p();let r;if(n(o))r=m(o.focus,"next");else{if(null!=o){const t=o.getNodes(),e=t[t.length-1];e&&(r=u(e,"next"))}r=r||l(i(),"previous").getFlipped().insert(h())}const c=At(t,r),f=s(c),d=a(f)?v(f):c;return y(w(d)),t.getLatest()}function At(t,e,n){let o=x(e,"next");for(let t=o;t;t=E(t,n))o=t;return S(o)&&P(283),o.insert(t.isInline()?h().append(t):t),x(u(t.getLatest(),"next"),e.direction)}function Ct(t,e){const n=e();return t.replace(n),n.append(t),n}function Lt(t,e){return null!==t&&Object.getPrototypeOf(t).constructor.name===e.name}function bt(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 Nt(t,e){l(t,"next").insert(e)}let Pt=!(et||!J)&&void 0;function Mt(t){let e=1;if(function(){if(void 0===Pt){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"),Pt=t.getBoundingClientRect().width===e.width,document.body.removeChild(t)}return Pt}())for(;t;)e*=Number(window.getComputedStyle(t).getPropertyValue("zoom")),t=t.parentElement;return e}function Rt(t){return null!==t._parentEditor}function Tt(t,e){return Bt(t,e,null)}function Bt(t,e,n){let r=!1;for(const i of Kt(t))e(i)?null!==n&&n(i):(r=!0,o(i)&&Bt(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 Kt(t))r.push(e);return n}function kt(t){return Ht(l(t,"next"))}function Kt(t){return Ht(l(t,"previous"))}function Ht(t){return f({hasNext:A,initial:t.getAdjacentCaret(),map:t=>t.origin.getLatest(),step:t=>t.getAdjacentCaret()})}function Ot(t){C(u(t,"next")).splice(1,t.getChildren())}function $t(t,e="root"){let n=0,o=t,r=s(o);for(;null===r;){if(n--,r=o.getParentCaret(e),!r)return null;o=r,r=s(o)}return r&&[r,n]}function Dt(t){const e=e=>L(e,t),n=(e,n)=>b(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,st as $dfs,at as $dfsIterator,bt as $filter,wt as $findMatchingParent,kt as $firstToLastIterator,ct as $getAdjacentCaret,$t as $getAdjacentSiblingOrParentSiblingCaret,pt as $getDepth,yt as $getNearestBlockElementAncestorOrThrow,vt as $getNearestNodeOfType,mt as $getNextRightPreorderNode,gt as $getNextSiblingOrParentSibling,Nt as $insertFirst,St as $insertNodeToNearestRoot,At as $insertNodeToNearestRootAtCaret,Rt as $isEditorIsNestedEditor,Kt as $lastToFirstIterator,Et as $restoreEditorState,ft as $reverseDfs,ht as $reverseDfsIterator,Tt as $unwrapAndFilterDescendants,Ot as $unwrapNode,Ct as $wrapNodeInElement,q as CAN_USE_BEFORE_INPUT,J as CAN_USE_DOM,Q as IS_ANDROID,X as IS_ANDROID_CHROME,Y as IS_APPLE,Z as IS_APPLE_WEBKIT,tt as IS_CHROME,et as IS_FIREFOX,nt as IS_IOS,ot as IS_SAFARI,rt as addClassNamesToElement,Mt as calculateZoomLevel,lt as isMimeType,Dt as makeStateWrapper,W as markSelection,ut as mediaFileReader,j as mergeRegister,Lt as objectKlassEquals,z as positionNodeOnRange,xt as registerNestedElementResolver,it as removeClassNamesFromElement,G as selectionAlwaysOnDisplay};