@betteroffice/xlsx-react 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import {a as a$1,e,d as d$2,b}from'./chunk-PCFKBGCZ.js';import {a as a$3,d as d$1}from'./chunk-UQEPJKDK.js';import {a as a$5}from'./chunk-XP7OJI3S.js';import {a as a$4}from'./chunk-QQHWSDLQ.js';import {ba,Fa as Fa$1,X,N,W,ea as ea$1,z,A,s,p,R,Q,O,B,Ba as Ba$1,I,r,q,t,a,o,D,C,n,j,za as za$1,P,ha,M,L,H,G as G$1,K,aa,_,da as da$1,Ca,ca,Aa,i,T,S as S$1,V as V$1,Da as Da$1,Ea,m,ia,ga,ua,Y,Z,F,h as h$1,g,y as y$1,u as u$1,w,xa,ya,va,x as x$1,e as e$1,ta as ta$1,na as na$1,pa,qa,oa,ja as ja$2,ra as ra$1,b as b$1,wa as wa$1,E as E$1,$}from'./chunk-3KQXHXGC.js';import {c,V,U,G,y,ja as ja$1,da,x,q as q$1,v,E,u,R as R$1,S,d,n as n$1,h,B as B$1,A as A$1,p as p$1,o as o$1,j as j$1,r as r$1}from'./chunk-NLAF4WIP.js';import'./chunk-WTQ7SZBY.js';import {a as a$2}from'./chunk-O2XFH626.js';import {normalizeRange,rangeRect,cellRect,buildA11yGrid,isProposalsAvailable,selectionAt,paintDisplayList,hyperlinkAtCell,chartRegionAtPoint,cellAtPoint,extendTo,safeExternalHyperlink,parseHyperlinkLocation,selectionKeyReducer,workbookSessionRecovery,WorkbookRecoveryReplayError,toTsv}from'@betteroffice/xlsx';import {createContext,memo,useContext,useState,useRef,useLayoutEffect,useMemo,useEffect,useSyncExternalStore,useCallback,useId,useReducer}from'react';import {flushSync}from'react-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';function yt(){let r,e,n=null,o=new Set,l=new Promise((a,h)=>{r=a,e=h;});return l.catch(()=>{}),{promise:l,resolve:r,reject(a){n={error:a},e(a);for(let h of o)h(a);o.clear();},wait(a){return n?(Promise.resolve(a).catch(()=>{}),Promise.reject(n.error)):new Promise((h,b)=>{let c=m=>{o.delete(c),b(m);};o.add(c),Promise.resolve(a).then(m=>{o.delete(c),h(m);},c);})}}}function kt(r,e){return r.generation===e.generation&&r.source===e.source&&r.sheet===e.sheet&&r.row===e.row&&r.col===e.col}function Ns(r,e){return kt(r,e)&&r.value===e.value&&(!("revision"in r&&"revision"in e)||r.revision===e.revision)}function Wl(r){return typeof r?.then=="function"}function Bs(r){return "target"in r.payload?structuredClone(r.payload.target??null):"toolbar"in r.payload?structuredClone(r.payload.toolbar.target??null):"selection"in r.payload?structuredClone(r.payload.selection??null):null}function $s(r,e){return e&&r.kind!=="setReadOnly"&&r.kind!=="applyUpdate"&&r.kind!=="collabPipe"?{...r,payload:{...r.payload,selection:e}}:r}function js(r){let e=(d,E)=>Number.isSafeInteger(d)&&d>0?Math.min(d,128):E,n=e(r.maxOutstanding,64),o=e(r.maxQueued,128),l=new Set,a=new Set,h=null,b="",c=r.generation(),m=yt(),P=[],C=[],x=new Map,L=new Map,v$1=null,f=[],M=new WeakMap,w=null,q=false,y=false,T=1,X=0,G=0,Q,re,_,D=new Map,Ie=new WeakMap,$=new WeakMap,he=1,de=r.readOnly?.()??false,ie=()=>{},ge=()=>{},we=false,O=null,Z=null,Fe=null,Le,Ae=d=>{let E=false,H=()=>{if(!E){E=true;for(let F of l)try{F(d);}catch{}}};try{r.onEvent?.(d,H);}catch{}H();},fe=(d,E)=>{d.ticket.outcome||d.ticket.failure||(d.ticket.failure={error:E},re===d.ticket&&(re=void 0),_===d.ticket&&(_=void 0),d.result.reject(E),Ae({type:"cancelled",seq:d.ticket.seq,target:d.target,draft:d.draft}));},et=(d,E,H)=>{if(!(d.ticket.outcome||d.ticket.failure)){d.ticket.failure={error:H},re===d.ticket&&(re=void 0),_===d.ticket&&(_=void 0),M.set(E,H),f=[...f.filter(F=>!kt(F,E)),E].slice(-o),v$1||(v$1=E),d.result.reject(H),Ae({type:"refused",seq:null,target:d.target,draft:E,error:H});for(let F of P)"ticket"in F&&F!==d&&tt(F)&&fe(F,H);}},Be=d=>{ie(),ge(),m.reject(d);for(let E of [...P,...x.values()])"ticket"in E?fe(E,d):E.reject(d);P=[],x=new Map,L.clear(),C=[],O=null,m=yt(),re=void 0,Q=void 0,_=void 0,v$1=null,f=[],D=new Map,$=new WeakMap,Ie=new WeakMap,a.clear();},ee=()=>{if(q)return;let d=r.session(),E=d?`${d.commandIdentity.session}:${d.commandIdentity.incarnation}:${d.confirmedBasis.epoch}`:"";if(d===h&&E===b&&c===r.generation())return;Be(new u("document-replaced")),h=d,b=E,c=r.generation(),y=false,w=null,de=r.readOnly?.()??false,X=h?.throughSeq??0,G=X,T=X+1;let H=m;ie=h?.onAck(F=>{if(ee(),H!==m||q||w||F.frame&&(F.frame.session!==h?.commandIdentity.session||F.frame.incarnation!==h?.commandIdentity.incarnation))return;let ue=F.statuses.filter(pe=>pe.committed&&pe.status==="applied"),oe=ue.length?L.get(ue[0].seq)?.acknowledge:void 0;for(let pe of F.statuses)Pe(pe);if(F.throughSeq>=X){X=F.throughSeq;let pe=()=>Ae({type:"coverage",throughSeq:X,coversThroughSeq:F.frame?.coversThroughSeq,ack:F});oe&&ue.every(le=>L.get(le.seq)?.acknowledge===oe)?oe(pe):pe();for(let le of L.keys())le<=X&&L.delete(le);}Se();})??(()=>{}),ge=h?.onFailure?.(F=>{ee(),H===m&&Te(F);})??(()=>{}),h?.failure&&Te(h.failure);},Te=d=>{if(w||q)return;C=(O&&!("ticket"in O)?[O,...P]:P).flatMap(H=>{if("ticket"in H&&(H.ticket.failure||tt(H)))return [];let F="ticket"in H?H.input:H.recoveryInput?.();return F?[structuredClone(F)]:[]}),w={error:d},de=true,m.reject(d);for(let H of [...P,...x.values()])"ticket"in H?fe(H,d):H.reject(d);P=[],x.clear(),L.clear(),a.clear();try{r.onError?.(d);}catch{}},tt=d=>{let E=d.after;return typeof E=="object"&&E.failure},Pe=d=>{let E=x.get(d.seq);if(E)if(x.delete(d.seq),E.ticket.outcome=d,d.status==="applied"||d.status==="noop")E.draft&&(f=f.filter(H=>!kt(H,E.draft))),E.result.resolve(d),Ae({type:"accepted",seq:d.seq,target:E.target,draft:E.draft,status:d});else {let H=new $e(d,E.target,E.draft,E.input);E.ticket.failure={error:H},re===E.ticket&&(re=void 0),_===E.ticket&&(_=void 0),d.status==="refused"&&E.draft&&(H.code==="sheet-protected"&&M.set(E.draft,H),f=[...f.filter(F=>!kt(F,E.draft)),E.draft].slice(-o),v$1||(v$1=E.draft)),E.result.reject(H),Ae({type:d.status,seq:d.seq,target:E.target,draft:E.draft,status:d});for(let F of P)"ticket"in F&&tt(F)&&fe(F,H);}},Ce=()=>{if(ee(),q)throw new u("document-replaced");if(y)throw new u("document-replaced");if(w)throw w.error;if(!r.isReady()||!h?.commandIdentity.session||!h.commandIdentity.incarnation)throw new u("editor-unavailable")},Me=d=>{if(P.length>=o)throw new E("Worker input queue is full");Z===null?P.push(d):P.splice(Z++,0,d);},Se=()=>{if(ee(),!(we||O||w||q||y)){we=true;try{for(;P.length&&!w&&!q;){let d=P[0];if("ticket"in d){if(d.ticket.failure){P.shift();continue}let E$1=tt(d);if(E$1){P.shift(),fe(d,E$1.error);continue}if(d.gate){if(x.size>0)break;let oe=d.gate;d.gate=void 0;try{d.prepare=oe(),d.prepare.catch(()=>{});}catch(pe){P.shift(),fe(d,pe);continue}}if(d.prepare){let oe=m;O=d,oe.wait(d.prepare).then(pe=>{if(!(oe!==m||O!==d)){try{d.input=structuredClone($s(pe,d.selection)),d.target=Bs(d.input),d.prepare=void 0,d.draft&&d.input.kind==="editCell"&&(d.draft=Object.freeze({...d.draft,value:d.input.payload.args[3]}));}catch(le){fe(d,le);}O=null,Se();}},pe=>{oe!==m||O!==d||(pe instanceof v&&d.draft?et(d,d.draft,pe):fe(d,pe),O=null,Se());});break}if(x.size>=n)break;let H=typeof d.after=="object"?d.after:void 0;if(H?.lease&&H.lease!==m){P.shift(),fe(d,new u("document-replaced"));continue}let F=H?.outcome?void 0:typeof d.after=="number"?d.after:d.after?.seq??void 0;if(typeof d.after=="number"&&(!Number.isSafeInteger(d.after)||d.after<=0||d.after>=T)){P.shift(),fe(d,new E("Invalid command dependency"));continue}if(d.after&&!H?.outcome&&F===void 0)break;P.shift();let ue=()=>{let oe=T++;(d.frame||!(d.input?.kind==="applyOps"&&"toolbar"in d.input.payload&&d.input.payload.toolbar.id==="refreshProposals"))&&(G=oe),Object.defineProperty(d.ticket,"seq",{value:oe,configurable:!0});let pe={...structuredClone(d.input),...h.commandIdentity,seq:oe,basis:{...h.confirmedBasis},...F?{afterSeq:F}:{},...d.frame?{frame:d.frame}:{}};x.set(oe,d),d.ticket.acknowledge&&L.set(oe,d.ticket);let le=m;if(Ae({type:"dispatched",seq:oe,target:d.target,draft:d.draft,command:pe,selectionRevision:d.selectionRevision}),!(le!==m||w||q))try{h.submit(pe).then(Re=>{ee(),!(le!==m||w||q)&&(Pe(Re),Se());},Re=>{ee(),le===m&&Te(Re);});}catch(Re){Te(Re);}};try{d.dispatch?d.dispatch(ue):ue();}catch(oe){fe(d,oe);}if(w||q)break}else {P.shift(),Z=0;try{let E=d.run();if(Wl(E)){O=d;let H=m;H.wait(E).then(()=>{H!==m||O!==d||(O=null,Se());},F=>{d.reject(F),!(H!==m||O!==d)&&(O=null,Se());});break}}catch(E){d.reject(E);}finally{Z=null;}}}}finally{we=false;}}},ut=(d,E,H={},F=false,ue,oe)=>{let pe=yt(),le={seq:null,result:pe.promise,lease:m,acknowledge:H.acknowledge},Re=null;try{if(Re=d?Bs(d):null,Ce(),le.lease=m,(Fe??de)&&(ue||oe||d&&d.kind!=="select"&&d.kind!=="setActiveSheet"&&d.kind!=="setReadOnly"&&d.kind!=="applyUpdate"&&d.kind!=="collabPipe"&&!(r.allowHostProposals?.()&&(d.kind==="propose"||d.kind==="acceptProposal"||d.kind==="rejectProposal"))&&!(d.kind==="applyOps"&&"toolbar"in d.payload&&d.payload.toolbar.id==="refreshProposals")))throw new u("input-failed");let Ee={input:d?structuredClone($s(d,H.selection)):null,draft:E?Object.freeze({...E}):null,target:Re,after:H.after===null?void 0:H.after??(Le!==void 0?(F?Le.last:Le.boundary)??void 0:F?_:re),ticket:le,result:pe,fence:F,prepare:ue,gate:oe,dispatch:H.dispatch,frame:structuredClone("frame"in H?H.frame:r.frame?.()),selection:structuredClone(H.selection),selectionRevision:"selectionRevision"in H?H.selectionRevision:r.selectionRevision?.()},ye=P[P.length-1];if(!F&&!ue&&!oe&&E&&ye&&"ticket"in ye&&!ye.fence&&!ye.ticket.failure&&!ye.prepare&&!ye.gate&&ye.draft&&kt(ye.draft,E)&&ye.after===Ee.after&&JSON.stringify(ye.target)===JSON.stringify(Ee.target))return ye.input=Ee.input,ye.draft=Ee.draft,ye.frame=Ee.frame,ye.selectionRevision=Ee.selectionRevision,Ie.set(E,ye.ticket),ye.ticket;Me(Ee),_=le,F&&(re=le),Se();}catch(Ee){le.failure={error:Ee},pe.reject(Ee);let ye=E?Object.freeze({...E}):null;ye&&(f=[...f.filter(qe=>!kt(qe,ye)),ye].slice(-o),v$1||(v$1=ye)),Ae({type:"refused",seq:null,target:Re,draft:ye});}return le},Zt=(d,E={})=>{ee();let H=E.compositionId?D.get(E.compositionId):Ie.get(d);if(H&&(E.compositionId||!H.failure))return H;let F;if("modified"in d&&d.modified===false||E.compositionId&&d.value===""){let ue={seq:0,status:"noop",committed:false};F={seq:null,result:Promise.resolve(ue),outcome:ue,lease:m};}else if(d.generation!==c){let ue=yt(),oe=new u("document-replaced");ue.reject(oe),F={seq:null,result:ue.promise,failure:{error:oe}};}else try{let ue=E.target??r.draftTarget?.(d)??r.target(d.sheet,d.row,d.col),oe=le=>({kind:"editCell",payload:{args:[d.sheet,d.row,d.col,le],target:ue}}),pe=r.gateCommit?.(d,ue)??null;F=ut(pe?null:oe(d.value),d,{...E,after:E.after===void 0?r.dependency?.(d)??null:E.after},!!(E.compositionId||E.selection),void 0,pe?()=>pe().then(oe):void 0);}catch(ue){let oe=yt();oe.reject(ue),F={seq:null,result:oe.promise,failure:{error:ue}};let pe=Object.freeze({...d});f=[...f.filter(le=>!kt(le,pe)),pe].slice(-o),v$1||(v$1=pe),Ae({type:"refused",seq:null,target:null,draft:pe});}return Ie.set(d,F),!F.failure&&v$1&&kt(v$1,d)&&v$1.value===d.value&&(v$1=null),E.compositionId&&(D.set(E.compositionId,F),D.size>o&&D.delete(D.keys().next().value)),F},dt=(d,E$1=false,H)=>{let F=yt();try{if(Ce(),a.size>=o)throw new E("Worker input queue is full");a.add(F),F.promise.then(()=>a.delete(F),()=>a.delete(F));let ue=m,oe=de,pe={last:_??null,boundary:re??null},le=H?{pendingInput:H}:r.seal();if(le.refused)throw new u(le.refused);let Re=Q,Ee=le.pendingInput?.ready??le.composition,ye=le.pendingInput?.draft??le.compositionDraft,qe=le.pendingInput?.ticket,Oe=!qe&&Ee!==Re?.composition?Ee:void 0;Ee||r.sync();let xe=Re?.compositionDraft?.()??Re?.pendingTarget,De=xe&&v$1&&!Ns(xe,v$1),Ke=!Oe&&Re?.composition&&!De?Re:qe?{ticket:Re?.ticket??qe}:{},ot=Oe?yt():void 0,Qt=ae=>{Ke.ticket=ae;let ke=()=>{Q===Ke&&(Q=void 0);};ae?ae.result.then(ke,ke):ke();},ne=Oe&&!le.pendingInput&&v$1?{...v$1}:null,st=ae=>ne?{...ae,generation:ne.generation,sheet:ne.sheet,row:ne.row,col:ne.col,source:ne.source}:ae,at=Oe&&!le.pendingInput?r.compositionId?.()??$.get(Oe)??`local-composition:${he++}`:void 0;Oe&&at&&$.set(Oe,at);let bt,Cr=!1;if(ot){let ae={seq:null,result:ot.promise,lease:m};Object.defineProperty(ae,"seq",{get:()=>bt?.seq??null}),ot.promise.then(ke=>{ae.outcome=ke,Se();},ke=>{ae.failure={error:ke},re===ae&&(re=void 0),_===ae&&(_=void 0),Se();}),F.promise.catch(ot.reject),Ke.composition=Oe,Ke.compositionDraft=ye,Ke.pendingTarget=le.pendingInput?.target,Q=Ke,Qt(ae),le.pendingInput&&(le.pendingInput.ticket=ae,_=re=ae);}else Ke.composition||(Ee&&!qe&&r.sync(),v$1&&(!qe||!Ns(v$1,le.pendingInput.target))&&(Q=Ke,bt=Zt(v$1,{after:Re?.ticket??qe}),Qt(bt)));let Tt=[...x.values(),...P.slice(0,Z??P.length).filter(ae=>"ticket"in ae)].map(ae=>ae.ticket.result);Ke.ticket&&Tt.push(Ke.ticket.result);let Ge=()=>{if(ue!==m)throw new u("document-replaced");Ce();let ae=Fe,ke=Le;Fe=oe;let nt=bt??Ke.ticket??Re?.ticket;Le=nt?{last:nt,boundary:nt}:pe;try{let Ue=d();return ue.wait(Ue).then(er=>{le.restoreFocus?.(),F.resolve(er);},F.reject),E$1===!0||E$1==="settled"||E$1==="read"?Promise.resolve(Ue).then(()=>{}):void 0}finally{Fe=ae,Le=ke;}},rt=async()=>{let ae=[...Tt,...[...x.values()].map(er=>er.ticket.result)];if(E$1==="settled"||E$1==="read")await ue.wait(Promise.allSettled(ae));else if(await ue.wait(Promise.all(ae)),f.length)throw M.get(f[0])??new u("input-failed");let ke=we,nt=Z;we=!0,Z=0;let Ue;try{Ue=Ge();}finally{Z=nt,we=ke;}await Ue;};Me({preservesMerges:E$1==="read"||!!H,reject:F.reject,recoveryInput:()=>{if(!Oe||Cr||oe||Ke.ticket?.failure||Re?.ticket?.failure)return null;let ae=ye?.();if(!ae||ae.generation!==c||ae.value===""&&!le.pendingInput||"modified"in ae&&ae.modified===!1)return null;let ke=st(ae),nt=r.draftTarget?.(ke)??r.target(ke.sheet,ke.row,ke.col);return {kind:"editCell",payload:{args:[ke.sheet,ke.row,ke.col,ke.value],target:nt}}},run:()=>Oe||E$1?(async()=>{if(Oe){let ae=await ue.wait(Oe);if(ue!==m)throw new u("document-replaced");we=!0,Z=0;try{if(ae){let ke=ye?.();ye||(r.sync(),ke=v$1);let nt=Fe;Fe=oe;try{ke&&(Cr=!0,bt=Zt(st(ke),{...le.pendingInput?.options,compositionId:at,after:Re?.ticket}));}finally{Fe=nt;}}bt??(bt=Re?.ticket),ot.resolve(bt?.result??{seq:0,status:"noop",committed:!1}),Ke.composition=void 0,E$1?Me({preservesMerges:E$1==="read"||!!H,run:rt,reject:F.reject}):Ge();}finally{Z=null,we=!1,O=null,Se();}return}await rt();})():Ge()}),Se();}catch(ue){F.reject(ue);}return F.promise};return ee(),{get draft(){return ee(),v$1},get committed(){return ee(),[...x.values(),...P.filter(d=>"ticket"in d)].flatMap(d=>d.draft&&!d.ticket.failure?[d.draft]:[])},get rejected(){return ee(),f},get pending(){return ee(),P.length>0||x.size>0||O!==null},get pendingSelectionGeometryStable(){return ee(),[...P,...x.values(),...O?[O]:[]].every(d=>"ticket"in d?d.input!==null&&(["select","setActiveSheet","editCell","editCells"].includes(d.input.kind)||d.input.kind==="applyOps"&&"toolbar"in d.input.payload&&["refreshProposals","paintFormat"].includes(d.input.payload.toolbar.id)):d.preservesMerges===true)},get error(){return ee(),w?.error??null},get readOnly(){return ee(),de||w!==null||q||y},get throughSeq(){return ee(),X},get submittedThroughSeq(){return ee(),T-1},get recoveryCommands(){return structuredClone(C)},setDraft(d){ee(),!Q?.pendingTarget&&(!d||!v$1&&!Q?.composition)&&(Q=void 0),v$1=d?Object.freeze({...d}):null;},discardRejected(d){ee(),f=f.filter(E=>!kt(E,d)),v$1&&kt(v$1,d)&&(v$1=null);},submit(d,E){return ee(),Zt(d,{...E,after:Q?.pendingTarget?Q.ticket??E?.after:E?.after})},reserveInput(d){if(ee(),d.ticket)return d.ticket;let E=dt(()=>{},false,d);return E.catch(()=>{}),Q?.composition===d.ready&&Q.ticket?Q.ticket:{seq:null,result:E.then(()=>({seq:0,status:"noop",committed:false}))}},command:(d,E)=>ut(d,null,E,d.kind==="setReadOnly"),clipboard(d,E$1,H){try{if(Ce(),P.length>=o)throw new E("Worker input queue is full");let F={...H,target:structuredClone(H?.target),selection:structuredClone(H?.selection),frame:structuredClone(H?.frame??r.frame?.()),selectionRevision:H?.selectionRevision??r.selectionRevision?.()},ue=m,oe=d(),pe=F.target,le=ue.wait(oe).then(qe=>{if(Ce(),ue!==m)throw new u("document-replaced");let Oe=E$1(qe);return pe?{...Oe,payload:{...Oe.payload,target:pe}}:Oe});le.catch(()=>{});let Re=yt(),Ee={seq:null,result:Re.promise,lease:m};return dt(()=>{let qe=ut(null,null,F,!0,le);return Object.defineProperty(Ee,"seq",{get:()=>qe.seq}),qe.result}).then(qe=>{Ee.outcome=qe,Re.resolve(qe);},qe=>{Ee.failure={error:qe},Re.reject(qe);}),Ee}catch(F){let ue=yt();return ue.reject(F),{seq:null,result:ue.promise}}},setReadOnly(d,E){ee();let H=yt(),F={seq:null,result:H.promise,lease:m};return dt(()=>{let oe=ut({kind:"setReadOnly",payload:{readOnly:d,...E!==void 0?{allowHostProposals:E}:{}}},null,{after:null},!0);return Object.defineProperty(F,"seq",{get:()=>oe.seq}),oe.result}).then(oe=>{F.outcome=oe,H.resolve(oe);},oe=>{!d&&F.lease===m&&(de=true),F.failure={error:oe},H.reject(oe);}),de=d,F},runAfterPendingInput:dt,flush:()=>dt(()=>{},true),whenApplied(d=T-1){try{if(Ce(),!Number.isSafeInteger(d)||d<0||d>=T)throw new E("Invalid command sequence");let E$1=m;return E$1.wait(Promise.all([...x.entries()].filter(([H])=>H<=d).map(([,H])=>H.ticket.result.catch(F=>{if(!(F instanceof $e))throw F})))).then(()=>{if(E$1!==m)throw new u("document-replaced");Ce();})}catch(E){return Promise.reject(E)}},save:()=>dt(()=>h.save(),true),whenPresented:d=>dt(()=>h.whenPresented(d??G),true),subscribe(d){return l.add(d),()=>{l.delete(d);}},fail:Te,reset(){ee(),Be(new u("document-replaced")),y=true;},retire(){q=true,Be(new u("document-replaced")),l.clear();}}}var $e=class extends E{constructor(n,o,l,a=null){let h=n.result,b$1=n.reason==="locked-target"&&B$1(h?.failure?.message??""),c=!b$1&&d$2(n,l,a);super(b$1?A$1:n.reason??"Worker command refused",false,b$1?"sheet-protected":c?"edit-unsupported":"input-failed");a$2(this,"status",n);a$2(this,"target",o);a$2(this,"draft",l);a$2(this,"input",a);a$2(this,"cause");this.cause=c?b(n):null,this.name="XlsxWorkerCommandRefusal";}};var Il=new Set(["zoom","searchMenus","proposalsPanel","cut","copy","paste","pastePlainText"]);function Tl(r,e){let n=new Set(e.map(o=>o.toLowerCase()));for(let o=e.length+1;;o++){let l=`${r}${o}`;if(!n.has(l.toLowerCase()))return l}}function El(r){return typeof r=="object"&&r!==null&&r.name==="NotAllowedError"}function ql(r){if(r.range.kind==="rowCol")return {top:r.range.start.row,left:r.range.start.col,bottom:r.range.end.row,right:r.range.end.col};let e=/^\$?([A-Za-z]+)\$?([1-9]\d*)(?::\$?([A-Za-z]+)\$?([1-9]\d*))?$/.exec(r.range.a1);if(!e)return null;let n=o=>[...o.toUpperCase()].reduce((l,a)=>l*26+a.charCodeAt(0)-64,0)-1;return {top:Number(e[2])-1,left:n(e[1]),bottom:Number(e[4]??e[2])-1,right:n(e[3]??e[1])}}function _s(r){let e=(n,o)=>{let l="";for(let a=o+1;a>0;a=Math.floor((a-1)/26))l=String.fromCharCode(65+(a-1)%26)+l;return `${l}${n+1}`};return `${e(r.top,r.left)}:${e(r.bottom,r.right)}`}function Al(r){let e=new Set,n=null,o=null,l="",a="",h=0,b=()=>{},c=()=>{},m=null,P=()=>{let w=r(),q=w.session();if(w.selection)return structuredClone(w.selection()??void 0);if(q?.selection)return structuredClone(q.selection);let y=w.view(),T=q?.editState.sheets?.find(G=>G.index===y.sheet)?.id;if(!T||!y.selection)return;let X=normalizeRange(y.selection);return {sheetId:T,activeCell:{...y.selection.anchor},range:{kind:"rowCol",start:{row:X.top,col:X.left},end:{row:X.bottom,col:X.right}}}},C=()=>{let w=r().session();return `${r().generation()}:${w?.commandIdentity.session}:${w?.commandIdentity.incarnation}:${w?.confirmedBasis.epoch}`},x=()=>{let w=r().session(),q=w?.editState;return JSON.stringify({formatting:q?.formatting,formattingAvailable:q?.formattingAvailable,selectionEditable:q?.selectionEditable,mergedRanges:q?.mergedRanges,canUndo:q?.canUndo,canRedo:q?.canRedo,readOnly:q?.readOnly,activeSheet:q?.activeSheet,sheets:q?.sheets,selection:w?.selection})},L=()=>{let w=r().session(),q=r().coordinator,y=C();if(w===n&&q===o&&l===y)return;b(),c(),n=w,o=q,l=y,h=0,a=x();let T=q.pending;c=q.subscribe(()=>{if(r().coordinator!==q||r().session()!==w||l!==y||C()!==y)return;let X=q.pending;if(X!==T){T=X;for(let G of e)G();}}),b=w?.onAck(X=>{if(r().session()!==w||l!==y||C()!==y||!X.selection&&(!X.editState||Object.keys(X.editState).every(Q=>Q==="calculation")))return;let G=x();if(G!==a){a=G;for(let Q of e)Q();}})??(()=>{});},v=w=>{if(L(),w&&m)return {...m.env,allowHostProposals:r().allowHostProposals?.()};let q=r(),y=q.view(),T=q.session(),X=T?.editState??{},G=q.selection?q.selection():T?.selection,Q=G?ql(G):q.selection?null:y.selection?normalizeRange(y.selection):null,re=G?X.sheets?.find(_=>_.id===G.sheetId)?.index??y.sheet:y.sheet;return {status:q.status(),readOnly:q.readOnly()||q.coordinator.readOnly||X.readOnly===true,allowHostProposals:q.allowHostProposals?.(),collaborative:q.collaborative(),selection:y.chartSelected?"chart":Q?{sheet:re,...Q,merged:X.mergedRanges??[],formatting:X.formattingAvailable===false?null:X.formatting??null}:null,canUndo:q.coordinator.pending||(X.canUndo??false),canRedo:q.coordinator.pending||(X.canRedo??false),pendingInput:q.coordinator.draft!==null||q.coordinator.committed.length>0,zoom:y.zoom,paintFormat:q.formatToken()!==null,borderStyle:y.borderStyle??X.formatting?.borderStyle??null,borderColor:y.borderColor??X.formatting?.borderColor??null,pngExport:T?.pngExport===true,proposals:y.proposalsAvailable?y.proposals.map(_=>({id:_.id,label:_.agentId})):null,proposalsPanelOpen:y.proposalsPanelOpen,fontFamilies:o$1,fontSizes:p$1,translate:q.translate,workbook:q.menu&&X.sheets?{sheets:[...X.sheets].sort((_,D)=>_.index-D.index).map(_=>_.name),active:y.sheet,clipboardRead:typeof navigator<"u"&&typeof navigator.clipboard?.readText=="function"}:void 0,hostDisabled:X.selectionEditable===false?new Set(Object.keys(j$1).filter(r$1)):void 0}},f=(w,q=v(false))=>{if(!r$1(w))return "document";let y=q.selection;return y==="chart"?"chart":y?`${y.sheet}:${y.top}:${y.left}:${y.bottom}:${y.right}`:"none"};return {requestSave:w=>r().requestSave?.(w)??w(),environment:v,ordered:w=>!Il.has(w),perform:async(w,q,y)=>{let T=r(),X=T.generation(),G=T.session(),Q=m,re=Q?Q.selection:P(),_=(O=true)=>({ok:true,status:O?"executed":"noop"}),D=O=>({ok:false,failure:n$1(O,y)});if(w==="zoom"){let O=q.scale;return O===y.zoom?_(false):(T.setZoom(O),_())}if(w==="proposalsPanel"){let O=q===null?!y.proposalsPanelOpen:q.open;return O===y.proposalsPanelOpen?_(false):(T.setProposalsPanelOpen(O),_())}if(w==="findReplace")return T.setReplaceOpen?.(true),_(false);if(!G)return D("editor-unavailable");if(w==="paintFormat"){let O=T.formatToken()!==null;if(T.setFormatToken(null),O)return _()}let Ie=T.formatRevision(),$=typeof y.selection=="object"?y.selection:null,he=$?G.editState.sheets?.find(O=>O.index===$.sheet)?.id:void 0,de=$&&he?{sheetId:he,range:{kind:"rowCol",start:{row:$.top,col:$.left},end:{row:$.bottom,col:$.right}}}:void 0,ie=q,ge=O=>{if(!$||!de)throw new u("editor-unavailable");return {kind:"patchRangeStyle",payload:{args:[$.sheet,_s($),O],target:de,selection:re}}},we=async O=>{try{return await O()}catch(Z){throw r().generation()===X&&r().session()===G&&!(Z instanceof $e)&&!(Z instanceof u)&&!T.coordinator.error&&T.coordinator.fail(Z),Z}};try{if(w==="save"){let ee=await we(()=>T.coordinator.save());return r().generation()!==X||r().session()!==G?D("document-replaced"):(T.deliver(ee),_())}if(w==="print")return await we(()=>T.coordinator.whenPresented()),r().generation()!==X||r().session()!==G?D("document-replaced"):(window.print(),_());if(w==="exportPng"){let ee=Q?Q.frame:T.frame();if(!G.pngExport||!G.call)return D("png-unavailable");if(!ee||!T.deliverPng)return D("editor-unavailable");let Te={sheet:ee.sheet,viewport:ee.viewport},tt=await T.exportFonts?.(await G.call.renderPngFonts(Te)),Pe=await G.call.renderPng(Te,{fonts:tt});return r().generation()!==X||r().session()!==G?D("document-replaced"):(T.deliverPng(Pe),_())}let O=T.menu,Z=y.workbook;if(w==="cut"||w==="copy"||w==="paste"||w==="pastePlainText")return O?(await O.clipboard(w),r().generation()===X&&r().session()===G?_():D("document-replaced")):D("unsupported-command");if(w==="clearContents")return O?(await O.clear(),r().generation()===X&&r().session()===G?_():D("document-replaced")):D("unsupported-command");if(w==="renameSheet"&&q===null)return O?(O.beginRename(),{ok:!0,status:"opened"}):D("unsupported-command");let Fe=Z?G.editState.sheets?.find(ee=>ee.index===Z.active)?.id:void 0,Le=Fe?{sheetId:Fe,range:{kind:"rowCol",start:{row:0,col:0},end:{row:0,col:0}}}:void 0,Ae=null,fe;switch(w){case "insertRows":case "deleteRows":case "insertColumns":case "deleteColumns":{if(!$||!de)return D("cell-selection-required");let ee=w==="insertRows"||w==="deleteRows",Te=ie?.position==="below"||ie?.position==="right",tt=ee?$.bottom-$.top+1:$.right-$.left+1,Pe=ee?Te?$.bottom+1:$.top:Te?$.right+1:$.left;fe={kind:"applyOps",payload:{args:[[{type:w==="insertRows"?"insertRows":w==="deleteRows"?"deleteRows":w==="insertColumns"?"insertCols":"deleteCols",sheet:$.sheet,at:Pe,count:tt,target:de}]],selection:re}};break}case "insertSheet":{if(!Z||!O)return D("unsupported-command");let ee=Tl(y.translate("editor.sheetNamePrefix"),Z.sheets);fe={kind:"applyOps",payload:{args:[[{type:"addSheet",index:Z.active,name:ee}]]}},Ae=()=>O.activate(ee);break}case "deleteSheet":{if(!Z||!O||!Le)return D("unsupported-command");let ee=Z.sheets.filter((tt,Pe)=>Pe!==Z.active),Te=ee[Math.min(Z.active,ee.length-1)];fe={kind:"applyOps",payload:{args:[[{type:"removeSheet",index:Z.active,target:Le}]]}},Ae=()=>O.activate(Te);break}case "renameSheet":{if(!Z||!Le)return D("unsupported-command");let ee=q.name;if(ee===Z.sheets[Z.active])return _(!1);fe={kind:"applyOps",payload:{args:[[{type:"renameSheet",sheet:Z.active,name:ee,target:Le}]]}};break}case "moveSheet":{if(!Z||!O||!Le)return D("unsupported-command");let ee=Z.active+(ie.direction==="left"?-1:1);fe={kind:"applyOps",payload:{args:[[{type:"moveSheet",from:Z.active,to:ee,target:Le}]]}};let Te=Z.sheets[Z.active];Ae=()=>O.activate(Te);break}case "bold":case "italic":case "strikethrough":case "fontSizeStep":case "merge":case "paintFormat":if(!de)return D("cell-selection-required");fe={kind:"applyOps",payload:{toolbar:{id:w,args:q,target:de},selection:re}};break;case "fontFamily":fe=ge({fontFamily:ie.family});break;case "fontSize":fe=ge({fontSize:ie.points});break;case "textColor":fe=ge({textColor:ie.color});break;case "fillColor":fe=ge({fillColor:ie.color});break;case "horizontalAlignment":fe=ge({horizontalAlignment:ie.value});break;case "verticalAlignment":fe=ge({verticalAlignment:ie.value});break;case "textWrapping":fe=ge({textWrapping:ie.value});break;case "borderPreset":fe=ge({border:{preset:ie.value,style:y.borderStyle??"solid",color:y.borderColor??"#000000"}});break;case "borderStyle":T.setBorderStyle(ie.value),fe=ge({border:{style:ie.value}});break;case "borderColor":T.setBorderColor(ie.color),fe=ge({border:{color:ie.color}});break;case "numberFormat":case "decimalPlaces":if(!$||!de)return D("cell-selection-required");w==="numberFormat"&&ie.value==="custom"?fe={kind:"applyOps",payload:{toolbar:{id:w,args:q,target:de},selection:re}}:fe={kind:"setNumberFormat",payload:{args:[$.sheet,_s($),w==="decimalPlaces"?ie.direction==="increase"?"increaseDecimal":"decreaseDecimal":ie.value],target:de,selection:re}};break;case "undo":case "redo":fe={kind:w,payload:{args:[]}};break;case "proposalAccept":fe={kind:"acceptProposal",payload:{args:[ie.proposalId,{force:ie.force}]}};break;case "proposalReject":fe={kind:"rejectProposal",payload:{args:[ie.proposalId]}};break;default:return D("unsupported-command")}let et=T.coordinator.command(fe,{frame:Q?.frame,selectionRevision:Q?.selectionRevision}),Be=await we(()=>et.result);if(r().generation()!==X||r().session()!==G)return D("document-replaced");if(w==="paintFormat"&&et.seq!==null&&et.seq>=h&&r().formatRevision()===Ie){let ee=Be.result;if(typeof ee?.formatToken!="string"){let Te=new Error("Worker format capture omitted its token");throw T.coordinator.fail(Te),Te}T.setFormatToken(ee.formatToken),h=et.seq;}return (w==="proposalAccept"||w==="proposalReject")&&(T.markStale(ie.proposalId,null),T.refreshProposals()),w==="proposalReject"&&Be.result===!1?D("proposal-not-found"):(Be.status!=="noop"&&Ae?.(),_(Be.status!=="noop"))}catch(O){if(r().generation()!==X||r().session()!==G)return D("document-replaced");if(O instanceof $e){if(w==="proposalAccept"&&O.status.reason==="stale-proposal"){let Z=O.status.result;return T.markStale(ie.proposalId,Z?.cells??[]),T.refreshProposals(),D("proposal-stale")}return O.status.reason==="read-only"?D("read-only"):w==="proposalReject"&&O.status.reason==="missing-target"?D("proposal-not-found"):O.code==="edit-unsupported"?{ok:false,failure:{code:O.code,message:y.translate(a$1[O.cause??"other"])}}:D(O.code)}return O instanceof u?O.code==="host-refused"?{ok:false,failure:{code:O.code,message:O.message}}:D(O.code):O instanceof Error&&O.name==="WorkbookPngUnavailableError"?D("png-unavailable"):El(O)?D("clipboard-denied"):D("command-failed")}},admit(w,q){let y=v(false),T={env:y,selection:P(),frame:structuredClone(r().frame()),selectionRevision:r().selectionRevision()};return r().coordinator.runAfterPendingInput(()=>{let X=m;m=T;try{return w(y.readOnly)}finally{m=X;}},q==="exportPng")},capture(w){return r().status()==="empty"?null:{generation:r().generation(),target:f(w)}},resume(w,q){return r().generation()!==w.generation?"document-replaced":f(q,m?.env)===w.target?null:"target-changed"},refuse:w=>r().refuse?.(w),chrome:()=>({i18n:r().i18n()}),focusEditor:()=>r().focusGrid(),subscribe(w){return e.add(w),L(),()=>{e.delete(w);}},refreshSubscription:L,dispose(){b(),c(),e.clear(),n=null,o=null,l="";}}}function Vs(r,e){let n=useRef(e);n.current=e;let o=useRef(null);useLayoutEffect(()=>{let l=Al(()=>n.current);o.current=l,r.attach(l);let a=l.subscribe(()=>r.refresh());return ()=>{a(),l.dispose(),r.detach(l),o.current=null;}},[r]),useLayoutEffect(()=>{o.current?.refreshSubscription(),r.refresh();});}function Ys(r,e,n){return r.call.cellInputs(e,n).then(o=>o.cells[0]?.[0]?.input??"")}function Js(r,e,n,o,l,a){let h;return r.runAfterPendingInput(async()=>{if(!l())try{let b=e().then(c=>{l()||n(c);});await Promise.race([b.then(()=>o),o]);}catch(b){throw h={error:b},b}},"read").catch(b=>{if(h)throw h.error;a(b);})}function Zs(r,e,n,o){if(!("identity"in e))throw new Error("Async plugin clients require document access");let l=()=>{let v=r.refusal();return v?xa(v):null},a=async(v,f=true)=>{let M=l();if(M)return M;let w=e.identity();if(!w)return xa("plugin-unavailable");let q=false,y=await ya([r.signal,r.lifetimeSignal],e.admit(w,()=>{let T=l();return T?{refused:T}:(q=true,{value:v(w)})},f),()=>q);if(!y)return l()??xa("aborted");if(!y.ok)return l()??xa(y.code);if("refused"in y.value)return y.value.refused;try{let T=await y.value.value;return e.identity()===w?T:xa("document-replaced")}catch{return l()??xa("input-failed")}},h={version:()=>a(v=>e.readVersion(v)),readCells(v){let f=structuredClone(v);return a(M=>e.readCells(M,f))},findText(v){let f=structuredClone(v);return a(M=>e.findText(M,f))},validateEdits(v){let f=structuredClone(v);return a(M=>e.validateEdits(M,f))}},b=v=>l()??(ua(n(),v)?null:xa("permission-denied")),c=v=>r.commit(v),m=ua(n(),"separate")?{async applyEdits(v){let f=b(v?.history);if(f)return f;if(!e.admitEdits)return a(y=>e.applyEdits(y,v,()=>b(v.history),c));let M=e.identity();if(!M)return xa("plugin-unavailable");let w=structuredClone(v),q=await e.admitEdits(M,w,y=>y?ua(n(),w.history)?null:xa("permission-denied"):b(w.history),c,[r.signal,r.lifetimeSignal]);return q.ok?q.value:xa(q.code)}}:null,P={getDescriptor:v=>o.getDescriptor(v),getState:(v,f)=>o.getState(v,f),subscribe:v=>o.subscribe(v),execute:async(v,f)=>l()??o.execute(v,f)},C=()=>r.refusal()===null,x=async(v,f)=>{let M=await a(w=>e.version(w)===v?.expectVersion?f(w):"stale-version");return M===null?{ok:true}:typeof M=="object"?M:{ok:false,failure:{code:M,message:va[M]}}};return {read:h,commands:P,edits:m,navigation:{selectCells(v,f){let M=structuredClone(v),w=structuredClone(f);return x(w,q=>e.navigator.selectCells(q,M,w.focus===true,C,w.expectVersion))},scrollToCell(v,f){let M=structuredClone(v),w=structuredClone(f);return x(w,q=>{let y=w.align??"nearest";return wa$1.has(y)?e.navigator.scrollToCell(q,M,y,C,w.expectVersion):"unsupported"})}}}}var Dl=new Set(["stale-version","missing-target","content-mismatch","overlapping-steps","locked-target","read-only","unsupported","invalid-step","limit-exceeded"]);function Qs(r){let e=c=>{let m=r.owner();if(m!==c||!m?.current||m.retiring)throw new u("document-replaced");if(m.failure)throw m.failure;return m},n=()=>{let c=r.coordinator();if(!c)throw new u("editor-unavailable");return c},o=c=>({ok:false,code:c instanceof u&&c.code==="document-replaced"?"document-replaced":"input-failed",error:c}),l=c=>typeof c=="object"&&c!==null&&"ok"in c&&c.ok===false&&"failure"in c,a=new WeakMap,h=(c,m)=>{let P=e(c),C=(a.get(P)??Promise.resolve()).then(()=>(e(c),m()));return a.set(P,C.then(()=>{},()=>{})),C},b={identity:()=>{let c=r.owner();return c?.ready&&c.current&&!c.retiring&&!c.failure?c:null},version:c=>b.identity()===c?e(c).session.confirmedBasis.version:null,currentVersion:c=>r.coordinator()?.pending?null:b.version(c),subscribe(c,m){let C=e(c).subscribe(()=>{b.identity()!==c&&m();}),x=n().subscribe(L=>{L.type==="coverage"&&b.identity()===c&&m();});return ()=>{x(),C();}},selection:c=>r.selection(e(c)),readOnly:c=>e(c).session.editState.readOnly===true,async admit(c,m,P=false){try{return e(c),await n().runAfterPendingInput(()=>{e(c);let C=m();return e(c),{ok:!0,value:C}},P)}catch(C){return o(C)}},readVersion:async c=>({ok:true,version:await e(c).session.call.version()}),readCells:(c,m)=>e(c).session.call.readCells(m),findText:(c,m)=>e(c).session.call.findText(m),validateEdits:(c,m)=>b.readOnlyRefusal(c)??e(c).session.call.validateEdits(m),readOnlyRefusal:c=>r.readOnly()||e(c).session.editState.readOnly?{ok:false,version:e(c).session.confirmedBasis.version,failure:{code:"read-only",message:"The editor is read-only"}}:null,applyEdits:()=>{throw xa("unsupported-policy")},async admitEdits(c,m,P,C,x=[]){let L=false,v=null;try{v=e(c);let f=n(),M=f.runAfterPendingInput(()=>{e(c);let q=P(!1);if(q)return q;let y=b.readOnlyRefusal(c);return y||f.command({kind:"applyEdits",payload:{args:[m]}},{acknowledge:C,dispatch(T){e(c);let X=P(!1)??b.readOnlyRefusal(c);if(X)throw X;return L=!0,C(T)}}).result.then(T=>{if(!T.result)throw xa("input-failed");return T.result})}),w=await ya(x,M,()=>L);if(w===null){let q=P(!1);if(q)return {ok:!0,value:q};throw xa("aborted")}return L||e(c),{ok:!0,value:w}}catch(f){if(l(f))return {ok:true,value:f};if(f instanceof $e){if(f.status.result)return {ok:true,value:f.status.result};let M=f.status.reason;if(M&&Dl.has(M)&&v)return {ok:true,value:{ok:false,version:v.session.confirmedBasis.version,failure:{code:M,message:f.message}}}}return o(f)}},commands:r.commands,navigator:{selectCells:(c,...m)=>h(c,()=>r.navigator.selectCells(c,...m)),scrollToCell:(c,...m)=>h(c,()=>r.navigator.scrollToCell(c,...m))}};return b}function ei(r,e,n,o,l,a,h,b){return ga(r,e,n,o,()=>{let c=l();return c.version===r.version&&c.painted===e},a,h,b)}function ti(r,e,n){let o=()=>{if(!r.current||r.retiring)throw new u("document-replaced")},l=v=>{try{if(o(),r.failure)throw r.failure;if(!r.ready)throw new u("editor-unavailable");let f=v(),M=n().exportCoordinator?.();if(!M)throw new u("editor-unavailable");return M.runAfterPendingInput(async()=>{o();let w=await f();return o(),w},!0)}catch(f){return Promise.reject(f)}},a=r.session.replica?.async,h=()=>{if(o(),r.failure||!r.ready)throw new u("editor-unavailable")},b=v=>({ok:false,failure:n$1(v,null)}),c=async v=>{if(o(),r.failure)throw r.failure;let f;try{f=await v();}catch(M){throw o(),r.failure?r.failure:M}if(o(),r.failure)throw r.failure;return f},m=()=>{if(o(),r.failure)throw r.failure;if(!r.ready)throw new u("editor-unavailable");let v=n().editorDocument?.();if(!v)throw new u("editor-unavailable");if(v.identity()!==r)throw new u("document-replaced");return v},P=v=>{if(v.ok)return v.value;throw v.error instanceof u?v.error:new u(v.code)},C=v=>c(async()=>{let f=m();return await P(await f.admit(r,()=>v(f),!0))}),x=a?{clientId:a.clientId,encodeStateVector:()=>c(()=>r.session.call.collaborationStateVector()),encodeStateAsUpdate:v=>{let f=v?.slice();return c(()=>r.session.call.collaborationStateAsUpdate(f))},applyUpdate:v=>{let f=v.slice();return c(()=>a.applyUpdate(f))},...a.applyUpdateChunks&&{applyUpdateChunks:v=>{let f=v.map(M=>M.slice());return c(()=>a.applyUpdateChunks(f))}},onUpdate(v){return o(),a.onUpdate((f,M)=>{r.current&&!r.retiring&&!r.failure&&v(f,M);})}}:null,L={get hydrated(){return r.ready},get failure(){return r.failure},whenHydrated:()=>r.whenReady(),recoverySave:()=>r.recoverySave(),version:()=>C(async v=>{let f=await v.readVersion(r);if(!f.ok)throw new u("input-failed");return f.version}),readCells(v){let f=structuredClone(v);return C(async M=>{let w=await M.readCells(r,f);if(!w.ok&&!("version"in w))throw new u("input-failed");return w})},findText(v){let f=structuredClone(v);return C(async M=>{let w=await M.findText(r,f);if(!w.ok&&!("version"in w))throw new u("input-failed");return w})},validateEdits(v){let f=structuredClone(v);return C(async M=>{let w=await M.validateEdits(r,f);if(!w.ok&&!("version"in w))throw new u("input-failed");return w})},applyEdits(v){let f=structuredClone(v);return c(async()=>{let M=m();if(!M.admitEdits)throw new u("editor-unavailable");return P(await M.admitEdits(r,f,()=>null,w=>w()))})},save:()=>c(async()=>{if(!r.ready)throw new u("editor-unavailable");let v=n().exportCoordinator?.();if(!v)throw new u("editor-unavailable");let f=await v.save();if(o(),r.failure)throw r.failure;return n().saved?.(f),f}),commands:y(e).guarded(o),collaboration:x,async proposeChanges(v){try{h();let f=structuredClone(v),M=n().exportCoordinator?.();if(!M)throw new u("editor-unavailable");return await M.runAfterPendingInput(async()=>{if(h(),M.readOnly&&!n().allowHostProposals?.())return b("read-only");let q=await M.command({kind:"propose",payload:{args:[f.agentId,f.note??null,f.edits]}}).result;return h(),{ok:!0,proposal:q.result}},"posted")}catch(f){return !r.current||r.retiring?b("document-replaced"):r.failure||!r.ready?b("editor-unavailable"):f instanceof $e?f.status.reason==="read-only"?b("read-only"):f.status.reason==="unsupported"?b("unsupported-command"):f.status.reason==="invalid-command"||f.status.reason==="invalid-step"?b("invalid-arguments"):b("input-failed"):f instanceof u?b(f.code):b("command-failed")}},renderPng:(v,f={})=>l(()=>{let{signal:M,...w}=f,q=structuredClone(v),y=structuredClone(w),T=n().defaultFonts?.();return async()=>{let X=r.session.call,G=y.fonts??await E$1(await X.renderPngFonts(q,y),X.decodeFontFace,T);return X.renderPng(q,{...y,fonts:G,signal:M})}}),exportStructured:v=>l(()=>{let f=structuredClone(v);return ()=>r.session.call.exportStructured(f)}),exportMarkdown:(v,f)=>l(()=>{let M=structuredClone([v,f]);return ()=>r.session.call.exportMarkdown(...M)}),printDisplayList:(...v)=>l(()=>{let f=structuredClone(v);return ()=>r.session.call.printDisplayList(...f)}),focus(){o(),r.failure||n().focus();}};return a$5(L)}var gr=class{constructor(e,n,o){a$2(this,"workerSession",e);a$2(this,"generation",n);a$2(this,"options",o);a$2(this,"alive",true);a$2(this,"retiring",false);a$2(this,"failure",null);a$2(this,"beforeRetire",null);a$2(this,"session");a$2(this,"painted",false);a$2(this,"cleanup");a$2(this,"listeners",new Set);a$2(this,"pending",new Set);a$2(this,"readiness");a$2(this,"resolveReady");a$2(this,"rejectReady");a$2(this,"offFailure",()=>{});a$2(this,"offAck",()=>{});a$2(this,"offDraft",()=>{});a$2(this,"offInput",()=>{});a$2(this,"recoveryInput",null);a$2(this,"recoveryDrafts",null);a$2(this,"checkpointTimer");a$2(this,"checkpointScheduler");a$2(this,"checkpointRevision",0);a$2(this,"checkpointBusy",false);a$2(this,"disposal",Promise.resolve());a$2(this,"disposeSession",()=>this.dispose());this.checkpointScheduler=o.checkpointScheduler??{now:()=>performance.now(),schedule(c,m){let P=setTimeout(c,m);return ()=>clearTimeout(P)}},this.readiness=new Promise((c,m)=>{this.resolveReady=c,this.rejectReady=m;}),this.readiness.catch(()=>{});let l=c=>{let m=new WeakMap;return P=>{let C=Reflect.get(c,P,c);if(typeof C!="function")return C;let x=m.get(C);return x||(x=(...L)=>this.track(()=>Reflect.apply(C,c,L),P==="submit"||P==="command"||P==="applyEdits"),m.set(C,x)),x}},a=l(e.call),h=l(e),b=new Proxy(e.call,{get:(c,m)=>a(m)});this.session=new Proxy(e,{get:(c,m)=>m==="call"?b:m==="dispose"?this.disposeSession:m==="submit"||m==="save"||m==="whenPresented"?h(m):Reflect.get(c,m,c)}),this.offFailure=e.onFailure(c=>this.fail(c)),this.offAck=e.onAck(()=>{this.notify(),this.scheduleCheckpoint(true);}),e.failure&&this.fail(e.failure);}get current(){return this.alive&&this.options.isCurrent()}get commandsAccepted(){let e=this.workerSession.commandIdentity;return this.current&&!this.retiring&&!this.failure&&this.workerSession.state.stage==="ready"&&!!(e.session&&e.incarnation)}get ready(){return this.commandsAccepted&&this.painted}get readOnly(){return !this.ready||this.workerSession.editState.readOnly===true}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}whenReady(){return !this.current||this.retiring?Promise.reject(new u("document-replaced")):this.failure?Promise.reject(this.failure):this.readiness}connectRecoveryInput(e,n){this.offDraft(),this.offInput(),this.recoveryInput=e,this.failure&&e.fail?.(this.failure),this.recoveryDrafts=n,this.offDraft=n.subscribe(()=>this.scheduleCheckpoint()),this.offInput=e.subscribe?.(()=>this.scheduleCheckpoint())??(()=>{}),this.scheduleCheckpoint();}recoverySave(){let e=()=>{if(!this.current||this.retiring)throw new u("document-replaced")};return this.track(async()=>{if(e(),this.workerSession.replica)throw new Error("Recovery is unavailable for collaborative workbooks");if(!this.failure)throw new Error("Recovery requires a failed workbook edit peer");try{let n=workbookSessionRecovery.get(this.workerSession);if(!n)throw new Error("Workbook recovery state is unavailable");let o=await n.save(e,this.recoveryInput?.recoveryCommands);return e(),{bytes:o,recovery:!0}}catch(n){if(e(),n instanceof u)throw n;this.failure=n instanceof d$1?n:new d$1(n),this.changed();try{this.options.onError(this.failure);}catch{}throw this.failure}},false,true)}firstPaint(){if(!(!this.commandsAccepted||this.painted)){this.painted=true;try{let e=this.options.onReady();!this.current&&typeof e=="function"?e():this.cleanup=e;}catch(e){this.fail(e);}this.ready&&this.resolveReady(),this.changed(),this.scheduleCheckpoint();}}fail(e){if(!(!this.current||this.failure)){this.failure=e instanceof d$1?e:new d$1(e),this.checkpointTimer?.(),this.checkpointTimer=void 0,this.checkpointRevision+=1,this.recoveryInput?.fail?.(this.failure),this.rejectReady(this.failure),this.rejectPending(this.failure),this.changed();try{this.options.onError(this.failure);}catch{}}}dispose(){if(!this.alive||this.retiring)return this.disposal;this.retiring=true;try{this.beforeRetire?.();}catch(n){try{this.options.onError(a$3(n));}catch{}}this.alive=false;let e=new u("document-replaced");this.rejectReady(e),this.rejectPending(e),this.offFailure(),this.offAck(),this.offDraft(),this.offInput(),this.checkpointTimer?.(),this.checkpointTimer=void 0,this.checkpointRevision+=1,this.recoveryInput=null,this.recoveryDrafts=null,this.changed(),this.listeners.clear();try{typeof this.cleanup=="function"&&this.cleanup();}catch(n){try{this.options.onError(a$3(n));}catch{}}finally{this.disposal=this.workerSession.dispose(),this.disposal.catch(()=>{});}return this.disposal}changed(){this.options.changed(),this.notify();}notify(){for(let e of this.listeners)try{e();}catch{}}rejectPending(e){for(let n of this.pending)n.reject(e);this.pending.clear();}scheduleCheckpoint(e=false){let n=++this.checkpointRevision;this.checkpointTimer?.(),this.checkpointTimer=void 0;let o=workbookSessionRecovery.get(this.workerSession),l=(o?.retainedCommands??0)>=192,a=()=>this.ready&&!!this.recoveryInput&&!this.recoveryInput?.draft&&!this.recoveryDrafts?.compositionId&&(l||n===this.checkpointRevision&&!this.recoveryInput?.pending);if(!o||o.retainedCommands<64||this.checkpointBusy||!a())return;let h=()=>{if(this.checkpointTimer=void 0,!a())return;this.checkpointBusy=true;let P=o.throughSeq;o.capture(a).then(C=>{this.checkpointBusy=false,(C&&o.throughSeq>P||n!==this.checkpointRevision)&&this.scheduleCheckpoint();},C=>{this.checkpointBusy=false,this.current&&!this.retiring&&this.fail(C);});};if(l){(e||!this.recoveryInput?.pending)&&h();return}let b=this.checkpointScheduler.now(),c=o.checkpointIdleMs??150,m=()=>{if(this.checkpointTimer=void 0,!a())return;let P=c-(this.checkpointScheduler.now()-b);P>0?this.checkpointTimer=this.checkpointScheduler.schedule(m,P):h();};this.checkpointTimer=this.checkpointScheduler.schedule(m,c);}track(e,n=false,o=false){return !this.current||this.retiring?Promise.reject(new u("document-replaced")):this.failure&&!o?Promise.reject(this.failure):n&&!this.ready?Promise.reject(new u("editor-unavailable")):new Promise((l,a)=>{let h={reject:a};this.pending.add(h);try{e().then(l,b=>{b instanceof WorkbookRecoveryReplayError&&this.fail(b),a(o?b:this.failure??b);}).finally(()=>this.pending.delete(h));}catch(b){this.pending.delete(h),b instanceof WorkbookRecoveryReplayError&&this.fail(b),a(this.failure??b);}})}};function ii(r,e$1,n,o){let l=useRef({props:r,bridge:n,options:o});l.current={props:r,bridge:n,options:o};let a=useRef(0),[h,b]=useState(null),[,c]=useState(0),[m,P]=useState(null),[C,x]=useState(false),L=r.collaboration,v=L!==void 0,f=L?.clientId,M=L?.initialUpdate,w=useCallback(T=>{let X=a$3(T);P(X);try{l.current.props.onError?.(X);}catch{}},[]);useEffect(()=>{let T=++a.current,X=new AbortController,G=false,Q,re=()=>!G&&T===a.current&&l.current.props.file===r.file,_=()=>{re()&&c(D=>D+1);};return b(null),P(null),x(!!r.file),r.file&&(async()=>{try{let D=await e.open(r.file,{signal:X.signal,png:!1,includeEditState:!0,...L?{collaborative:!0,clientId:f,initialUpdate:M?.slice()}:{},...l.current.options.initialViewport?{initialViewport:l.current.options.initialViewport()}:{}});if(!re()){D.dispose().catch(()=>{});return}let Ie={changed:_,isCurrent:re,onError:de=>{if(re())w(de);else try{l.current.props.onError?.(de);}catch{}}},$=new gr(D,T,{...Ie,onReady:()=>re()?l.current.props.onReady?.(he):void 0}),he=ti($,e$1,()=>l.current.bridge);Q=$,b(Q),x(!1);}catch(D){if(!re())return;Q?Q.fail(D):w(new d$1(D));}finally{re()&&x(false);}})(),()=>{G=true,a.current+=1,X.abort(),Q?.dispose();}},[r.file,v,f,M,e$1,w]),useLayoutEffect(()=>()=>{h?.dispose();},[h,r.file,v,f,M]);let q=L?.onReplica,y=h instanceof gr&&h.ready;return useEffect(()=>{if(!y||!(h instanceof gr)||!q)return;let T=h.session.replica;if(T)for(let X of ["encodeStateVector","encodeStateAsUpdate"])T[X]=()=>{throw new a$4(`replica.${X}()`,`await api.collaboration.${X}()`)};return q(T??null),()=>q(null)},[h,y,q]),{run:h?.current?h:null,error:m,loading:C,reportError:w}}var Fl={request:r=>requestAnimationFrame(r),cancel:r=>cancelAnimationFrame(r)};function yr(r){return {...r,viewport:{...r.viewport}}}function Xn(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function ar(r,e,n=true){return r!==null&&r.generation===e.generation&&r.sheet===e.sheet&&(!n||r.navigation===e.navigation)&&r.width===e.width&&r.height===e.height&&r.zoom===e.zoom&&r.dpr===e.dpr&&Xn(r.viewport,e.viewport)}var Zr=class{constructor(e){a$2(this,"options",e);a$2(this,"scheduler");a$2(this,"disposed",false);a$2(this,"failed",false);a$2(this,"raf",null);a$2(this,"pipeRaf",null);a$2(this,"pipeFrame",null);a$2(this,"revision",0);a$2(this,"paintedRevision",-1);a$2(this,"pending",null);a$2(this,"inFlight",null);a$2(this,"running",false);a$2(this,"lastPaint",null);a$2(this,"lastFrameSequence",0);a$2(this,"commandCoverage",0);a$2(this,"installation",0);a$2(this,"transactions",new Set);this.scheduler=e.scheduler??Fl;}get painted(){return this.lastPaint}get coversThroughSeq(){return this.commandCoverage}selectionPaintReady(e,n){let o=this.revision,l=this.lastPaint,a=this.current&&!this.failed&&(this.raf!==null&&n===e||this.pipeFrame?.request.sheet===e||this.pending?.request.sheet===e||this.inFlight?.sheet===e);return ()=>!a||this.lastPaint!==l&&this.lastPaint?.request.sheet===e&&!this.lastPaint.provisional&&this.paintedRevision>=o}registerPaintTransaction(e){return this.disposed?()=>{}:(this.transactions.add(e),()=>{this.transactions.delete(e);})}captureCommandFrame(){let e=this.failed?null:this.capture();return e?{...e,requestGeneration:this.revision,coversThroughSeq:this.options.sentSequence()}:null}installInitial(e){let n=this.capture();if(!e||!n||this.failed||this.lastPaint||this.running||this.pending||this.pipeFrame||this.raf!==null||this.revision!==0||e.coversThroughSeq!==0||e.sequence!==0||!Number.isSafeInteger(e.requestGeneration)||e.requestGeneration<0||e.viewport.width!==n.width/e.zoom||e.viewport.height!==n.height/e.zoom||n.requestGeneration!==void 0&&e.requestGeneration!==n.requestGeneration)return false;let o={...n,sheet:e.sheet,viewport:{...e.viewport},zoom:e.zoom,dpr:e.dpr,requestGeneration:e.requestGeneration};return this.revision=e.requestGeneration,this.install(e,o)?true:(this.revision=0,false)}install(e,n){if(!e||!this.accepts(e,n))return false;try{return this.publish("worker",yr(n),{displayList:e.displayList,mergedRanges:e.mergedRanges??[],version:e.version},e.sequence,e.coversThroughSeq),this.installation+=1,!0}catch(o){return this.fail(o),false}}installProvisional(e,n){if(!this.current||this.failed||!ar(this.capture(),n))return false;try{return this.publish("worker",yr(n),e,this.lastPaint?.sequence??0,void 0,!0),!0}catch(o){return this.fail(o),false}}queuePipeFrame(e,n){return this.accepts(e,n)?((!this.pipeFrame||e.coversThroughSeq>this.pipeFrame.frame.coversThroughSeq||e.coversThroughSeq===this.pipeFrame.frame.coversThroughSeq&&e.sequence>=this.pipeFrame.frame.sequence)&&(this.pipeFrame={frame:e,request:yr(n)}),this.pipeRaf===null&&(this.pipeRaf=this.scheduler.request(()=>{this.pipeRaf=null;let o=this.pipeFrame;this.pipeFrame=null,o&&!this.install(o.frame,o.request)&&this.schedule();})),true):false}advanceCoverage(e,n){if(!this.current||this.failed||this.pipeFrame||!this.lastPaint||this.lastPaint.provisional||this.paintedRevision!==this.revision||this.lastPaint.version!==e||!ar(this.capture(),this.lastPaint.request,false)||!Number.isSafeInteger(n)||n<this.commandCoverage)return false;if(n>this.commandCoverage){let o=this.commandCoverage;this.commandCoverage=n;try{this.options.onCovered?.(n);}catch(l){return this.commandCoverage=o,this.fail(l),false}}return true}schedule(){!this.current||this.failed||(this.cancelPipeFrame(),this.revision+=1,this.raf===null&&(this.raf=this.scheduler.request(()=>{if(this.raf=null,!this.current||this.failed)return;let e=this.capture();e&&(this.pending={request:e,revision:this.revision,sequence:this.options.sentSequence(),installation:this.installation},this.drain().catch(n=>this.fail(n)));})));}fail(e){if(!(!this.current||this.failed)){this.failed=true,this.cancelFrame();try{this.options.onError(e);}catch{}}}dispose(){this.disposed||(this.disposed=true,this.cancelFrame(),this.transactions.clear());}get current(){return !this.disposed&&(this.options.isCurrent?.()??true)}capture(){if(!this.current)return null;let e=this.options.capture();return e?.generation===this.options.generation?yr(e):null}matches(e){return e.revision===this.revision&&e.installation===this.installation&&ar(this.capture(),e.request)}accepts(e,n){let o=this.options.commandIdentity;return !!o&&this.current&&!this.failed&&e.session===o.session&&e.incarnation===o.incarnation&&e.requestGeneration===(n.requestGeneration??n.generation)&&(n.requestGeneration===void 0||n.requestGeneration===this.revision)&&e.zoom===n.zoom&&e.dpr===n.dpr&&e.sheet===n.sheet&&Xn(e.viewport,n.viewport)&&ar(this.capture(),n)&&Number.isSafeInteger(e.coversThroughSeq)&&Number.isSafeInteger(e.sequence)&&e.sequence>=0&&e.coversThroughSeq>=Math.max(this.commandCoverage,n.coversThroughSeq??0)}cancelPipeFrame(){this.pipeRaf!==null&&this.scheduler.cancel(this.pipeRaf),this.pipeRaf=null,this.pipeFrame=null;}cancelFrame(){this.raf!==null&&this.scheduler.cancel(this.raf),this.raf=null,this.pending=null,this.cancelPipeFrame();}retry(e){let n=this.capture();!n||ar(n,e.request)&&this.options.sentSequence()===e.sequence||!this.pending&&this.raf===null&&this.schedule();}publish(e,n,o,l,a,h=false){let b={...o,source:e,request:n,sequence:l,geometry:o.displayList.grid,...a===void 0?{}:{coversThroughSeq:a},...h?{provisional:true}:{}},c=this.lastPaint,m=this.lastFrameSequence,P=this.commandCoverage,C=this.revision;this.lastPaint=b,h||(this.lastFrameSequence=Math.max(this.lastFrameSequence,l)),a!==void 0&&(this.commandCoverage=a);try{let x=()=>{this.options.publish(b);};for(let L of [...this.transactions].reverse()){let v=x;x=()=>{L(b,v);};}x();}catch(x){throw this.lastPaint===b&&(this.lastPaint=c,this.lastFrameSequence=m,this.commandCoverage=P),x}return h||(this.paintedRevision=C),this.pipeFrame&&a!==void 0&&a>=this.pipeFrame.frame.coversThroughSeq&&this.cancelPipeFrame(),this.options.onInstalled?.(b),!h&&!this.pipeFrame&&o.displayList.conditionalPending&&this.schedule(),b}async drain(){if(!(this.running||!this.current||this.failed)){this.running=true;try{for(;this.current&&!this.failed&&this.pending;){let e=this.pending;if(this.pending=null,!this.matches(e)){this.retry(e);continue}let{request:n}=e;this.inFlight=n;let o;try{o=await this.options.requestFrame(yr(n));}catch(a){if(!this.current||this.failed)break;e.installation!==this.installation||!ar(this.capture(),n)||a instanceof Error&&a.name==="SessionSuperseded"?this.retry(e):this.fail(a);continue}if(!this.current||this.failed)break;let l="coversThroughSeq"in o&&typeof o.coversThroughSeq=="number"?o.coversThroughSeq:void 0;if(!this.matches(e)||o.sheet!==n.sheet||!Xn(o.viewport,n.viewport)||(n.coversThroughSeq===void 0?!(o.sequence>=this.options.sentSequence())||o.sequence<this.lastFrameSequence:l===void 0||l<Math.max(n.coversThroughSeq,this.commandCoverage))){this.retry(e);continue}try{this.publish("worker",n,{displayList:o.displayList,mergedRanges:o.mergedRanges??[],version:o.version},o.sequence,l);}catch(a){this.fail(a);}}}finally{this.running=false,this.inFlight=null;}}}};function Fn(r){return `${r.sheet}:${r.row}:${r.col}`}function Ln(r,e){let n=Math.max(r.x,e.x),o=Math.max(r.y,e.y),l=Math.min(r.x+r.w,e.x+e.w)-n,a=Math.min(r.y+r.h,e.y+e.h)-o;return l>0&&a>0?{x:n,y:o,w:l,h:a}:null}function zl(r,e){return !r.chart&&r.x>=e.x&&r.x<e.x+e.w&&r.y>=e.y&&r.y<e.y+e.h}function Nl(r,e){let n=Ln(r,e);return n?[{x:r.x,y:r.y,w:r.w,h:n.y-r.y},{x:r.x,y:n.y+n.h,w:r.w,h:r.y+r.h-n.y-n.h},{x:r.x,y:n.y,w:n.x-r.x,h:n.h},{x:n.x+n.w,y:n.y,w:r.x+r.w-n.x-n.w,h:n.h}].filter(l=>l.w>0&&l.h>0):[r]}var Qr=class{constructor(e){a$2(this,"options",e);a$2(this,"frame");a$2(this,"patches",new Map);a$2(this,"appearance",new Map);a$2(this,"maxPatches");a$2(this,"maxTextLength");a$2(this,"unregister");a$2(this,"disposed",false);if(this.maxPatches=Math.max(0,Math.floor(e.maxPatches??256)),this.maxTextLength=Math.max(0,Math.floor(e.maxTextLength??4096)),!Number.isSafeInteger(this.maxPatches)||!Number.isSafeInteger(this.maxTextLength))throw new RangeError("Invalid cell echo limit");this.frame=e.source.painted,this.unregister=e.source.registerPaintTransaction((n,o)=>{let l=this.frame,a=this.patches,h=this.appearance;try{this.frame=n,this.patches=new Map,this.appearance=new Map;for(let[b,c]of a)if(!(n.coversThroughSeq!==void 0&&b<=n.coversThroughSeq))for(let m of c.values())this.cellAppearance(m)&&this.store(b,m);o(),this.repaint(this.appearanceBounds());}catch(b){throw this.frame=l,this.patches=a,this.appearance=h,b}});}get size(){let e=0;for(let n of this.patches.values())e+=n.size;return e}patch(e,n){if(this.disposed||!this.frame||this.maxPatches===0||!Number.isSafeInteger(e)||e<=this.options.source.coversThroughSeq)return;let o=this.options.source.captureCommandFrame(),l=this.frame.request;if(!o||o.sheet!==l.sheet||o.zoom!==l.zoom||o.dpr!==l.dpr||o.width!==l.width||o.height!==l.height||o.viewport.x!==l.viewport.x||o.viewport.y!==l.viewport.y||o.viewport.width!==l.viewport.width||o.viewport.height!==l.viewport.height)return;let a=[],h=n[Symbol.iterator]();for(let b=0;b<this.maxPatches;b++){let c=h.next();if(c.done)break;let m=c.value;if(!Number.isSafeInteger(m.row)||!Number.isSafeInteger(m.col)||m.row<0||m.col<0||m.text.length>this.maxTextLength)continue;let P=this.cellAppearance(m);if(P)for(a.push(P.bounds),this.store(e,{...m});this.size>this.maxPatches;){let C=Math.min(...this.patches.keys()),x=this.patches.get(C),L=x.keys().next().value,v=this.appearance.get(L)?.bounds;v&&a.push(v),x.delete(L),x.size===0&&this.patches.delete(C);}}h.return?.(),this.pruneAppearance(),this.paint(a);}paste(e,n,o){let l=this.frame?.geometry;if(!l||!this.frame||n!==this.frame.request.sheet||o.length===0)return;let a=(b,c)=>{let m=0,P=o.length;for(;m<P;){let C=Math.floor((m+P)/2),x=o[C];x.row<b||x.row===b&&x.col<c?m=C+1:P=C;}return m},h=this.maxPatches;this.patch(e,(function*(){let b=0;for(let c=0;c<l.rowOffsets.length-1;c++){let m=l.rowIndices?.[c]??l.startRow+c,P=a(m,0),C=a(m+1,0);if(P!==C)for(let x=0;x<l.colOffsets.length-1;x++){let L=l.colIndices?.[x]??l.startCol+x;if(L<o[P].col||L>o[C-1].col)continue;if(b++>=h)return;let v=a(m,L),f=o[v];f?.row===m&&f.col===L&&(yield {sheet:n,row:m,col:L,text:f.input});}}})());}clear(e,n){let o=this.frame?.geometry;if(!o||!this.frame||n.sheet!==this.frame.request.sheet)return;let{rowOffsets:l,colOffsets:a,rowIndices:h,colIndices:b,startRow:c,startCol:m}=o;function*P(){for(let C=0;C<l.length-1;C++){let x=h?.[C]??c+C;if(!(x<n.top||x>n.bottom))for(let L=0;L<a.length-1;L++){let v=b?.[L]??m+L;v>=n.left&&v<=n.right&&(yield {sheet:n.sheet,row:x,col:v,text:""});}}}this.patch(e,P());}acknowledge(e){let n=new Set;for(let o of e.statuses)if(!(o.status!=="refused"&&o.status!=="cancelled")){n.add(o.seq);for(let l of o.affectedSeqs??[])n.add(l);}this.drop(n);}refuse(e){this.drop(new Set([e]));}dispose(){if(this.disposed)return;let e=this.appearanceBounds();this.patches.clear(),this.appearance.clear(),this.paint(e),this.disposed=true,this.unregister(),this.frame=null;}store(e,n){let o=this.patches.get(e);o||this.patches.set(e,o=new Map),o.set(Fn(n),n);}drop(e){if(this.disposed)return;let n=[];for(let o of e){for(let l of this.patches.get(o)?.values()??[]){let a=this.appearance.get(Fn(l));a&&n.push(a.bounds);}this.patches.delete(o);}this.pruneAppearance(),this.paint(n);}pruneAppearance(){let e=new Set;for(let n of this.patches.values())for(let o of n.keys())e.add(o);for(let n of this.appearance.keys())e.has(n)||this.appearance.delete(n);}appearanceBounds(){return [...this.appearance.values()].map(e=>e.bounds)}cellAppearance(e){if(!this.frame||e.sheet!==this.frame.request.sheet)return null;let n=Fn(e),o=this.appearance.get(n);if(o)return o;let l=cellRect(this.frame.geometry,e.row,e.col);if(!l)return null;let a=this.frame.mergedRanges.find(x=>e.row>=x.start.row&&e.row<=x.end.row&&e.col>=x.start.col&&e.col<=x.end.col),h=a?rangeRect(this.frame.geometry,{top:a.start.row,left:a.start.col,bottom:a.end.row,right:a.end.col}):l;if(!h)return null;let b=this.frame.displayList,c=this.frame.request,m=Ln(h,{x:0,y:0,w:Math.min(b.width,c.viewport.width,c.width/c.zoom),h:Math.min(b.height,c.viewport.height,c.height/c.zoom)});if(!m||b.charts?.some(x=>Ln(x.clip,m)))return null;let P=b.commands.find(x=>x.op==="text"&&!x.ghost&&zl(x,h)),C={bounds:m,text:P?{...P,clip:m}:{op:"text",text:"",x:m.x+4,y:m.y+Math.min(18,m.h-2),fontSize:11,color:"#000000",clip:m}};return this.appearance.set(n,C),C}paint(e){try{this.repaint(e);}catch(n){this.options.source.fail(n);}}repaint(e){if(!this.frame||e.length===0)return;let n=this.options.context();if(!n)throw new Error("Cell echo canvas context is unavailable");let o=new Map;for(let P of [...this.patches.keys()].sort((C,x)=>C-x))for(let[C,x]of this.patches.get(P))o.delete(C),o.set(C,x);let l=[];for(let[P,C]of o){let x=this.appearance.get(P);x&&l.push({...x.text,text:C.text,numberFormat:void 0});}let a=this.frame.displayList,h={x:0,y:0,w:a.width,h:a.height},b=[];for(let P of a.commands){if(P.op!=="text"||P.chart||l.length===0){b.push(P);continue}let C=[P.clip??h];for(let x of l)C=C.flatMap(L=>Nl(L,x.clip));for(let x of C)b.push({...P,clip:x});}let c={...a,commands:[...b,...l]},m=this.frame.request.dpr*this.frame.request.zoom;n.save();try{n.setTransform(m,0,0,m,0,0),n.beginPath();for(let P of e)n.rect(P.x,P.y,P.w,P.h);n.clip(),paintDisplayList(n,c,m);}finally{n.restore();}}};function en(r,e){if("inputType"in r){if(r.isComposing||r.inputType==="insertCompositionText")return null;if(["insertText","insertReplacementText","insertFromPaste","insertFromDrop"].includes(r.inputType))return {kind:"insert",text:r.data??r.dataTransfer?.getData("text/plain")??""};let h=/^delete(Content|Word|SoftLine|HardLine)(Backward|Forward)$/.exec(r.inputType);return h?{kind:"delete",direction:h[2]==="Backward"?"backward":"forward",unit:h[1]==="Content"?"character":h[1]==="Word"?"word":"line"}:null}let n=r.ctrlKey||r.metaKey,o=e?r.altKey&&!r.metaKey:r.ctrlKey&&!r.altKey,l=e&&r.metaKey&&!r.altKey;if(n&&!r.altKey&&r.key.toLowerCase()==="a")return {kind:"selectAll"};if(!n&&r.key.length===1)return {kind:"insert",text:r.key};if(!e&&r.altKey)return null;let a=r.key==="Home"||l&&r.key==="ArrowLeft"?"start":r.key==="End"||l&&r.key==="ArrowRight"?"end":r.key==="ArrowLeft"?"left":r.key==="ArrowRight"?"right":null;return a?{kind:"move",direction:a,extend:r.shiftKey,...o?{unit:"word"}:{}}:r.key==="Backspace"||r.key==="Delete"?{kind:"delete",direction:r.key==="Backspace"?"backward":"forward",unit:l?"line":o?"word":"character"}:null}function On(r,e,n){if(!n)return Math.min(r.length,e+((r.codePointAt(e)??0)>65535?2:1));let o=r.charCodeAt(e-1),l=r.charCodeAt(e-2);return Math.max(0,e-(o>=56320&&o<=57343&&l>=55296&&l<=56319?2:1))}function li(r,e,n){let o=()=>On(r,e,n),l=()=>r.slice(Math.min(e,o()),Math.max(e,o()));for(;/\s/u.test(l());)e=o();let a=/[\p{L}\p{N}_]/u.test(l());for(;l()&&!/\s/u.test(l())&&/[\p{L}\p{N}_]/u.test(l())===a;)e=o();return e}function kr(r,e,n){let o=Math.max(0,Math.min(r.length,n?.anchor??r.length)),l=Math.max(0,Math.min(r.length,n?.focus??r.length));for(let a of e){let h=Math.min(o,l),b=Math.max(o,l);if(a.kind==="select"){o=Math.max(0,Math.min(r.length,a.anchor)),l=Math.max(0,Math.min(r.length,a.focus));continue}if(a.kind==="selectAll"){o=0,l=r.length;continue}if(a.kind==="move"){let m=a.direction==="left",P=a.direction==="start"?0:a.direction==="end"?r.length:h!==b&&!a.extend?m?h:b:a.unit==="word"?li(r,l,m):On(r,l,m);a.extend||(o=P),l=P;continue}if(a.kind==="delete"&&h===b){let m=a.direction==="backward",P=a.unit==="line"?m?0:r.length:a.unit==="word"?li(r,l,m):On(r,l,m);h=Math.min(l,P),b=Math.max(l,P);}let c=a.kind==="insert"?a.text:"";r=r.slice(0,h)+c+r.slice(b),o=l=h+c.length;}return {value:r,anchor:o,focus:l}}var tn=class{constructor(e){a$2(this,"options",e);a$2(this,"coordinator",null);a$2(this,"listeners",new Set);a$2(this,"snapshot",{cell:null,formula:null,refused:[]});a$2(this,"draft",null);a$2(this,"formulaTarget",null);a$2(this,"formulaThroughSeq",null);a$2(this,"restoredRefusal",null);a$2(this,"revision",0);a$2(this,"compositionRevision",0);a$2(this,"composing",null);a$2(this,"trailing",null);a$2(this,"conversionEnter",false);a$2(this,"disposed",false);a$2(this,"loading",null);a$2(this,"cellSelection",null);a$2(this,"cellInput",null);a$2(this,"formulaInput",null);a$2(this,"focusedCellInput",null);a$2(this,"getSnapshot",()=>this.snapshot);a$2(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e);}));a$2(this,"sync",()=>{if(this.loading)return;let e=this.draft,n=e?.source==="cell"?this.cellInput:this.formulaInput;if(!e||!n||n.value===e.value)return;let o={...e,value:n.value,modified:true,revision:++this.revision};this.setDraft(o),this.composing||this.publish(o.source==="cell"?{cell:o}:{formula:o.value});});a$2(this,"cancel",()=>{this.options.defer?.(this.cancel)||(this.cancelPrefill(),this.composing?.settle(false),this.composing=null,this.compositionRevision+=1,this.trailing=null,this.formulaTarget=null,this.formulaThroughSeq=null,this.restoredRefusal&&this.coordinator?.discardRejected(this.restoredRefusal),this.setDraft(null),this.publish({cell:null,formula:null}),this.options.focus());});a$2(this,"seal",()=>{if(this.loading&&(this.loading.operations.length||this.composing?.loading===this.loading))return this.sealPrefill(this.loading);if(!this.composing)return !this.draft&&this.snapshot.cell&&this.publish({cell:null}),{};let e=this.composing;e.sealed=true;let n=e.source==="cell"?this.cellInput:this.formulaInput;return n?.blur(),{composition:e.done,compositionDraft:()=>e.completed,restoreFocus:()=>{if(this.disposed||this.composing||this.draft||!this.options.editable())return;let o=document.activeElement;o&&o!==document.body&&o!==n||(e.source==="formula"?this.formulaInput?.focus({preventScroll:true}):this.options.focus());}}});}attach(e){this.coordinator=e;}get compositionId(){return this.composing?.id}get loadingCell(){return this.loading!==null}get prefillIdentity(){return `${this.revision}:${this.compositionRevision}`}get focusedCellIdentity(){let e=this.options.selection()?.anchor;return JSON.stringify([this.options.identity(),this.options.navigation(),this.options.sheet(),e?.row,e?.col,this.options.valueRevision?.()])}isComposing(e){return this.composing?.source===e}get ownsFocus(){return this.draft!==null||this.snapshot.cell!==null||this.composing!==null}publish(e){this.snapshot={...this.snapshot,...e};for(let n of this.listeners)n();}setDraft(e){this.draft=e,e||(this.cellSelection=null),e||(this.restoredRefusal=null),this.coordinator?.setDraft(e);}create(e,n,o,l=true){return {generation:this.options.generation(),sheet:this.options.sheet(),...n,source:e,value:o,revision:++this.revision,modified:l,after:this.options.dependency(),target:this.options.target(this.options.sheet(),n.row,n.col)}}open(e){if(this.options.defer?.(()=>this.open(e)))return;let n=this.options.selection();if(!this.coordinator||!this.options.editable()||!n||this.composing||this.snapshot.cell)return;this.commit("formula"),this.trailing=null;let o=this.focusedCellInput?.identity===this.focusedCellIdentity?this.focusedCellInput.value:void 0,l=this.coordinator.pending?void 0:o,a=this.create("cell",n.anchor,e??l??"",e!==void 0),h,b=new Promise(P=>{h=P;}),c=e===void 0?{draft:a,identity:this.options.identity(),navigation:this.options.navigation(),operations:[],cancelled:false,sealed:false,completed:null,settle:h,input:{ready:b,target:a,draft:()=>c.completed}}:null,m=c?Js(this.coordinator,()=>{let P=a.target?this.options.resolveSheet(a.target.sheetId):a.sheet;return P===void 0?Promise.resolve(""):this.options.prefill(P,a)},P=>{c.value=P,this.completePrefill(c);},c.input.ready,()=>c.cancelled,P=>this.refusePrefill(c,P)):null;this.loading=c,this.setDraft(a),this.publish({cell:a,formula:null}),!(!c||!m)&&m.catch(P=>{c.settle(false),!c.cancelled&&!this.disposed&&this.options.identity()===c.identity&&this.options.fail(P);});}completePrefill(e){if(e.cancelled||this.disposed||this.options.identity()!==e.identity||!e.sealed&&(this.loading!==e||this.options.navigation()!==e.navigation)){e.settle(false);return}if(e.completed||e.value===void 0||this.composing?.loading===e)return;this.loading===e&&this.captureCellSelection();let n=kr(e.value,e.operations),o=n.value!==e.value||e.operations.some(a=>a.kind==="insert"||a.kind==="delete"),l=Object.freeze({...e.draft,value:n.value,modified:o,reserved:e.sealed,revision:o?++this.revision:e.draft.revision});e.completed=l,e.sealed||(this.loading=null,this.setDraft(l),this.trailing?.prefill&&this.trailing.input===this.cellInput&&(this.trailing.replay=n),this.writeCellSelection(l,n),this.publish({cell:l})),e.settle(true);}refusePrefill(e,n){e.settle(false),!(e.cancelled||this.disposed||this.options.identity()!==e.identity)&&(this.loading===e&&(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null})),this.coordinator?.error||this.options.report(n));}cancelPrefill(){this.loading&&(this.loading.cancelled=true,this.loading.settle(false)),this.loading=null;}sealPrefill(e){let n=this.cellInput,o=e.sealed;return e.sealed=true,this.composing?.loading===e?!o&&n&&n.ownerDocument?.activeElement===n&&n.blur():this.loading===e&&(this.loading=null,this.setDraft(null),this.publish({cell:null})),{pendingInput:e.input,restoreFocus:()=>{if(!n||this.disposed||this.composing||this.draft||!this.options.editable())return;let l=this.options.selection()?.anchor,a=e.draft.target?this.options.resolveSheet(e.draft.target.sheetId):e.draft.sheet;if(this.options.sheet()!==a||l?.row!==e.draft.row||l?.col!==e.draft.col)return;let h=n.ownerDocument.activeElement;h&&h!==n.ownerDocument.body&&h!==n||this.options.focus();}}}reservePrefill(e){this.sealPrefill(e),this.coordinator&&!e.input.ticket&&(e.input.ticket=this.coordinator.reserveInput(e.input),this.options.committed(e.input.ticket,e.draft));}writeCellSelection(e,n){let o=this.cellInput;this.cellSelection=o&&o.ownerDocument.activeElement===o?null:{revision:e.revision,anchor:n.anchor,focus:n.focus},o&&(o.value=n.value,o.setSelectionRange(Math.min(n.anchor,n.focus),Math.max(n.anchor,n.focus),n.anchor>n.focus?"backward":"forward"));}restoreCellSelection(){let e=this.cellSelection,n=this.cellInput;!e||!n||(this.cellSelection=null,this.draft?.revision===e.revision&&n.setSelectionRange(Math.min(e.anchor,e.focus),Math.max(e.anchor,e.focus),e.anchor>e.focus?"backward":"forward"));}holdCellEdit(e){return this.loading?(this.loading.sealed||this.loading.operations.push(e),true):false}captureCellSelection(){let e=this.loading,n=this.cellInput;if(!e||!n||this.composing?.loading===e||!n.value.length)return;let o=n.selectionStart??n.value.length,l=n.selectionEnd??o,a=n.selectionDirection==="backward"?{anchor:l,focus:o}:{anchor:o,focus:l},h=e.nativeSelection;h?.anchor===a.anchor&&h.focus===a.focus||(e.nativeSelection=a,o===0&&l===n.value.length?this.holdCellEdit({kind:"selectAll"}):o===l&&l===n.value.length?h&&this.holdCellEdit({kind:"move",direction:"end"}):this.holdCellEdit({kind:"select",...a}));}holdCellBeforeInput(e){if(this.trailing?.prefill&&!this.composing&&["insertText","insertFromComposition","insertCompositionText"].includes(e.inputType)&&e.data===this.trailing.data)return this.trailing.data!=="";if(!this.loading||this.composing?.loading===this.loading)return false;this.captureCellSelection();let n=this.cellInput;if(e.inputType==="insertReplacementText"&&n?.value.length){let l=e.getTargetRanges?.()[0];l&&this.holdCellEdit(l.startOffset===0&&l.endOffset===n.value.length?{kind:"selectAll"}:{kind:"select",anchor:l.startOffset,focus:l.endOffset});}let o=en(e,h());return o?this.holdCellEdit(o):false}holdCellKey(e){let n=this.loading;if(!n)return false;this.captureCellSelection();let o=en(e,h());if(!o||o.kind==="insert")return false;this.holdCellEdit(o);let l=this.cellInput;if(l){let a=kr(l.value,[o],{anchor:l.selectionDirection==="backward"?l.selectionEnd??0:l.selectionStart??0,focus:l.selectionDirection==="backward"?l.selectionStart??0:l.selectionEnd??0});l.setSelectionRange(Math.min(a.anchor,a.focus),Math.max(a.anchor,a.focus),a.anchor>a.focus?"backward":"forward"),n.nativeSelection={anchor:a.anchor,focus:a.focus};}return true}cellKey(e){let n=en(e,h()),o=this.snapshot.cell;if(!n||!o)return false;if(this.holdCellEdit(n))return true;let l=this.cellSelection?.revision===o.revision?this.cellSelection:void 0,a=kr(o.value,[n],l);return (n.kind==="insert"||n.kind==="delete")&&this.change("cell",a.value,null),this.writeCellSelection(this.draft??o,a),true}change(e,n,o){if(this.options.defer?.(()=>this.change(e,n,o))||!this.options.editable()||!this.coordinator)return;if(this.trailing?.source===e&&this.trailing.input===o&&this.trailing.value===n){this.trailing.replay&&this.draft?.value===this.trailing.replay.value&&this.writeCellSelection(this.draft,this.trailing.replay);return}if(e==="cell"&&this.composing?.loading){this.composing.value=n;return}e==="cell"&&this.loading&&this.cancelPrefill(),this.cellSelection=null,this.trailing=null;let l=this.options.selection();if(!l)return;this.draft&&this.draft.source!==e&&!this.composing&&this.commit(this.draft.source);let h={...this.draft??(e==="cell"?this.snapshot.cell:null)??this.create(e,l.anchor,n),value:n,modified:true,revision:++this.revision};this.setDraft(h),!this.composing&&this.publish(e==="cell"?{cell:h,formula:null}:{formula:n,cell:null});}commit(e,n,o=false){if(!o&&this.options.defer?.(()=>this.commit(e,n,true),true)){e==="formula"&&n&&this.options.focus();return}if(!this.composing&&!(e==="cell"?this.loading||this.snapshot.cell:this.formulaTarget)&&this.draft?.source!==e||!this.options.editable()||!this.coordinator)return;if(this.composing){let c=this.composing.loading;e==="cell"&&!n&&c&&!c.sealed&&this.reservePrefill(c);return}if(e==="cell"&&this.loading){let c=this.loading;if(c.operations.length){if(this.reservePrefill(c),n){let m=c.draft.target?this.options.resolveSheet(c.draft.target.sheetId):c.draft.sheet;m!==void 0&&this.options.select(m,c.draft,n),c.input.options={selection:this.options.selectionTarget(),selectionRevision:this.options.navigation()},c.operations.some(P=>P.kind==="insert"||P.kind==="delete")||this.options.navigate(),this.options.focus();}return}this.cancelPrefill();}if(this.trailing?.source===e&&this.conversionEnter&&(n==="up"||n==="down")){this.trailing=null,this.conversionEnter=false;return}n&&(this.trailing=null,this.conversionEnter=false),o||this.sync();let l=this.draft?.source===e?this.draft:null,a=e==="cell"?this.snapshot.cell:this.formulaTarget;if(!l&&!a||!l&&e==="formula"&&!n)return;let h=l??a;this.setDraft(null),e==="cell"?this.publish({cell:null}):l&&(this.formulaTarget={...l,modified:false},this.formulaThroughSeq=null,this.publish({formula:l.value}));let b=h.target?this.options.resolveSheet(h.target.sheetId):h.sheet;if(b!==void 0&&this.options.select(b,h,n),l?.modified){let c=this.coordinator.submit(l,{selection:this.options.selectionTarget(),after:l.after});this.options.committed(c,l);}else this.options.navigate();(n||e==="cell")&&this.options.focus();}start(e){if(this.options.defer?.(()=>this.start(e))||!this.options.editable()||this.composing)return;e==="cell"&&this.captureCellSelection();let n=this.options.selection();if(!n)return;this.draft&&this.draft.source!==e&&this.commit(this.draft.source);let o=e==="cell"?this.cellInput:this.formulaInput,l=this.draft??this.create(e,n.anchor,o?.value??"",false);this.setDraft(l),this.trailing=null,this.conversionEnter=false;let a,h=new Promise(c=>{a=c;}),b=e==="cell"?this.loading??void 0:void 0;this.composing={id:`${this.options.identity()}:composition:${++this.compositionRevision}`,source:e,target:l,done:h,settle:a,sealed:false,completed:null,loading:b,inputState:b?{value:o?.value??"",anchor:o?.selectionStart??0,focus:o?.selectionEnd??0}:void 0};}end(e,n,o=false){if(!o&&this.options.defer?.(()=>this.end(e,n,true)))return;let l=this.composing;l&&(e!==void 0&&(l.result=e),o&&n!==void 0&&(l.completedValue=n),queueMicrotask(()=>{this.composing===l&&this.completeComposition();}));}completeComposition(){let e=this.composing;if(!e||!this.coordinator)return;if(e.loading){let l=e.loading,a=this.cellInput,h=e.inputState,b=e.completedValue??a?.value??e.value??"",c=Math.min(h.anchor,h.focus),m=h.value.length-Math.max(h.anchor,h.focus),P=e.result??(b===h.value?"":b.slice(c,Math.max(c,b.length-m))),C=P===""?h:kr(h.value,[{kind:"insert",text:P}],h);P!==""&&l.operations.push({kind:"insert",text:P}),a&&(this.trailing={source:"cell",input:a,value:C.value,data:P,prefill:true}),this.composing=null,a&&(a.value=C.value,a.setSelectionRange(Math.min(C.anchor,C.focus),Math.max(C.anchor,C.focus))),l.sealed&&(this.loading=null,this.setDraft(null),this.publish({cell:null})),this.completePrefill(l),e.settle(P!=="");return}e.completedValue===void 0&&this.sync();let n=e.source==="cell"?this.cellInput:this.formulaInput,o={...e.target,value:e.completedValue??n?.value??this.draft?.value??"",modified:true,revision:++this.revision};if(e.completed=o.value!==""?Object.freeze({...o}):null,this.composing=null,this.setDraft(e.sealed&&o.value!==""?o:null),n&&(this.trailing={source:o.source,input:n,value:o.value}),o.value!==""){let l=o.target?this.options.resolveSheet(o.target.sheetId):o.sheet;if(!e.sealed&&l!==void 0&&l!==this.options.sheet()&&this.options.select(l,o),o.source==="formula"&&(this.formulaTarget={...o,modified:false},this.formulaThroughSeq=null,this.publish({formula:o.value})),!e.sealed){let a=this.coordinator.submit(o,{compositionId:e.id,selection:this.options.selectionTarget(),after:o.after});this.options.committed(a,o);}this.publish(o.source==="cell"?{cell:o}:{formula:o.value});}else this.publish({cell:null,formula:null});e.settle(o.value!=="");}key(e,n){return this.isComposing(e)||n.nativeEvent.isComposing||n.keyCode===229?(n.key==="Enter"&&(this.conversionEnter=true),true):n.key==="Enter"&&this.conversionEnter?(this.conversionEnter=false,this.trailing=null,true):(this.trailing?.prefill&&(this.trailing=null),false)}keyUp(){this.composing||(this.trailing=null,this.conversionEnter=false);}refused(e,n){let o={...n,modified:true,revision:++this.revision,after:null},l={seq:e,draft:o};this.publish({refused:[...this.snapshot.refused,l].slice(-64)});let a=this.options.selection()?.anchor,h=o.target?this.options.resolveSheet(o.target.sheetId):o.sheet,b=this.options.sheet()===h&&a?.row===o.row&&a?.col===o.col;!this.ownsFocus&&this.options.editable()&&(!n.reserved||b)?this.restore(l):this.coordinator?.setDraft(this.draft);}restore(e=this.snapshot.refused[0]){if(!e||this.options.defer?.(()=>this.restore(e))||this.ownsFocus||!this.options.editable())return;let n=e.draft.target?this.options.resolveSheet(e.draft.target.sheetId):e.draft.sheet;n!==void 0&&(this.options.restoreCell?this.options.restoreCell(n,e.draft,o=>this.restoreResolved(e,n,o,true)):this.restoreResolved(e,n,e.draft,false));}restoreResolved(e,n,o,l){if(this.ownsFocus||!this.options.editable())return;let a={...e.draft,row:o.row,col:o.col,sheet:n,reserved:false,target:this.options.target(n,o.row,o.col)};l||this.options.select(n,a),this.setDraft(a),this.restoredRefusal=e.draft,this.publish({cell:a.source==="cell"?a:null,formula:a.source==="formula"?a.value:null,refused:this.snapshot.refused.filter(h=>h!==e)}),e.draft.source==="formula"&&this.formulaInput?.focus({preventScroll:true});}finish(){if(this.loading){this.loading.operations.length||this.composing?.loading===this.loading?(this.reservePrefill(this.loading),this.composing&&this.end()):(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null,formula:null}));return}if(this.composing){this.sync(),this.end();return}this.sync();let e=this.draft;e?.modified&&this.coordinator&&this.options.committed(this.coordinator.submit(e,{after:e.after}),e),this.setDraft(null),this.publish({cell:null,formula:null});}selectionChanged(){this.loading&&this.options.navigation()!==this.loading.navigation&&(this.loading.operations.length||this.composing?.loading===this.loading?this.reservePrefill(this.loading):(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null}))),this.formulaTarget=null,this.formulaThroughSeq=null,!this.draft&&!this.composing&&this.snapshot.formula!==null&&this.publish({formula:null});}submitted(e,n){if(this.composing)return;let o=e,l=this.draft?.source===e.source&&this.draft.sheet===e.sheet&&this.draft.row===e.row&&this.draft.col===e.col&&this.draft.value===e.value&&this.draft.revision===o.revision;l&&(this.draft=null),e.source==="cell"?l&&this.publish({cell:null}):(l||this.formulaTarget?.revision===o.revision)&&(this.formulaTarget={...o,modified:false},this.formulaThroughSeq=n);}presented(e){this.formulaThroughSeq===null||e<this.formulaThroughSeq||this.draft||this.composing||(this.formulaThroughSeq=null,this.snapshot.formula!==null&&this.publish({formula:null}));}dispose(){this.disposed=true,this.cancelPrefill(),this.composing?.settle(false),this.composing=null,this.listeners.clear();}};function jl(r,e){return r===e||!!(r&&e&&r.sheet===e.sheet&&r.contentWidth===e.contentWidth&&r.contentHeight===e.contentHeight&&r.frozenRows===e.frozenRows&&r.frozenCols===e.frozenCols&&r.frozenWidth===e.frozenWidth&&r.frozenHeight===e.frozenHeight&&r.initialScrollX===e.initialScrollX&&r.initialScrollY===e.initialScrollY)}var rn=class{constructor(){a$2(this,"selectionRef",{current:null});a$2(this,"viewRef",{current:null});a$2(this,"snapshot",{selection:null,view:null,painted:null});a$2(this,"listeners",new Set);a$2(this,"coverageListeners",new Set);a$2(this,"coverage",0);a$2(this,"publication",null);a$2(this,"getSnapshot",()=>this.snapshot);a$2(this,"subscribeCoverage",e=>(this.coverageListeners.add(e),()=>{this.coverageListeners.delete(e);}));a$2(this,"advanceCoverage",e=>{if(!(e<=this.coverage)){this.coverage=e;for(let n of this.coverageListeners)n();}});a$2(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e);}));a$2(this,"publish",()=>{this.publication=null;for(let e of this.listeners)e();});a$2(this,"setSelection",e=>{this.selectionRef.current=e,this.snapshot.selection!==e&&(this.snapshot={...this.snapshot,selection:e},this.publish());});a$2(this,"setView",e=>{this.viewRef.current=e,!jl(this.snapshot.view,e)&&(this.snapshot={...this.snapshot,view:e},this.schedule());});a$2(this,"setPainted",e=>{this.snapshot.painted!==e&&(this.snapshot={...this.snapshot,painted:e},e?.coversThroughSeq!==void 0&&this.advanceCoverage(e.coversThroughSeq),this.schedule());});}get coversThroughSeq(){return this.coverage}schedule(){if(this.publication)return;let e={};this.publication=e,queueMicrotask(()=>{this.publication===e&&this.publish();});}reset(){this.selectionRef.current=null,this.viewRef.current=null,this.snapshot={selection:null,view:null,painted:null},this.coverage=0,this.publish();}cancel(){this.publication=null;}};function Ye(r,e){let n=useMemo(()=>{let o;return ()=>{let l=r.getSnapshot();return (!o||o.state!==l)&&(o={state:l,value:e(l)}),o.value}},[r,e]);return useSyncExternalStore(r.subscribe,n)}function br(r,e){return `${I(e)}${r+1}`}function ai(r,e,n,o){let l=e?e.indexOf(o):o-r;return l>=0&&l<n?l:-1}function Kl(r,e,n,o){if(!e)return Math.min(o-r,n-1);let l=-1;for(let a=0;a<n&&a<e.length;a++)e[a]<=o&&(l=a);return l}function Gl(r,e,n){let o=Math.min(.5,e.w/2);return n==="left"?e.x+o:n==="right"?e.x+e.w-o:Math.min(Math.max(r,e.x+o),e.x+e.w-o)}function ui(r,e,n,o=[]){let l=r.grid;if(!l)return null;let a=l.colOffsets.length-1,h=ai(l.startRow,l.rowIndices,l.rowOffsets.length-1,e),b=ai(l.startCol,l.colIndices,a,n);if(h<0||b<0)return null;let c=o.find(({start:f,end:M})=>Math.min(f.row,M.row)===e&&Math.min(f.col,M.col)===n),m=c?Math.max(c.start.col,c.end.col):n,P=Math.max(b,m===n?b:Kl(l.startCol,l.colIndices,a,m)),C=l.colOffsets[b],x=l.colOffsets[P+1],L=Math.round(l.rowOffsets[h]*1e3),v=[];for(let f of r.commands){if(f.op!=="text"||!f.clip||f.ghost||f.chart||Math.round(f.clip.y*1e3)!==L)continue;let M=Gl(f.x,f.clip,f.align);M>=C&&M<x&&v.push(f.text);}return v.join(" ").trim()}function di(r,e){let n=normalizeRange(e);return `${r}:${n.top},${n.left},${n.bottom},${n.right}:${e.anchor.row},${e.anchor.col}`}function zn(r,e=[]){let n=normalizeRange(r);return n.top===n.bottom&&n.left===n.right?true:e.some(({start:o,end:l})=>Math.min(o.row,l.row)===n.top&&Math.min(o.col,l.col)===n.left&&Math.max(o.row,l.row)===n.bottom&&Math.max(o.col,l.col)===n.right)}var ci=(r,e)=>r.replace(/\{(\w+)\}/g,(n,o)=>e[o]??n);function fi(r,e,n,o,l=[]){let a=[];o&&a.push(n.sheetActivated({name:o.name,index:o.index+1,count:o.count}));let h=normalizeRange(r);if(zn(r,l)){let b=br(r.anchor.row,r.anchor.col),c=e.text??"",m=c?ci(n.cellLabel,{address:b,value:c}):ci(n.emptyCellLabel,{address:b});a.push(e.formula?n.hasFormula(m):m);}else a.push(n.rangeSelected({start:br(h.top,h.left),end:br(h.bottom,h.right),rows:h.bottom-h.top+1,columns:h.right-h.left+1}));return a.join(", ")}var Bn=createContext(null),Ql=150,ea=600,ta=r=>r.selection,ra=r=>r.painted,na={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap",border:0},mi=memo(function({store:e,active:n,sheets:o,focusTarget:l,announceRef:a}){let{t:h}=c(),b=Ye(e,ra),c$1=Ye(e,ta),m=useContext(Bn),[P,C]=useState(""),[x,L]=useState(0),v=useRef(false),f=useRef(null),M=useRef(null);useLayoutEffect(()=>(a.current=()=>{f.current=null,M.current=null,L(he=>he+1);},()=>{a.current=null;}),[a]);let w=useMemo(()=>({cellLabel:h("a11y.cellLabel"),emptyCellLabel:h("a11y.emptyCellLabel"),hasFormula:he=>h("a11y.hasFormula",{label:he}),rangeSelected:he=>h("a11y.rangeSelected",he),sheetActivated:he=>h("a11y.sheetActivated",he)}),[h]),q=b?.request.sheet===n?b:null,y=c$1?di(n,c$1):null,T=q?.mergedRanges,X=c$1?zn(c$1,T):false,G=c$1&&q?ui(q.displayList,c$1.anchor.row,c$1.anchor.col,T):null,Q=c$1?`${n}:${br(c$1.anchor.row,c$1.anchor.col)}`:"",re=m&&m.at===Q?m.value.startsWith("="):null,_=!X||G!==null&&re!==null,D=_?X?`${G}
2
+ ${re}`:"":null,Ie=o.findIndex(he=>he.index===n),$=Ie>=0?o[Ie]:void 0;return useEffect(()=>{if(!c$1||y===null)return;let he=f.current?.key===y;if(he&&(!X||D===null||m?.painted!==b||f.current?.content===D))return;let de=setTimeout(()=>{let ie=l.current,ge=ie?.ownerDocument.activeElement,we=!!(ie&&ie.contains(ge??null)),O=M.current!==null&&M.current!==n;if(f.current={key:y,content:D},M.current=n,!we||he&&ge!==ie)return;let Z=fi(c$1,{text:G,formula:re},w,O&&$?{name:$.name,index:Ie,count:o.length}:void 0,T);v.current=!v.current,C(v.current?`${Z}\xA0`:Z);},_?Ql:ea);return ()=>clearTimeout(de)},[c$1,y,_,X,D,m,b,G,re,w,n,Ie,$,o.length,T,l,x]),jsx("div",{"data-testid":"xlsx-live-region",role:"status","aria-live":"polite","aria-atomic":"true",style:na,children:P})});var yi=memo(function({controller:e,presentation:n,run:o,active:l,selectedChart:a,error:h,readOnly:b,navigation:c,onNavigate:m,cellEditable:P,children:C}){let{selection:x,view:L,painted:v}=useSyncExternalStore(n.subscribe,n.getSnapshot),[f,M]=useState(null),w=v?.coversThroughSeq??0,q=Kn(o,b);useEffect(()=>{if(!o?.current||o.failure||!x||a)return;let D=`${o.generation}:${o.session.confirmedBasis.epoch}`,Ie=c.current,$=e.focusedCellIdentity,he=`${l}:${nn(x.anchor)}`,de=false;return o.session.call.cellInputs(l,nn(x.anchor)).then(ie=>{if(!de&&o.current&&!o.failure&&D===`${o.generation}:${o.session.confirmedBasis.epoch}`&&c.current===Ie&&e.focusedCellIdentity===$){let ge=ie.cells[0]?.[0]?.input??"";e.focusedCellInput={identity:$,value:ge},M({at:he,value:ge,painted:v}),e.presented(w);}}).catch(ie=>{!de&&o.current&&o.fail(ie);}),()=>{de=true;}},[o,l,x,a,v,w,e,c]),useLayoutEffect(()=>{M(null);},[o]);let y=useSyncExternalStore(e.subscribe,e.getSnapshot),T=useMemo(()=>({native:true,onNavigate:m,inputRef:D=>{e.formulaInput=D;},isComposing:()=>e.isComposing("formula"),onChange:D=>e.change("formula",D,e.formulaInput),onCommit:D=>e.commit("formula",D),onCancel:e.cancel,onBlur:()=>e.commit("formula"),onCompositionStart:()=>e.start("formula"),onCompositionEnd:()=>e.end(void 0,e.formulaInput?.value),onKeyDown:D=>e.key("formula",D)?(D.stopPropagation(),true):false,onKeyUp:()=>e.keyUp()}),[e,m]),X=x?nn(x.anchor):"",G=y.formula??(f?.at===`${l}:${X}`?f.value:"");useLayoutEffect(()=>{let D=e.formulaInput;D&&!e.isComposing("formula")&&D.value!==G&&V(D,G);},[e,y,G]);let Q=!L||!x||h,re=x!==null&&!P(x.anchor),_=useMemo(()=>({...T,a1:X,value:G,disabled:Q,readOnly:q||a||re,...re&&{onChange:()=>{}}}),[T,X,G,Q,q,a,re]);return jsxs(U.Provider,{value:_,children:[jsx(Bn.Provider,{value:f,children:C}),y.refused.map(D=>jsx("button",{"data-testid":"xlsx-refused-draft","data-sheet":D.draft.sheet,"data-row":D.draft.row,"data-col":D.draft.col,onClick:()=>e.restore(D),children:D.draft.value},D.seq??D.draft.revision))]})}),ki=memo(function({controller:e,rect:n,colors:o,disabled:l,zoom:a}){let{t:h}=c(),b=useContext(G),c$1=b?y(b):null,m=useCallback(y=>{e.cellInput=y;},[e]),C=useSyncExternalStore(e.subscribe,e.getSnapshot).cell,x=useRef({target:"",rect:null}),L=C?`${C.generation}:${C.sheet}:${C.row}:${C.col}`:"";L!==x.current.target&&(x.current={target:L,rect:null});let v=C?n(C.row,C.col,C.sheet):null;v&&!e.isComposing("cell")&&(x.current.rect=v);let f=x.current.rect;if(useLayoutEffect(()=>{let y=e.cellInput;if(!y)return;let T=G=>{e.holdCellBeforeInput(G)&&G.preventDefault();},X=()=>e.captureCellSelection();return y.addEventListener("beforeinput",T),y.addEventListener("select",X),()=>{y.removeEventListener("beforeinput",T),y.removeEventListener("select",X);}},[e,C!==null,f!==null]),useLayoutEffect(()=>{let y=e.cellInput;if(!C||!y||e.isComposing("cell"))return;y.value!==C.value&&(y.value=C.value);let T=y.ownerDocument.activeElement;if(T!==y){let X=y.closest("[tabindex]");if(T&&T!==y.ownerDocument.body&&!X?.contains(T))return;y.focus({preventScroll:true}),y.setSelectionRange(y.value.length,y.value.length);}e.restoreCellSelection();},[e,C,f!==null]),!C||!f)return null;let{color:M,background:w}=o?.(C.sheet,f)??ba(null,f),q={position:"absolute",left:f.x*a,top:f.y*a,width:f.w*a,height:f.h*a,boxSizing:"border-box",border:"2px solid #217346",background:w,color:M,padding:"0 3px",font:`${13*a}px system-ui, sans-serif`,pointerEvents:"auto",outline:"none"};return jsx("input",{ref:m,"data-testid":"xlsx-cell-editor","aria-label":h("a11y.cellInputLabel",{address:nn(C)}),defaultValue:C.value,disabled:l,style:q,onChange:y=>e.change("cell",y.target.value,y.currentTarget),onCompositionStart:()=>e.start("cell"),onCompositionEnd:y=>e.end(y.nativeEvent.data,y.currentTarget.value),onKeyDown:y=>{if(c$1?.claimsKey(y)||y.stopPropagation(),!e.key("cell",y)){if(e.holdCellKey(y)){y.preventDefault(),y.stopPropagation();return}y.key==="Enter"?(e.commit("cell",y.shiftKey?"up":"down"),y.preventDefault()):y.key==="Tab"?(e.commit("cell",y.shiftKey?"left":"right"),y.preventDefault()):y.key==="Escape"&&(e.cancel(),y.preventDefault());}},onKeyUp:()=>e.keyUp(),onBlur:()=>e.commit("cell")})});function nn(r){let e="";for(let n=r.col+1;n>0;n=Math.floor((n-1)/26))e=String.fromCharCode(65+(n-1)%26)+e;return `${e}${r.row+1}`}function Kn(r,e){let n=useCallback(l=>r?.subscribe(l)??(()=>{}),[r]),o=useCallback(()=>!r||!r.ready||r.readOnly,[r]);return useSyncExternalStore(n,o)||e}function bi(r,e,n,o,l){let[a,h]=useState({run:null,provider:null,peers:[]});return useLayoutEffect(()=>{if(h({run:r,provider:e,peers:[]}),!r?.current||r.failure||!e)return;let b=e.onAwareness(c=>{r.current&&!r.retiring&&!r.failure&&h({run:r,provider:e,peers:[...c]});});return ()=>{b(),e.setCursor(null);}},[r,r?.failure,e]),useEffect(()=>{if(!e)return;if(!r?.ready){e.setCursor(null);return}let b=l.find(m=>m.index===n)?.id,c=o?normalizeRange(o):null;e.setCursor(b&&o&&c?{sheet:b,anchor:o.range?{row:c.top,col:c.left}:{...o.anchor},head:o.range?{row:c.bottom,col:c.right}:{...o.focus}}:null);},[r,r?.ready,e,n,o,l]),r?.current&&!r.retiring&&!r.failure&&a.run===r&&a.provider===e?a.peers:[]}var wr=r=>r.selection,ln=r=>r.painted,xi=r=>r.view,Pi={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},Ci=memo(function({store:e,active:n,leadingInset:o=0,headerHandlers:l,selectAllLabel:a,showSheetHeaders:h=false,children:b}){let c=Ye(e,ln),m=Ye(e,wr),P=c?.request.sheet===n?n:null;return jsx(Fa$1,{frame:c?.request.sheet===n?c.displayList:null,zoom:c?.request.zoom??1,leadingInset:o,showSheetHeaders:h,headerHandlers:l,sheet:P,selectAllLabel:a,selection:c?.request.sheet===n?m:null,children:b})}),Si=memo(function({store:e,zoom:n}){let o=Ye(e,xi);return jsx("div",{style:{position:"absolute",top:0,left:0,width:o?o.contentWidth*n:"100%",height:o?o.contentHeight*n:"100%"}})}),Ri=memo(function({store:e,active:n,zoom:o,selectedChart:l,chartPreview:a,chartSheetExtent:h,onResizeStart:b,onResizeNudge:c$1,controller:m,disabled:P,run:C,showSheetHeaders:x=false,onFill:L,cellAt:v,fillHandle:f}){let M=Kn(C,P),{t:w}=c(),q$1=useSyncExternalStore(m.subscribe,m.getSnapshot),y=q$1.cell!==null||q$1.formula!==null,T=Ye(e,ln),X$1=Ye(e,wr),G=Ye(e,xi),Q$1=T?.request.zoom??o,re=T?.request.sheet===n?X$1:null,_=T?.displayList.grid,D=re?X(normalizeRange(re),T?.mergedRanges??[],x):null,Ie=_&&D?rangeRect(_,D):null,$=_&&D?cellRect(_,D.bottom,D.right):null,he=N(Ie?W(Ie,Q$1):null,$?W($,Q$1):null),de=re?X({top:re.anchor.row,left:re.anchor.col,bottom:re.anchor.row,right:re.anchor.col},T?.mergedRanges??[]):null,ie=_&&de?rangeRect(_,de):null,ge=Pe=>{let Ce=_?rangeRect(_,Pe):null;return Ce?W(Ce,Q$1):null},we=l?T?.displayList.charts?.find(Pe=>Pe.id===l.id)??null:null,O$1=T&&G?ea$1(T.displayList.grid,G.frozenRows,G.frozenCols):null,Z=we&&T&&G?z(we,{x:T.request.viewport.x,y:T.request.viewport.y,frozenRows:G.frozenRows,frozenCols:G.frozenCols,frozenWidth:O$1?.width,frozenHeight:O$1?.height,sheetWidth:h?.width,sheetHeight:h?.height}):void 0,Fe=we&&a?.kind==="resize"?A(we.rect,a.handle,a.dx,a.dy,Z):we?.rect??null,Le=Fe&&l?.movable&&l.resizable&&!l.placeholder&&!M&&a?.kind!=="move",Ae=Fe?W(Fe,Q$1):null,fe=useCallback((Pe,Ce,Me)=>T?.geometry&&T.request.sheet===Me?cellRect(T.geometry,Pe,Ce):null,[T]),et=useCallback((Pe,Ce)=>ba(T?.request.sheet===Pe?T.displayList:null,Ce),[T]),Be=(Pe,Ce,Me)=>{let Se=W(Pe,Q$1);return {position:"absolute",left:Se.x,top:Se.y,width:Se.w,height:Se.h,boxSizing:"border-box",border:Ce,background:Me}},ee=(Pe,Ce,Me=2)=>{let Se=W(Pe,Q$1);return {position:"absolute",left:Se.x,top:Se.y,width:Se.w,height:Se.h,outline:`${Me}px solid ${Ce}`,outlineOffset:-Me/2}},Te=(Pe,Ce=1)=>{let Me=r(W(Pe,Q$1),Ce);return {position:"absolute",left:Me.left,top:Me.top,width:Me.width,height:Me.height,boxShadow:`inset 0 0 0 ${Ce}px ${q}`}},tt=x&&Ie&&!l?s(W(Ie,Q$1),ie?W(ie,Q$1):null):[];return jsxs("div",{"data-testid":"xlsx-overlay-host",style:{position:"absolute",top:0,left:0,width:0,height:0,pointerEvents:"none"},children:[tt.map((Pe,Ce)=>jsx("div",{"data-testid":"xlsx-selection-fill",style:{position:"absolute",left:Pe.x,top:Pe.y,width:Pe.w,height:Pe.h,background:p}},Ce)),Ie&&!l&&jsx("div",{"data-testid":"xlsx-selection",style:x?Te(Ie):Be(Ie,"1px solid #217346","rgba(33, 115, 70, 0.12)")}),f&&!M&&!l&&!y&&he&&D&&L&&v&&!R(D,Q(T?.displayList??null,0))&&jsx(O,{rect:he,source:D,rectForRange:ge,cellAt:v,onFill:L,ariaLabel:w("a11y.fillHandleLabel")}),ie&&!l&&jsx("div",{"data-testid":x?"xlsx-active-cell":"xlsx-focus",style:x?Te(ie,2):Be(ie,"2px solid #217346")}),Fe&&jsx("div",{"data-testid":"xlsx-chart-selection","data-chart-id":l?.id,"aria-hidden":true,style:{...x?ee(Fe,"#217346"):Be(Fe,"2px solid #217346"),...a?.kind==="move"?{transform:`translate(${a.x}px, ${a.y}px)`}:{}}}),Le&&Ae&&jsx(B,{rect:Ae,onStart:b,onNudge:c$1}),jsx(ki,{controller:m,zoom:Q$1,disabled:M,rect:fe,colors:et})]})}),Wi=memo(function({store:e,active:n,sheets:o,onFollowLink:l}){let{t:a}=c(),h=Ye(e,ln),b=Ye(e,wr),c$1=h?.displayList,m=h?.request.sheet===n?b:null,P=h?o[h.request.sheet]?.name??"":"",C=useMemo(()=>c$1?buildA11yGrid(c$1,m,P,{gridLabel:a("a11y.gridLabel"),rowHeaderLabel:a("a11y.rowHeaderLabel"),columnHeaderLabel:a("a11y.columnHeaderLabel"),cellLabel:a("a11y.cellLabel"),cellLabelSelected:a("a11y.cellLabelSelected"),emptyCellLabel:a("a11y.emptyCellLabel"),emptyCellLabelSelected:a("a11y.emptyCellLabelSelected")}):null,[c$1,m,P,a]);return C?jsx(wa,{grid:C,onFollowLink:l}):null}),wa=memo(function({grid:e,onFollowLink:n}){return jsxs(Fragment,{children:[jsx(Ba$1,{grid:e,style:Pi,onFollowLink:n}),e.charts.map((o,l)=>jsx("div",{style:Pi,role:"img","aria-label":o.label},`${l}:${o.label}`))]})});function Ii({store:r,onChange:e}){let n=Ye(r,wr);return useEffect(e,[n,e]),null}function Ti({store:r,run:e,provider:n,active:o,sheets:l}){let a=Ye(r,ln),h=Ye(r,wr),b=bi(e,n,o,h,l),c=l.map(m=>m.id);return jsxs(Fragment,{children:[jsx("div",{style:{position:"absolute",top:8,left:0,width:a?.request.width??0,display:"flex",justifyContent:"flex-end",pointerEvents:"none"},children:jsx(Y,{peers:b,sheetIds:c,sheetNames:l.map(m=>m.name),activeSheet:o})}),a?.request.sheet===o&&jsx("div",{style:{pointerEvents:"none"},children:jsx(Z,{peers:b,sheetIds:c,activeSheet:o,grid:a.displayList.grid,zoom:a.request.zoom,mergedRanges:a.mergedRanges??[]})})]})}var Mi="#217346",Da="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Ma={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]},Xa=1048575,Fa=16383;function Lt(r){let e="";for(let n=r.col+1;n>0;n=Math.floor((n-1)/26))e=String.fromCharCode(65+(n-1)%26)+e;return `${e}${r.row+1}`}function an(r,e){let n,o;if(r.range.kind==="rowCol")({start:n,end:o}=r.range);else {let h=/^\$?([A-Z]+)\$?([1-9]\d*)(?::\$?([A-Z]+)\$?([1-9]\d*))?$/i.exec(r.range.a1);if(!h)return null;let b=(c,m)=>({row:Number(m)-1,col:[...c.toUpperCase()].reduce((P,C)=>P*26+C.charCodeAt(0)-64,0)-1});n=b(h[1],h[2]),o=b(h[3]??h[1],h[4]??h[2]);}let l=r.activeCell??n,a=e?normalizeRange(e):null;return e&&e.anchor.row===l.row&&e.anchor.col===l.col&&a?.top===n.row&&a.left===n.col&&a.bottom===o.row&&a.right===o.col?e:l.row!==n.row&&l.row!==o.row||l.col!==n.col&&l.col!==o.col?{...selectionAt(l),range:{top:n.row,left:n.col,bottom:o.row,right:o.col}}:{anchor:{...l},focus:{row:l.row===n.row?o.row:n.row,col:l.col===n.col?o.col:n.col}}}var La=10*b$1;function Jn(r){return `${Lt({row:r.top,col:r.left})}:${Lt({row:r.bottom,col:r.right})}`}function Zn(r){let e=Promise.reject(r);return e.catch(()=>{}),e}function Ft(r){return F(r.nativeEvent)!==null||G$1(r.target)}function Jt(r){let[e,n]=useState(r),o=useRef(e),l=useCallback(a=>{o.current=typeof a=="function"?a(o.current):a,n(o.current);},[]);return [e,l,o]}function Xi(r,e){let n=r.request;return n.generation===e.generation&&n.sheet===e.sheet&&n.navigation===e.navigation&&n.zoom===e.zoom&&n.dpr===e.dpr&&n.width===e.width&&n.height===e.height&&JSON.stringify(n.viewport)===JSON.stringify(e.viewport)}var Oa=400,Ha=1500,za=24;function Na(r,e){return r.generation===e.generation&&r.sheet===e.sheet&&r.zoom===e.zoom&&r.dpr===e.dpr&&r.width===e.width&&r.height===e.height&&r.viewport.x===e.viewport.x&&r.viewport.y===e.viewport.y&&r.viewport.width===e.viewport.width&&r.viewport.height===e.viewport.height}function Fi(r,e,n,o,l,a){return n?null:a==="start"?r:a==="center"?Math.max(0,r-Math.max(0,l-e)/2):r>=o&&r+e<=o+l?null:r<o||e>=l?r:Math.max(0,r+e-l)}var Ba=memo(function(){return jsxs(ja$1,{mode:"commands",children:[jsx(ja$1.Toolbar,{}),jsxs("div",{style:{display:"flex",padding:"4px 8px"},children:[jsx(ja$1.FormulaBar,{}),isProposalsAvailable()&&jsx(da,{id:"proposalsPanel"})]})]})});function xr(r,e){let n=e();return r.map(o=>o.kind==="item"?{...o,disabled:o.disabled||!n,onSelect:()=>{e()&&o.onSelect();}}:o.kind==="submenu"?{...o,disabled:o.disabled||!n,entries:xr(o.entries,e)}:o.kind==="group"?{...o,entries:xr(o.entries,e)}:o)}function Cd(r){let{t:e,lang:n$2}=c(),[o$1]=useState(()=>new t),l=useRef(null);a(l);let a$2=useRef(null),h$2=useRef(null),b=useId(),c$1=useRef(null),m$1=useRef(null),P$1=useRef(()=>null);useLayoutEffect(()=>()=>m$1.current?.host.close("unmounted"),[]);let C$1=useRef(r);C$1.current=r;let[x$2]=useState(x),[L$1,v$1,f]=Jt(0),M$1=useRef(void 0),[w$1]=useState(()=>new rn),{setSelection:q,selectionRef:y,setView:T$1,viewRef:X,setPainted:G$2}=w$1,[Q$1,re,_$1]=Jt([]),[D$1,Ie,$$1]=Jt(q$1(r.initialZoom)),[he,de]=useState(null),[ie,ge,we]=Jt(null),[O,Z]=useState(null),[Fe,Le]=useState(null),[Ae,fe]=useState(null),et=useRef(null),Be=useRef(null),[,ee]=useReducer(t=>t+1,0),[Te,tt,Pe]=Jt(null),Ce=useRef(null),Me=useRef(0),Se=useRef(null),ut=t=>{Me.current++,Se.current=null,tt(t),t||(Ce.current=null);},Zt=useRef(void 0),dt=useRef(void 0),[d$1,E$2,H$1]=Jt([]),[F,ue,oe]=Jt(false),[pe,le]=useState(false),[Re,Ee]=useState(null),ye=useRef(()=>{}),[qe,Oe]=useState({}),xe=useRef(0),[De]=useState(o),Ke=useRef(selectionAt({row:0,col:0})),ot=useRef(null),Qt=useRef(0),ne=useRef(null),st=useRef(null),at=useRef(false),[bt,Cr]=useState(0),Tt=useRef(null),Ge=useRef(null),rt=useRef(null),ae=useRef(null),ke=useRef(null),nt=useRef(()=>{}),Ue=useCallback(()=>a$2.current?.focus({preventScroll:true}),[]),er=useRef(()=>{}),Qn=useRef(()=>{}),Sr=useRef(0),Li=useCallback(t=>er.current(t),[]),eo=useRef(null),[Oi]=useState(()=>({coordinator:()=>null,readOnly:()=>C$1.current.readOnly??false,allowHostProposals:()=>C$1.current.allowHostProposals??false,focus:Ue,exportCoordinator:()=>eo.current,defaultFonts:()=>C$1.current.defaultFonts,editorDocument:()=>Er,saved:t=>C$1.current.onSave?.(t),clearSelection:()=>{},refreshProposals:()=>{},recoverInput:async()=>{},selectCells:()=>false,selectCellsAsync:async()=>false,apply:()=>{}})),{run:k,error:vt,loading:Hi}=ii(r,x$2.store,Oi,{backend:"peerless",initialViewport:()=>{let t=a$2.current;if(!(!t?.clientWidth||!t.clientHeight))return {width:t.clientWidth,height:t.clientHeight,zoom:$$1.current,dpr:window.devicePixelRatio||1,requestGeneration:0}}}),te=useRef(k);te.current=k;let to=D(k,k?.session.call.decodeFontFace,r.defaultFonts,()=>{k?.current&&!k.failure&&ne.current?.schedule();},()=>{c$1.current&&(c$1.current.dataset.defaultFonts="settled");},r.remoteFonts),cn=useMemo(()=>new Map,[k]),Ht=useMemo(()=>new Map,[k]),Et=useMemo(()=>new Map,[k]),qt=useRef(null),ur=useRef(0),un=useRef(void 0),ro=useMemo(()=>new Set,[k]),dn=useRef(()=>{}),At=t=>(te.current?.session.editState.sheets??te.current?.session.state.sheets)?.find(s=>s.index===t)?.id,Rr=t=>{let s=At(t);if(s&&s===M$1.current&&y.current)return y.current;let i=te.current?.session.selection;return (s?cn.get(s):void 0)??(i&&i.sheetId===s?an(i):null)??selectionAt({row:0,col:0})},no=t=>{let s=a$2.current;if(!s)return;let i=s.firstElementChild;i&&(i.style.width=`${t.contentWidth*$$1.current}px`,i.style.height=`${t.contentHeight*$$1.current}px`);let u=At(t.sheet),p=u?Ht.get(u):void 0;s.scrollLeft=(p?.x??t.initialScrollX)*$$1.current,s.scrollTop=(p?.y??t.initialScrollY)*$$1.current;},Qe=()=>!!(te.current?.ready&&!te.current.retiring&&!te.current.failure&&!te.current.readOnly&&!C$1.current.readOnly&&!fr.current?.readOnly),oo=useRef(()=>{}),{start:zi,cancel:zt,nudge:Ni,active:so}=C({zoom:()=>ne.current?.painted?.request.zoom??$$1.current,preview:Z,commit:(t,s)=>oo.current(s)}),io=O?.kind==="resize";useEffect(()=>{let t=k;if(!ie||!io||!t?.ready||!t.current){Le(null);return}let s=false;return t.session.call.cellGeometry(L$1,Xa,Fa).then(i=>{s||Le({width:i.rect.x+i.rect.w,height:i.rect.y+i.rect.h});}).catch(()=>{s||Le(null);}),()=>{s=true;}},[k,k?.ready,L$1,ie,io]);let ze=useCallback(t=>{t instanceof v?de({code:t.code,message:t.message}):t instanceof $e&&t.status.reason==="read-only"?de({code:"read-only"}):t instanceof $e&&t.code==="edit-unsupported"?de({code:t.code,cause:t.cause??"other"}):t instanceof E?de({code:t.code,detail:t.code==="sheet-protected"?void 0:t.message}):t instanceof u?de({code:t.code}):de({code:"input-failed",detail:t instanceof Error?t.message:String(t)});},[]),He=(t,s)=>{let i=te.current?.session.editState.sheets?.find(p=>p.index===t)?.id??te.current?.session.state.sheets.find(p=>p.index===t)?.id;if(!i)throw new u("editor-unavailable");let u$1=normalizeRange(s);return {sheetId:i,range:{kind:"rowCol",start:{row:u$1.top,col:u$1.left},end:{row:u$1.bottom,col:u$1.right}},activeCell:{...s.anchor}}},tr=()=>{let t=te.current,s=t?.session.editState.sheets??t?.session.state.sheets;return y.current&&s?.some(i=>i.index===f.current)?He(f.current,y.current):void 0},Bi=()=>{let t=tr();if(!t||t.range.kind!=="rowCol")Ee(null);else {let{start:s,end:i}=t.range,u=Lt(s),p=Lt(i);Ee({sheetId:t.sheetId,range:t.range,label:u===p?u:`${u}:${p}`,activeCell:t.activeCell,sheets:(k?.session.editState.sheets??k?.session.state.sheets)?.map(g=>({sheetId:g.id,name:g.name}))});let R=k?.session.call;R&&Promise.resolve(R.readCells({ranges:[]})).then(g=>{Ee(W=>W?.sheets&&W.sheetId===t.sheetId?{...W,sheets:$(W.sheets,g)}:W);},()=>{});}le(true);},$i=useMemo(()=>({version:()=>k?.session.call.version()??"",find:t=>{let s=k?.session.call;if(!s)throw new Error("The editor is not ready.");return s.findText(t)},reveal:t=>ye.current(t),validate:t=>{let s=k?.session.call;if(!s)throw new Error("The editor is not ready.");return s.validateEdits(t)},apply:t=>se.runAfterPendingInput(()=>se.command({kind:"applyEdits",payload:{args:[t]}}).result.then(s=>{if(!s.result)throw new Error("The replacement was not applied.");return Qt.current+=1,s.result}))}),[k]),Wr=()=>g(ne.current?.painted?.displayList.grid),ft=()=>{let t=te.current;if(!t?.current||t.retiring||t.failure)return null;let s=t.session.confirmedBasis;return {owner:t,sheet:f.current,selection:y.current??Ke.current,navigation:xe.current,version:`${s.epoch}:${s.version}:${t.session.state.version}`}},Nt=(t=ft())=>{let s=ne.current?.painted,i$1=te.current?.session.confirmedBasis,u=s?.request.sheet===t?.sheet&&s?.version===i$1?.version?i(s?.mergedRanges):void 0;return t?De.merges(t,u):i(void 0)},rr=()=>Q(ne.current?.painted?.displayList??null,(a$2.current?.clientHeight??0)/$$1.current),it=(t,s)=>{let i=At(t);if(t===f.current&&i===M$1.current&&n(y.current,s))return;let u=M$1.current,p=a$2.current;if((i!==u||t!==f.current)&&p){u&&Ht.set(u,{x:p.scrollLeft/$$1.current,y:p.scrollTop/$$1.current});let R=i?Ht.get(i):void 0;p.scrollLeft=(R?.x??0)*$$1.current,p.scrollTop=(R?.y??0)*$$1.current;}i!==u&&u&&y.current&&cn.set(u,structuredClone(y.current)),i&&cn.set(i,structuredClone(s)),xe.current+=1,M$1.current=i,v$1(t),q(structuredClone(s)),ge(null),B.selectionChanged(),x$2.refresh();},lo=(t,s,i=false)=>{let u=ne.current?.painted,p=te.current?.session.confirmedBasis;return !i&&se.pending&&!se.pendingSelectionGeometryStable?false:De.known(t,s)?true:!u||u.request.sheet!==t.sheet||u.version!==p?.version?false:h$1(u.displayList.grid,s)},pt=()=>({context:ft,activeCell:t=>t.anchor,limits:rr,hidden:Wr,merges:Nt,known:lo,query:(t,s)=>te.current.session.call.selectionData(t.sheet,t.selection.focus.row,t.selection.focus.col,s),apply:(t,s=f.current)=>(it(s,t),Bt(s,t.focus),_e({kind:"select",payload:{selection:He(s,t)}}),true)}),Dt=(t,s,i=false,u=false)=>{t===f.current&&n(y.current,s)||De.select(s,{...pt(),known:(p,R)=>lo(p,R,u),apply:p=>(it(t,p),true)},t,i);},Bt=(t,s,i)=>{let u=te.current,p=ne.current?.painted;if(!u?.current||u.failure)return;let R=a$2.current,g=p?.geometry&&p.request.sheet===t?cellRect(p.geometry,s.row,s.col):null,W=$$1.current,I=2/W;if(i===void 0&&g&&R&&p?.request.zoom===W&&p.request.viewport.x===R.scrollLeft/W&&p.request.viewport.y===R.scrollTop/W&&(g.x===0||g.x>=I)&&(g.y===0||g.y>=I)&&g.x+g.w+I<=R.clientWidth/W&&g.y+g.h+I<=R.clientHeight/W)return;let N=xe.current;if(ke.current?.generation===u.generation&&ke.current.navigation===N)return;let ce={generation:u.generation,navigation:N};ke.current=ce;let U=Sr.current;u.session.call.cellGeometry(t,s.row,s.col).then(me=>{let Y=a$2.current;if(!u.current||te.current!==u||xe.current!==N||Sr.current!==U||!Y||i!==void 0&&!T(Y,me.rect,i))return;let S=X.current,K=At(t);if(!S||S.sheet!==t){K&&Ht.set(K,me.scrollPosition),Y.scrollLeft=me.scrollPosition.x*$$1.current,Y.scrollTop=me.scrollPosition.y*$$1.current,ne.current?.schedule();return}let z=$$1.current,V=2/z,We=S$1(Y,S,{...me.rect,w:me.rect.w+V,h:me.rect.h+V},z);Ut.current={sheet:t,contentWidth:We.contentWidth,contentHeight:We.contentHeight},T$1(We);let be=V$1(me.rect,s,S,{x:Y.scrollLeft/z,y:Y.scrollTop/z,width:Y.clientWidth/z,height:Y.clientHeight/z},V);K&&Ht.set(K,be),Y.scrollLeft=be.x*z,Y.scrollTop=be.y*z,ne.current?.schedule();}).catch(me=>{u.current&&te.current===u&&xe.current===N&&Sr.current===U&&u.fail(me);}).finally(()=>{ke.current===ce&&(ke.current=null);});},fn=useRef(D$1);useLayoutEffect(()=>{if(fn.current===D$1)return;let t=fn.current;fn.current=D$1;let s=y.current;s&&!we.current&&Bt(f.current,s.anchor,t);},[D$1]);let mt=useMemo(()=>new Map,[k]),$t=useMemo(()=>new Set,[k]),ao=useMemo(()=>({current:0}),[k]),dr=useMemo(()=>new Set,[k]),jt=useMemo(()=>new Map,[k]),Ir=useMemo(()=>new Map,[k]),co=useRef(()=>{}),fr=useRef(null),B=useMemo(()=>new tn({defer:(t,s)=>s||B.ownsFocus?De.defer(ft(),t,s&&!B.ownsFocus):De.beforeInput({...pt(),apply:i=>(it(f.current,i),true)},t,()=>ze(new u("editor-unavailable"))),restoreCell:(t,s,i)=>{De.select(selectionAt(s),{...pt(),apply:u=>(it(t,u),i(u.anchor),Bt(t,u.anchor),true)},t);},generation:()=>k?.generation??0,identity:()=>`${k?.generation}:${k?.session.commandIdentity.session}:${k?.session.commandIdentity.incarnation}:${k?.session.confirmedBasis.epoch}`,valueRevision:()=>k?.session.confirmedBasis.version??"",navigation:()=>xe.current,sheet:()=>f.current,selection:()=>{let t=y.current,s=t&&j(t.anchor,Nt());return t&&s!==t.anchor?{...t,anchor:s}:t},target:(t,s,i)=>He(t,selectionAt({row:s,col:i})),resolveSheet:t=>(k?.session.editState.sheets??k?.session.state.sheets)?.find(s=>s.id===t)?.index,editable:Qe,prefill:(t,s)=>Ys(k.session,t,Lt(s)),select:(t,s,i)=>{let u=selectionAt(s);if((t!==f.current||!n(y.current,u))&&Dt(t,u),i){let p=true;De.enqueue({key:i==="down"||i==="up"?"Enter":"Tab",shiftKey:i==="up"||i==="left"},{...pt(),apply:R=>(it(t,R),Bt(t,R.focus),p||_e({kind:"select",payload:{selection:He(t,R)}}),true)}),p=false;}},selectionTarget:tr,dependency:()=>ot.current,navigate:()=>{let t=tr();t&&fr.current?.command({kind:"select",payload:{selection:t}}).result.catch(ze);},committed:t=>{t.result.catch(ze),x$2.refresh();},fail:t=>k?.fail(t),report:ze,focus:Ue}),[k]),Kt=useCallback(()=>{let t=te.current,s=a$2.current;if(!t?.current||!s?.clientWidth||!s.clientHeight||!c$1.current||!X.current)return null;let i=$$1.current;return {generation:t.generation,sheet:f.current,navigation:xe.current,coversThroughSeq:Math.max(t.session.throughSeq,fr.current?.submittedThroughSeq??0),width:s.clientWidth,height:s.clientHeight,zoom:i,dpr:window.devicePixelRatio||1,viewport:{x:s.scrollLeft/i,y:s.scrollTop/i,width:s.clientWidth/i,height:s.clientHeight/i}}},[]),se=useMemo(()=>js({generation:()=>k?.generation??0,session:()=>k?.session??null,isReady:()=>k?.ready??false,readOnly:()=>C$1.current.readOnly??false,allowHostProposals:()=>C$1.current.allowHostProposals??false,seal:()=>Ge.current||so()?{refused:"gesture-active"}:(nt.current(),B.seal()),sync:B.sync,compositionId:()=>B.compositionId,dependency:t=>t.after,target:(t,s,i)=>He(t,selectionAt({row:s,col:i})),draftTarget:t=>t.target,gateCommit:(t,s)=>P$1.current(t,s),frame:()=>ne.current?.captureCommandFrame()??void 0,selectionRevision:()=>xe.current,onEvent:(t,s)=>co.current(t,s),onError:t=>k?.fail(t)}),[k,B]);fr.current=se,eo.current=se,B.attach(se);let pn=useRef(null),Gt=useRef(null),Tr=useRef(null),[Er]=useState(()=>Qs({owner:()=>te.current,coordinator:()=>fr.current,readOnly:()=>C$1.current.readOnly??false,commands:()=>x$2,selection(t){let s=t.session.selection,i=t.session.editState.sheets??t.session.state.sheets,u=t.session.editState.activeSheet??t.session.state.activeSheet,p=i.find(N=>N.index===u),R=s&&i.find(N=>N.id===s.sheetId),g=p??R,W=Tr.current,I=W?.owner===t&&W.sheetId===g?.id&&W.target===JSON.stringify(s)?W.cells:s&&R?.id===g?.id?an(s):null;return g?{sheetId:g.id,sheetIndex:g.index,cells:we.current?null:I,chartId:we.current?.id??null}:null},navigator:{selectCells:(...t)=>pn.current.selectCells(...t),scrollToCell:(...t)=>pn.current.scrollToCell(...t)}})),mn=Er.identity(),ji=mn?Er.selection(mn):null,Xe=za$1({locale:n$2,focusRoot:a$2,...r,access:Er,commands:x$2,createClients:Zs,createGeometry:ei,readOnly:r.readOnly??false,handle:mn,selection:ji,proposals:d$1,staleFor:qe,proposalsPending:()=>se.pending||Mt.current!==null,canvasRef:c$1,t:e,selectionPaintReady:t=>{let s=ne.current,i=s?.selectionPaintReady(t,f.current)??(()=>true),u=Math.max(0,...[...mt].filter(([,p])=>p.sheet===t).map(([p])=>p));return ()=>{let p=s?.painted;return i()&&(!u||p?.request.sheet===t&&!p.provisional&&(s?.coversThroughSeq??-1)>=u)}},positionAtPoint:(t,s)=>{let i=te.current,u=ne.current?.painted;return !i?.current||i.retiring||i.failure||!u||u.request.generation!==i.generation?null:P(u.displayList,u.request.sheet,c$1.current,t,s)}});m$1.current=Xe;let wt=Xe.host,uo=useCallback(t=>{let s=te.current;if(!s?.ready||!wt.gatesEdits()||s.session.editState.selectionEditable===false)return true;let i=s.session.editState.sheets?.find(u=>u.index===f.current)?.id??s.session.state.sheets.find(u=>u.index===f.current)?.id;return !i||wt.openGate().cellEditable({sheetId:i,row:t.row,col:t.col})},[wt]),hn=async(t,s,i)=>{let u=await t.session.call.readCells({ranges:[]}),p=u.ok?u.sheets.find(g=>g.sheetId===s):void 0;if(!u.ok||!p||p.editable)return false;let R=await t.session.call.validateEdits({expectVersion:u.version,steps:i.map(({top:g,left:W,bottom:I,right:N})=>({op:"setCellInputs",inputs:Array.from({length:I-g+1},()=>Array(N-W+1).fill("")),target:{sheetId:s,range:{kind:"rowCol",start:{row:g,col:W},end:{row:I,col:N}}}}))});return !R.ok&&R.failure.code==="locked-target"},gn=(t,s,i)=>{let u=s.map(({row:g,col:W})=>({sheetId:t,row:g,col:W}));if(s.length>0&&wt.editGateStarting())throw new v(e("commands.reasons.hostStarting"));let p=g=>new v(g??e("commands.reasons.hostRefused")),R=wt.openGate();if(!u.every(g=>R.cellEditable(g)))throw p(null);return s.map((g,W)=>{let I=R.beforeCellCommit({...u[W],input:g.input,source:i});if(!I.ok)throw p(I.message);return {...g,input:I.input}})},fo=async(t,s,i,u)=>i.length===0?[...i]:await hn(t,s,i.map(({row:p,col:R})=>({top:p,bottom:p,left:R,right:R})))?[...i]:gn(s,i,u),Ki=async(t,s,i,u)=>{let p=u.flatMap((R,g)=>R.flatMap(({input:W},I)=>W===""?[]:[{row:i.top+g,col:i.left+I,input:""}]));if(p.length===0)return p;if(p.length>ja$2)throw new v(e("commands.reasons.tooManyToCheck",{limit:ja$2}));if(await hn(t,s,ta$1(p)))throw new E(e("commands.reasons.sheetProtected"),false,"sheet-protected");return gn(s,p,"cut")},Gi=async(t,s,i,u)=>{if(u.length===0||!wt.gatesEdits()||await hn(t,i,ta$1(u)))return u;let p=na$1(u),R=pa(u),[g,W]=await Promise.all([p.items.length?t.session.call.translateFormulas(p.items):[],Promise.all(R.map(async N=>(await t.session.call.cellInputs(s,Jn(N))).cells))]),I=qa(u,oa(u,p,g),R,W);if(I.length>ja$2)throw new v(e("commands.reasons.tooManyToCheck",{limit:ja$2}));return ra$1(u,I,gn(i,I,"paste"))},Ui=async(t,s,i)=>{let{usedRange:u}=await t.session.call.selectionData(s,0,0,"usedRange");if(!u)return [];let p=Math.max(i.top,u.top),R=Math.min(i.bottom,u.bottom),g=Math.max(i.left,u.left),W=Math.min(i.right,u.right);if(p>R||g>W)return [];let I=W-g+1;if((R-p+1)*I>La)return null;let N=Math.max(1,Math.floor(b$1/I)),ce=[];for(let U=p;U<=R;U+=N){let me=Math.min(R,U+N-1),{cells:Y}=await t.session.call.cellInputs(s,Jn({top:U,left:g,bottom:me,right:W}));if(Y.forEach((S,K)=>S.forEach((z,V)=>{z.input!==""&&ce.push({row:U+K,col:g+V,input:""});})),ce.length>b$1)return null}return ce};P$1.current=(t,s)=>{let i=te.current;return !i||!wt.gatesEdits()?null:()=>fo(i,s.sheetId,[{row:t.row,col:t.col,input:t.value}],t.source==="cell"?"cell-editor":"formula-bar").then(([u])=>u.input)};let[_i,Vi]=ha(Xe.managed);useLayoutEffect(()=>{let t=async([s,...i])=>{let u=await se.command({kind:"applyUpdate",payload:{update:s,...i.length?{updates:i}:{}}},{after:null}).result;if(u.status!=="applied"&&u.status!=="noop")throw new Error(u.reason??"Remote update refused");let p=u.result?.refusedUpdate;if(p)throw new Error(p);return u};return k?.session.bindCollaboration?.(s=>t([s]),t,async s=>{let i=await se.command({kind:"collabPipe",payload:s},{after:null}).result;if(i.status!=="applied"&&i.status!=="noop")throw new Error(i.reason??"Collaboration pipe refused");return i})},[k,se]),useLayoutEffect(()=>{k?.connectRecoveryInput(se,B);},[k,se,B]);let Pt=useRef(0),xt=useRef(0),nr=useRef(null),Mt=useRef(null),Yi=useCallback((t=false)=>{let s=te.current;if(!s?.ready||s.failure||s.retiring||!isProposalsAvailable())return Promise.resolve();let i=t?se.submittedThroughSeq:xt.current;if(Mt.current?.owner===s)return Mt.current.requiredSequence=Math.max(Mt.current.requiredSequence,i),Mt.current.promise;if(t&&Pt.current++,nr.current?.owner===s&&nr.current.revision===Pt.current&&nr.current.sequence>=xt.current)return Promise.resolve();let u$1={owner:s,requiredSequence:i,promise:Promise.resolve()};return Mt.current=u$1,u$1.promise=Promise.resolve().then(async()=>{for(;;){if(te.current!==s||!s.current||s.retiring)throw new u("document-replaced");if(s.failure)throw s.failure;let p=u$1.requiredSequence;if(await se.whenApplied(p),p!==u$1.requiredSequence)continue;let R=Pt.current,g=se.command({kind:"applyOps",payload:{toolbar:{id:"refreshProposals",args:null}}},{after:null,frame:void 0}),W=await g.result;if(te.current!==s||!s.current||s.retiring)throw new u("document-replaced");if(s.failure)throw s.failure;let I=g.seq??0,N=Math.max(xt.current,u$1.requiredSequence);if(R!==Pt.current||I<N){let U=nr.current;if(U?.owner===s&&U.revision===Pt.current&&U.sequence>=N)return;continue}let ce=W.result;ce?.proposals&&JSON.stringify(ce.proposals)!==JSON.stringify(H$1.current)&&(E$2(ce.proposals),x$2.refresh()),nr.current={owner:s,revision:R,sequence:I};return}}).finally(()=>{Mt.current===u$1&&(Mt.current=null);}),u$1.promise},[se,x$2]),qr=(t=false)=>{let s=te.current;Yi(t).catch(i=>{s?.current&&!s.retiring&&!s.failure&&te.current===s&&ze(i);});},pr=useRef(0),Ut=useRef(null),Ar=useCallback((t=false)=>{let s=te.current;if(!s?.ready||s.failure)return;let i=f.current,u=++pr.current;s.session.call.sheetView(i).then(p=>{if(te.current!==s||!s.current||s.failure||u!==pr.current||f.current!==p.sheet)return;let R=X.current?.sheet!==p.sheet,g=Ut.current;g?.sheet!==p.sheet&&(Ut.current=null);let W=g?.sheet===p.sheet?{...p,contentWidth:Math.max(p.contentWidth,g.contentWidth),contentHeight:Math.max(p.contentHeight,g.contentHeight)}:p;T$1(W),R&&no(W),(t||R)&&ne.current?.schedule();}).catch(p=>{te.current===s&&s.current&&!s.failure&&u===pr.current&&s.fail(p);});},[T$1,X,Ht]),Ji=()=>{let t=y.current;if(!t)return "";let s=normalizeRange(t);return `${f.current}:${s.top}:${s.left}:${s.bottom}:${s.right}`};co.current=(t,s)=>{if(!k?.current||k.failure)return;if(t.type==="dispatched"&&t.seq!==null&&t.command){let S=t.command;Ir.set(t.seq,S),S.kind==="collabPipe"&&$t.add(t.seq);let K=S.kind==="editCells"&&JSON.stringify(S.payload.selection)===JSON.stringify(tr())?xe.current:t.selectionRevision??xe.current;for(jt.set(t.seq,K);jt.size>256;)jt.delete(jt.keys().next().value);for(S.frame&&(S.kind!=="collabPipe"&&(ao.current=t.seq),mt.set(t.seq,{...S.frame,navigation:K,coversThroughSeq:t.seq}));mt.size>256;)mt.delete(mt.keys().next().value);if((S.kind==="select"||S.kind==="setActiveSheet"||S.kind==="undo"||S.kind==="redo"||"selection"in S.payload)&&(dr.add(t.seq),ot.current=t.seq),S.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="paintFormat"){let z=S.payload.toolbar.target,V=k.session.editState.sheets?.find(We=>We.id===z?.sheetId)?.index;V!==void 0&&z?.range.kind==="rowCol"&&(Ce.current=`${V}:${z.range.start.row}:${z.range.start.col}:${z.range.end.row}:${z.range.end.col}`);}if(t.draft)st.current?.patch(t.seq,[{...t.draft,text:t.draft.value}]),B.submitted(t.draft,t.seq);else if(S.kind==="editCells"){let[z,V]=S.payload.args;st.current?.paste(t.seq,z,V);}else if(S.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="clear"){let z=S.payload.toolbar.target,V=k.session.editState.sheets?.find(We=>We.id===z?.sheetId)?.index;V!==void 0&&z?.range.kind==="rowCol"&&st.current?.clear(t.seq,{sheet:V,top:z.range.start.row,left:z.range.start.col,bottom:z.range.end.row,right:z.range.end.col});}return}if(t.type==="accepted"&&t.seq!==null){let S=Ir.get(t.seq);t.status?.committed&&(o$1.changed(),de(null)),Ir.delete(t.seq);let K=S?.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="refreshProposals";S&&!K&&S.kind!=="select"&&S.kind!=="setActiveSheet"&&S.kind!=="setReadOnly"&&S.kind!=="applyUpdate"&&S.kind!=="collabPipe"&&(t.status?.committed||S.kind==="rejectProposal"||(S.kind==="propose"||S.kind==="acceptProposal"||S.kind==="undo"||S.kind==="redo")&&t.status?.status==="applied")&&(xt.current=Math.max(xt.current,t.seq),qr());return}if(t.type==="refused"||t.type==="cancelled"){t.status?.reason==="stale-proposal"&&(Pt.current++,qr()),t.seq!==null&&Ir.delete(t.seq),t.seq!==null&&st.current?.refuse(t.seq),t.type==="refused"&&t.draft&&(B.refused(t.seq,t.draft),ze(t.error??new $e(t.status??{seq:t.seq??0,status:"refused"},t.target,t.draft)));return}if(t.type!=="coverage")return;st.current?.acknowledge(t.ack);let i=t.ack,u=Gt.current,p=u?.owner===k?i.statuses.find(S=>S.seq===u.ticket?.seq):void 0;u?.clear&&p&&(p.status==="applied"||p.status==="noop")?Tr.current={owner:k,sheetId:u.sheetId,target:JSON.stringify(k.session.selection),cells:null}:i.statuses.some(S=>dr.has(S.seq)&&(S.status==="applied"||S.status==="noop"))&&(Tr.current=null);let R=false;for(let S of i.statuses){let K=S.result;K?.remoteUpdate&&(R=true,o$1.changed(),xt.current=Math.max(xt.current,S.seq),K.proposals&&(E$2(K.proposals),nr.current={owner:k,revision:Pt.current,sequence:S.seq}),x$2.refresh());}let g=Math.max(0,...dr),W=!De.isPending(ft())&&g>0&&i.throughSeq>=g&&jt.get(g)===xe.current&&!B.ownsFocus;if(i.editState?.sheets&&JSON.stringify(i.editState.sheets)!==JSON.stringify(_$1.current)){let S=i.editState.sheets;re(S);let K=S.find(z=>z.id===M$1.current);if((!K||K.index!==f.current)&&(Sr.current+=1),K&&K.index!==f.current){let z=f.current;pr.current+=1,X.current?.sheet===z&&T$1({...X.current,sheet:K.index}),Ut.current?.sheet===z&&(Ut.current={...Ut.current,sheet:K.index}),v$1(K.index),ne.current?.schedule();}else if(!K&&S.length>0){let z=W&&i.selection?i.selection:void 0,V=(z&&S.find(be=>be.id===z.sheetId))??S.find(be=>be.index===k.session.editState.activeSheet)??S.find(be=>be.index===Math.min(f.current,S.length-1))??S[0],We=z?.sheetId===V.id?an(z,y.current):null;it(V.index,We??Rr(V.index)),queueMicrotask(()=>Qn.current(V.index));}}if(i.selection&&W){let S=i.selection,K=k.session.editState.sheets?.find(V=>V.id===S.sheetId)?.index,z=an(S,y.current);K!==void 0&&z&&Dt(K,z);}else !i.selection&&i.editState?.activeSheet!==void 0&&W&&i.editState.activeSheet!==f.current&&Dt(i.editState.activeSheet,Rr(i.editState.activeSheet));s?.();let I=ne.current,N=i.frame,ce=N&&mt.get(N.coversThroughSeq),U=false;if(N&&ce&&I){let S=W?{...ce,navigation:xe.current}:ce,K=ao.current>I.coversThroughSeq;U=$t.has(N.coversThroughSeq)&&!K?I.queuePipeFrame(N,S):I.install(N,S);}let me=false;for(let S of $t)if(S>(I?.coversThroughSeq??0)&&S<=i.throughSeq){me=true;break}let Y=me&&!i.frame&&I?.advanceCoverage(i.version,i.throughSeq);!U&&!Y&&(i.frame||R||me&&i.throughSeq>=se.submittedThroughSeq)&&I?.schedule();for(let S of $t)S<=(I?.coversThroughSeq??0)&&$t.delete(S);for(let S of mt.keys())S<=(ne.current?.coversThroughSeq??0)&&mt.delete(S);for(let S of dr)S<=i.throughSeq&&dr.delete(S);for(let S of jt.keys())S<=i.throughSeq&&jt.delete(S);ot.current!==null&&ot.current<=i.throughSeq&&(ot.current=null),i.statuses.some(S=>S.committed&&S.status==="applied")&&(Qt.current+=1,Ar(),C$1.current.onDocumentChange?.({version:i.version}),C$1.current.onChange?.());};let Zi=async(t,s,i,u,p,R)=>{let g=xe.current,W=ne.current?.painted,I=X.current?.sheet===s&&X.current.version===R?X.current:null,N=W?.version===R&&W.request.sheet===s&&W.geometry?cellRect(W.geometry,i.row,i.col):null,[ce,U]=await Promise.all([N&&W?{version:R,rect:N}:t.session.call.cellGeometry(s,i.row,i.col),I??t.session.call.sheetView(s)]);if(te.current!==t||!t.current||t.failure||!p()||xe.current!==g||f.current!==s)return "unsupported";if(ce.version!==R||U.version!==R||t.session.confirmedBasis.version!==R)return "stale-version";let me=a$2.current;if(!me)return "layout-unavailable";X.current!==U&&(pr.current+=1,T$1(U));let Y=$$1.current,S=me.scrollLeft/Y,K=me.scrollTop/Y,z=Fi(ce.rect.x+(N&&W&&i.col>=U.frozenCols?W.request.viewport.x:0),ce.rect.w,i.col<U.frozenCols,S,me.clientWidth/Y-U.frozenWidth,u),V=Fi(ce.rect.y+(N&&W&&i.row>=U.frozenRows?W.request.viewport.y:0),ce.rect.h,i.row<U.frozenRows,K,me.clientHeight/Y-U.frozenHeight,u),We=z!==null&&z!==S,be=V!==null&&V!==K;return We&&(me.scrollLeft=z*Y),be&&(me.scrollTop=V*Y),(We||be||W?.request.sheet!==s||W.version!==R)&&ne.current?.schedule(),null},po=async(t,s,i,u$1,p,R)=>{let g=te.current;if(!g||g!==t||!g.current||g.failure||!p())return "unsupported";let W=(g.session.editState.sheets??g.session.state.sheets).find(U=>U.id===s?.sheetId),I=s?.selection?.anchor??{row:s?.row,col:s?.col},N=U=>U&&Number.isInteger(U.row)&&Number.isInteger(U.col)&&U.row>=0&&U.row<1048576&&U.col>=0&&U.col<16384;if(!W||!N(I)||s.selection&&!N(s.selection.focus))return "missing-target";let ce=null;try{let U=ft();if(s.selection&&U){let S;if(!await De.select(s.selection,{...pt(),apply:z=>!g.current||g.failure||!p()?!1:(S=z,it(W.index,z),!0)},W.index)||!S||!g.current||g.failure||!p())return "unsupported";s={...s,selection:S},I=S.anchor;}if(s.selection||W.index!==f.current){let S=s.selection?He(W.index,s.selection):void 0,K=xe.current,z=null,V=null;ce={owner:g,sheetId:W.id,clear:!s.selection,ticket:null},Gt.current=ce;let We=g.session.onAck(be=>{let St=be.statuses.find(Rt=>Rt.seq===z?.seq);St&&(V=be.statuses.some(Rt=>Rt.seq!==z?.seq&&Rt.committed)||!St.committed&&be.version!==R?null:be.version);});try{z=se.command({kind:"setActiveSheet",payload:{args:[W.index],target:{sheetId:W.id,range:{kind:"rowCol",start:I,end:I}},...S?{selection:S}:{},expectVersion:R}},{frame:void 0,dispatch(be){if(te.current!==g||!g.current||g.failure||!p())throw new u("document-replaced");return be()}}),ce.ticket=z,await z.result,await new Promise(be=>{De.defer(ft(),be,!1,be)||be();});}finally{We();}if(!V||g.session.confirmedBasis.version!==V)return "stale-version";if(te.current!==g||!g.current||g.failure||!p()||xe.current>K+1||f.current!==W.index||s.selection&&!n(y.current,s.selection))return "unsupported";s.selection||q(null),R=V;}let me=xe.current,Y=await Zi(g,W.index,I,i,p,R);if(Y)return Y;if(te.current!==g||!g.current||g.retiring||g.failure||!p()||xe.current!==me||f.current!==W.index)return "unsupported";if(g.session.confirmedBasis.version!==R)return "stale-version";if(s.selection){if(flushSync(()=>ge(null)),te.current!==g||!g.current||g.retiring||g.failure||!p()||xe.current!==me||f.current!==W.index)return "unsupported";if(g.session.confirmedBasis.version!==R)return "stale-version";let S=ne.current,K=S?.painted,z=S?.captureCommandFrame(),V=ce?.ticket?.seq;S&&V&&K&&!K.provisional&&K.version===R&&z&&Xi(K,{...z,navigation:K.request.navigation})&&S.install({...g.session.commandIdentity,sheet:z.sheet,viewport:z.viewport,requestGeneration:z.requestGeneration,zoom:z.zoom,dpr:z.dpr,version:K.version,epoch:g.session.confirmedBasis.epoch,sequence:K.sequence,coversThroughSeq:V,displayList:K.displayList,mergedRanges:[...K.mergedRanges]},{...z,coversThroughSeq:V});}return u$1&&Ue(),null}catch(U){if(U instanceof $e){if(U.status.reason==="stale-version")return "stale-version";if(U.status.reason==="missing-target"||U.status.reason==="stale-target")return "missing-target"}if(U instanceof RangeError)return "missing-target";throw U}finally{Gt.current===ce&&(Gt.current=null,te.current===g&&g.current&&!g.failure&&f.current!==X.current?.sheet&&Ar(true));}};pn.current={selectCells:(t,s,i,u,p)=>po(t,structuredClone(s),"nearest",i,u,p),scrollToCell:(t,s,i,u,p)=>po(t,structuredClone(s),i,false,u,p)},useLayoutEffect(()=>{let t=()=>{ae.current!==null&&clearTimeout(ae.current),ae.current=null,rt.current=null,Ge.current=null,at.current=false,Tt.current=null,ke.current=null,zt();};if(Xe.beginLoad(),t(),de(null),w$1.reset(),M$1.current=void 0,ge(null),Z(null),ut(null),E$2([]),Oe({}),ue(false),Ce.current=null,re(k?.session.editState.sheets??k?.session.state.sheets??[]),xe.current+=1,Ut.current=null,ot.current=null,Pt.current++,xt.current=0,Tr.current=null,Gt.current=null,!k)return;let s=new Zr({generation:k.generation,commandIdentity:k.session.commandIdentity,capture:Kt,isCurrent:()=>k.current&&!k.failure,sentSequence:()=>se.submittedThroughSeq,requestFrame:async g=>{k.ready&&await se.whenApplied(Math.min(g.coversThroughSeq??0,se.submittedThroughSeq));let W=Math.max(g.coversThroughSeq??0,k.session.throughSeq),I=await k.session.call.frame(g.viewport,{sheet:g.sheet});return {...I,coversThroughSeq:"coversThroughSeq"in I&&typeof I.coversThroughSeq=="number"?I.coversThroughSeq:W}},publish(g){let W=c$1.current,I=W?.getContext("2d");if(!W||!I)throw new Error("Canvas context is unavailable");let N=g.request;W.width=Math.round(N.width*N.dpr),W.height=Math.round(N.height*N.dpr),W.style.width=`${N.width}px`,W.style.height=`${N.height}px`,W.dataset.defaultFonts=to(g.displayList,()=>paintDisplayList(I,g.displayList,N.dpr*N.zoom))?"settled":"pending",W.dataset.workerSequence=String(g.sequence),W.dataset.commandCoverage=String(g.coversThroughSeq??0),W.dataset.paintSource=g.source,W.dataset.workerZoom=String(N.zoom);},onInstalled(g){for(let I of $t)I<=s.coversThroughSeq&&$t.delete(I);for(let I of mt.keys())I<=s.coversThroughSeq&&mt.delete(I);G$2(g);let W=(k.session.editState.sheets??k.session.state.sheets).find(I=>I.index===g.request.sheet)?.id;Xe.presentGrid(W?{frame:g.displayList,version:g.version,sheetId:W,sheet:g.request.sheet,zoom:g.request.zoom,viewport:g.request.viewport}:null),g.coversThroughSeq!==void 0&&k.session.markPresented({...k.session.commandIdentity,coversThroughSeq:g.coversThroughSeq}),k.firstPaint();},onCovered(g){let W=c$1.current;W&&(W.dataset.commandCoverage=String(g)),w$1.advanceCoverage(g),k.session.markPresented({...k.session.commandIdentity,coversThroughSeq:g});},onError:g=>k.fail(g)});ne.current=s;let i=new Qr({source:s,context:()=>c$1.current?.getContext("2d")??null});st.current=i;let u=k.session.editState.activeSheet??k.session.state.activeSheet;M$1.current=At(u),v$1(u);let p=g=>{if(!k.current||k.failure||ne.current!==s)return;T$1(g),M$1.current=At(u);let W=Rr(u);q(selectionAt({row:0,col:0})),n(y.current,W)||De.select(W,{...pt(),apply:I=>(it(u,I),true)},u),no(g);},R=k.session.initialPaint;return R?(p(R.sheetView),s.installInitial(R.frame)||s.schedule()):k.session.call.sheetView(u).then(g=>{p(g),s.schedule();}).catch(g=>k.fail(g)),k.beforeRetire=()=>{Xe.beginLoad(),t(),w$1.cancel(),se.retire(),B.dispose(),s.dispose();},()=>{t(),w$1.cancel(),i.dispose(),s.dispose(),se.retire(),B.dispose(),ne.current===s&&(ne.current=null),st.current===i&&(st.current=null);}},[k,se,B,Kt,zt]),useEffect(()=>{Et.clear(),ur.current+=1;},[d$1,Et]),useEffect(()=>{let t=ne.current;if(!k||!t)return;let s=t.registerPaintTransaction((i,u)=>{u();let p=c$1.current;p&&(p.dataset.paintedSheet=String(i.request.sheet),p.dataset.provisional=i.provisional?"true":"false"),!i.provisional&&i.request.sheet===f.current&&dn.current();});return t.painted&&!t.painted.provisional&&dn.current(),()=>{s(),ur.current+=1,qt.current!==null&&clearTimeout(qt.current),qt.current=null;}},[k,se,B,Kt]),useEffect(()=>{if(!k?.current||k.failure)return;let t=a$2.current;if(!t)return;let s=()=>{let u=ne.current,p=Kt(),R=u?.painted;R&&p&&(u?.coversThroughSeq??-1)>=se.submittedThroughSeq&&Xi(R,{...p,navigation:R.request.navigation})||u?.schedule();},i=new ResizeObserver(s);return i.observe(t),t.addEventListener("scroll",s,{passive:true}),s(),()=>{i.disconnect(),t.removeEventListener("scroll",s);}},[k,k?.failure,D$1,Kt,se]),useEffect(()=>{if(typeof window.matchMedia!="function")return;let t,s=()=>{ne.current?.schedule(),t?.removeEventListener("change",s),t=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`),t.addEventListener("change",s);};return s(),()=>t?.removeEventListener("change",s)},[]),useEffect(()=>{!k?.ready||L$1===X.current?.sheet||Gt.current?.owner===k&&Gt.current.sheetId===k.session.editState.sheets?.find(t=>t.index===L$1)?.id||Ar(true);},[k,L$1,Ar]);let mr=useRef({owner:null,readOnly:false,allowHostProposals:false});useLayoutEffect(()=>{if(!k?.ready||mr.current.owner===k&&mr.current.readOnly===!!r.readOnly&&mr.current.allowHostProposals===!!r.allowHostProposals)return;let t=mr.current;mr.current={owner:k,readOnly:!!r.readOnly,allowHostProposals:!!r.allowHostProposals},!(t.owner!==k&&!!k.session.editState.readOnly==!!r.readOnly&&!r.allowHostProposals)&&(r.readOnly&&(nt.current(true),B.finish(),ut(null),Ge.current=null,rt.current=null,zt(),Z(null)),se.setReadOnly(!!r.readOnly,r.allowHostProposals).result.catch(ze));},[k,k?.ready,r.readOnly,r.allowHostProposals,se,B,zt]),useEffect(()=>{k?.failure&&(st.current?.dispose(),ne.current?.dispose(),se.fail(k.failure),B.dispose(),Ge.current=null,rt.current=null,zt());},[k,k?.failure,se,B,zt]);let _e=t=>{let s=ne.current?.captureCommandFrame()??void 0,i=xe.current;t.kind==="select"&&!B.ownsFocus?se.command(t,{frame:s,selectionRevision:i}).result.catch(ze):se.runAfterPendingInput(()=>se.command(t,{frame:s,selectionRevision:i}).result).catch(ze);},Qi=(t,s)=>{let i=y.current;if(!Qe()||!i||B.getSnapshot().cell)return;let u=f.current,p;try{p=He(u,i);}catch(I){ze(I);return}let R=Lt({row:t.top,col:t.left}),g=Lt({row:t.bottom,col:t.right}),W=Lt({row:s.bottom,col:s.right});_e({kind:"fillRange",payload:{args:[u,R===g?R:`${R}:${g}`,`${R}:${W}`],target:p}});},mo=()=>{let t=tr(),s=te.current,i=y.current;if(!Qe()||!t||!s||!i)return;let u={kind:"applyOps",payload:{toolbar:{id:"clear",args:null,target:t},selection:t}};if(!wt.gatesEdits()){_e(u);return}let p=f.current,R=normalizeRange(i),g=se.runAfterPendingInput(async()=>{let I=await Ui(s,p,R);if(!I)throw new E(e("editor.clearExceedsLimit"));let N=await fo(s,t.sheetId,I,"clear-key");return N.length>0?N:null},"posted"),W=se.clipboard(()=>g,I=>I?{kind:"editCells",payload:{args:[p,I],target:t,selection:t}}:u,{frame:ne.current?.captureCommandFrame()??void 0,selectionRevision:xe.current});return W.result.catch(ze),W.result},yn=t=>{let s=te.current;return !!(s?.ready&&!s.failure&&y.current&&(t==="copy"||Qe()))},ho=t=>{if(t==="paste"){let W=y$1();return W.catch(()=>{}),{read:W}}let s=u$1(),i,u,p=new Promise((W,I)=>{i=W,u=I;});p.catch(()=>{});let R,g;try{if(typeof ClipboardItem=="function"&&typeof navigator.clipboard?.write=="function")R=navigator.clipboard.write([new ClipboardItem({"text/plain":p,"text/html":w({marker:s},p)})]),R.catch(()=>{});else if(t==="cut"&&typeof navigator.clipboard?.writeText!="function")throw new E("Cut requires clipboard write access")}catch(W){g={error:W};}return {write:R,resolve:i,reject:u,refused:g,marker:s}},go=()=>{let t=navigator.clipboard.readText().then(s=>({text:s,html:null}));return t.catch(()=>{}),{read:t}},yo=(t,s)=>{if(!yn(t)){let V=new u("editor-unavailable");return s.reject?.(V),Zn(V)}let i=te.current,u$1=y.current,p=f.current,R=xe.current,g=He(p,u$1),W=normalizeRange(u$1);if(t==="paste"){let V=null,be=se.clipboard(()=>{let St=s.read,Rt=o$1.pending;return se.runAfterPendingInput(async()=>{await Rt;let{text:wo,html:Pl}=await St;V=o$1.paste(i,wo,W,Pl,p);let Po=V?[]:x$1(wo),xo=V?.edits??[],Rn=0;V||Po.forEach((Co,Cl)=>{Rn=Math.max(Rn,Co.length-1),Co.forEach((Sl,Rl)=>xo.push({row:W.top+Cl,col:W.left+Rl,input:Sl}));});let xl={anchor:{row:W.top,col:W.left},focus:{row:V?.bottom??W.top+Math.max(0,Po.length-1),col:V?.right??W.left+Rn}};return {edits:await Gi(i,p,g.sheetId,xo),next:xl}},true)},({edits:St,next:Rt})=>(te.current===i&&xe.current===R&&!B.ownsFocus&&!De.isPending(ft())&&Dt(p,Rt,false,true),{kind:"editCells",payload:{args:[p,St],target:g,selection:He(p,Rt)}})).result.then(St=>{V&&o$1.consume(V,St.status==="applied"&&St.committed===true);});return be.catch(ze),be}let I=()=>{if(te.current!==i||!i.current||i.retiring)throw new u("document-replaced");if(i.failure)throw i.failure},{write:N,resolve:ce,reject:U,refused:me,marker:Y}=s;if(me)return U(me.error),ze(me.error),Zn(me.error);let S=o$1.begin(void 0,Y),K=se.runAfterPendingInput(async()=>{I();let V=await e$1(i.session,p,u$1),We=await i.session.call.cellInputs(p,Jn(V));I();let be=t==="cut"&&wt.gatesEdits()?await Ki(i,g.sheetId,V,We.cells):null;return {range:V,cells:We.cells,cleared:be}},t==="cut"?true:"posted"),z=K.then(async({range:V,cells:We})=>{I();let be=toTsv(We);N?(ce(new Blob([be],{type:"text/plain"})),await N):await navigator.clipboard.writeText(be),I(),t==="copy"&&o$1.capture(S,{owner:i,sheet:p,range:V,cells:We,cut:false},!!N);});if(o$1.pending=z.catch(()=>{}),t==="cut"){let V=se.clipboard(()=>z.then(()=>K),({cleared:We})=>We?.length?{kind:"editCells",payload:{args:[p,We],target:g,selection:g}}:{kind:"applyOps",payload:{toolbar:{id:"clear",args:null,target:g},selection:g}});return V.result.catch(We=>{U(We),ze(We);}),V.result}return z.catch(V=>{U(V),ze(V);}),z},el=t=>{let s=t==="pastePlainText"?"paste":t;return !yn(s)||B.getSnapshot().cell?Zn(new u("editor-unavailable")):yo(s,t==="pastePlainText"?go():ho(s))},kn=t=>te.current===t&&t.ready&&t.current&&!t.retiring&&!t.failure&&!se.pending&&!B.ownsFocus&&t.session.throughSeq>=se.submittedThroughSeq,bn=()=>`${Pt.current}:${xt.current}`,tl=async(t,s)=>{let i=t.session.confirmedBasis.version,u=bn();un.current=i;let p=()=>s===ur.current&&kn(t)&&t.session.confirmedBasis.version===i&&bn()===u,R=_$1.current,g=R.findIndex(I=>I.index===f.current),W=g<0?[]:[R[g+1],R[g-1]].filter(I=>I!==void 0);for(let I of [...Et.keys()])W.some(N=>N.index===I)||Et.delete(I);for(let I of W){let N=Kt();if(!N||!p())return;if(ro.has(I.id))continue;let ce=Et.get(I.index),U=Ht.get(I.id);if(ce&&ce.sheetId===I.id&&ce.paint.version===i&&ce.proposals===u&&(!U||U.x===ce.request.viewport.x&&U.y===ce.request.viewport.y)&&ce.request.generation===N.generation&&ce.request.zoom===N.zoom&&ce.request.dpr===N.dpr&&ce.request.width===N.width&&ce.request.height===N.height)continue;Et.delete(I.index);let me=await t.session.call.sheetView(I.index);if(!p()||me.sheet!==I.index)return;let Y=performance.now(),S=await t.session.call.frame({x:U?.x??me.initialScrollX,y:U?.y??me.initialScrollY,width:N.viewport.width,height:N.viewport.height},{sheet:I.index});if(performance.now()-Y>za){ro.add(I.id);continue}if(!p()||S.version!==i||S.sheet!==I.index)return;Et.set(I.index,{sheetId:I.id,proposals:u,request:{...N,sheet:I.index,viewport:{...S.viewport}},paint:{displayList:S.displayList,mergedRanges:S.mergedRanges??[],version:S.version}}),to.preload(S.displayList,p);}};dn.current=()=>{let t=te.current;qt.current!==null&&clearTimeout(qt.current),qt.current=null;let s=++ur.current;t&&(qt.current=setTimeout(()=>{qt.current=null,s===ur.current&&kn(t)&&tl(t,s).catch(()=>{});},un.current===void 0||un.current===t.session.confirmedBasis.version?Oa:Ha));};let rl=t=>{let s=te.current,i=ne.current,u=Et.get(t);if(!s||!i||!u||u.sheetId!==At(t)||!kn(s)||u.paint.version!==s.session.confirmedBasis.version||u.proposals!==bn())return;let p=Kt();p&&Na(u.request,p)&&i.installProvisional(u.paint,p);},Ct=(t,s)=>{if(!k?.ready||k.failure||B.isComposing("cell")||B.isComposing("formula"))return;B.commit("cell"),B.commit("formula");let i=s??Rr(t);De.select(i,{...pt(),apply:u=>{let p=He(t,u),R=t!==f.current;return it(t,u),s?Bt(t,u.anchor):R&&rl(t),_e({kind:"setActiveSheet",payload:{args:[t],target:p,selection:p}}),true}},t,true);};er.current=t=>{Ct(f.current,selectionAt(t)),Ue();},Qn.current=t=>{t===f.current&&Ct(t);},ye.current=t=>{let i=(k?.session.editState.sheets??k?.session.state.sheets)?.find(u=>u.id===t.sheetId)?.index;i!==void 0&&Ct(i,selectionAt({row:t.row,col:t.col}));};let vn=(t,s,i,u,p=false,R=k?.generation)=>{if(!k?.ready||!k.current||k.retiring||R!==k.generation||k.failure||!p&&!Qe()||i===0&&u===0)return;let g=He(t,y.current??selectionAt({row:0,col:0}));_e({kind:"moveChart",payload:{args:[t,s,i,u],target:g}}),Z(null);};oo.current=t=>{let s=we.current;if(!s)return;let i=k?.generation;if(!k?.ready||!k.current||k.retiring||i!==k.generation||k.failure||!Qe())return;let u=f.current,p=He(u,y.current??selectionAt({row:0,col:0}));Z(null),_e({kind:"resizeChart",payload:{args:[u,s.id,t],target:p}});};let _t=(t=false)=>{let s=rt.current;rt.current=null,ae.current!==null&&clearTimeout(ae.current),ae.current=null,s&&vn(s.sheet,s.id,s.dx,s.dy,t,s.generation);};nt.current=_t;let Dr=useRef({moveChart:vn,flushNudge:_t});Dr.current={moveChart:vn,flushNudge:_t},useEffect(()=>{let t=i=>{let u=at.current;at.current=false,u&&i.button===0&&Cr(R=>R+1);let p=Ge.current;Ge.current=null,p&&i.button===0?Dr.current.moveChart(p.sheet,p.id,(i.clientX-p.x)/p.zoom,(i.clientY-p.y)/p.zoom,false,p.generation):Z(null);},s=()=>{at.current=false,Ge.current=null,Z(null),Dr.current.flushNudge();};return window.addEventListener("mouseup",t),window.addEventListener("blur",s),()=>{window.removeEventListener("mouseup",t),window.removeEventListener("blur",s),ae.current!==null&&clearTimeout(ae.current);}},[]);let nl=M({document:()=>te.current?.current?te.current:null,onSaveRequest:r.onSaveRequest,fail:ze});Vs(x$2,{requestSave:nl,session:()=>k?.session??null,coordinator:se,status:()=>k?.ready?"ready":k&&!k.failure||Hi?"loading":"empty",readOnly:()=>C$1.current.readOnly??false,allowHostProposals:()=>C$1.current.allowHostProposals??false,collaborative:()=>C$1.current.collaboration!==void 0,generation:()=>k?.generation??0,mutation:()=>Qt.current,selection:()=>tr()??null,frame:()=>ne.current?.captureCommandFrame()??void 0,selectionRevision:()=>xe.current,view:()=>({sheet:f.current,selection:y.current,chartSelected:we.current!==null,zoom:$$1.current,capturedFormat:null,borderStyle:Zt.current,borderColor:dt.current,proposals:H$1.current,proposalsAvailable:isProposalsAvailable(),proposalsPanelOpen:oe.current,pngExport:k?.session.pngExport===true}),formatToken:()=>Pe.current,formatRevision:()=>Me.current,setFormatToken:ut,setZoom:t=>Ie(t),setBorderStyle:t=>{Zt.current=t;},setBorderColor:t=>{dt.current=t;},setProposalsPanelOpen:t=>{ue(t),t&&qr(true);},setReplaceOpen:t=>{t?Bi():le(false);},markStale:(t,s)=>Oe(({[t]:i,...u})=>s?{...u,[t]:s}:u),refreshProposals:()=>qr(),i18n:()=>C$1.current.i18n,translate:e,fail:t=>k?.fail(t),afterPaint:()=>se.whenPresented().then(()=>true,()=>false),deliver(t){if(C$1.current.onSave&&C$1.current.onSave(t),C$1.current.downloadOnSave??!C$1.current.onSave){let s=URL.createObjectURL(new Blob([new Uint8Array(t)],{type:Da})),i=document.createElement("a");i.href=s,i.download=C$1.current.fileName??"workbook.xlsx",document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(s);}},exportFonts:t=>E$1(t,k?.session.call.decodeFontFace,C$1.current.defaultFonts),deliverPng(t){let s=URL.createObjectURL(new Blob([new Uint8Array(t)],{type:"image/png"})),i=document.createElement("a");i.href=s,i.download=`${(C$1.current.fileName??"workbook.xlsx").replace(/\.xlsx$/i,"")}.png`,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(s);},focusGrid:Ue,refuse:t=>de(t.code==="edit-unsupported"?{code:t.code,message:t.message}:{code:t.code}),menu:{clipboard:el,clear:()=>mo()??Promise.resolve(),beginRename:()=>fe(f.current),activate:t=>{Be.current=t.toLowerCase(),ee();}}}),L(x$2,l,r),useEffect(()=>{let t=Be.current,s=t===null?void 0:Q$1.find(i=>i.name.toLowerCase()===t);s&&(Be.current=null,(s.index!==f.current||s.id!==M$1.current)&&Ct(s.index));});let ol=t=>{let{cell:s,chart:i}=Vt({clientX:t.x,clientY:t.y});if(i)return ge({id:i.id,movable:i.movable,resizable:i.resizable,placeholder:i.placeholder??false}),null;if(!s)return null;let u=f.current,p=()=>{let R=y.current?normalizeRange(y.current):null;return !we.current&&R!==null&&f.current===u&&s.row>=R.top&&s.row<=R.bottom&&s.col>=R.left&&s.col<=R.right};if(!p()){ge(null);let R=selectionAt(j(s,Nt()));Dt(u,R,true),_e({kind:"select",payload:{selection:He(u,R)}});}return p},sl=H({surface:a$2,subscribe:x$2.store.subscribe,keyboardPoint:()=>{let t=y.current,s=ne.current?.painted,i=c$1.current,u=t&&s?.geometry?cellRect(s.geometry,t.focus.row,t.focus.col):null;if(!u||!i||!s)return null;let p=i.getBoundingClientRect();return {x:p.left+(u.x+u.w/2)*s.request.zoom,y:p.top+(u.y+u.h)*s.request.zoom}},resolve:t=>{if(!k?.ready||k.failure||G$1(t.target)||B.cellInput?.contains(t.target))return null;let s=()=>true;if(t.modality==="pointer"){let i=ol(t);if(!i)return null;s=i;}else if(we.current)return null;return {label:e("editor.cellMenuLabel"),testId:"xlsx-cell-menu",entries:()=>xr(K("cell",x$2.store,e),s)}}}),il=H({surface:et,subscribe:x$2.store.subscribe,keyboardPoint:()=>{let s=et.current?.querySelector('[role="tab"][aria-selected="true"]')?.getBoundingClientRect();return s?{x:s.left,y:s.top}:null},resolve:t=>{if(!k?.ready||k.failure||Ae!==null)return null;let s=t.target instanceof Element?t.target.closest('[role="tab"]'):null,i=Number(s?.dataset.sheetIndex);if(!s||!Number.isInteger(i))return null;let u=At(i);(i!==f.current||u!==M$1.current)&&Ct(i);let p=()=>f.current===i&&M$1.current===u;return {label:e("editor.sheetTabMenuLabel"),testId:"xlsx-sheet-tab-menu",entries:()=>xr(K("sheetTab",x$2.store,e),p)}}}),wn=useRef(false),Pn=(t,s,i)=>{let u=f.current,p=i?y.current:null,R=t==="col"?p?.anchor.col??s:p?.anchor.row??s,g=t==="col"?{top:0,left:Math.min(R,s),bottom:1048575,right:Math.max(R,s)}:{top:Math.min(R,s),left:0,bottom:Math.max(R,s),right:16383},W=t==="col"?{row:0,col:s}:{row:s,col:0},I=p?{anchor:p.anchor,focus:W,range:g}:{...selectionAt(W),range:g};it(u,I),_e({kind:"select",payload:{selection:He(u,I)}});},ll=()=>{Ge.current=null,zt(),Z(null);},Mr=()=>{ll(),ge(null);},al=()=>{if(!k?.ready||k.failure)return;B.commit("cell"),B.commit("formula"),_t(),Mr();let t=f.current,s={anchor:{row:0,col:0},focus:{row:0,col:0},range:{top:0,left:0,bottom:1048575,right:16383}};it(t,s),_e({kind:"select",payload:{selection:He(t,s)}}),Ue();},cl=(t,s,i)=>{i.button!==0||Ft(i)||!k?.ready||k.failure||B.cellInput?.contains(i.target)||B.isComposing("cell")||B.isComposing("formula")||(B.commit("cell"),B.commit("formula"),_t(),Mr(),Pn(t,s,i.shiftKey),Ue());},ul=(t,s,i,u)=>{if(u&&(t==="row"&&u.count>=1048576||t==="col"&&u.count>=16384)||!Qe()||!Number.isFinite(i))return;let p=f.current,R=u?Array.from({length:u.count},(g,W)=>t==="col"?{type:"setColWidth",sheet:p,col:u.at+W,width:Da$1(i)}:{type:"setRowHeight",sheet:p,row:u.at+W,height:Ea(i)}):[t==="col"?{type:"setColWidth",sheet:p,col:s,width:Da$1(i)}:{type:"setRowHeight",sheet:p,row:s,height:Ea(i)}];_e({kind:"applyOps",payload:{args:[R]}});},dl=useMemo(()=>({onHeaderMouseDown:cl,onHeaderResize:ul,onSelectAll:al,onHeaderPress:Mr,onHeaderDragSelect:(t,s)=>{!k?.ready||k.failure||Pn(t,s,true);}}),[k]),fl=H({surface:l,subscribe:x$2.store.subscribe,resolve:t=>{if(!k?.ready||k.failure||G$1(t.target)||B.cellInput?.contains(t.target))return null;let s=t.target instanceof Element?t.target.closest('[data-testid="xlsx-column-headers"], [data-testid="xlsx-row-headers"]'):null;if(!s)return null;let i=s.dataset.testid==="xlsx-column-headers"?"columnHeader":"rowHeader",u=t.target instanceof Element?t.target.closest("[data-col], [data-row]"):null,p=Number(i==="columnHeader"?u?.dataset.col:u?.dataset.row);if(!u||!Number.isInteger(p))return null;Mr(),Pn(i==="columnHeader"?"col":"row",p,false);let R=()=>{let g=ne.current?.painted;if(!(!g||g.request.sheet!==f.current))return {rows:g.displayList.grid?.frozenRows??0,cols:g.displayList.grid?.frozenCols??0,index:p,apply:(W,I)=>{if(!Qe()||g.request.sheet!==f.current)return;let N=f.current;_e({kind:"applyOps",payload:{args:[[{type:"setFreezePane",sheet:N,pane:W===0&&I===0?null:{rows:W,cols:I,top_left:{row:W,col:I}}}]]}});}}};return {label:e(i==="columnHeader"?"editor.columnHeaderMenuLabel":"editor.rowHeaderMenuLabel"),testId:i==="columnHeader"?"xlsx-column-header-menu":"xlsx-row-header-menu",entries:()=>xr(K(i,x$2.store,e,R()),()=>!k?.failure&&Qe())}}}),xn=(t,s)=>{if(wn.current)return;wn.current=true;let i=t?.value??"";fe(null),requestAnimationFrame(()=>et.current?.querySelector('[role="tab"][aria-selected="true"]')?.focus()),s&&x$2.store.execute("renameSheet",{name:i});};useLayoutEffect(()=>{Ae!==null&&(wn.current=false);},[Ae]);let pl=useCallback(()=>{let t=y.current,s=f.current;if(!Te||Pe.current!==Te||!t||!Qe()||at.current||Se.current!==null||Ji()===Ce.current)return;let i=He(s,t),u=k,p=++Me.current;Se.current=p;let R=ne.current?.captureCommandFrame()??void 0,g=xe.current;se.runAfterPendingInput(()=>se.command({kind:"applyFormat",payload:{target:i,formatToken:Te,selection:i}},{frame:R,selectionRevision:g}).result).then(()=>{te.current!==u||!u?.current||Me.current!==p||(ut(null),x$2.refresh());}).catch(ze).finally(()=>{Se.current===p&&(Se.current=null);});},[Te,k,se,bt]),Vt=t=>{let s=ne.current?.painted,i=c$1.current;if(!s||s.request.sheet!==f.current||!i)return {cell:null,chart:null};let u=i.getBoundingClientRect(),p=(t.clientX-u.left)/s.request.zoom,R=(t.clientY-u.top)/s.request.zoom;return {cell:s.geometry?cellAtPoint(s.geometry,p,R):null,chart:chartRegionAtPoint(s.displayList.charts,p,R)}},ml=useCallback((t,s)=>Vt({clientX:t,clientY:s}).cell,[]),ko=t=>{let s=y.current;!k?.ready||!Qe()||!s||!uo(s.anchor)||(Bt(f.current,s.anchor),B.open(t));},hl=t=>{if(Ft(t)||!k?.ready||k.failure||B.cellInput?.contains(t.target)||B.isComposing("cell")||B.isComposing("formula")||(B.commit("cell"),B.commit("formula"),_t(),t.button===2||t.button===0&&t.ctrlKey&&h()))return;let{cell:s,chart:i}=Vt(t);if(Tt.current=null,i){ge({id:i.id,movable:i.movable,resizable:i.resizable,placeholder:i.placeholder??false}),Z(null),Qe()&&i.movable&&t.button===0&&(Ge.current={generation:k.generation,sheet:f.current,id:i.id,zoom:ne.current?.painted?.request.zoom??$$1.current,x:t.clientX,y:t.clientY}),Ue(),t.preventDefault();return}ge(null);let u=y.current;if(!s||t.shiftKey&&!u)return;let p=t.shiftKey?extendTo(u,s,rr()):selectionAt(j(s,Nt()));Dt(f.current,p,true),_e({kind:"select",payload:{selection:He(f.current,p)}}),Tt.current=s,at.current=true,Ue();},gl=t=>{if(Ft(t)||k?.failure||so())return;let s=Ge.current;if(s){Z({kind:"move",x:t.clientX-s.x,y:t.clientY-s.y}),t.currentTarget.style.cursor="move";return}let{cell:i,chart:u}=Vt(t);if(at.current&&i&&y.current){let R=extendTo(y.current,i,rr());Dt(f.current,R,true),_e({kind:"select",payload:{selection:He(f.current,R)}});return}let p=i&&ne.current?.painted?hyperlinkAtCell(ne.current.painted.displayList,i.row,i.col):null;t.currentTarget.style.cursor=u?.movable&&Qe()?"move":u||p?"pointer":"default",t.currentTarget.title=u?"":p?.tooltip??"";},Cn=(t,s)=>{let i=ne.current?.painted?.displayList;if(!i||k?.failure)return;let u=hyperlinkAtCell(i,t,s);if(!u)return;let p=safeExternalHyperlink(u);if(p){window.open(p,"_blank","noopener,noreferrer");return}let R=k?.session.editState.sheets??k?.session.state.sheets??[],g=u.location?parseHyperlinkLocation(u.location,R[f.current]?.name??""):null;if(!g)return;let W=R.findIndex(I=>I.name.toLowerCase()===g.sheetName.toLowerCase());W>=0&&Ct(W,selectionAt(g));},bo=useRef(Cn);bo.current=Cn;let yl=useCallback((t,s)=>bo.current(t,s),[]),kl=t=>{if(Ft(t)||k?.failure)return;let{cell:s}=Vt(t),i=Tt.current;Tt.current=null;let u=ne.current?.painted?.displayList;!s||!i||!u||s.row!==i.row||s.col!==i.col||Cn(s.row,s.col);},bl=t=>{if(Ft(t)||!k?.ready||k.failure||!y.current||!X.current||B.isComposing("formula")||x$2.claimsKey(t))return;let s=t.metaKey||t.ctrlKey;if(B.getSnapshot().cell){if(B.cellInput||B.key("cell",t))return;if(B.cellKey(t)){t.preventDefault();return}if(t.key==="Enter")B.commit("cell",t.shiftKey?"up":"down");else if(t.key==="Tab")B.commit("cell",t.shiftKey?"left":"right");else if(t.key==="Escape")B.cancel();else return;t.preventDefault();return}let u$1=we.current;if(u$1){if(t.key==="Escape"){Ge.current=null,rt.current=null,Z(null),ge(null),t.preventDefault();return}let Y=!s&&Ma[t.key];if(Y&&Qe()&&u$1.movable){let S=t.shiftKey?10:1,K=rt.current??{generation:k.generation,sheet:f.current,id:u$1.id,dx:0,dy:0};rt.current={...K,dx:K.dx+Y[0]*S,dy:K.dy+Y[1]*S},Z({kind:"move",x:rt.current.dx*$$1.current,y:rt.current.dy*$$1.current}),ae.current!==null&&clearTimeout(ae.current);let z=k;ae.current=setTimeout(()=>{z.current&&!z.retiring&&te.current===z&&Dr.current.flushNudge();},250),t.preventDefault();}return}let p=(Y,S)=>{De.beforeInput({...pt(),apply:K=>(it(f.current,K),true)},Y,S)||Y();},R=x$2.clipboardKey(t);if(R){let Y=R==="pastePlainText"?"paste":R;if(yn(Y)){let S=R==="pastePlainText"?go():ho(Y),K=()=>S.reject?.(new u("editor-unavailable"));p(()=>B.getSnapshot().cell?K():yo(Y,S),K);}t.preventDefault();return}if(t.ctrlKey&&!t.metaKey&&(t.key==="PageDown"||t.key==="PageUp")){let Y=_$1.current,S=Y.findIndex(z=>z.index===f.current),K=Y[S+(t.key==="PageDown"?1:-1)];S>=0&&K&&Ct(K.index),t.preventDefault();return}let g=m(t),W=selectionKeyReducer(y.current,t,rr(),void 0,Wr(),Nt()).type==="move";if(g||W){let Y={key:t.key,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey},S=()=>{if(B.getSnapshot().cell){if(B.cellKey(Y))return;Y.key==="Enter"?B.commit("cell",Y.shiftKey?"up":"down"):Y.key==="Tab"&&B.commit("cell",Y.shiftKey?"left":"right");return}De.enqueue(Y,pt());};if(De.defer(ft(),S,true)){t.preventDefault();return}t.preventDefault(),De.enqueue(t,pt());return}let I={key:t.key,shiftKey:t.shiftKey,metaKey:t.metaKey,ctrlKey:t.ctrlKey,altKey:t.altKey},N=I.shiftKey&&I.key!=="Tab"&&I.key!=="Enter",ce=Y=>N?Y:selectionAt(Y.anchor),U=()=>{let Y=y.current;if(!Y||we.current)return;if(B.getSnapshot().cell){if(B.cellKey(I))return;I.key==="Enter"?B.commit("cell",I.shiftKey?"up":"down"):I.key==="Tab"?B.commit("cell",I.shiftKey?"left":"right"):I.key==="Escape"&&B.cancel();return}let S=selectionKeyReducer(ce(Y),I,rr(),void 0,Wr(),Nt());S.type==="move"?(Dt(f.current,S.selection),Bt(f.current,S.selection.focus),_e({kind:"select",payload:{selection:He(f.current,S.selection)}})):S.type==="startEdit"?ko(S.initialInput):S.type==="clear"&&mo();};if(selectionKeyReducer(ce(y.current),I,rr(),void 0,Wr(),Nt()).type==="none"){I.key==="Escape"&&De.defer(ft(),U,true)&&t.preventDefault();return}t.preventDefault(),De.defer(ft(),U,false)||U();},ht=Q$1,vl=useMemo(()=>jsx(Ba,{}),[]),wl=r.allowHostProposals&&isProposalsAvailable()?jsx(da,{id:"proposalsPanel"}):null,vo=r.showToolbar===false?null:r.toolbar===void 0?r.readOnly?wl:vl:r.toolbar,Sn=t=>Xe.managed?jsx(ia,{host:Xe.host,placement:t,activations:Xe.activations.filter(s=>s.plugin.panel?.placement===t),available:Vi}):null,Xr=ne.current?.painted;return jsx(G.Provider,{value:x$2.store,children:jsx(R$1.Provider,{value:true,children:jsx(S.Provider,{value:true,children:jsx(yi,{onNavigate:Li,controller:B,presentation:w$1,run:k,active:L$1,selectedChart:ie!==null,error:!!vt,readOnly:!!r.readOnly,navigation:xe,cellEditable:uo,gateRevision:Xe.activations,children:jsxs("div",{dir:"ltr",ref:l,className:r.className,role:"application","aria-label":e("editor.appLabel"),onKeyDownCapture:t=>{!Ft(t)&&t.key==="Escape"&&!(t.target instanceof Element&&t.target.closest('[role="menu"]'))&&(o$1.cancelCut(),ut(null),x$2.refresh());},onKeyDown:t=>{Ft(t)||t.key!=="F6"||t.altKey||t.ctrlKey||t.metaKey||t.target instanceof Element&&t.target.closest('[aria-modal="true"], [role="menu"]')||ja(t.currentTarget,a$2.current,t.shiftKey)&&t.preventDefault();},style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,color:"#202124",background:"#ffffff",fontFamily:"ui-sans-serif, system-ui, sans-serif",...r.style},children:[jsx(Ii,{store:w$1,onChange:pl}),vo!=null&&jsx("div",{"data-testid":"xlsx-toolbar",style:{flex:"0 0 auto"},children:vo}),jsxs("div",{ref:_i,"data-testid":"xlsx-workspace",style:{position:"relative",display:"flex",flex:1,minHeight:0},children:[Sn("left"),jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0},children:[jsx(aa,{open:pe,target:Re,api:$i,readOnly:!!r.readOnly,onClose:()=>le(false),onApplied:()=>x$2.refresh()}),isProposalsAvailable()&&F&&jsx(_,{proposals:d$1,staleFor:qe,style:{top:4,right:8,width:"min(320px, calc(100% - 16px))",maxHeight:"min(420px, calc(100% - 12px))"}}),Xe.rowGutter&&jsx(da$1,{host:Xe.host,index:Xe.rowGutter,painted:Xe.painted,zoom:D$1,top:r.showSheetHeaders?Ca:0}),jsx(Ci,{store:w$1,active:L$1,leadingInset:Xe.rowGutter?24*D$1:0,showSheetHeaders:!!r.showSheetHeaders,headerHandlers:dl,selectAllLabel:e("commands.selectAll"),children:jsxs("div",{ref:a$2,id:b,"data-testid":"xlsx-scroll",tabIndex:0,onKeyDown:bl,role:"group","aria-roledescription":e("a11y.gridRoleDescription"),"aria-label":ht.find(t=>t.index===L$1)?.name||e("a11y.gridLabel"),onFocus:t=>{t.target===t.currentTarget&&h$2.current?.();},onMouseDown:hl,onMouseMove:gl,onClick:kl,onDoubleClick:t=>{if(Ft(t)||Vt(t).chart)return;let s=Vt(t).cell,i=ne.current?.painted?.displayList;s&&i&&hyperlinkAtCell(i,s.row,s.col)||ko();},onMouseLeave:t=>{t.currentTarget.style.cursor="default",t.currentTarget.title="";},style:{position:"relative",flex:1,overflow:"auto",minHeight:0,outline:"none",...Xe.rowGutter&&!r.showSheetHeaders?{marginLeft:24*D$1}:{}},children:[jsx(Si,{store:w$1,zoom:D$1}),jsxs("div",{style:{position:"sticky",top:0,left:0,width:0,height:0},children:[jsx("canvas",{ref:c$1,style:{display:"block",position:"absolute",top:0,left:0}}),jsx(Ri,{store:w$1,active:L$1,zoom:D$1,selectedChart:ie,chartPreview:O,chartSheetExtent:Fe,onResizeStart:(t,s)=>{_t(),zi(t,s);},onResizeNudge:Ni,controller:B,run:k,disabled:!!vt||!!r.readOnly,showSheetHeaders:!!r.showSheetHeaders,onFill:Qi,cellAt:ml,fillHandle:r.fillHandle}),jsx(Ti,{store:w$1,run:k,provider:r.collaboration?.provider,active:L$1,sheets:ht}),Xe.managed&&jsx(ca,{host:Xe.host,activations:Xe.activations,layerRef:Xe.overlayLayerRef,width:(Xr?.displayList.width??0)*(Xr?.request.zoom??D$1),height:(Xr?.displayList.height??0)*(Xr?.request.zoom??D$1)})]})]})}),Sn("bottom")]}),Sn("right"),vt&&ht.length===0&&jsx(d,{kind:"open",details:vt.message}),!r.file&&!vt&&jsx("div",{"data-testid":"xlsx-empty",role:"status",style:{position:"absolute",inset:0,display:"grid",placeItems:"center",color:"#5f6368",pointerEvents:"none"},children:e("editor.openPrompt")}),r.file&&!k?.ready&&!vt?jsx(Aa,{children:r.loadingIndicator}):null]}),jsx(Wi,{store:w$1,active:L$1,sheets:ht,onFollowLink:yl}),jsx(mi,{store:w$1,active:L$1,sheets:ht,focusTarget:a$2,announceRef:h$2}),he&&jsx("div",{"data-testid":"xlsx-input-refusal",role:"alert",children:he.message??(he.cause?e(a$1[he.cause]):jsxs(Fragment,{children:[n$1(he.code,{translate:e}).message,he.detail?`: ${he.detail}`:""]}))}),vt&&ht.length>0&&jsx(d,{kind:"stopped",details:vt.message}),sl.element,il.element,fl.element,ht.length>0&&jsx("div",{ref:et,"data-testid":"xlsx-sheet-tabs",role:"tablist","aria-label":e("editor.sheetTabsLabel"),style:{display:"flex",gap:2,padding:"4px 6px",borderTop:"1px solid #e0e0e0",background:"#fafafa",overflowX:"auto"},children:ht.map((t,s)=>Ae===t.index?jsx("input",{"data-testid":"xlsx-sheet-rename","aria-label":e("editor.renameSheetLabel"),defaultValue:t.name,maxLength:31,autoFocus:true,onFocus:i=>i.currentTarget.select(),onKeyDown:i=>{i.key==="F6"&&i.stopPropagation(),i.key==="Enter"?(i.preventDefault(),xn(i.currentTarget,true)):i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),xn(i.currentTarget,false));},onBlur:i=>xn(i.currentTarget,true),style:{border:`1px solid ${Mi}`,padding:"3px 8px",font:"inherit",width:Math.max(80,t.name.length*9)}},t.id):jsx("button",{role:"tab","aria-selected":t.index===L$1,disabled:!!vt,tabIndex:t.index===L$1?0:-1,"aria-controls":b,"data-sheet-index":t.index,onClick:()=>Ct(t.index),onDoubleClick:()=>{x$2.store.getState("renameSheet").enabled&&x$2.store.execute("renameSheet",null);},onKeyDown:i=>{if(i.target!==i.currentTarget)return;let u=$a(i.key,s,ht.length);u!==null&&(i.preventDefault(),Ct(ht[u].index),i.currentTarget.parentElement?.children[u]?.focus());},style:{border:"none",padding:"4px 12px",cursor:"pointer",background:t.index===L$1?"#ffffff":"transparent",borderBottom:t.index===L$1?`2px solid ${Mi}`:"2px solid transparent",fontWeight:t.index===L$1?600:400},children:t.name},t.id))})]})})})})})}function $a(r,e,n){return n===0?null:r==="ArrowRight"?(e+1)%n:r==="ArrowLeft"?(e-1+n)%n:r==="Home"?0:r==="End"?n-1:null}function ja(r,e,n){let o=r.querySelector('[data-testid="xlsx-toolbar"]'),l=r.querySelector('[data-testid="xlsx-sheet-tabs"]'),a=o?[...o.querySelectorAll("button, input, select, [tabindex]")].filter(P=>P.getAttribute("tabindex")!=="-1"&&!P.disabled&&!P.closest('[inert], [aria-hidden="true"]')):[],h=[a.find(P=>P.getAttribute("tabindex")==="0")??a[0]??null,e,l?.querySelector('[role="tab"][aria-selected="true"]')??null],b=[o,e,l],c=r.ownerDocument.activeElement,m=b.findIndex(P=>P&&c&&P.contains(c));for(let P=1;P<=b.length;P++){let C=((m<0?n?0:b.length-1:m)+(n?-P:P)+b.length*2)%b.length,x=h[C];if(x&&(x.focus(),r.ownerDocument.activeElement===x))return true}return false}export{Cd as XlsxPeerlessWorkerEditor};
@@ -0,0 +1 @@
1
+ import {F}from'./chunk-NLAF4WIP.js';import {a as a$1}from'./chunk-O2XFH626.js';function n(r){return r instanceof Error?r:new Error(r&&typeof r=="object"&&"message"in r?String(r.message):String(r))}var s=class extends F{constructor(){super(),this.name="XlsxPeerNotReadyError";}},t=class extends Error{constructor(){super("Collaboration is unavailable in the worker editor");a$1(this,"code","collaboration-unavailable");this.name="XlsxWorkerEditorCollaborationError";}},a=class extends Error{constructor(c){super(`Workbook worker session failed: ${n(c).message}`);a$1(this,"cause",c);a$1(this,"code","worker-session-failed");this.name="XlsxWorkerSessionFailedError";}};export{n as a,s as b,t as c,a as d};
@@ -0,0 +1 @@
1
+ import {useState,useRef,useCallback}from'react';var e={ink:"var(--bo-toolbar-ink, #1f1f1f)",inkMuted:"var(--bo-toolbar-ink-muted, #444746)",rail:"var(--bo-toolbar-rail, #f1f1f1)",surface:"var(--bo-toolbar-surface, #ffffff)",hover:"var(--bo-toolbar-hover, rgba(31, 31, 31, 0.08))",selected:"var(--bo-toolbar-selected, rgba(31, 31, 31, 0.12))",line:"var(--bo-toolbar-line, rgba(31, 31, 31, 0.16))",accent:"var(--bo-toolbar-accent, #1f1f1f)",accentInk:"var(--bo-toolbar-accent-ink, #ffffff)"},S=28,I=18,m=6,y=.38,g='ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',A="0 4px 16px rgba(0, 0, 0, 0.12), 0 1px 3px rgba(0, 0, 0, 0.08)";function h(o,t=1){return o===void 0?{}:o?{outline:`2px solid ${e.accent}`,outlineOffset:t}:{outline:"none"}}function F({disabled:o=false,pressed:t=false,open:i=false,hovered:n=false,focusRing:s}){return {appearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:2,minWidth:S,height:S,padding:"0 4px",border:0,borderRadius:m,background:t?e.selected:(n||i)&&!o?e.hover:"transparent",color:t||n||i?e.ink:e.inkMuted,cursor:o?"default":"pointer",opacity:o?y:1,font:`500 13px ${g}`,lineHeight:1,whiteSpace:"nowrap",boxSizing:"border-box",...h(s)}}function _({disabled:o=false,focusRing:t}){return {...F({disabled:o,focusRing:t}),background:e.accent,color:e.accentInk}}function H({disabled:o=false,focusRing:t}){return {height:S,border:`1px solid ${e.line}`,borderRadius:m,background:e.surface,color:e.ink,opacity:o?y:1,font:`400 13px ${g}`,boxSizing:"border-box",...h(t)}}var B={display:"flex",alignItems:"center",gap:0,minHeight:36,padding:"4px 8px",borderRadius:18,background:e.rail,color:e.ink,font:`400 13px ${g}`,boxSizing:"border-box"},D={width:1,height:20,margin:"0 6px",background:e.line,flex:"0 0 auto"},K={padding:4,border:`1px solid ${e.line}`,borderRadius:8,background:e.surface,color:e.ink,boxShadow:A,boxSizing:"border-box",outline:"none"};function $({disabled:o=false,hovered:t=false,focusRing:i}){return {appearance:"none",display:"flex",alignItems:"center",gap:10,width:"100%",minHeight:32,padding:"4px 10px",border:0,borderRadius:m,background:(t||i)&&!o?e.hover:"transparent",color:e.ink,cursor:o?"default":"pointer",opacity:o?y:1,font:`400 13px ${g}`,textAlign:"left",boxSizing:"border-box",...h(i,-2)}}var z={height:1,margin:"4px 2px",background:e.line};function w(o){try{return o.matches(":focus-visible")}catch{return true}}function N(o={}){let[t,i]=useState(false);return {focusRing:t,focusProps:{onFocus:n=>{i(w(n.currentTarget)),o.onFocus?.(n);},onBlur:n=>{i(false),o.onBlur?.(n);}}}}var j={surface:e.surface,text:e.ink,mutedText:e.inkMuted,border:e.line,hover:e.hover,shadow:"rgba(0, 0, 0, 0.12)",focus:e.accent};var M=500;function Z(o){let t=useRef(o);t.current=o;let i=useRef({buffer:"",at:0}),n=useCallback(()=>{let{container:r,itemSelector:a,scope:c}=t.current,f=r.current;return f?Array.from(f.querySelectorAll(a)).filter(x=>!c||x.closest(c)===f):[]},[]),s=useCallback(r=>{let a=n();a.length!==0&&a[(r+a.length)%a.length].focus();},[n]),E=useCallback(r=>{let a=n();if(a.length===0)return false;let c=a.findIndex(d=>d===document.activeElement),f=(t.current.orientation??"vertical")==="vertical",x=f?"ArrowDown":"ArrowRight",C=f?"ArrowUp":"ArrowLeft",b=null;if(r.key===x)b=c+1;else if(r.key===C)b=c<0?a.length-1:c-1;else if(r.key==="Home")b=0;else if(r.key==="End")b=a.length-1;else if(r.key.length===1&&r.key!==" "&&!r.ctrlKey&&!r.metaKey&&!r.altKey){let d=Date.now(),l=i.current;l.buffer=d-l.at>M?r.key.toLowerCase():l.buffer+r.key.toLowerCase(),l.at=d;let k=t.current.labelOf??(u=>u.textContent??""),v=[...a.slice(c+1),...a.slice(0,c+1)],O=[...l.buffer].every(u=>u===l.buffer[0]),R=v.find(u=>k(u).trim().toLowerCase().startsWith(l.buffer))??(O?v.find(u=>k(u).trim().toLowerCase().startsWith(l.buffer[0])):void 0);return R?(r.preventDefault(),R.focus(),true):false}return b===null?false:(r.preventDefault(),s(b),true)},[s,n]);return {items:n,focusFirst:useCallback(()=>s(0),[s]),focusLast:useCallback(()=>s(-1),[s]),onKeyDown:E}}export{e as a,I as b,y as c,g as d,h as e,F as f,_ as g,H as h,B as i,D as j,K as k,$ as l,z as m,N as n,j as o,Z as p};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-QQHWSDLQ.js';var n={saveAsync:"save()",handle:"commands",cell:"readCells(request)",cellAsync:"readCells(request)",rangeCells:"readCells(request)",rangeCellsAsync:"readCells(request)",readCellsSync:"readCells(request)",editCell:"applyEdits(request)",editCellAsync:"applyEdits(request)",selectCells:"plugin.navigation.selectCells",selectCellsAsync:"plugin.navigation.selectCells",clearSelection:"plugin.navigation.selectCells",getPositionAtPoint:"plugin.geometry.getPositionAtPoint",undo:'commands.execute("undo", null)',redo:'commands.execute("redo", null)',refreshProposals:'commands.execute("proposalsPanel", { open: true })',flush:'commands.execute("save", null)',flushPendingInput:'commands.execute("save", null)'};function i(t){return new Proxy(t,{get(r,e,o){let l=typeof e=="string"&&Object.hasOwn(n,e)?n[e]:null;if(l)throw new a(String(e),l);return Reflect.get(r,e,o)}})}export{i as a};
@@ -0,0 +1,2 @@
1
+ import'./chunk-O2XFH626.js';import {PngExportError}from'@betteroffice/xlsx';var oe="https://cdn.jsdelivr.net/npm/",re=1e4,se=Symbol.for("betteroffice.fonts.cdn");var Q=Symbol.for("betteroffice.fonts.cdn.test-globals"),K=globalThis;function Z(e){return e.process?.versions?.node!==void 0||e.Deno!==void 0||e.Bun!==void 0}function ie(e){return e.window?.document!=null&&!Z(e)}function ae(e){if(e&&!(e.implicit&&Z(K[Q]??K)))return {...e}}function ce(){let e=K[se];if(e)return ae(e);if(ie(K[Q]??K))return {baseUrl:oe,timeoutMs:re,implicit:true}}function _(e=ce()??null){return e?JSON.stringify([e.baseUrl,e.timeoutMs,e.implicit]):""}function X(e){return e instanceof Error&&e.diagnostic?.reason==="cdn-unavailable"}function z({diagnostic:e}){typeof globalThis.dispatchEvent=="function"&&typeof CustomEvent=="function"&&globalThis.dispatchEvent(new CustomEvent("betteroffice:font-pack-diagnostic",{detail:{...e}}));}var V={load:()=>import('@betteroffice/fonts'),loadRemote:()=>import('@betteroffice/fonts/remote')},A=new Map,ee;function de(e){let r=null;try{r=document.createElement("canvas").getContext("2d");}catch{}if(!r)return false;let l="mmmmmmmmmmwwwwwlliI0O&@";return ["monospace","serif","sans-serif"].some(i=>{r.font=`72px ${i}`;let p=r.measureText(l).width;return r.font=`72px ${JSON.stringify(e)}, ${i}`,r.measureText(l).width!==p})}function fe(e,r,l){let i=r.toLowerCase(),p=typeof e[Symbol.iterator]=="function"?[...e].filter(d=>d.family.replace(/^(['"])(.*)\1$/,"$2").toLowerCase()===i):[];return p.length>0?p.some(d=>!l(d)):de(r)}function ue(e,r,l){r.owners.delete(l),!(r.owners.size>0)&&(r.controller.abort(),A.get(e)===r&&A.delete(e));}async function pe(e,r,l,i,p,d,o,f){let g=document.fonts;if(ee!==g){for(let u of A.values())u.controller.abort();A.clear(),ee=g;}let m=JSON.stringify([i,e.trim().toLowerCase(),r,l,f]),y=A.get(m);if(!y){let u=new AbortController,M=(async()=>{let h=await V.loadRemote();return u.signal.throwIfAborted(),h.resolveWordFamilySubstitute(e)?.remote?fe(g,e.trim(),E=>h.isRemoteFontFace?.(E)??false)?{success:false,partial:false}:(await h.loadRemoteFontFaces(e,e,{weight:r?700:400,style:l?"italic":"normal"},g,{provider:i,signal:u.signal,text:f}),{success:true,partial:false}):{success:false,partial:false}})().catch(h=>({success:false,partial:(h?.faces?.length??0)>0})),C={done:M,owners:new Set,controller:u};y=C,A.set(m,C),M.then(()=>{A.get(m)===C&&A.delete(m);});}let v=y;v.owners.add(p),d.set(m,v);try{let{success:u,partial:M}=await v.done;return {success:u&&o(),partial:M&&o()}}finally{d.get(m)===v&&d.delete(m),v.owners.delete(p);}}var me=1.5*1024*1024,O=new Map,B=new Map,H;function ge(e,r,l,i,p){let d=()=>H===i&&p.size>0;return (async()=>{try{if(!d())return !1;let o=await l();if(o.byteLength!==e.byteLength||!d())return !1;let f=await new FontFace(r,o,{weight:String(e.weight),style:e.style}).load();return d()?(i.add(f),!0):!1}catch(o){return X(o)&&z(o),false}})()}function Ae(e,r,l={}){let i=Symbol(),p=new Map,d=new Set,o=new Set,f=new Set,g=new Map,m=new Set,y=new Map,v=new Map,u=false,M=false,C=false,h,E;async function q(n,s,t,c,F,b,T=true,S=1/0){let a;try{if(!E){let R=V.load().then(L=>({fonts:L,source:L.createFontProvider(void 0,{...e?{decoder:e,retain:!1}:{},strict:!0})}));E=R,R.catch(()=>{E===R&&(E=void 0);});}let{fonts:k,source:w}=await E;if(u||typeof document>"u"||!document.fonts)return !1;let x=k.resolveMetricCompatFace(n,s,t)??k.resolveBundledFamilyFace(n,s,t);if(!x){let R=l.remoteFonts??"bunny";if(R==="off"||S!==1/0)return !1;F();let{success:L,partial:J}=await pe(n,s,t,R,i,p,()=>!u,c);return J&&b(),L}if(x.byteLength>S)return !1;let U=_();if(w.faceUnavailableUntil&&await w.faceUnavailableUntil(x)!==void 0||u||!document.fonts||U!==_())return !1;let D=document.fonts;H!==D&&(O.clear(),B.clear(),H=D);let P=JSON.stringify([n.trim().toLowerCase(),x.weight,x.style,U]),I=O.get(P),te=I!==void 0;if(a=B.get(P),!I){let R=w.resolve(n,s,t)??w.resolveFamily(n,s,t);if(!R)return !1;a=new Set([i]),B.set(P,a),I=ge(x,n,R,D,a),O.set(P,I);let L=I,J=a;L.then(ne=>{ne!==!0&&O.get(P)===L&&O.delete(P),B.get(P)===J&&B.delete(P);});}a&&(a.add(i),d.add(a));let Y=await I;return Y===!1&&te&&T&&!u?await q(n,s,t,c,F,b,!1,S):Y}catch{return false}finally{a&&(a.delete(i),d.delete(a));}}let G=()=>u||l.defaultFonts===false||e===void 0||typeof document>"u"||typeof FontFace>"u"||!document.fonts;function N(n){let s=_(),t=new Map;for(let c of n.commands){if(c.op!=="text"||!c.fontFamily||c.chart)continue;let{fontFamily:F,bold:b=false,italic:T=false}=c,S=JSON.stringify([F.trim().toLowerCase(),b,T,s]),a=t.get(S);a||t.set(S,a={fontFamily:F,bold:b,italic:T,characters:new Set});for(let k of c.text??"")a.characters.add(k);if(c.numberFormat&&a.characters.add("#"),c.numberFormat?.general!==void 0)for(let k of "0123456789.-E+")a.characters.add(k);for(let k of c.numberFormat?.parts??[])for(let w of k.character)a.characters.add(w);}for(let c of t.values())[" ",`
2
+ `,"\f","\r"].some(F=>c.characters.has(F))&&c.characters.add(" ");return t}function j(n,s,t){let c=n.get(s),F="";for(let b of t)c?.has(b)||(F+=b);return F}function $(n){if(G())return true;for(let[s,{characters:t}]of N(n))if(!f.has(s)||m.has(s)&&j(v,s,t))return false;return true}async function W(n){if(G())return;let s=[];for(let[t,{fontFamily:c,bold:F,italic:b,characters:T}]of N(n)){if(g.has(t))continue;let S=o.has(t)?j(y,t,T):[...T].join("");if(o.has(t)&&!(m.has(t)&&S))continue;let a=false,k=q(c,F,b,S,()=>{m.add(t);},()=>{a=!0;}).then(w=>{g.delete(t);for(let U of w?[v,y]:[v]){let D=U.get(t);D||U.set(t,D=new Set);for(let P of S)D.add(P);}f.add(t),w&&o.add(t),(w||a)&&(M=true);let x=!u&&m.has(t)&&h?N(h).get(t):void 0;return x&&j(v,t,x.characters)&&W(h).catch(()=>{}),!u&&!g.size&&M?(M=false,C=false,r()):!u&&!g.size&&C&&h&&$(h)&&(C=false,l.onSettled?.()),w});g.set(t,k),s.push(k);}await Promise.all(s);}return {load:W,preload(n,s){(async()=>{for(let[t,{fontFamily:c,bold:F,italic:b}]of N(n)){if(G()||!s())return;o.has(t)||g.has(t)||f.has(t)||await q(c,F,b,"",()=>{},()=>{},true,me)===true&&(o.add(t),f.add(t));}})().catch(()=>{});},adopt(n){if(h=n,$(n)){u||l.onSettled?.();return}C=true,W(n).catch(()=>{});},paint(n,s){h=n;let t=$(n);return t||(C=true),s(),W(n).catch(()=>{}),t},dispose(){u=true;for(let[n,s]of p)ue(n,s,i);p.clear();for(let n of d)n.delete(i);d.clear(),g.clear();}}}async function Ee(e,r,l=new Set){if(e.length===0)return [];let i=await V.load(),p=i.createFontProvider(void 0,{...r?{decoder:r,retain:false}:{},strict:true}),d=[];for(let o of e){let f=i.resolveMetricCompatFace(o.family,o.bold,o.italic)??i.resolveBundledFamilyFace(o.family,o.bold,o.italic),g=f&&(p.resolve(o.family,o.bold,o.italic)??p.resolveFamily(o.family,o.bold,o.italic));if(!f||!g)continue;let m;try{m=await g();}catch(y){if(f.script&&f.script!=="arabic"&&f.script!=="hebrew"&&i.isMissingFontAddon(y))continue;if(X(y)&&(y.diagnostic.pack==="cjk"||y.diagnostic.pack==="intl")){l.has(y)||(l.add(y),z(y));continue}throw new PngExportError("font-unavailable",`The font "${o.family}" could not load, so the sheet was not exported with a substitute.`)}m.byteLength===f.byteLength&&d.push({family:o.family,bold:f.weight>=600,italic:f.style==="italic",bytes:new Uint8Array(m)});}return d}export{Ae as createDefaultFontPainter,Ee as exportFaces,V as xlsxDefaultFontManager};