@aiquants/spreadsheet 0.17.2 → 0.18.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.
package/dist/index.cjs CHANGED
@@ -1,14 +1,14 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qt=require("./tsv.cjs"),Te=require("./view-BkwCUzTl.cjs"),Je=require("@aiquants/virtualscroll"),Y=require("react/jsx-runtime"),i=require("react"),ys=1e3,on=1e4,Rs=10,zl=2**(1/4),Nu=(e,t)=>e<=0?e:t>0?e>=on?e:Math.min(on,Math.max(e+1,Math.round(e*zl))):Math.max(1,Math.min(e-1,Math.round(e/zl))),Nl=(e,t)=>t.reduce((n,r)=>{const o=e.sizeOf(r.index)===0,s=r.size===0;return n+(s&&!o?1:0)-(!s&&o?1:0)},0),vs=(e,t,n,r)=>{if(t.length===0)return{ok:!0,entries:[]};const o=r.axisKind==="row"?Math.floor(r.maxOperationCells/Rs):r.maxOperationCells;if(t.length>o)return{ok:!1,reason:"limit",count:t.length};const s=new Map;for(const u of t){if(!(Number.isFinite(u.size)&&u.size>=0))throw new RangeError(`[spreadsheet] gateResizeEntries requires a finite size >= 0, received ${u.size} at index ${u.index}`);s.set(u.index,Math.min(Math.round(u.size),on))}let l=[...s].map(([u,h])=>({index:u,size:h}));if(e.count-e.hiddenCount()-Nl(e,l)===0){const u=n===null?l[0].index:n;l=l.map(h=>h.index===u?{index:h.index,size:1}:h)}if(r.axisKind==="row"){const u=e.hiddenCount()+Nl(e,l);if(u>r.rowHiddenLimit)return{ok:!1,reason:"bounds",count:u}}return{ok:!0,entries:l}},Ss="#000000",zr=e=>e===void 0?{}:{minimumFractionDigits:e,maximumFractionDigits:e},Fu=20,Pu=256,Nr=new Map,_o=new WeakMap,ot=e=>{const t=e.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d{1,4})?$/.test(t)&&Number.isFinite(Number(t))?t:null},_u=(e,t)=>{const n=e.search(/[eE]/);return n<0?`${e}e${t}`:`${e.slice(0,n)}e${Number(e.slice(n+1))+t}`},qu=e=>{switch(e.type){case"number":return{signDisplay:"negative",useGrouping:e.grouping??!1,...e.decimals===void 0?{maximumFractionDigits:Fu}:zr(e.decimals)};case"percent":return{signDisplay:"negative",style:"percent",...zr(e.decimals)};case"currency":return{signDisplay:"negative",style:"currency",currency:e.currency,...zr(e.decimals)};case"scientific":return{signDisplay:"negative",notation:"scientific",...zr(e.decimals)};default:return null}},Iu=e=>{const t=_o.get(e);if(t!==void 0)return t;const n=JSON.stringify([e.type,e.locale??null,e.decimals===void 0?null:String(e.decimals),e.type==="number"?e.grouping??!1:null,e.type==="currency"?e.currency:null]),r=Nr.get(n);if(r!==void 0)return _o.set(e,r),r;Nr.size>=Pu&&Nr.clear();const o=qu(e);let s=null;if(o!==null)try{s=new Intl.NumberFormat(e.locale,o)}catch{s=null}return Nr.set(n,s),_o.set(e,s),s},ju=(e,t)=>{switch(t){case 2:return e%4===0&&e%100!==0||e%400===0?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}},ec=e=>{const t=/^(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);return r<1||r>12||o<1||o>ju(n,r)||s>23||l>59||c>59?null:{year:n,month:r,day:o,hour:s,minute:l,second:c}},Hu=(e,t)=>{const n=ec(e);if(n===null)return e;const r=(o,s)=>String(o).padStart(s,"0");return t.replace(/yyyy|MM|dd|HH|mm|ss/g,o=>{switch(o){case"yyyy":return r(n.year,4);case"MM":return r(n.month,2);case"dd":return r(n.day,2);case"HH":return r(n.hour,2);case"mm":return r(n.minute,2);default:return r(n.second,2)}})},Wn=(e,t)=>{if(t===void 0||t.type==="text"||e==="")return e;if(t.type==="date")return Hu(e,t.pattern??"yyyy/MM/dd");const n=ot(e);if(n===null)return e;const r=Iu(t);return r===null?e:r.format(t.type==="percent"&&t.scale===!1?_u(n,-2):n)},Fl=(e,t,n)=>e!==void 0?e:t!==void 0&&t.type==="text"?"left":t!==void 0&&t.type==="date"?ec(n)!==null?"right":"left":ot(n)!==null?"right":"left",fr=e=>e==="center"?"center":e==="right"?"flex-end":"flex-start",tc=["align","background","bold","borders","color","fontFamily","fontSize","italic","strikethrough","underline","value","verticalAlign","wrap"],Bu=["bottom","left","right","top"],nc=(e,t,n)=>{e[t]=n},rc=e=>{const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=t[r]);return n},Vu=e=>{if(e===void 0)return;const t={};for(const n of Bu){const r=e[n];r!==void 0&&(t[n]=rc(r))}return Object.keys(t).length===0?void 0:t},gt=e=>{const t={};for(const n of tc){const r=n==="borders"?Vu(e.borders):n==="value"?e.value===void 0?void 0:rc(e.value):e[n];r!==void 0&&r!==!1&&nc(t,n,r)}return Object.keys(t).length===0?void 0:t},ks=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;const o=e,s=t;for(let l=0;l<n.length;l+=1){const c=n[l];if(c!==r[l]||!ks(o[c],s[c]))return!1}return!0},Wu=(e,t)=>e===t?!0:ks(e===void 0?void 0:gt(e),t===void 0?void 0:gt(t)),Es=(e,t)=>{const n={};for(const o of tc){const s=t[o];nc(n,o,s===void 0?e?.[o]:s===null?void 0:s)}const r=gt(n);return ks(r,e===void 0?void 0:gt(e))?e:r},oc="data-aqsp-clip",no="application/x-aqsp-clip",os=512,Pl=16*1024,ss=`${oc}=`,Ku=16,As=()=>{const e=globalThis.crypto;if(e===void 0||typeof e.getRandomValues!="function")throw new RangeError("[spreadsheet] newClipId requires crypto.getRandomValues — there is no counter or randomUUID substitute by design");const t=e.getRandomValues(new Uint8Array(Ku));let n="";for(const r of t)n+=r.toString(16).padStart(2,"0");return n},br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=e=>typeof e=="string",Ge=e=>typeof e=="boolean",en=e=>typeof e=="number"&&Number.isFinite(e),mt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0,_l=e=>mt(e)&&e>=1,Yu=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=on,_t=e=>{const t=new Set(e);return n=>typeof n=="string"&&t.has(n)},Uu=e=>t=>Array.isArray(t)&&t.every(e),$e=(e,t)=>({fields:new Map(Object.entries(e)),required:t}),jt=(e,t)=>{if(!br(e))return!1;for(const n of Object.keys(e)){const r=e[n];if(r===void 0)continue;const o=t.fields.get(n);if(o===void 0||!o(r))return!1}for(const n of t.required)if(e[n]===void 0)return!1;return!0},Os=e=>t=>{if(!br(t)||typeof t.type!="string")return!1;const n=e.get(t.type);return n!==void 0&&jt(t,n)},Xu=["left","center","right"],Gu=["top","middle","bottom"],Zu=["thin","medium","thick","dashed","dotted","double","hair"],qo=["gt","gte","lt","lte","eq","neq","between","notBetween"],Ju=["contains","notContains","startsWith","endsWith","isEmail","isUrl"],Qu=["eq","neq","gt","gte","lt","lte","between","notBetween"],ed=["contains","notContains","startsWith","endsWith"],td=new Map([["number",$e({type:ae,decimals:en,grouping:Ge,locale:ae},["type"])],["percent",$e({type:ae,decimals:en,scale:Ge,locale:ae},["type"])],["currency",$e({type:ae,currency:ae,decimals:en,locale:ae},["type","currency"])],["scientific",$e({type:ae,decimals:en,locale:ae},["type"])],["date",$e({type:ae,pattern:ae},["type"])],["text",$e({type:ae},["type"])]]),nd=$e({style:_t(Zu),color:ae},["style"]),Fr=e=>jt(e,nd),rd=$e({top:Fr,right:Fr,bottom:Fr,left:Fr},[]),od=$e({value:Os(td),align:_t(Xu),verticalAlign:_t(Gu),wrap:Ge,background:ae,color:ae,bold:Ge,italic:Ge,underline:Ge,strikethrough:Ge,fontFamily:ae,fontSize:en,borders:e=>jt(e,rd)},[]),sd=e=>jt(e,od),fn={strict:Ge,inputMessage:ae,errorMessage:ae},ld=new Map([["list",$e({...fn,type:ae,values:Uu(ae),showDropdown:Ge},["type","values"])],["number",$e({...fn,type:ae,op:_t(qo),a:ae,b:ae},["type","op","a"])],["textLength",$e({...fn,type:ae,op:_t(qo),a:en,b:en},["type","op","a"])],["date",$e({...fn,type:ae,op:_t(qo),a:ae,b:ae},["type","op","a"])],["text",$e({...fn,type:ae,op:_t(Ju),value:ae},["type","op"])],["checkbox",$e({...fn,type:ae,checked:ae,unchecked:ae},["type"])],["custom",$e({...fn,type:ae,formula:ae},["type","formula"])]]),id=Os(ld),cd=$e({startRow:mt,startCol:mt,endRow:mt,endCol:mt},["startRow","startCol","endRow","endCol"]),ad=e=>{if(!jt(e,cd))return!1;const{startRow:t,startCol:n,endRow:r,endCol:o}=e;return mt(t)&&mt(r)&&mt(n)&&mt(o)&&t<=r&&n<=o},ud=$e({color:ae,value:en},["color"]),Io=e=>jt(e,ud),dd=new Map([["cellValue",$e({type:ae,op:_t(Qu),a:ae,b:ae},["type","op","a"])],["text",$e({type:ae,op:_t(ed),value:ae},["type","op","value"])],["empty",$e({type:ae},["type"])],["notEmpty",$e({type:ae},["type"])],["colorScale",$e({type:ae,min:Io,mid:Io,max:Io},["type","min","max"])],["customFormula",$e({type:ae,formula:ae},["type","formula"])]]),fd=$e({background:ae,color:ae,bold:Ge,italic:Ge,underline:Ge,strikethrough:Ge},[]),pd=$e({sourceRuleId:ae,ranges:Array.isArray,condition:Os(dd),style:e=>jt(e,fd),stopIfTrue:Ge},["sourceRuleId","ranges","condition","style"]),hd=(e,t,n)=>{if(!jt(e,pd))return!1;const r=e.ranges;if(!Array.isArray(r))return!1;for(const o of r)if(!ad(o)||o.endRow>=t||o.endCol>=n)return!1;return!0},md=$e({text:ae,author:ae,createdAt:ae},["text","author","createdAt"]),gd=e=>jt(e,md),wd=(e,t,n)=>{if(!br(e)||typeof e.t!="string")return!1;for(const r of Object.keys(e)){const o=e[r];if(o!==void 0)switch(r){case"t":break;case"f":if(typeof o!="string"||!o.startsWith("="))return!1;break;case"fmt":if(!mt(o)||o>=t)return!1;break;case"val":if(!mt(o)||o>=n)return!1;break;case"note":case"link":if(typeof o!="string")return!1;break;case"comments":if(!(Array.isArray(o)&&o.every(gd)))return!1;break;default:return!1}}return!0},ql=(e,t)=>Array.isArray(e)&&e.length===t&&e.every(Yu),Cd=new Set(["v","rows","cols","clipId","formats","validations","cells","colWidths","rowHeights","wholeRows","wholeCols","conditionalFormats"]),sc=e=>{if(!br(e))return!1;for(const c of Object.keys(e))if(e[c]!==void 0&&!Cd.has(c))return!1;if(e.v!==1)return!1;const t=e.rows,n=e.cols;if(!(_l(t)&&_l(n))||typeof e.clipId!="string"||e.clipId==="")return!1;const r=e.formats;if(!(Array.isArray(r)&&r.every(sd)))return!1;const o=e.validations;if(!(Array.isArray(o)&&o.every(id)))return!1;const s=e.cells;if(!Array.isArray(s)||s.length!==t)return!1;for(const c of s){if(!Array.isArray(c)||c.length!==n)return!1;for(const u of c)if(!wd(u,r.length,o.length))return!1}if(e.colWidths!==void 0&&!ql(e.colWidths,n)||e.rowHeights!==void 0&&!ql(e.rowHeights,t)||typeof e.wholeRows!="boolean"||typeof e.wholeCols!="boolean")return!1;const l=e.conditionalFormats;return Array.isArray(l)&&l.every(c=>hd(c,t,n))},gr=e=>Array.isArray(e)?`[${e.map(gr).join(",")}]`:br(e)?`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${gr(e[n])}`).join(",")}}`:JSON.stringify(e),bd=e=>{const t=gt(e);return t===void 0?"{}":JSON.stringify(t)},yd=e=>`{"text":${JSON.stringify(e.text)},"author":${JSON.stringify(e.author)},"createdAt":${JSON.stringify(e.createdAt)}}`,Rd=e=>{let t=`{"t":${JSON.stringify(e.t)}`;return e.f!==void 0&&(t+=`,"f":${JSON.stringify(e.f)}`),e.fmt!==void 0&&(t+=`,"fmt":${e.fmt}`),e.val!==void 0&&(t+=`,"val":${e.val}`),e.note!==void 0&&(t+=`,"note":${JSON.stringify(e.note)}`),e.comments!==void 0&&(t+=`,"comments":[${e.comments.map(yd).join(",")}]`),e.link!==void 0&&(t+=`,"link":${JSON.stringify(e.link)}`),`${t}}`},lc=e=>{if(!sc(e))throw new RangeError("[spreadsheet] serializeClipPayload received a payload outside the wire format v1 vocabulary");const t=`{"v":1,"rows":${e.rows},"cols":${e.cols},"clipId":${JSON.stringify(e.clipId)}`,n=e.formats.map(bd).join(","),r=e.validations.map(gr).join(","),o=e.cells.map(u=>`[${u.map(Rd).join(",")}]`).join(","),s=e.colWidths===void 0?"":`,"colWidths":[${e.colWidths.join(",")}]`,l=e.rowHeights===void 0?"":`,"rowHeights":[${e.rowHeights.join(",")}]`,c=e.conditionalFormats.map(gr).join(",");return`${t},"formats":[${n}],"validations":[${r}],"cells":[${o}]${s}${l},"wholeRows":${e.wholeRows},"wholeCols":${e.wholeCols},"conditionalFormats":[${c}]}`},ls=e=>{let t;try{t=JSON.parse(e)}catch{return null}return sc(t)?t:null},vd=/&(?:amp|lt|gt|quot|#39|nbsp);/g,Sd=Object.freeze({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&nbsp;":" "}),ic=e=>e.includes("&")?e.replace(vd,t=>Sd[t]):e,kd=/^\{"v":1,"rows":([1-9]\d{0,14}),"cols":([1-9]\d{0,14}),"clipId":"([^"\\]+)"/,Il=e=>{const t=e.length>os?e.slice(0,os):e,n=kd.exec(ic(t));return n===null?null:{v:1,rows:Number(n[1]),cols:Number(n[2]),clipId:n[3]}},Ed=e=>{const t=e.indexOf(ss);if(t===-1)return null;const n=t+ss.length,r=e.charAt(n);return r!=="'"&&r!=='"'?null:{start:n+1,quote:r}},cc=(e,t)=>{if(t==="event"&&e.types.includes(no))return{kind:"mime",json:e.getData(no)};if(!e.types.includes("text/html"))return null;const n=e.getData("text/html"),r=Ed(n);return r===null?null:{kind:"attribute",html:n,at:r}},Ad=(e,t)=>{const n=cc(e,t);return n===null?null:n.kind==="mime"?Il(n.json):Il(n.html.slice(n.at.start,n.at.start+os))},Od=(e,t)=>{const n=cc(e,t);if(n===null)return null;if(n.kind==="mime")return ls(n.json);const r=n.html.indexOf(n.at.quote,n.at.start);return r===-1?null:ls(ic(n.html.slice(n.at.start,r)))},xd=/<google-sheets-html-origin[\s>]/,Td='data-sheets-root="1"',$d=/<meta\s+name=["']?Generator["']?\s+content=["']?Microsoft Excel/,Ld="mso-",Dd=/\.xl\d+\s*\{/,Md="<table",zd=e=>e.includes(ss)?"aqsp":xd.test(e)&&e.includes(Td)?"sheets":$d.test(e)||e.includes(Ld)||Dd.test(e)?"excel":null,ac=(e,t)=>{if(t==="event"&&e.types.includes(no))return"aqsp";if(e.types.includes("text/html")){const n=e.getData("text/html"),r=n.length>Pl?n.slice(0,Pl):n,o=zd(r);if(o==="aqsp")return"aqsp";if(n.includes(Md))return o===null?"html":o}return e.types.includes("text/plain")&&e.getData("text/plain")!==""?"tsv":"none"},xs=1e3,uc=65534,Nd=9,Fd=10,Pd=12,_d=13,qd=32,dc=34,fc=39,Id=43,Ts=47,jl=48,jd=57,Hd=61,Bd=62,Vd=97,Wd=98,Kd=100,Yd=102,pc=104,hc=114,mc=116,Ud=["able","body","head","foot"],pr=e=>e===qd||e===Nd||e===Fd||e===_d||e===Pd,is=e=>e===Bd||e===Ts||pr(e),Xd=e=>pr(e)||e===Ts||e===dc||e===fc,Gd=(e,t,n,r)=>{if(t===0||!Xd(e.charCodeAt(t-1)))return null;let o=t+n;for(;pr(e.charCodeAt(o));)o+=1;if(e.charCodeAt(o)!==Hd)return 1;for(o+=1;pr(e.charCodeAt(o));)o+=1;const s=e.charCodeAt(o);for((s===dc||s===fc)&&(o+=1);pr(e.charCodeAt(o));)o+=1;e.charCodeAt(o)===Id&&(o+=1);let l=0,c=0;for(let u=e.charCodeAt(o);u>=jl&&u<=jd;u=e.charCodeAt(o))l=l*10+(u-jl),c+=1,o+=1;return c===0||l===0?1:l>r?r:l},Hl=(e,t,n)=>{let r=e.indexOf(t);return(o,s)=>{for(;r!==-1&&r<o;)r=e.indexOf(t,r+t.length);for(;r!==-1&&r<s;r=e.indexOf(t,r+t.length)){const l=Gd(e,r,t.length,n);if(l!==null)return l}return 1}},Zd=(e,t)=>{if(e.charCodeAt(t+2)!==mc)return!1;const n=e.charCodeAt(t+3);if(n===hc)return is(e.charCodeAt(t+4));if(n!==Vd&&n!==Wd&&n!==pc&&n!==Yd)return!1;for(const r of Ud)if(e.startsWith(r,t+3)&&is(e.charCodeAt(t+3+r.length)))return!0;return!1},Jd=e=>{const t=e.toLowerCase(),n=Hl(t,"colspan",xs),r=Hl(t,"rowspan",uc);let o=0;const s=_=>(o!==-1&&o<_&&(o=t.indexOf(">",_)),o===-1?t.length:o);let l=0,c=0,u=0,h=0,m=!1;const R=new Map,N=(_,U)=>{const W=R.get(_);R.set(_,W===void 0?U:W+U)},H=()=>{m&&u+h>c&&(c=u+h),m=!1},L=()=>{H(),l+=1,m=!0,u=0;const _=R.get(l-1);_!==void 0&&(h+=_)};for(let _=t.indexOf("<");_!==-1;_=t.indexOf("<",_+1)){const U=t.charCodeAt(_+1);if(U===Ts){Zd(t,_)&&H();continue}if(U!==mc||!is(t.charCodeAt(_+3)))continue;const W=t.charCodeAt(_+2);if(W===hc)L();else if(W===Kd||W===pc){m||L();const k=_+3,x=s(k),z=n(k,x);u+=z;const I=r(k,x);I>1&&(N(l,z),N(l-1+I,-z))}}return H(),{rows:l,cols:c}},gc=e=>{const t=[],n=new Map;return{intern:o=>{const s=e(o),l=n.get(s);if(l!==void 0)return l;const c=t.length;return t.push(o),n.set(s,c),c},entries:t}},wc=()=>{const e=new WeakMap,t=gc(r=>JSON.stringify(r));return{intern:r=>{if(e.has(r))return e.get(r);const o=gt(r),s=o===void 0?void 0:t.intern(o);return e.set(r,s),s},entries:t.entries}},Qd=()=>{const e=new WeakMap,t=gc(gr);return{intern:r=>{const o=e.get(r);if(o!==void 0)return o;const s=t.intern(r);return e.set(r,s),s},entries:t.entries}},ef=new Set(["http:","https:","mailto:","tel:"]),sn=e=>{const t=e.trim();if(!URL.canParse(t))return null;const n=new URL(t);return ef.has(n.protocol)?n.href:null},Un=e=>{if(e===void 0)return;const t=sn(e);return t===null?void 0:t},Cc=(e,t)=>e.startCol===0&&e.endCol===t-1,bc=(e,t)=>e.startRow===0&&e.endRow===t-1,cs=13,Pt=Object.freeze({style:Object.freeze({}),lineBoxPx:cs,verticalAlign:"middle"}),tf={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",transparent:"#00000000"},nf=new Map(Object.entries(tf)),rf=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/,of=/^rgba?\((.*)\)$/,yc=/^(\d+(?:\.\d+)?)%$/,Pr=e=>e.toString(16).padStart(2,"0"),jo=e=>{const t=yc.exec(e);if(t!==null){const r=Number(t[1]);return r<=100?Math.round(r*255/100):null}if(!/^\d+$/.test(e))return null;const n=Number(e);return n<=255?n:null},sf=e=>{const t=yc.exec(e);if(t!==null){const r=Number(t[1]);return r<=100?Math.round(r*255/100):null}if(!/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(e))return null;const n=Number(e);return n<=1?Math.round(n*255):null},lf=e=>{const t=e.trim().split(/\s*[,/]\s*|\s+/);if(t.length!==3&&t.length!==4)return null;const n=jo(t[0]),r=jo(t[1]),o=jo(t[2]);if(n===null||r===null||o===null)return null;const s=`#${Pr(n)}${Pr(r)}${Pr(o)}`;if(t.length===3)return s;const l=sf(t[3]);return l===null?null:l===255?s:`${s}${Pr(l)}`},Ze=e=>{const t=e.trim().toLowerCase(),n=rf.exec(t);if(n!==null){const s=n[1],l=s.length<=4?s.replace(/./g,c=>c+c):s;return l.length===8&&l.endsWith("ff")?`#${l.slice(0,6)}`:`#${l}`}const r=of.exec(t);if(r!==null)return lf(r[1]);const o=nf.get(t);return o===void 0?null:o},Bl={thin:{width:1,line:"solid"},medium:{width:2,line:"solid"},thick:{width:3,line:"solid"},dashed:{width:1,line:"dashed"},dotted:{width:1,line:"dotted"},double:{width:3,line:"double"},hair:{width:1,line:"dotted"}},Vl=e=>{if(!Object.hasOwn(Bl,e.style))return null;const t=Bl[e.style],n=e.color===void 0?Ss:Ze(e.color);return n===null?null:`${t.width}px ${t.line} ${n}`},cf={top:"flex-start",middle:"center",bottom:"flex-end"},af=e=>e==="left"||e==="center"||e==="right",Rc=e=>e==="top"||e==="middle"||e==="bottom",vc=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e*4/3:null,Sc=(e,t)=>{if(typeof e.background=="string"){const s=Ze(e.background);s!==null&&(t.background=s)}if(typeof e.color=="string"){const s=Ze(e.color);s!==null&&(t.color=s)}e.bold===!0&&(t.fontWeight="bold"),e.italic===!0&&(t.fontStyle="italic");const n=e.underline===!0,r=e.strikethrough===!0;(n||r)&&(t.textDecoration=n&&r?"underline line-through":n?"underline":"line-through"),typeof e.fontFamily=="string"&&e.fontFamily.trim()!==""&&(t.fontFamily=e.fontFamily);const o=vc(e.fontSize);o!==null&&(t.fontSize=`${o}px`),e.wrap===!0&&(t.whiteSpace="pre-wrap")},_r=(e,t)=>{const n=e===void 0?null:Vl(e);return n!==null?n:t===void 0?null:Vl(t)},Ho=(e,t,n,r,o)=>{const s={},l={};e!==void 0&&(af(e.align)&&(l["data-aqsp-align"]=e.align,s.justifyContent=fr(e.align)),Rc(e.verticalAlign)&&(l["data-aqsp-valign"]=e.verticalAlign,s.alignItems=cf[e.verticalAlign]),e.wrap===!0&&(l["data-aqsp-wrap"]=""),Sc(e,s));const c=e?.borders,u=_r(c?.right,t);u!==null&&(s.borderRight=u);const h=_r(c?.bottom,n);if(h!==null&&(s.borderBottom=h),r){const m=_r(c?.left,void 0);m!==null&&(s.borderLeft=m)}if(o){const m=_r(c?.top,void 0);m!==null&&(s.borderTop=m)}return Object.keys(s).length===0&&Object.keys(l).length===0?null:Object.freeze({style:Object.freeze(s),attrs:Object.freeze(l)})},Wl=new WeakMap,uf=(e,t,n,r,o)=>{const s=t?.borders?.left,l=n?.borders?.top,c=!(r||o)&&s===void 0&&l===void 0;if(e===void 0)return c?null:Ho(void 0,s,l,r,o);if(!c)return Ho(e,s,l,r,o);const u=Wl.get(e);if(u!==void 0)return u;const h=Ho(e,void 0,void 0,!1,!1);return Wl.set(e,h),h},df=e=>{if(e===void 0)return Pt;const t={};Sc(e,t);const n=vc(e.fontSize),r=n===null?cs:Math.round(n),o=Rc(e.verticalAlign)?e.verticalAlign:"middle";return Object.keys(t).length===0&&r===cs&&o==="middle"?Pt:Object.freeze({style:Object.freeze(t),lineBoxPx:r,verticalAlign:o})},ff="#REF!",pf=11,hf=15,mf=4096,Xr=33,hr=34,$s=36,gf=38,as=39,kc=40,wf=42,Cf=43,bf=44,Ec=45,yf=46,Rf=47,jn=58,vf=59,Sf=60,Ac=61,kf=62,Ef=67,Af=82,co=91,Oc=93,Of=94,xf=95,xc=e=>e>=65&&e<=90||e>=97&&e<=122,Tc=e=>e>=48&&e<=57,Ls=e=>xc(e)||Tc(e)||e===xf||e===yf||e===$s||e>=128,Tf=e=>e===32||e>=9&&e<=13||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279,$f=e=>e===Ac||e===kc||e===bf||e===vf||e===Cf||e===Ec||e===wf||e===Rf||e===Of||e===gf||e===Sf||e===kf||e===jn,$c=(e,t)=>{if(t>=e.length)return!0;const n=e.charCodeAt(t);return!(Ls(n)||n===kc||n===Xr||n===co)},Kl=(e,t)=>{let n=t;for(;n<e.length&&Ls(e.charCodeAt(n));)n+=1;return n},us=(e,t,n)=>{let r=t+1;for(;r<e.length;){if(e.charCodeAt(r)===n){if(e.charCodeAt(r+1)===n){r+=2;continue}return r+1}r+=1}return e.length},Lf=(e,t)=>{let n=0,r=t;for(;r<e.length;){const o=e.charCodeAt(r);if(o===as){r+=2;continue}if(o===co)n+=1;else if(o===Oc&&(n-=1,n===0))return r+1;r+=1}return e.length},Yl=(e,t,n,r,o)=>{const s=r(e,n+1);return s!==null&&$c(e,s.end)?(o.push({start:t,end:s.end,token:{...s.token,sheet:e.slice(t,n)}}),s.end):n+1},Lc=(e,t)=>{const n=[],r=e.length;let o=0;for(;o<r;){const s=e.charCodeAt(o);if(s===hr){o=us(e,o,hr);continue}if(s===as){const u=us(e,o,as);o=e.charCodeAt(u)===Xr?Yl(e,o,u,t,n):u;continue}if(s===co){o=Lf(e,o);continue}if(!Ls(s)){o+=1;continue}const l=t(e,o);if(l!==null&&$c(e,l.end)){n.push({start:o,end:l.end,token:l.token}),o=l.end;continue}let c=Kl(e,o);if(e.charCodeAt(c)===jn){const u=Kl(e,c+1);u>c+1&&e.charCodeAt(u)===Xr&&(c=u)}o=e.charCodeAt(c)===Xr?Yl(e,o,c,t,n):c}return n},Bo=(e,t)=>{let n=t;const r=e.charCodeAt(n)===$s;r&&(n+=1);let o=0,s=0;for(;n<e.length;){const l=e.charCodeAt(n);if(!xc(l))break;if(s+=1,s>pf)return null;o=o*26+(l&31),n+=1}return s===0?null:{end:n,col:o-1,abs:r}},ds=(e,t)=>{let n=t,r=0;for(;n<e.length;){const o=e.charCodeAt(n);if(!Tc(o))break;if(n-t>=hf)return null;r=r*10+(o-48),n+=1}return n===t?null:{end:n,value:r}},qr=(e,t)=>{const n=e.charCodeAt(t)===$s,r=ds(e,n?t+1:t);return r===null||r.value===0?null:{end:r.end,index:r.value-1,abs:n}},Df=(e,t)=>{const n=Bo(e,t);if(n!==null){const o=qr(e,n.end);if(o!==null){if(e.charCodeAt(o.end)===jn){const s=Bo(e,o.end+1);if(s!==null){const l=qr(e,s.end);if(l!==null)return{end:l.end,token:{kind:"range",start:{row:o.index,col:n.col,absRow:o.abs,absCol:n.abs},end:{row:l.index,col:s.col,absRow:l.abs,absCol:s.abs}}}}}return{end:o.end,token:{kind:"cell",row:o.index,col:n.col,absRow:o.abs,absCol:n.abs}}}if(e.charCodeAt(n.end)===jn){const s=Bo(e,n.end+1);if(s!==null)return{end:s.end,token:{kind:"column",start:{col:n.col,abs:n.abs},end:{col:s.col,abs:s.abs}}}}return null}const r=qr(e,t);if(r!==null&&e.charCodeAt(r.end)===jn){const o=qr(e,r.end+1);if(o!==null)return{end:o.end,token:{kind:"row",start:{row:r.index,abs:r.abs},end:{row:o.index,abs:o.abs}}}}return null},yr=e=>Lc(e,Df),Dc=(e,t=mf)=>{if(!Number.isInteger(t)||t<=0)throw new RangeError(`[spreadsheet] createFormulaMemo requires a positive integer limit, received ${t}`);const n=new Map;return r=>{const o=n.get(r);if(o!==void 0)return o;n.size>=t&&n.clear();const s=e(r);return n.set(r,s),s}},fs=e=>{let t=e+1,n="";for(;t>0;){const r=(t-1)%26;n=String.fromCharCode(65+r)+n,t=Math.floor((t-1)/26)}return n},Vo=e=>`${e.absCol?"$":""}${fs(e.col)}${e.absRow?"$":""}${e.row+1}`,Ds=e=>e.sheet===void 0?"":`${e.sheet}!`,tn=e=>{const t=Ds(e);switch(e.kind){case"cell":return`${t}${Vo(e)}`;case"range":return`${t}${Vo(e.start)}:${Vo(e.end)}`;case"column":return`${t}${e.start.abs?"$":""}${fs(e.start.col)}:${e.end.abs?"$":""}${fs(e.end.col)}`;case"row":return`${t}${e.start.abs?"$":""}${e.start.row+1}:${e.end.abs?"$":""}${e.end.row+1}`}},Fn=(e,t)=>{if(!Number.isInteger(e)||e<0)throw new RangeError(`[spreadsheet] ${t} must be a non-negative integer, received ${e}`)},Mf=(e,t)=>{const n="startRow"in e?e:{startRow:e.row,startCol:e.col,endRow:e.row,endCol:e.col};switch(Fn(n.startRow,"formatRangeReference startRow"),Fn(n.startCol,"formatRangeReference startCol"),Fn(n.endRow,"formatRangeReference endRow"),Fn(n.endCol,"formatRangeReference endCol"),t){case"columns":return tn({kind:"column",start:{col:n.startCol,abs:!1},end:{col:n.endCol,abs:!1}});case"rows":return tn({kind:"row",start:{row:n.startRow,abs:!1},end:{row:n.endRow,abs:!1}});case"cells":return n.startRow===n.endRow&&n.startCol===n.endCol?tn({kind:"cell",row:n.startRow,col:n.startCol,absRow:!1,absCol:!1}):tn({kind:"range",start:{row:n.startRow,col:n.startCol,absRow:!1,absCol:!1},end:{row:n.endRow,col:n.endCol,absRow:!1,absCol:!1}})}},Ms=(e,t,n)=>{if(t.length===0)return e;let r="",o=0;for(const s of t){const l=n(s.token);r+=e.slice(o,s.start)+(l===null?`${Ds(s.token)}${ff}`:l),o=s.end}return r+e.slice(o)},ao=e=>e.charCodeAt(0)===Ac,Wo=(e,t,n)=>{const r=e.absRow?e.row:e.row+t,o=e.absCol?e.col:e.col+n;return r<0||o<0?null:{row:r,col:o,absRow:e.absRow,absCol:e.absCol}},zf=(e,t,n)=>{switch(e.kind){case"cell":{const r=Wo(e,t,n);return r===null?null:{...e,...r}}case"range":{const r=Wo(e.start,t,n),o=Wo(e.end,t,n);return r===null||o===null?null:{...e,start:r,end:o}}case"column":{const r=e.start.abs?e.start.col:e.start.col+n,o=e.end.abs?e.end.col:e.end.col+n;return r<0||o<0?null:{...e,start:{col:r,abs:e.start.abs},end:{col:o,abs:e.end.abs}}}case"row":{const r=e.start.abs?e.start.row:e.start.row+t,o=e.end.abs?e.end.row:e.end.row+t;return r<0||o<0?null:{...e,start:{row:r,abs:e.start.abs},end:{row:o,abs:e.end.abs}}}}},Mc=(e,t,n)=>{if(!(Number.isInteger(t)&&Number.isInteger(n)))throw new RangeError(`[spreadsheet] shiftFormula requires integer deltas, received ${t}, ${n}`);return ao(e)?Ms(e,yr(e),r=>{const o=zf(r,t,n);return o===null?null:tn(o)}):e},zc=(e,t)=>{Fn(e.row,`${t} origin.row`),Fn(e.col,`${t} origin.col`)},Pn=(e,t,n,r)=>n?`${e}${t+1}`:`${e}[${t-r}]`,Ko=(e,t)=>`${Pn("R",e.row,e.absRow,t.row)}${Pn("C",e.col,e.absCol,t.col)}`,Nf=(e,t)=>{const n=Ds(e);switch(e.kind){case"cell":return`${n}${Ko(e,t)}`;case"range":return`${n}${Ko(e.start,t)}:${Ko(e.end,t)}`;case"column":return`${n}${Pn("C",e.start.col,e.start.abs,t.col)}:${Pn("C",e.end.col,e.end.abs,t.col)}`;case"row":return`${n}${Pn("R",e.start.row,e.start.abs,t.row)}:${Pn("R",e.end.row,e.end.abs,t.row)}`}},uo=(e,t)=>(zc(t,"toR1C1"),ao(e)?Ms(e,yr(e),n=>Nf(n,t)):e),Ul=(e,t,n)=>{const r=e.charCodeAt(t);if(r!==n&&r!==n+32)return null;const o=t+1;if(e.charCodeAt(o)===co){const l=e.charCodeAt(o+1)===Ec,c=ds(e,l?o+2:o+1);return c===null||e.charCodeAt(c.end)!==Oc?null:{end:c.end+1,axis:{rel:!0,n:l?-c.value:c.value}}}const s=ds(e,o);return s===null?{end:o,axis:{rel:!0,n:0}}:s.value===0?null:{end:s.end,axis:{rel:!1,n:s.value}}},Xl=(e,t)=>{const n=Ul(e,t,Af),r=Ul(e,n===null?t:n.end,Ef);return n!==null&&r!==null?{end:r.end,shape:"cell",cell:{row:n.axis,col:r.axis}}:n!==null?{end:n.end,shape:"row",row:n.axis}:r===null?null:{end:r.end,shape:"column",col:r.axis}},Ff=e=>{switch(e.shape){case"cell":return{shape:"cell",start:e.cell,end:null};case"row":return{shape:"row",start:e.row,end:null};case"column":return{shape:"column",start:e.col,end:null}}},Pf=(e,t)=>e.shape==="cell"&&t.shape==="cell"?{shape:"cell",start:e.cell,end:t.cell}:e.shape==="row"&&t.shape==="row"?{shape:"row",start:e.row,end:t.row}:e.shape==="column"&&t.shape==="column"?{shape:"column",start:e.col,end:t.col}:null,_f=(e,t)=>{const n=Xl(e,t);if(n===null)return null;if(e.charCodeAt(n.end)===jn){const r=Xl(e,n.end+1);if(r!==null){const o=Pf(n,r);if(o!==null)return{end:r.end,token:o}}}return{end:n.end,token:Ff(n)}},qf=e=>Lc(e,_f),If=Dc(qf),_n=(e,t)=>e.rel?t+e.n:e.n-1,Gl=(e,t)=>{const n=_n(e.row,t.row),r=_n(e.col,t.col);return n<0||r<0?null:{row:n,col:r,absRow:!e.row.rel,absCol:!e.col.rel}},jf=(e,t)=>{const n=e.sheet===void 0?{}:{sheet:e.sheet};switch(e.shape){case"cell":{const r=Gl(e.start,t);if(r===null)return null;if(e.end===null)return{kind:"cell",...r,...n};const o=Gl(e.end,t);return o===null?null:{kind:"range",start:r,end:o,...n}}case"row":{const r=e.end===null?e.start:e.end,o=_n(e.start,t.row),s=_n(r,t.row);return o<0||s<0?null:{kind:"row",start:{row:o,abs:!e.start.rel},end:{row:s,abs:!r.rel},...n}}case"column":{const r=e.end===null?e.start:e.end,o=_n(e.start,t.col),s=_n(r,t.col);return o<0||s<0?null:{kind:"column",start:{col:o,abs:!e.start.rel},end:{col:s,abs:!r.rel},...n}}}},Rr=(e,t)=>(zc(t,"fromR1C1"),ao(e)?Ms(e,If(e),n=>{const r=jf(n,t);return r===null?null:tn(r)}):e),Zl=(e,t)=>e||t?e&&t?{absCol:!1,absRow:!0}:!e&&t?{absCol:!0,absRow:!1}:{absCol:!1,absRow:!1}:{absCol:!0,absRow:!0},Hf=e=>{switch(e.kind){case"cell":return{...e,...Zl(e.absCol,e.absRow)};case"range":{const t=Zl(e.start.absCol,e.start.absRow);return{...e,start:{...e.start,...t},end:{...e.end,...t}}}case"column":{const t=!e.start.abs;return{...e,start:{col:e.start.col,abs:t},end:{col:e.end.col,abs:t}}}case"row":{const t=!e.start.abs;return{...e,start:{row:e.start.row,abs:t},end:{row:e.end.row,abs:t}}}}},Nc=(e,t)=>ao(e)&&Number.isInteger(t)&&t>=1&&t<=e.length,Fc=(e,t)=>{if(!Nc(e,t))return null;for(const n of yr(e))if(n.start<=t&&t<=n.end)return n;return null},Bf=(e,t)=>{const n=Fc(e,t);if(n===null)return null;const r=tn(Hf(n.token));return{text:`${e.slice(0,n.start)}${r}${e.slice(n.end)}`,caret:n.start+r.length}},Jl=(e,t)=>{let n=-1,r=0;for(;r<t;){const o=e.charCodeAt(r);if(o===hr){const s=us(e,r,hr);if(s>t)return!1;n=hr,r=s;continue}Tf(o)||(n=o),r+=1}return $f(n)},Pc=(e,t)=>{if(!Nc(e,t))return null;for(const n of yr(e))if(n.start<=t&&t<=n.end)return Jl(e,n.start)?{replace:[n.start,n.end]}:null;return Jl(e,t)?{insertAt:t}:null},Kn=[{code:"JPY",symbol:"¥",lcid:"411",locale:"ja-JP",digits:0},{code:"USD",symbol:"$",lcid:"409",locale:"en-US",digits:2},{code:"EUR",symbol:"€",lcid:"407",locale:"de-DE",digits:2},{code:"GBP",symbol:"£",lcid:"809",locale:"en-GB",digits:2},{code:"CNY",symbol:"¥",lcid:"804",locale:"zh-CN",digits:2},{code:"KRW",symbol:"₩",lcid:"412",locale:"ko-KR",digits:0},{code:"AUD",symbol:"$",lcid:"c09",locale:"en-AU",digits:2},{code:"CAD",symbol:"$",lcid:"1009",locale:"en-CA",digits:2},{code:"CHF",symbol:"CHF",lcid:"807",locale:"de-CH",digits:2},{code:"INR",symbol:"₹",lcid:"4009",locale:"en-IN",digits:2},{code:"HKD",symbol:"HK$",lcid:"c04",locale:"zh-HK",digits:2},{code:"SGD",symbol:"$",lcid:"1004",locale:"zh-SG",digits:2},{code:"TWD",symbol:"NT$",lcid:"404",locale:"zh-TW",digits:2},{code:"EUR",symbol:"€",lcid:"40c",locale:"fr-FR",digits:2},{code:"EUR",symbol:"€",lcid:"410",locale:"it-IT",digits:2},{code:"EUR",symbol:"€",lcid:"c0a",locale:"es-ES",digits:2},{code:"EUR",symbol:"€",lcid:"413",locale:"nl-NL",digits:2},{code:"EUR",symbol:"€",lcid:"816",locale:"pt-PT",digits:2},{code:"EUR",symbol:"€",lcid:"1809",locale:"en-IE",digits:2},{code:"NZD",symbol:"$",lcid:"1409",locale:"en-NZ",digits:2},{code:"MXN",symbol:"$",lcid:"80a",locale:"es-MX",digits:2},{code:"BRL",symbol:"R$",lcid:"416",locale:"pt-BR",digits:2}],fo=(e,t)=>`[$${e}-${t}]`,Vf=new Map(Kn.map(e=>[fo(e.symbol,e.lcid),e])),Wf=new Map(Kn.filter((e,t)=>Kn.findIndex(n=>n.code===e.code)===t).map(e=>[e.code,e]));new Map(Kn.map(e=>[fo(e.symbol,e.lcid),e.code]));const Kf=new Set([...Kn.map(e=>e.symbol),...Kn.map(e=>e.code),"¥"]),Yf=20,Uf="yyyy/MM/dd",_c=/yyyy|MM|dd|HH|mm|ss/g,qc=" -+/():!^&'~{}<>=",Xf="$¥€£₩₹¥",ps=e=>{let t="",n=0;for(;n<e.length;){const r=e[n];if(r!=="\\"){t+=r,n+=1;continue}const o=e.slice(n+1,n+5);if(/^[0-9a-fA-F]{4}$/.test(o)){t+=String.fromCharCode(Number.parseInt(o,16)),n+=5;continue}if(n+1<e.length){t+=e[n+1],n+=2;continue}t+=r,n+=1}return t},Gf=e=>{let t=0;for(;t<e.length;){const n=e[t];if(n==='"'){const r=e.indexOf('"',t+1);t=r<0?e.length:r+1}else if(n==="["){const r=e.indexOf("]",t+1);t=r<0?e.length:r+1}else if(n==="\\"||n==="_"||n==="*")t+=2;else{if(n===";")return e.slice(0,t);t+=1}}return e},Zf=e=>{const t=[],n=o=>{const s=t[t.length-1];s!==void 0&&s.kind==="literal"?t[t.length-1]={kind:"literal",text:s.text+o}:t.push({kind:"literal",text:o})};let r=0;for(;r<e.length;){const o=e[r];if(o==='"'){const s=e.indexOf('"',r+1);if(s<0)return null;n(e.slice(r+1,s)),r=s+1}else if(o==="\\"){if(r+1>=e.length)return null;n(e[r+1]),r+=2}else if(o==="_"||o==="*"){if(r+1>=e.length)return null;r+=2}else if(o==="["){const s=e.indexOf("]",r+1),l=s<0?"":e.slice(r+1,s);if(s<0||l[0]!=="$")return null;const c=l.slice(1),u=c.lastIndexOf("-"),h=u<0?c:c.slice(0,u),m=u<0?null:c.slice(u+1);if(m!==null&&!/^[0-9a-fA-F]{1,8}$/.test(m)||h===""&&m===null)return null;const R=m===null?null:Number.parseInt(m,16).toString(16);t.push(h===""?{kind:"locale"}:{kind:"currency",symbol:h,lcid:R}),r=s+1}else if(o==="%")t.push({kind:"percent"}),r+=1;else if("#0?,.".includes(o)){let s=r;for(;s<e.length&&"#0?,.".includes(e[s]);)s+=1;const l=e.slice(r,s);/[#0?]/.test(l)?t.push({kind:"digits",text:l}):n(l),r=s}else if(/[A-Za-z]/.test(o))if((o==="E"||o==="e")&&(e[r+1]==="+"||e[r+1]==="-")){let s=r+2;for(;e[s]==="0";)s+=1;if(s===r+2)return null;t.push({kind:"exponent"}),r=s}else{let s=r;for(;s<e.length&&e[s].toLowerCase()===o.toLowerCase();)s+=1;t.push({kind:"date",text:e.slice(r,s).toLowerCase()}),r=s}else if(qc.includes(o)||Xf.includes(o)||o.charCodeAt(0)>=128)n(o),r+=1;else return null}return t},ht=e=>e===void 0?{}:{locale:e},Jf=/^(0|#,##0)(?:\.(0+))?$/,Ql=(e,t,n,r)=>{if(t!==null){const o=Vf.get(fo(e,t));return o===void 0?void 0:{type:"currency",currency:o.code,decimals:n,locale:o.locale}}if(!(!Kf.has(e)||r.currency===void 0))return{type:"currency",currency:r.currency,decimals:n,...ht(r.locale)}},Qf=(e,t)=>{let n="",r=!1,o=null,s=!1,l=0,c="",u="";for(const L of e)switch(L.kind){case"locale":break;case"literal":r?u+=L.text:c+=L.text;break;case"digits":if(r)return;n=L.text,r=!0;break;case"currency":if(o!==null)return;o=L;break;case"percent":l+=1;break;case"exponent":if(s||!r)return;s=!0;break;default:return}const h=Jf.exec(n);if(h===null)return;const m=h[1]==="#,##0",R=h[2]===void 0?0:h[2].length,N=c.trim(),H=u.trim();if(s)return l===0&&o===null&&!m&&N===""&&H===""?{type:"scientific",decimals:R,...ht(t.locale)}:void 0;if(l>0)return l===1&&o===null&&N===""&&H===""?{type:"percent",decimals:R,...ht(t.locale)}:void 0;if(H==="%"&&N===""&&o===null)return{type:"percent",decimals:R,scale:!1,...ht(t.locale)};if(o!==null)return N===""&&H===""?Ql(o.symbol,o.lcid,R,t):void 0;if(!(N!==""&&H!==""))return N!==""||H!==""?Ql(N+H,null,R,t):{type:"number",decimals:R,...m?{grouping:!0}:{},...ht(t.locale)}},ep=new Map([["yyyy","yyyy"],["dd","dd"],["hh","HH"],["ss","ss"]]),tp=(e,t)=>{const n=[...e.matchAll(_c)];return n.length===t.length&&n.every((r,o)=>r.index===t[o].index&&r[0]===t[o].text)},np=e=>{const t=e.flatMap(s=>s.kind==="date"?[s.text]:[]),n=[];let r="",o=0;for(const s of e){if(s.kind==="locale")continue;if(s.kind==="literal"){r+=s.text;continue}if(s.kind!=="date")return;const l=s.text==="mm"?t[o-1]==="hh"||t[o+1]==="ss"?"mm":"MM":ep.get(s.text);if(o+=1,l===void 0)return;n.push({index:r.length,text:l}),r+=l}return n.length>0&&tp(r,n)?{type:"date",pattern:r}:void 0},rp=new Map([["General",()=>{}],["@",()=>({type:"text"})],["Fixed",e=>({type:"number",decimals:2,...ht(e.locale)})],["Standard",e=>({type:"number",decimals:2,grouping:!0,...ht(e.locale)})],["Percent",e=>({type:"percent",decimals:2,...ht(e.locale)})],["Scientific",e=>({type:"scientific",decimals:2,...ht(e.locale)})],["Currency",e=>e.currency===void 0?void 0:{type:"currency",currency:e.currency,decimals:2,...ht(e.locale)}],["Euro Currency",e=>({type:"currency",currency:"EUR",decimals:2,...ht(e.locale)})],["Short Date",()=>({type:"date"})],["Short Time",()=>({type:"date",pattern:"HH:mm"})]]),zs=(e,t)=>{const n=Gf(e).trim(),r=rp.get(n);if(r!==void 0)return r(t);const o=Zf(n);if(o!==null){if(o.some(s=>s.kind==="digits"))return Qf(o,t);if(o.some(s=>s.kind==="date"))return np(o)}},op=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;const r=n,o=r[1],s=r[2];if(typeof o!="number"||!Number.isInteger(o)||o<0||o>8||s!==void 0&&typeof s!="string"||o===0)return;if(o===1)return{type:"text"};const l=s===void 0?void 0:zs(s,t);return o===5?l!==void 0&&l.type==="date"?l:{type:"date"}:l},ar=e=>e===0?"":`.${"0".repeat(e)}`,Gr=e=>e!==void 0&&Number.isInteger(e)&&e>=0&&e<=Yf,sp=`${qc}.,`,ei=e=>e.includes('"')?null:[...e].every(t=>sp.includes(t))?e:`"${e}"`,lp=e=>{const t=[];let n=0,r=0;for(const c of e.matchAll(_c)){const u=ei(e.slice(r,c.index));if(u===null)return null;t.push(u,c[0].toLowerCase()),n+=1,r=c.index+c[0].length}const o=ei(e.slice(r));if(o===null||n===0)return null;t.push(o);const s=t.join(""),l=zs(s,{});return l!==void 0&&l.type==="date"&&l.pattern===e?s:null},ip=e=>{const t=Wf.get(e.currency.toUpperCase());if(t===void 0)return null;const n=e.decimals===void 0?t.digits:e.decimals;if(!Gr(n))return null;const r=`#,##0${ar(n)}`;return t.code==="USD"&&e.locale==="en-US"?`"$"${r}`:`${fo(t.symbol,t.lcid)}${r}`},Ic=e=>{switch(e.type){case"text":return"@";case"date":return lp(e.pattern===void 0?Uf:e.pattern);case"number":return Gr(e.decimals)?`${e.grouping===!0?"#,##0":"0"}${ar(e.decimals)}`:null;case"percent":{const t=e.decimals===void 0?0:e.decimals;return Gr(t)?e.scale===!1?`0${ar(t)}"%"`:`0${ar(t)}%`:null}case"scientific":return Gr(e.decimals)?`0${ar(e.decimals)}E+00`:null;case"currency":return ip(e);default:return null}},ti="-−",cp=(e,t)=>{if(t===""||!e.includes(t))return/^\d+$/.test(e)?e:null;const n=e.split(t);return!/^\d{1,3}$/.test(n[0])||n.slice(1).some(r=>!/^\d{3}$/.test(r))?null:n.join("")},ap=(e,t,n,r)=>{const o=/^(.*?)[eE]([+-]?\d{1,4})$/.exec(e);if(o!==null&&r==="none"||o===null&&r==="required")return null;const s=o===null?e:o[1],l=o===null?0:Number(o[2]),c=s.split(n);if(c.length>2)return null;const u=c.length===2?c[1]:"";if(c.length===2&&!/^\d+$/.test(u))return null;const h=cp(c[0],t);return h===null?null:{integer:h,fraction:u,exponent:l}},up=(e,t,n,r)=>{const o=e+t,s=e.length+n;let l,c;s<=0?(l="0",c="0".repeat(-s)+o):s>=o.length?(l=o+"0".repeat(s-o.length),c=""):(l=o.slice(0,s),c=o.slice(s)),l=l.replace(/^0+(?=\d)/,""),c=c.replace(/0+$/,"");const u=c===""?l:`${l}.${c}`;return r&&u!=="0"?`-${u}`:u},dp=(e,t,n)=>{if(n.decimal===""||n.group===n.decimal)throw new RangeError(`numberDisplayToCanonical: separators must declare a non-empty decimal separator distinct from the group separator (got group="${n.group}", decimal="${n.decimal}")`);if(t!==void 0&&(t.type==="date"||t.type==="text"))return e;const r=t===void 0?"general":t.type;let o=e.trim(),s=!1;if(o.startsWith("(")&&o.endsWith(")")&&(s=!0,o=o.slice(1,-1).trim()),r==="percent"){if(!o.endsWith("%"))return e;o=o.slice(0,-1).trim()}else if(o.includes("%"))return e;const l=r==="general"?"":n.group,c=r==="scientific"||r==="general",u=z=>z>="0"&&z<="9"||l!==""&&l.includes(z)||n.decimal.includes(z)||c&&(z==="e"||z==="E");let h=0;for(;h<o.length&&!u(o[h]);)h+=1;let m=o.length;for(;m>h&&!u(o[m-1]);)m-=1;let R=0,N=0,H=0,L="";for(const z of o.slice(0,h))ti.includes(z)?R+=1:z==="("?N+=1:L+=z;for(const z of o.slice(m))ti.includes(z)?R+=1:z===")"?H+=1:L+=z;const _=R+N;if(N!==H||_>1||_===1&&s||(s=s||_===1,r!=="currency"&&L.trim()!==""))return e;const U=ap(o.slice(h,m).trim(),l,n.decimal,r==="scientific"?"required":r==="general"?"optional":"none");if(U===null)return e;const W=t!==void 0&&t.type==="percent"&&t.scale!==!1?-2:0,k=U.exponent+W;if(k>330||k<-330)return e;const x=up(U.integer,U.fraction,k,s);return Number.isFinite(Number(x))?x:e},ni="google-sheets-html-origin",jc=Object.freeze({group:",",decimal:"."}),ri=Object.freeze({thin:".5pt solid",medium:"1.0pt solid",thick:"1.5pt solid",dashed:".5pt dashed",dotted:".5pt dotted",double:"1.5pt double",hair:".5pt hairline"}),Hc=["top","right","bottom","left"],fp=new Set(["solid","dashed","dotted","double","hairline","none","hidden","groove","ridge","inset","outset"]),pp=new Set(["windowtext","currentcolor","inherit","initial","unset"]),hp=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),oi=["","#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#ERROR!"],mp=Object.freeze({number:2,percent:3,currency:4,scientific:8}),gp=new Set(["script","style","template","noscript","rt","rp","img","svg","video","audio","picture","canvas","iframe","object","textarea","select","button","input"]),wp=new Set(["div","p","li","ul","ol","dl","dt","dd","h1","h2","h3","h4","h5","h6","blockquote","pre","section","article","header","footer","table","tr","hr"]),Cp=new Set(["b","strong","i","em","u","s","strike","del","a","font","span"]),bp=3,yp=1,Bc=-25569,Zr=86400,Rp=-693959,vp=2958465,Sp=" ",po=e=>{const t=new Map;let n=0,r=null,o=0;const s=l=>{const c=e.slice(n,l),u=c.indexOf(":");if(u>0){const h=c.slice(0,u).trim().toLowerCase(),m=c.slice(u+1).trim();h!==""&&m!==""&&t.set(h,m)}n=l+1};for(let l=0;l<e.length;l+=1){const c=e[l];r!==null?c==="\\"?l+=1:c===r&&(r=null):c==='"'||c==="'"?r=c:c==="("?o+=1:c===")"?o=o>0?o-1:0:c===";"&&o===0&&s(l)}return s(e.length),t},ro=e=>{const t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.endsWith(t)?e.slice(1,-1):e},Ns=e=>{const t=[];let n="",r=0;for(const o of e)o==="("?r+=1:o===")"&&(r=r>0?r-1:0),r===0&&/\s/.test(o)?n!==""&&(t.push(n),n=""):n+=o;return n!==""&&t.push(n),t},kp=/^(?:[a-z][a-z0-9]*)?\.([A-Za-z_-][\w-]*)$/i,Ep=e=>{const t=new Map;let n=null,r=null;for(const s of e.querySelectorAll("style")){const l=s.innerHTML.replaceAll("<!--","").replaceAll("-->","").replace(/\/\*[\s\S]*?\*\//g,"");let c=0;for(;c<l.length;){const u=l.indexOf("{",c);if(u===-1)break;const h=l.indexOf("}",u+1);if(h===-1)break;const m=l.slice(c,u),R=l.slice(u+1,h);if(c=h+1,m.trim().startsWith("@"))continue;const N=po(R);for(const H of m.split(",")){const L=H.trim(),_=kp.exec(L);if(_!==null){const U=t.get(_[1]);if(U===void 0)t.set(_[1],new Map(N));else for(const[W,k]of N)U.set(W,k)}else if(L.toLowerCase()==="table"){const U=N.get("mso-displayed-decimal-separator"),W=N.get("mso-displayed-thousand-separator");U!==void 0&&(n=ps(ro(U))),W!==void 0&&(r=ps(ro(W)))}}}}return{classes:t,separators:n!==null&&r!==null&&n!==""&&r!==n?{group:r,decimal:n}:jc}},Ap="%_-*? ",Op=e=>{let t="";for(const n of e)n==='"'?t+="\\0022":n==="\\"?t+="\\\\":/[A-Za-z0-9]/.test(n)||Ap.includes(n)||n.charCodeAt(0)>=128?t+=n:t+=`\\${n}`;return t},xp=(e,t,n)=>{const r=t<=2?e-1:e,o=Math.floor(r/400),s=r-o*400,l=t>2?t-3:t+9,c=Math.floor((153*l+2)/5)+n-1,u=s*365+Math.floor(s/4)-Math.floor(s/100)+c;return o*146097+u-719468},Vc=e=>{const t=e+719468,n=Math.floor(t/146097),r=t-n*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),s=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),l=Math.floor((5*s+2)/153),c=s-Math.floor((153*l+2)/5)+1,u=l<10?l+3:l-9;return{year:o+n*400+(u<=2?1:0),month:u,day:c}},Mn=(e,t)=>String(e).padStart(t,"0"),Wc=e=>{if(e<Rp||e>vp)return null;let t=Math.floor(e),n=Math.round((e-t)*Zr);n>=Zr&&(t+=1,n-=Zr);const r=Vc(t+Bc),o=`${Mn(r.year,4)}-${Mn(r.month,2)}-${Mn(r.day,2)}`;if(n===0)return o;const s=Math.floor(n/3600),l=Math.floor(n%3600/60);return`${o} ${Mn(s,2)}:${Mn(l,2)}:${Mn(n%60,2)}`},Tp=/^(\d{4})([-/])(\d{2})\2(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/,$p=e=>{const t=Tp.exec(e);if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);if(r<1||r>12||o<1||s>23||l>59||c>59)return null;const u=xp(n,r,o),h=Vc(u);return h.year!==n||h.month!==r||h.day!==o?null:u-Bc+(s*3600+l*60+c)/Zr},Fs=e=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),pn=e=>Fs(e).replaceAll('"',"&quot;"),Kc=e=>Fs(e).replaceAll("'","&#39;"),Lp=e=>Fs(e).replaceAll(`\r
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Wt=require("./tsv.cjs"),De=require("./view-BkwCUzTl.cjs"),st=require("@aiquants/virtualscroll"),Y=require("react/jsx-runtime"),i=require("react"),As=1e3,an=1e4,xs=10,ql=2**(1/4),Vu=(e,t)=>e<=0?e:t>0?e>=an?e:Math.min(an,Math.max(e+1,Math.round(e*ql))):Math.max(1,Math.min(e-1,Math.round(e/ql))),jl=(e,t)=>t.reduce((n,r)=>{const o=e.sizeOf(r.index)===0,s=r.size===0;return n+(s&&!o?1:0)-(!s&&o?1:0)},0),Ts=(e,t,n,r)=>{if(t.length===0)return{ok:!0,entries:[]};const o=r.axisKind==="row"?Math.floor(r.maxOperationCells/xs):r.maxOperationCells;if(t.length>o)return{ok:!1,reason:"limit",count:t.length};const s=new Map;for(const u of t){if(!(Number.isFinite(u.size)&&u.size>=0))throw new RangeError(`[spreadsheet] gateResizeEntries requires a finite size >= 0, received ${u.size} at index ${u.index}`);s.set(u.index,Math.min(Math.round(u.size),an))}let l=[...s].map(([u,h])=>({index:u,size:h}));if(e.count-e.hiddenCount()-jl(e,l)===0){const u=n===null?l[0].index:n;l=l.map(h=>h.index===u?{index:h.index,size:1}:h)}if(r.axisKind==="row"){const u=e.hiddenCount()+jl(e,l);if(u>r.rowHiddenLimit)return{ok:!1,reason:"bounds",count:u}}return{ok:!0,entries:l}},$s="#000000",Br=e=>e===void 0?{}:{minimumFractionDigits:e,maximumFractionDigits:e},Yu=20,Ku=256,Wr=new Map,Wo=new WeakMap,wt=e=>{const t=e.trim();return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d{1,4})?$/.test(t)&&Number.isFinite(Number(t))?t:null},Uu=(e,t)=>{const n=e.search(/[eE]/);return n<0?`${e}e${t}`:`${e.slice(0,n)}e${Number(e.slice(n+1))+t}`},Xu=e=>{switch(e.type){case"number":return{signDisplay:"negative",useGrouping:e.grouping??!1,...e.decimals===void 0?{maximumFractionDigits:Yu}:Br(e.decimals)};case"percent":return{signDisplay:"negative",style:"percent",...Br(e.decimals)};case"currency":return{signDisplay:"negative",style:"currency",currency:e.currency,...Br(e.decimals)};case"scientific":return{signDisplay:"negative",notation:"scientific",...Br(e.decimals)};default:return null}},Gu=e=>{const t=Wo.get(e);if(t!==void 0)return t;const n=JSON.stringify([e.type,e.locale??null,e.decimals===void 0?null:String(e.decimals),e.type==="number"?e.grouping??!1:null,e.type==="currency"?e.currency:null]),r=Wr.get(n);if(r!==void 0)return Wo.set(e,r),r;Wr.size>=Ku&&Wr.clear();const o=Xu(e);let s=null;if(o!==null)try{s=new Intl.NumberFormat(e.locale,o)}catch{s=null}return Wr.set(n,s),Wo.set(e,s),s},Zu=(e,t)=>{switch(t){case 2:return e%4===0&&e%100!==0||e%400===0?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}},pc=e=>{const t=/^(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);return r<1||r>12||o<1||o>Zu(n,r)||s>23||l>59||c>59?null:{year:n,month:r,day:o,hour:s,minute:l,second:c}},Ju=(e,t)=>{const n=pc(e);if(n===null)return e;const r=(o,s)=>String(o).padStart(s,"0");return t.replace(/yyyy|MM|dd|HH|mm|ss/g,o=>{switch(o){case"yyyy":return r(n.year,4);case"MM":return r(n.month,2);case"dd":return r(n.day,2);case"HH":return r(n.hour,2);case"mm":return r(n.minute,2);default:return r(n.second,2)}})},Xn=(e,t)=>{if(t===void 0||t.type==="text"||e==="")return e;if(t.type==="date")return Ju(e,t.pattern??"yyyy/MM/dd");const n=wt(e);if(n===null)return e;const r=Gu(t);return r===null?e:r.format(t.type==="percent"&&t.scale===!1?Uu(n,-2):n)},Il=(e,t,n)=>e!==void 0?e:t!==void 0&&t.type==="text"?"left":t!==void 0&&t.type==="date"?pc(n)!==null?"right":"left":wt(n)!==null?"right":"left",Rr=e=>e==="center"?"center":e==="right"?"flex-end":"flex-start",hc=["align","background","bold","borders","color","fontFamily","fontSize","italic","strikethrough","underline","value","verticalAlign","wrap"],Qu=["bottom","left","right","top"],mc=(e,t,n)=>{e[t]=n},gc=e=>{const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=t[r]);return n},ed=e=>{if(e===void 0)return;const t={};for(const n of Qu){const r=e[n];r!==void 0&&(t[n]=gc(r))}return Object.keys(t).length===0?void 0:t},xt=e=>{const t={};for(const n of hc){const r=n==="borders"?ed(e.borders):n==="value"?e.value===void 0?void 0:gc(e.value):e[n];r!==void 0&&r!==!1&&mc(t,n,r)}return Object.keys(t).length===0?void 0:t},Ls=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;const o=e,s=t;for(let l=0;l<n.length;l+=1){const c=n[l];if(c!==r[l]||!Ls(o[c],s[c]))return!1}return!0},td=(e,t)=>e===t?!0:Ls(e===void 0?void 0:xt(e),t===void 0?void 0:xt(t)),Ds=(e,t)=>{const n={};for(const o of hc){const s=t[o];mc(n,o,s===void 0?e?.[o]:s===null?void 0:s)}const r=xt(n);return Ls(r,e===void 0?void 0:xt(e))?e:r},wc="data-aqsp-clip",po="application/x-aqsp-clip",us=512,Hl=16*1024,ds=`${wc}=`,nd=16,Ms=()=>{const e=globalThis.crypto;if(e===void 0||typeof e.getRandomValues!="function")throw new RangeError("[spreadsheet] newClipId requires crypto.getRandomValues — there is no counter or randomUUID substitute by design");const t=e.getRandomValues(new Uint8Array(nd));let n="";for(const r of t)n+=r.toString(16).padStart(2,"0");return n},xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=e=>typeof e=="string",rt=e=>typeof e=="boolean",on=e=>typeof e=="number"&&Number.isFinite(e),At=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0,Bl=e=>At(e)&&e>=1,rd=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=an,Bt=e=>{const t=new Set(e);return n=>typeof n=="string"&&t.has(n)},od=e=>t=>Array.isArray(t)&&t.every(e),Me=(e,t)=>({fields:new Map(Object.entries(e)),required:t}),Yt=(e,t)=>{if(!xr(e))return!1;for(const n of Object.keys(e)){const r=e[n];if(r===void 0)continue;const o=t.fields.get(n);if(o===void 0||!o(r))return!1}for(const n of t.required)if(e[n]===void 0)return!1;return!0},zs=e=>t=>{if(!xr(t)||typeof t.type!="string")return!1;const n=e.get(t.type);return n!==void 0&&Yt(t,n)},sd=["left","center","right"],ld=["top","middle","bottom"],id=["thin","medium","thick","dashed","dotted","double","hair"],Vo=["gt","gte","lt","lte","eq","neq","between","notBetween"],cd=["contains","notContains","startsWith","endsWith","isEmail","isUrl"],ad=["eq","neq","gt","gte","lt","lte","between","notBetween"],ud=["contains","notContains","startsWith","endsWith"],dd=new Map([["number",Me({type:ce,decimals:on,grouping:rt,locale:ce},["type"])],["percent",Me({type:ce,decimals:on,scale:rt,locale:ce},["type"])],["currency",Me({type:ce,currency:ce,decimals:on,locale:ce},["type","currency"])],["scientific",Me({type:ce,decimals:on,locale:ce},["type"])],["date",Me({type:ce,pattern:ce},["type"])],["text",Me({type:ce},["type"])]]),fd=Me({style:Bt(id),color:ce},["style"]),Vr=e=>Yt(e,fd),pd=Me({top:Vr,right:Vr,bottom:Vr,left:Vr},[]),hd=Me({value:zs(dd),align:Bt(sd),verticalAlign:Bt(ld),wrap:rt,background:ce,color:ce,bold:rt,italic:rt,underline:rt,strikethrough:rt,fontFamily:ce,fontSize:on,borders:e=>Yt(e,pd)},[]),md=e=>Yt(e,hd),Cn={strict:rt,inputMessage:ce,errorMessage:ce},gd=new Map([["list",Me({...Cn,type:ce,values:od(ce),showDropdown:rt},["type","values"])],["number",Me({...Cn,type:ce,op:Bt(Vo),a:ce,b:ce},["type","op","a"])],["textLength",Me({...Cn,type:ce,op:Bt(Vo),a:on,b:on},["type","op","a"])],["date",Me({...Cn,type:ce,op:Bt(Vo),a:ce,b:ce},["type","op","a"])],["text",Me({...Cn,type:ce,op:Bt(cd),value:ce},["type","op"])],["checkbox",Me({...Cn,type:ce,checked:ce,unchecked:ce},["type"])],["custom",Me({...Cn,type:ce,formula:ce},["type","formula"])]]),wd=zs(gd),Cd=Me({startRow:At,startCol:At,endRow:At,endCol:At},["startRow","startCol","endRow","endCol"]),bd=e=>{if(!Yt(e,Cd))return!1;const{startRow:t,startCol:n,endRow:r,endCol:o}=e;return At(t)&&At(r)&&At(n)&&At(o)&&t<=r&&n<=o},yd=Me({color:ce,value:on},["color"]),Yo=e=>Yt(e,yd),Rd=new Map([["cellValue",Me({type:ce,op:Bt(ad),a:ce,b:ce},["type","op","a"])],["text",Me({type:ce,op:Bt(ud),value:ce},["type","op","value"])],["empty",Me({type:ce},["type"])],["notEmpty",Me({type:ce},["type"])],["colorScale",Me({type:ce,min:Yo,mid:Yo,max:Yo},["type","min","max"])],["customFormula",Me({type:ce,formula:ce},["type","formula"])]]),vd=Me({background:ce,color:ce,bold:rt,italic:rt,underline:rt,strikethrough:rt},[]),Sd=Me({sourceRuleId:ce,ranges:Array.isArray,condition:zs(Rd),style:e=>Yt(e,vd),stopIfTrue:rt},["sourceRuleId","ranges","condition","style"]),kd=(e,t,n)=>{if(!Yt(e,Sd))return!1;const r=e.ranges;if(!Array.isArray(r))return!1;for(const o of r)if(!bd(o)||o.endRow>=t||o.endCol>=n)return!1;return!0},Ed=Me({text:ce,author:ce,createdAt:ce},["text","author","createdAt"]),Od=e=>Yt(e,Ed),Ad=(e,t,n)=>{if(!xr(e)||typeof e.t!="string")return!1;for(const r of Object.keys(e)){const o=e[r];if(o!==void 0)switch(r){case"t":break;case"f":if(typeof o!="string"||!o.startsWith("="))return!1;break;case"fmt":if(!At(o)||o>=t)return!1;break;case"val":if(!At(o)||o>=n)return!1;break;case"note":case"link":if(typeof o!="string")return!1;break;case"comments":if(!(Array.isArray(o)&&o.every(Od)))return!1;break;default:return!1}}return!0},Wl=(e,t)=>Array.isArray(e)&&e.length===t&&e.every(rd),xd=new Set(["v","rows","cols","clipId","formats","validations","cells","colWidths","rowHeights","wholeRows","wholeCols","conditionalFormats"]),Cc=e=>{if(!xr(e))return!1;for(const c of Object.keys(e))if(e[c]!==void 0&&!xd.has(c))return!1;if(e.v!==1)return!1;const t=e.rows,n=e.cols;if(!(Bl(t)&&Bl(n))||typeof e.clipId!="string"||e.clipId==="")return!1;const r=e.formats;if(!(Array.isArray(r)&&r.every(md)))return!1;const o=e.validations;if(!(Array.isArray(o)&&o.every(wd)))return!1;const s=e.cells;if(!Array.isArray(s)||s.length!==t)return!1;for(const c of s){if(!Array.isArray(c)||c.length!==n)return!1;for(const u of c)if(!Ad(u,r.length,o.length))return!1}if(e.colWidths!==void 0&&!Wl(e.colWidths,n)||e.rowHeights!==void 0&&!Wl(e.rowHeights,t)||typeof e.wholeRows!="boolean"||typeof e.wholeCols!="boolean")return!1;const l=e.conditionalFormats;return Array.isArray(l)&&l.every(c=>kd(c,t,n))},Er=e=>Array.isArray(e)?`[${e.map(Er).join(",")}]`:xr(e)?`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Er(e[n])}`).join(",")}}`:JSON.stringify(e),Td=e=>{const t=xt(e);return t===void 0?"{}":JSON.stringify(t)},$d=e=>`{"text":${JSON.stringify(e.text)},"author":${JSON.stringify(e.author)},"createdAt":${JSON.stringify(e.createdAt)}}`,Ld=e=>{let t=`{"t":${JSON.stringify(e.t)}`;return e.f!==void 0&&(t+=`,"f":${JSON.stringify(e.f)}`),e.fmt!==void 0&&(t+=`,"fmt":${e.fmt}`),e.val!==void 0&&(t+=`,"val":${e.val}`),e.note!==void 0&&(t+=`,"note":${JSON.stringify(e.note)}`),e.comments!==void 0&&(t+=`,"comments":[${e.comments.map($d).join(",")}]`),e.link!==void 0&&(t+=`,"link":${JSON.stringify(e.link)}`),`${t}}`},bc=e=>{if(!Cc(e))throw new RangeError("[spreadsheet] serializeClipPayload received a payload outside the wire format v1 vocabulary");const t=`{"v":1,"rows":${e.rows},"cols":${e.cols},"clipId":${JSON.stringify(e.clipId)}`,n=e.formats.map(Td).join(","),r=e.validations.map(Er).join(","),o=e.cells.map(u=>`[${u.map(Ld).join(",")}]`).join(","),s=e.colWidths===void 0?"":`,"colWidths":[${e.colWidths.join(",")}]`,l=e.rowHeights===void 0?"":`,"rowHeights":[${e.rowHeights.join(",")}]`,c=e.conditionalFormats.map(Er).join(",");return`${t},"formats":[${n}],"validations":[${r}],"cells":[${o}]${s}${l},"wholeRows":${e.wholeRows},"wholeCols":${e.wholeCols},"conditionalFormats":[${c}]}`},fs=e=>{let t;try{t=JSON.parse(e)}catch{return null}return Cc(t)?t:null},Dd=/&(?:amp|lt|gt|quot|#39|nbsp);/g,Md=Object.freeze({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&nbsp;":" "}),yc=e=>e.includes("&")?e.replace(Dd,t=>Md[t]):e,zd=/^\{"v":1,"rows":([1-9]\d{0,14}),"cols":([1-9]\d{0,14}),"clipId":"([^"\\]+)"/,Vl=e=>{const t=e.length>us?e.slice(0,us):e,n=zd.exec(yc(t));return n===null?null:{v:1,rows:Number(n[1]),cols:Number(n[2]),clipId:n[3]}},Fd=e=>{const t=e.indexOf(ds);if(t===-1)return null;const n=t+ds.length,r=e.charAt(n);return r!=="'"&&r!=='"'?null:{start:n+1,quote:r}},Rc=(e,t)=>{if(t==="event"&&e.types.includes(po))return{kind:"mime",json:e.getData(po)};if(!e.types.includes("text/html"))return null;const n=e.getData("text/html"),r=Fd(n);return r===null?null:{kind:"attribute",html:n,at:r}},Nd=(e,t)=>{const n=Rc(e,t);return n===null?null:n.kind==="mime"?Vl(n.json):Vl(n.html.slice(n.at.start,n.at.start+us))},Pd=(e,t)=>{const n=Rc(e,t);if(n===null)return null;if(n.kind==="mime")return fs(n.json);const r=n.html.indexOf(n.at.quote,n.at.start);return r===-1?null:fs(yc(n.html.slice(n.at.start,r)))},_d=/<google-sheets-html-origin[\s>]/,qd='data-sheets-root="1"',jd=/<meta\s+name=["']?Generator["']?\s+content=["']?Microsoft Excel/,Id="mso-",Hd=/\.xl\d+\s*\{/,Bd="<table",Wd=e=>e.includes(ds)?"aqsp":_d.test(e)&&e.includes(qd)?"sheets":jd.test(e)||e.includes(Id)||Hd.test(e)?"excel":null,vc=(e,t)=>{if(t==="event"&&e.types.includes(po))return"aqsp";if(e.types.includes("text/html")){const n=e.getData("text/html"),r=n.length>Hl?n.slice(0,Hl):n,o=Wd(r);if(o==="aqsp")return"aqsp";if(n.includes(Bd))return o===null?"html":o}return e.types.includes("text/plain")&&e.getData("text/plain")!==""?"tsv":"none"},Fs=1e3,Sc=65534,Vd=9,Yd=10,Kd=12,Ud=13,Xd=32,kc=34,Ec=39,Gd=43,Ns=47,Yl=48,Zd=57,Jd=61,Qd=62,ef=97,tf=98,nf=100,rf=102,Oc=104,Ac=114,xc=116,of=["able","body","head","foot"],vr=e=>e===Xd||e===Vd||e===Yd||e===Ud||e===Kd,ps=e=>e===Qd||e===Ns||vr(e),sf=e=>vr(e)||e===Ns||e===kc||e===Ec,lf=(e,t,n,r)=>{if(t===0||!sf(e.charCodeAt(t-1)))return null;let o=t+n;for(;vr(e.charCodeAt(o));)o+=1;if(e.charCodeAt(o)!==Jd)return 1;for(o+=1;vr(e.charCodeAt(o));)o+=1;const s=e.charCodeAt(o);for((s===kc||s===Ec)&&(o+=1);vr(e.charCodeAt(o));)o+=1;e.charCodeAt(o)===Gd&&(o+=1);let l=0,c=0;for(let u=e.charCodeAt(o);u>=Yl&&u<=Zd;u=e.charCodeAt(o))l=l*10+(u-Yl),c+=1,o+=1;return c===0||l===0?1:l>r?r:l},Kl=(e,t,n)=>{let r=e.indexOf(t);return(o,s)=>{for(;r!==-1&&r<o;)r=e.indexOf(t,r+t.length);for(;r!==-1&&r<s;r=e.indexOf(t,r+t.length)){const l=lf(e,r,t.length,n);if(l!==null)return l}return 1}},cf=(e,t)=>{if(e.charCodeAt(t+2)!==xc)return!1;const n=e.charCodeAt(t+3);if(n===Ac)return ps(e.charCodeAt(t+4));if(n!==ef&&n!==tf&&n!==Oc&&n!==rf)return!1;for(const r of of)if(e.startsWith(r,t+3)&&ps(e.charCodeAt(t+3+r.length)))return!0;return!1},af=e=>{const t=e.toLowerCase(),n=Kl(t,"colspan",Fs),r=Kl(t,"rowspan",Sc);let o=0;const s=j=>(o!==-1&&o<j&&(o=t.indexOf(">",j)),o===-1?t.length:o);let l=0,c=0,u=0,h=0,m=!1;const y=new Map,N=(j,U)=>{const V=y.get(j);y.set(j,V===void 0?U:V+U)},W=()=>{m&&u+h>c&&(c=u+h),m=!1},D=()=>{W(),l+=1,m=!0,u=0;const j=y.get(l-1);j!==void 0&&(h+=j)};for(let j=t.indexOf("<");j!==-1;j=t.indexOf("<",j+1)){const U=t.charCodeAt(j+1);if(U===Ns){cf(t,j)&&W();continue}if(U!==xc||!ps(t.charCodeAt(j+3)))continue;const V=t.charCodeAt(j+2);if(V===Ac)D();else if(V===nf||V===Oc){m||D();const O=j+3,T=s(O),P=n(O,T);u+=P;const H=r(O,T);H>1&&(N(l,P),N(l-1+H,-P))}}return W(),{rows:l,cols:c}},Tc=e=>{const t=[],n=new Map;return{intern:o=>{const s=e(o),l=n.get(s);if(l!==void 0)return l;const c=t.length;return t.push(o),n.set(s,c),c},entries:t}},$c=()=>{const e=new WeakMap,t=Tc(r=>JSON.stringify(r));return{intern:r=>{if(e.has(r))return e.get(r);const o=xt(r),s=o===void 0?void 0:t.intern(o);return e.set(r,s),s},entries:t.entries}},uf=()=>{const e=new WeakMap,t=Tc(Er);return{intern:r=>{const o=e.get(r);if(o!==void 0)return o;const s=t.intern(r);return e.set(r,s),s},entries:t.entries}},df=new Set(["http:","https:","mailto:","tel:"]),un=e=>{const t=e.trim();if(!URL.canParse(t))return null;const n=new URL(t);return df.has(n.protocol)?n.href:null},Jn=e=>{if(e===void 0)return;const t=un(e);return t===null?void 0:t},Lc=(e,t)=>e.startCol===0&&e.endCol===t-1,Dc=(e,t)=>e.startRow===0&&e.endRow===t-1,hs=13,Ht=Object.freeze({style:Object.freeze({}),lineBoxPx:hs,verticalAlign:"middle"}),ff={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",transparent:"#00000000"},pf=new Map(Object.entries(ff)),hf=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/,mf=/^rgba?\((.*)\)$/,Mc=/^(\d+(?:\.\d+)?)%$/,Yr=e=>e.toString(16).padStart(2,"0"),Ko=e=>{const t=Mc.exec(e);if(t!==null){const r=Number(t[1]);return r<=100?Math.round(r*255/100):null}if(!/^\d+$/.test(e))return null;const n=Number(e);return n<=255?n:null},gf=e=>{const t=Mc.exec(e);if(t!==null){const r=Number(t[1]);return r<=100?Math.round(r*255/100):null}if(!/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(e))return null;const n=Number(e);return n<=1?Math.round(n*255):null},wf=e=>{const t=e.trim().split(/\s*[,/]\s*|\s+/);if(t.length!==3&&t.length!==4)return null;const n=Ko(t[0]),r=Ko(t[1]),o=Ko(t[2]);if(n===null||r===null||o===null)return null;const s=`#${Yr(n)}${Yr(r)}${Yr(o)}`;if(t.length===3)return s;const l=gf(t[3]);return l===null?null:l===255?s:`${s}${Yr(l)}`},ot=e=>{const t=e.trim().toLowerCase(),n=hf.exec(t);if(n!==null){const s=n[1],l=s.length<=4?s.replace(/./g,c=>c+c):s;return l.length===8&&l.endsWith("ff")?`#${l.slice(0,6)}`:`#${l}`}const r=mf.exec(t);if(r!==null)return wf(r[1]);const o=pf.get(t);return o===void 0?null:o},Ul={thin:{width:1,line:"solid"},medium:{width:2,line:"solid"},thick:{width:3,line:"solid"},dashed:{width:1,line:"dashed"},dotted:{width:1,line:"dotted"},double:{width:3,line:"double"},hair:{width:1,line:"dotted"}},Xl=e=>{if(!Object.hasOwn(Ul,e.style))return null;const t=Ul[e.style],n=e.color===void 0?$s:ot(e.color);return n===null?null:`${t.width}px ${t.line} ${n}`},Cf={top:"flex-start",middle:"center",bottom:"flex-end"},bf=e=>e==="left"||e==="center"||e==="right",zc=e=>e==="top"||e==="middle"||e==="bottom",Fc=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e*4/3:null,Nc=(e,t)=>{if(typeof e.background=="string"){const s=ot(e.background);s!==null&&(t.background=s)}if(typeof e.color=="string"){const s=ot(e.color);s!==null&&(t.color=s)}e.bold===!0&&(t.fontWeight="bold"),e.italic===!0&&(t.fontStyle="italic");const n=e.underline===!0,r=e.strikethrough===!0;(n||r)&&(t.textDecoration=n&&r?"underline line-through":n?"underline":"line-through"),typeof e.fontFamily=="string"&&e.fontFamily.trim()!==""&&(t.fontFamily=e.fontFamily);const o=Fc(e.fontSize);o!==null&&(t.fontSize=`${o}px`),e.wrap===!0&&(t.whiteSpace="pre-wrap")},Kr=(e,t)=>{const n=e===void 0?null:Xl(e);return n!==null?n:t===void 0?null:Xl(t)},Uo=(e,t,n,r,o)=>{const s={},l={};e!==void 0&&(bf(e.align)&&(l["data-aqsp-align"]=e.align,s.justifyContent=Rr(e.align)),zc(e.verticalAlign)&&(l["data-aqsp-valign"]=e.verticalAlign,s.alignItems=Cf[e.verticalAlign]),e.wrap===!0&&(l["data-aqsp-wrap"]=""),Nc(e,s));const c=e?.borders,u=Kr(c?.right,t);u!==null&&(s.borderRight=u);const h=Kr(c?.bottom,n);if(h!==null&&(s.borderBottom=h),r){const m=Kr(c?.left,void 0);m!==null&&(s.borderLeft=m)}if(o){const m=Kr(c?.top,void 0);m!==null&&(s.borderTop=m)}return Object.keys(s).length===0&&Object.keys(l).length===0?null:Object.freeze({style:Object.freeze(s),attrs:Object.freeze(l)})},Gl=new WeakMap,yf=(e,t,n,r,o)=>{const s=t?.borders?.left,l=n?.borders?.top,c=!(r||o)&&s===void 0&&l===void 0;if(e===void 0)return c?null:Uo(void 0,s,l,r,o);if(!c)return Uo(e,s,l,r,o);const u=Gl.get(e);if(u!==void 0)return u;const h=Uo(e,void 0,void 0,!1,!1);return Gl.set(e,h),h},Rf=e=>{if(e===void 0)return Ht;const t={};Nc(e,t);const n=Fc(e.fontSize),r=n===null?hs:Math.round(n),o=zc(e.verticalAlign)?e.verticalAlign:"middle";return Object.keys(t).length===0&&r===hs&&o==="middle"?Ht:Object.freeze({style:Object.freeze(t),lineBoxPx:r,verticalAlign:o})},vf="#REF!",Sf=11,kf=15,Ef=4096,so=33,Sr=34,Ps=36,Of=38,ms=39,Pc=40,Af=42,xf=43,Tf=44,_c=45,$f=46,Lf=47,Vn=58,Df=59,Mf=60,qc=61,zf=62,Ff=67,Nf=82,bo=91,jc=93,Pf=94,_f=95,Ic=e=>e>=65&&e<=90||e>=97&&e<=122,Hc=e=>e>=48&&e<=57,_s=e=>Ic(e)||Hc(e)||e===_f||e===$f||e===Ps||e>=128,qf=e=>e===32||e>=9&&e<=13||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279,jf=e=>e===qc||e===Pc||e===Tf||e===Df||e===xf||e===_c||e===Af||e===Lf||e===Pf||e===Of||e===Mf||e===zf||e===Vn,Bc=(e,t)=>{if(t>=e.length)return!0;const n=e.charCodeAt(t);return!(_s(n)||n===Pc||n===so||n===bo)},Zl=(e,t)=>{let n=t;for(;n<e.length&&_s(e.charCodeAt(n));)n+=1;return n},gs=(e,t,n)=>{let r=t+1;for(;r<e.length;){if(e.charCodeAt(r)===n){if(e.charCodeAt(r+1)===n){r+=2;continue}return r+1}r+=1}return e.length},If=(e,t)=>{let n=0,r=t;for(;r<e.length;){const o=e.charCodeAt(r);if(o===ms){r+=2;continue}if(o===bo)n+=1;else if(o===jc&&(n-=1,n===0))return r+1;r+=1}return e.length},Jl=(e,t,n,r,o)=>{const s=r(e,n+1);return s!==null&&Bc(e,s.end)?(o.push({start:t,end:s.end,token:{...s.token,sheet:e.slice(t,n)}}),s.end):n+1},Wc=(e,t)=>{const n=[],r=e.length;let o=0;for(;o<r;){const s=e.charCodeAt(o);if(s===Sr){o=gs(e,o,Sr);continue}if(s===ms){const u=gs(e,o,ms);o=e.charCodeAt(u)===so?Jl(e,o,u,t,n):u;continue}if(s===bo){o=If(e,o);continue}if(!_s(s)){o+=1;continue}const l=t(e,o);if(l!==null&&Bc(e,l.end)){n.push({start:o,end:l.end,token:l.token}),o=l.end;continue}let c=Zl(e,o);if(e.charCodeAt(c)===Vn){const u=Zl(e,c+1);u>c+1&&e.charCodeAt(u)===so&&(c=u)}o=e.charCodeAt(c)===so?Jl(e,o,c,t,n):c}return n},Xo=(e,t)=>{let n=t;const r=e.charCodeAt(n)===Ps;r&&(n+=1);let o=0,s=0;for(;n<e.length;){const l=e.charCodeAt(n);if(!Ic(l))break;if(s+=1,s>Sf)return null;o=o*26+(l&31),n+=1}return s===0?null:{end:n,col:o-1,abs:r}},ws=(e,t)=>{let n=t,r=0;for(;n<e.length;){const o=e.charCodeAt(n);if(!Hc(o))break;if(n-t>=kf)return null;r=r*10+(o-48),n+=1}return n===t?null:{end:n,value:r}},Ur=(e,t)=>{const n=e.charCodeAt(t)===Ps,r=ws(e,n?t+1:t);return r===null||r.value===0?null:{end:r.end,index:r.value-1,abs:n}},Hf=(e,t)=>{const n=Xo(e,t);if(n!==null){const o=Ur(e,n.end);if(o!==null){if(e.charCodeAt(o.end)===Vn){const s=Xo(e,o.end+1);if(s!==null){const l=Ur(e,s.end);if(l!==null)return{end:l.end,token:{kind:"range",start:{row:o.index,col:n.col,absRow:o.abs,absCol:n.abs},end:{row:l.index,col:s.col,absRow:l.abs,absCol:s.abs}}}}}return{end:o.end,token:{kind:"cell",row:o.index,col:n.col,absRow:o.abs,absCol:n.abs}}}if(e.charCodeAt(n.end)===Vn){const s=Xo(e,n.end+1);if(s!==null)return{end:s.end,token:{kind:"column",start:{col:n.col,abs:n.abs},end:{col:s.col,abs:s.abs}}}}return null}const r=Ur(e,t);if(r!==null&&e.charCodeAt(r.end)===Vn){const o=Ur(e,r.end+1);if(o!==null)return{end:o.end,token:{kind:"row",start:{row:r.index,abs:r.abs},end:{row:o.index,abs:o.abs}}}}return null},Tr=e=>Wc(e,Hf),Vc=(e,t=Ef)=>{if(!Number.isInteger(t)||t<=0)throw new RangeError(`[spreadsheet] createFormulaMemo requires a positive integer limit, received ${t}`);const n=new Map;return r=>{const o=n.get(r);if(o!==void 0)return o;n.size>=t&&n.clear();const s=e(r);return n.set(r,s),s}},Cs=e=>{let t=e+1,n="";for(;t>0;){const r=(t-1)%26;n=String.fromCharCode(65+r)+n,t=Math.floor((t-1)/26)}return n},Go=e=>`${e.absCol?"$":""}${Cs(e.col)}${e.absRow?"$":""}${e.row+1}`,qs=e=>e.sheet===void 0?"":`${e.sheet}!`,sn=e=>{const t=qs(e);switch(e.kind){case"cell":return`${t}${Go(e)}`;case"range":return`${t}${Go(e.start)}:${Go(e.end)}`;case"column":return`${t}${e.start.abs?"$":""}${Cs(e.start.col)}:${e.end.abs?"$":""}${Cs(e.end.col)}`;case"row":return`${t}${e.start.abs?"$":""}${e.start.row+1}:${e.end.abs?"$":""}${e.end.row+1}`}},jn=(e,t)=>{if(!Number.isInteger(e)||e<0)throw new RangeError(`[spreadsheet] ${t} must be a non-negative integer, received ${e}`)},Bf=(e,t)=>{const n="startRow"in e?e:{startRow:e.row,startCol:e.col,endRow:e.row,endCol:e.col};switch(jn(n.startRow,"formatRangeReference startRow"),jn(n.startCol,"formatRangeReference startCol"),jn(n.endRow,"formatRangeReference endRow"),jn(n.endCol,"formatRangeReference endCol"),t){case"columns":return sn({kind:"column",start:{col:n.startCol,abs:!1},end:{col:n.endCol,abs:!1}});case"rows":return sn({kind:"row",start:{row:n.startRow,abs:!1},end:{row:n.endRow,abs:!1}});case"cells":return n.startRow===n.endRow&&n.startCol===n.endCol?sn({kind:"cell",row:n.startRow,col:n.startCol,absRow:!1,absCol:!1}):sn({kind:"range",start:{row:n.startRow,col:n.startCol,absRow:!1,absCol:!1},end:{row:n.endRow,col:n.endCol,absRow:!1,absCol:!1}})}},js=(e,t,n)=>{if(t.length===0)return e;let r="",o=0;for(const s of t){const l=n(s.token);r+=e.slice(o,s.start)+(l===null?`${qs(s.token)}${vf}`:l),o=s.end}return r+e.slice(o)},yo=e=>e.charCodeAt(0)===qc,Zo=(e,t,n)=>{const r=e.absRow?e.row:e.row+t,o=e.absCol?e.col:e.col+n;return r<0||o<0?null:{row:r,col:o,absRow:e.absRow,absCol:e.absCol}},Wf=(e,t,n)=>{switch(e.kind){case"cell":{const r=Zo(e,t,n);return r===null?null:{...e,...r}}case"range":{const r=Zo(e.start,t,n),o=Zo(e.end,t,n);return r===null||o===null?null:{...e,start:r,end:o}}case"column":{const r=e.start.abs?e.start.col:e.start.col+n,o=e.end.abs?e.end.col:e.end.col+n;return r<0||o<0?null:{...e,start:{col:r,abs:e.start.abs},end:{col:o,abs:e.end.abs}}}case"row":{const r=e.start.abs?e.start.row:e.start.row+t,o=e.end.abs?e.end.row:e.end.row+t;return r<0||o<0?null:{...e,start:{row:r,abs:e.start.abs},end:{row:o,abs:e.end.abs}}}}},Yc=(e,t,n)=>{if(!(Number.isInteger(t)&&Number.isInteger(n)))throw new RangeError(`[spreadsheet] shiftFormula requires integer deltas, received ${t}, ${n}`);return yo(e)?js(e,Tr(e),r=>{const o=Wf(r,t,n);return o===null?null:sn(o)}):e},Kc=(e,t)=>{jn(e.row,`${t} origin.row`),jn(e.col,`${t} origin.col`)},In=(e,t,n,r)=>n?`${e}${t+1}`:`${e}[${t-r}]`,Jo=(e,t)=>`${In("R",e.row,e.absRow,t.row)}${In("C",e.col,e.absCol,t.col)}`,Vf=(e,t)=>{const n=qs(e);switch(e.kind){case"cell":return`${n}${Jo(e,t)}`;case"range":return`${n}${Jo(e.start,t)}:${Jo(e.end,t)}`;case"column":return`${n}${In("C",e.start.col,e.start.abs,t.col)}:${In("C",e.end.col,e.end.abs,t.col)}`;case"row":return`${n}${In("R",e.start.row,e.start.abs,t.row)}:${In("R",e.end.row,e.end.abs,t.row)}`}},Ro=(e,t)=>(Kc(t,"toR1C1"),yo(e)?js(e,Tr(e),n=>Vf(n,t)):e),Ql=(e,t,n)=>{const r=e.charCodeAt(t);if(r!==n&&r!==n+32)return null;const o=t+1;if(e.charCodeAt(o)===bo){const l=e.charCodeAt(o+1)===_c,c=ws(e,l?o+2:o+1);return c===null||e.charCodeAt(c.end)!==jc?null:{end:c.end+1,axis:{rel:!0,n:l?-c.value:c.value}}}const s=ws(e,o);return s===null?{end:o,axis:{rel:!0,n:0}}:s.value===0?null:{end:s.end,axis:{rel:!1,n:s.value}}},ei=(e,t)=>{const n=Ql(e,t,Nf),r=Ql(e,n===null?t:n.end,Ff);return n!==null&&r!==null?{end:r.end,shape:"cell",cell:{row:n.axis,col:r.axis}}:n!==null?{end:n.end,shape:"row",row:n.axis}:r===null?null:{end:r.end,shape:"column",col:r.axis}},Yf=e=>{switch(e.shape){case"cell":return{shape:"cell",start:e.cell,end:null};case"row":return{shape:"row",start:e.row,end:null};case"column":return{shape:"column",start:e.col,end:null}}},Kf=(e,t)=>e.shape==="cell"&&t.shape==="cell"?{shape:"cell",start:e.cell,end:t.cell}:e.shape==="row"&&t.shape==="row"?{shape:"row",start:e.row,end:t.row}:e.shape==="column"&&t.shape==="column"?{shape:"column",start:e.col,end:t.col}:null,Uf=(e,t)=>{const n=ei(e,t);if(n===null)return null;if(e.charCodeAt(n.end)===Vn){const r=ei(e,n.end+1);if(r!==null){const o=Kf(n,r);if(o!==null)return{end:r.end,token:o}}}return{end:n.end,token:Yf(n)}},Xf=e=>Wc(e,Uf),Gf=Vc(Xf),Hn=(e,t)=>e.rel?t+e.n:e.n-1,ti=(e,t)=>{const n=Hn(e.row,t.row),r=Hn(e.col,t.col);return n<0||r<0?null:{row:n,col:r,absRow:!e.row.rel,absCol:!e.col.rel}},Zf=(e,t)=>{const n=e.sheet===void 0?{}:{sheet:e.sheet};switch(e.shape){case"cell":{const r=ti(e.start,t);if(r===null)return null;if(e.end===null)return{kind:"cell",...r,...n};const o=ti(e.end,t);return o===null?null:{kind:"range",start:r,end:o,...n}}case"row":{const r=e.end===null?e.start:e.end,o=Hn(e.start,t.row),s=Hn(r,t.row);return o<0||s<0?null:{kind:"row",start:{row:o,abs:!e.start.rel},end:{row:s,abs:!r.rel},...n}}case"column":{const r=e.end===null?e.start:e.end,o=Hn(e.start,t.col),s=Hn(r,t.col);return o<0||s<0?null:{kind:"column",start:{col:o,abs:!e.start.rel},end:{col:s,abs:!r.rel},...n}}}},$r=(e,t)=>(Kc(t,"fromR1C1"),yo(e)?js(e,Gf(e),n=>{const r=Zf(n,t);return r===null?null:sn(r)}):e),ni=(e,t)=>e||t?e&&t?{absCol:!1,absRow:!0}:!e&&t?{absCol:!0,absRow:!1}:{absCol:!1,absRow:!1}:{absCol:!0,absRow:!0},Jf=e=>{switch(e.kind){case"cell":return{...e,...ni(e.absCol,e.absRow)};case"range":{const t=ni(e.start.absCol,e.start.absRow);return{...e,start:{...e.start,...t},end:{...e.end,...t}}}case"column":{const t=!e.start.abs;return{...e,start:{col:e.start.col,abs:t},end:{col:e.end.col,abs:t}}}case"row":{const t=!e.start.abs;return{...e,start:{row:e.start.row,abs:t},end:{row:e.end.row,abs:t}}}}},Uc=(e,t)=>yo(e)&&Number.isInteger(t)&&t>=1&&t<=e.length,Xc=(e,t)=>{if(!Uc(e,t))return null;for(const n of Tr(e))if(n.start<=t&&t<=n.end)return n;return null},Qf=(e,t)=>{const n=Xc(e,t);if(n===null)return null;const r=sn(Jf(n.token));return{text:`${e.slice(0,n.start)}${r}${e.slice(n.end)}`,caret:n.start+r.length}},ri=(e,t)=>{let n=-1,r=0;for(;r<t;){const o=e.charCodeAt(r);if(o===Sr){const s=gs(e,r,Sr);if(s>t)return!1;n=Sr,r=s;continue}qf(o)||(n=o),r+=1}return jf(n)},Gc=(e,t)=>{if(!Uc(e,t))return null;for(const n of Tr(e))if(n.start<=t&&t<=n.end)return ri(e,n.start)?{replace:[n.start,n.end]}:null;return ri(e,t)?{insertAt:t}:null},Gn=[{code:"JPY",symbol:"¥",lcid:"411",locale:"ja-JP",digits:0},{code:"USD",symbol:"$",lcid:"409",locale:"en-US",digits:2},{code:"EUR",symbol:"€",lcid:"407",locale:"de-DE",digits:2},{code:"GBP",symbol:"£",lcid:"809",locale:"en-GB",digits:2},{code:"CNY",symbol:"¥",lcid:"804",locale:"zh-CN",digits:2},{code:"KRW",symbol:"₩",lcid:"412",locale:"ko-KR",digits:0},{code:"AUD",symbol:"$",lcid:"c09",locale:"en-AU",digits:2},{code:"CAD",symbol:"$",lcid:"1009",locale:"en-CA",digits:2},{code:"CHF",symbol:"CHF",lcid:"807",locale:"de-CH",digits:2},{code:"INR",symbol:"₹",lcid:"4009",locale:"en-IN",digits:2},{code:"HKD",symbol:"HK$",lcid:"c04",locale:"zh-HK",digits:2},{code:"SGD",symbol:"$",lcid:"1004",locale:"zh-SG",digits:2},{code:"TWD",symbol:"NT$",lcid:"404",locale:"zh-TW",digits:2},{code:"EUR",symbol:"€",lcid:"40c",locale:"fr-FR",digits:2},{code:"EUR",symbol:"€",lcid:"410",locale:"it-IT",digits:2},{code:"EUR",symbol:"€",lcid:"c0a",locale:"es-ES",digits:2},{code:"EUR",symbol:"€",lcid:"413",locale:"nl-NL",digits:2},{code:"EUR",symbol:"€",lcid:"816",locale:"pt-PT",digits:2},{code:"EUR",symbol:"€",lcid:"1809",locale:"en-IE",digits:2},{code:"NZD",symbol:"$",lcid:"1409",locale:"en-NZ",digits:2},{code:"MXN",symbol:"$",lcid:"80a",locale:"es-MX",digits:2},{code:"BRL",symbol:"R$",lcid:"416",locale:"pt-BR",digits:2}],vo=(e,t)=>`[$${e}-${t}]`,ep=new Map(Gn.map(e=>[vo(e.symbol,e.lcid),e])),tp=new Map(Gn.filter((e,t)=>Gn.findIndex(n=>n.code===e.code)===t).map(e=>[e.code,e]));new Map(Gn.map(e=>[vo(e.symbol,e.lcid),e.code]));const np=new Set([...Gn.map(e=>e.symbol),...Gn.map(e=>e.code),"¥"]),rp=20,op="yyyy/MM/dd",Zc=/yyyy|MM|dd|HH|mm|ss/g,Jc=" -+/():!^&'~{}<>=",sp="$¥€£₩₹¥",bs=e=>{let t="",n=0;for(;n<e.length;){const r=e[n];if(r!=="\\"){t+=r,n+=1;continue}const o=e.slice(n+1,n+5);if(/^[0-9a-fA-F]{4}$/.test(o)){t+=String.fromCharCode(Number.parseInt(o,16)),n+=5;continue}if(n+1<e.length){t+=e[n+1],n+=2;continue}t+=r,n+=1}return t},lp=e=>{let t=0;for(;t<e.length;){const n=e[t];if(n==='"'){const r=e.indexOf('"',t+1);t=r<0?e.length:r+1}else if(n==="["){const r=e.indexOf("]",t+1);t=r<0?e.length:r+1}else if(n==="\\"||n==="_"||n==="*")t+=2;else{if(n===";")return e.slice(0,t);t+=1}}return e},ip=e=>{const t=[],n=o=>{const s=t[t.length-1];s!==void 0&&s.kind==="literal"?t[t.length-1]={kind:"literal",text:s.text+o}:t.push({kind:"literal",text:o})};let r=0;for(;r<e.length;){const o=e[r];if(o==='"'){const s=e.indexOf('"',r+1);if(s<0)return null;n(e.slice(r+1,s)),r=s+1}else if(o==="\\"){if(r+1>=e.length)return null;n(e[r+1]),r+=2}else if(o==="_"||o==="*"){if(r+1>=e.length)return null;r+=2}else if(o==="["){const s=e.indexOf("]",r+1),l=s<0?"":e.slice(r+1,s);if(s<0||l[0]!=="$")return null;const c=l.slice(1),u=c.lastIndexOf("-"),h=u<0?c:c.slice(0,u),m=u<0?null:c.slice(u+1);if(m!==null&&!/^[0-9a-fA-F]{1,8}$/.test(m)||h===""&&m===null)return null;const y=m===null?null:Number.parseInt(m,16).toString(16);t.push(h===""?{kind:"locale"}:{kind:"currency",symbol:h,lcid:y}),r=s+1}else if(o==="%")t.push({kind:"percent"}),r+=1;else if("#0?,.".includes(o)){let s=r;for(;s<e.length&&"#0?,.".includes(e[s]);)s+=1;const l=e.slice(r,s);/[#0?]/.test(l)?t.push({kind:"digits",text:l}):n(l),r=s}else if(/[A-Za-z]/.test(o))if((o==="E"||o==="e")&&(e[r+1]==="+"||e[r+1]==="-")){let s=r+2;for(;e[s]==="0";)s+=1;if(s===r+2)return null;t.push({kind:"exponent"}),r=s}else{let s=r;for(;s<e.length&&e[s].toLowerCase()===o.toLowerCase();)s+=1;t.push({kind:"date",text:e.slice(r,s).toLowerCase()}),r=s}else if(Jc.includes(o)||sp.includes(o)||o.charCodeAt(0)>=128)n(o),r+=1;else return null}return t},Ot=e=>e===void 0?{}:{locale:e},cp=/^(0|#,##0)(?:\.(0+))?$/,oi=(e,t,n,r)=>{if(t!==null){const o=ep.get(vo(e,t));return o===void 0?void 0:{type:"currency",currency:o.code,decimals:n,locale:o.locale}}if(!(!np.has(e)||r.currency===void 0))return{type:"currency",currency:r.currency,decimals:n,...Ot(r.locale)}},ap=(e,t)=>{let n="",r=!1,o=null,s=!1,l=0,c="",u="";for(const D of e)switch(D.kind){case"locale":break;case"literal":r?u+=D.text:c+=D.text;break;case"digits":if(r)return;n=D.text,r=!0;break;case"currency":if(o!==null)return;o=D;break;case"percent":l+=1;break;case"exponent":if(s||!r)return;s=!0;break;default:return}const h=cp.exec(n);if(h===null)return;const m=h[1]==="#,##0",y=h[2]===void 0?0:h[2].length,N=c.trim(),W=u.trim();if(s)return l===0&&o===null&&!m&&N===""&&W===""?{type:"scientific",decimals:y,...Ot(t.locale)}:void 0;if(l>0)return l===1&&o===null&&N===""&&W===""?{type:"percent",decimals:y,...Ot(t.locale)}:void 0;if(W==="%"&&N===""&&o===null)return{type:"percent",decimals:y,scale:!1,...Ot(t.locale)};if(o!==null)return N===""&&W===""?oi(o.symbol,o.lcid,y,t):void 0;if(!(N!==""&&W!==""))return N!==""||W!==""?oi(N+W,null,y,t):{type:"number",decimals:y,...m?{grouping:!0}:{},...Ot(t.locale)}},up=new Map([["yyyy","yyyy"],["dd","dd"],["hh","HH"],["ss","ss"]]),dp=(e,t)=>{const n=[...e.matchAll(Zc)];return n.length===t.length&&n.every((r,o)=>r.index===t[o].index&&r[0]===t[o].text)},fp=e=>{const t=e.flatMap(s=>s.kind==="date"?[s.text]:[]),n=[];let r="",o=0;for(const s of e){if(s.kind==="locale")continue;if(s.kind==="literal"){r+=s.text;continue}if(s.kind!=="date")return;const l=s.text==="mm"?t[o-1]==="hh"||t[o+1]==="ss"?"mm":"MM":up.get(s.text);if(o+=1,l===void 0)return;n.push({index:r.length,text:l}),r+=l}return n.length>0&&dp(r,n)?{type:"date",pattern:r}:void 0},pp=new Map([["General",()=>{}],["@",()=>({type:"text"})],["Fixed",e=>({type:"number",decimals:2,...Ot(e.locale)})],["Standard",e=>({type:"number",decimals:2,grouping:!0,...Ot(e.locale)})],["Percent",e=>({type:"percent",decimals:2,...Ot(e.locale)})],["Scientific",e=>({type:"scientific",decimals:2,...Ot(e.locale)})],["Currency",e=>e.currency===void 0?void 0:{type:"currency",currency:e.currency,decimals:2,...Ot(e.locale)}],["Euro Currency",e=>({type:"currency",currency:"EUR",decimals:2,...Ot(e.locale)})],["Short Date",()=>({type:"date"})],["Short Time",()=>({type:"date",pattern:"HH:mm"})]]),Is=(e,t)=>{const n=lp(e).trim(),r=pp.get(n);if(r!==void 0)return r(t);const o=ip(n);if(o!==null){if(o.some(s=>s.kind==="digits"))return ap(o,t);if(o.some(s=>s.kind==="date"))return fp(o)}},hp=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;const r=n,o=r[1],s=r[2];if(typeof o!="number"||!Number.isInteger(o)||o<0||o>8||s!==void 0&&typeof s!="string"||o===0)return;if(o===1)return{type:"text"};const l=s===void 0?void 0:Is(s,t);return o===5?l!==void 0&&l.type==="date"?l:{type:"date"}:l},Cr=e=>e===0?"":`.${"0".repeat(e)}`,lo=e=>e!==void 0&&Number.isInteger(e)&&e>=0&&e<=rp,mp=`${Jc}.,`,si=e=>e.includes('"')?null:[...e].every(t=>mp.includes(t))?e:`"${e}"`,gp=e=>{const t=[];let n=0,r=0;for(const c of e.matchAll(Zc)){const u=si(e.slice(r,c.index));if(u===null)return null;t.push(u,c[0].toLowerCase()),n+=1,r=c.index+c[0].length}const o=si(e.slice(r));if(o===null||n===0)return null;t.push(o);const s=t.join(""),l=Is(s,{});return l!==void 0&&l.type==="date"&&l.pattern===e?s:null},wp=e=>{const t=tp.get(e.currency.toUpperCase());if(t===void 0)return null;const n=e.decimals===void 0?t.digits:e.decimals;if(!lo(n))return null;const r=`#,##0${Cr(n)}`;return t.code==="USD"&&e.locale==="en-US"?`"$"${r}`:`${vo(t.symbol,t.lcid)}${r}`},Qc=e=>{switch(e.type){case"text":return"@";case"date":return gp(e.pattern===void 0?op:e.pattern);case"number":return lo(e.decimals)?`${e.grouping===!0?"#,##0":"0"}${Cr(e.decimals)}`:null;case"percent":{const t=e.decimals===void 0?0:e.decimals;return lo(t)?e.scale===!1?`0${Cr(t)}"%"`:`0${Cr(t)}%`:null}case"scientific":return lo(e.decimals)?`0${Cr(e.decimals)}E+00`:null;case"currency":return wp(e);default:return null}},li="-−",Cp=(e,t)=>{if(t===""||!e.includes(t))return/^\d+$/.test(e)?e:null;const n=e.split(t);return!/^\d{1,3}$/.test(n[0])||n.slice(1).some(r=>!/^\d{3}$/.test(r))?null:n.join("")},bp=(e,t,n,r)=>{const o=/^(.*?)[eE]([+-]?\d{1,4})$/.exec(e);if(o!==null&&r==="none"||o===null&&r==="required")return null;const s=o===null?e:o[1],l=o===null?0:Number(o[2]),c=s.split(n);if(c.length>2)return null;const u=c.length===2?c[1]:"";if(c.length===2&&!/^\d+$/.test(u))return null;const h=Cp(c[0],t);return h===null?null:{integer:h,fraction:u,exponent:l}},yp=(e,t,n,r)=>{const o=e+t,s=e.length+n;let l,c;s<=0?(l="0",c="0".repeat(-s)+o):s>=o.length?(l=o+"0".repeat(s-o.length),c=""):(l=o.slice(0,s),c=o.slice(s)),l=l.replace(/^0+(?=\d)/,""),c=c.replace(/0+$/,"");const u=c===""?l:`${l}.${c}`;return r&&u!=="0"?`-${u}`:u},Rp=(e,t,n)=>{if(n.decimal===""||n.group===n.decimal)throw new RangeError(`numberDisplayToCanonical: separators must declare a non-empty decimal separator distinct from the group separator (got group="${n.group}", decimal="${n.decimal}")`);if(t!==void 0&&(t.type==="date"||t.type==="text"))return e;const r=t===void 0?"general":t.type;let o=e.trim(),s=!1;if(o.startsWith("(")&&o.endsWith(")")&&(s=!0,o=o.slice(1,-1).trim()),r==="percent"){if(!o.endsWith("%"))return e;o=o.slice(0,-1).trim()}else if(o.includes("%"))return e;const l=r==="general"?"":n.group,c=r==="scientific"||r==="general",u=P=>P>="0"&&P<="9"||l!==""&&l.includes(P)||n.decimal.includes(P)||c&&(P==="e"||P==="E");let h=0;for(;h<o.length&&!u(o[h]);)h+=1;let m=o.length;for(;m>h&&!u(o[m-1]);)m-=1;let y=0,N=0,W=0,D="";for(const P of o.slice(0,h))li.includes(P)?y+=1:P==="("?N+=1:D+=P;for(const P of o.slice(m))li.includes(P)?y+=1:P===")"?W+=1:D+=P;const j=y+N;if(N!==W||j>1||j===1&&s||(s=s||j===1,r!=="currency"&&D.trim()!==""))return e;const U=bp(o.slice(h,m).trim(),l,n.decimal,r==="scientific"?"required":r==="general"?"optional":"none");if(U===null)return e;const V=t!==void 0&&t.type==="percent"&&t.scale!==!1?-2:0,O=U.exponent+V;if(O>330||O<-330)return e;const T=yp(U.integer,U.fraction,O,s);return Number.isFinite(Number(T))?T:e},ii="google-sheets-html-origin",ea=Object.freeze({group:",",decimal:"."}),ci=Object.freeze({thin:".5pt solid",medium:"1.0pt solid",thick:"1.5pt solid",dashed:".5pt dashed",dotted:".5pt dotted",double:"1.5pt double",hair:".5pt hairline"}),ta=["top","right","bottom","left"],vp=new Set(["solid","dashed","dotted","double","hairline","none","hidden","groove","ridge","inset","outset"]),Sp=new Set(["windowtext","currentcolor","inherit","initial","unset"]),kp=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),ai=["","#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#ERROR!"],Ep=Object.freeze({number:2,percent:3,currency:4,scientific:8}),Op=new Set(["script","style","template","noscript","rt","rp","img","svg","video","audio","picture","canvas","iframe","object","textarea","select","button","input"]),Ap=new Set(["div","p","li","ul","ol","dl","dt","dd","h1","h2","h3","h4","h5","h6","blockquote","pre","section","article","header","footer","table","tr","hr"]),xp=new Set(["b","strong","i","em","u","s","strike","del","a","font","span"]),Tp=3,$p=1,na=-25569,io=86400,Lp=-693959,Dp=2958465,Mp=" ",So=e=>{const t=new Map;let n=0,r=null,o=0;const s=l=>{const c=e.slice(n,l),u=c.indexOf(":");if(u>0){const h=c.slice(0,u).trim().toLowerCase(),m=c.slice(u+1).trim();h!==""&&m!==""&&t.set(h,m)}n=l+1};for(let l=0;l<e.length;l+=1){const c=e[l];r!==null?c==="\\"?l+=1:c===r&&(r=null):c==='"'||c==="'"?r=c:c==="("?o+=1:c===")"?o=o>0?o-1:0:c===";"&&o===0&&s(l)}return s(e.length),t},ho=e=>{const t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.endsWith(t)?e.slice(1,-1):e},Hs=e=>{const t=[];let n="",r=0;for(const o of e)o==="("?r+=1:o===")"&&(r=r>0?r-1:0),r===0&&/\s/.test(o)?n!==""&&(t.push(n),n=""):n+=o;return n!==""&&t.push(n),t},zp=/^(?:[a-z][a-z0-9]*)?\.([A-Za-z_-][\w-]*)$/i,Fp=e=>{const t=new Map;let n=null,r=null;for(const s of e.querySelectorAll("style")){const l=s.innerHTML.replaceAll("<!--","").replaceAll("-->","").replace(/\/\*[\s\S]*?\*\//g,"");let c=0;for(;c<l.length;){const u=l.indexOf("{",c);if(u===-1)break;const h=l.indexOf("}",u+1);if(h===-1)break;const m=l.slice(c,u),y=l.slice(u+1,h);if(c=h+1,m.trim().startsWith("@"))continue;const N=So(y);for(const W of m.split(",")){const D=W.trim(),j=zp.exec(D);if(j!==null){const U=t.get(j[1]);if(U===void 0)t.set(j[1],new Map(N));else for(const[V,O]of N)U.set(V,O)}else if(D.toLowerCase()==="table"){const U=N.get("mso-displayed-decimal-separator"),V=N.get("mso-displayed-thousand-separator");U!==void 0&&(n=bs(ho(U))),V!==void 0&&(r=bs(ho(V)))}}}}return{classes:t,separators:n!==null&&r!==null&&n!==""&&r!==n?{group:r,decimal:n}:ea}},Np="%_-*? ",Pp=e=>{let t="";for(const n of e)n==='"'?t+="\\0022":n==="\\"?t+="\\\\":/[A-Za-z0-9]/.test(n)||Np.includes(n)||n.charCodeAt(0)>=128?t+=n:t+=`\\${n}`;return t},_p=(e,t,n)=>{const r=t<=2?e-1:e,o=Math.floor(r/400),s=r-o*400,l=t>2?t-3:t+9,c=Math.floor((153*l+2)/5)+n-1,u=s*365+Math.floor(s/4)-Math.floor(s/100)+c;return o*146097+u-719468},ra=e=>{const t=e+719468,n=Math.floor(t/146097),r=t-n*146097,o=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),s=r-(365*o+Math.floor(o/4)-Math.floor(o/100)),l=Math.floor((5*s+2)/153),c=s-Math.floor((153*l+2)/5)+1,u=l<10?l+3:l-9;return{year:o+n*400+(u<=2?1:0),month:u,day:c}},Pn=(e,t)=>String(e).padStart(t,"0"),oa=e=>{if(e<Lp||e>Dp)return null;let t=Math.floor(e),n=Math.round((e-t)*io);n>=io&&(t+=1,n-=io);const r=ra(t+na),o=`${Pn(r.year,4)}-${Pn(r.month,2)}-${Pn(r.day,2)}`;if(n===0)return o;const s=Math.floor(n/3600),l=Math.floor(n%3600/60);return`${o} ${Pn(s,2)}:${Pn(l,2)}:${Pn(n%60,2)}`},qp=/^(\d{4})([-/])(\d{2})\2(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/,jp=e=>{const t=qp.exec(e);if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);if(r<1||r>12||o<1||s>23||l>59||c>59)return null;const u=_p(n,r,o),h=ra(u);return h.year!==n||h.month!==r||h.day!==o?null:u-na+(s*3600+l*60+c)/io},Bs=e=>e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),bn=e=>Bs(e).replaceAll('"',"&quot;"),sa=e=>Bs(e).replaceAll("'","&#39;"),Ip=e=>Bs(e).replaceAll(`\r
2
2
  `,`
3
3
  `).replaceAll("\r",`
4
4
  `).replaceAll(`
5
- `,'<br style="mso-data-placement:same-cell">').replaceAll(" ","&#9;"),Jr=(e,t)=>`${e}="${pn(JSON.stringify(t))}"`,Yc=e=>e.type==="number"||e.type==="percent"||e.type==="currency"||e.type==="scientific",Dp=e=>{if(ot(e)===null)return null;const t=Number(e);return Number.isFinite(t)?t:null},Mp=e=>{const t=/yyyy|MM|dd/.test(e),n=/HH|mm|ss/.test(e);return t&&n?7:n?6:5},zp=e=>{if(e.type==="text")return{1:1};const t=Ic(e);return t===null?null:{1:e.type==="date"?Mp(e.pattern===void 0?"yyyy/MM/dd":e.pattern):mp[e.type],2:t,3:1}},Np=/[;"'{}<>&\\]/,Uc=e=>e==="left"||e==="center"||e==="right",Xc=e=>e==="top"||e==="middle"||e==="bottom",Fp=e=>{const t=[];e.bold===!0&&t.push("font-weight:bold"),e.italic===!0&&t.push("font-style:italic");const n=[...e.underline===!0?["underline"]:[],...e.strikethrough===!0?["line-through"]:[]];n.length>0&&t.push(`text-decoration:${n.join(" ")}`);const r=typeof e.color=="string"?Ze(e.color):null;r!==null&&t.push(`color:${r}`);const o=typeof e.background=="string"?Ze(e.background):null;if(o!==null&&t.push(`background-color:${o}`),Uc(e.align)&&t.push(`text-align:${e.align}`),Xc(e.verticalAlign)&&t.push(`vertical-align:${e.verticalAlign}`),typeof e.fontFamily=="string"&&e.fontFamily.trim()!==""&&!Np.test(e.fontFamily)&&t.push(`font-family:${e.fontFamily.trim()}`),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize>0&&t.push(`font-size:${e.fontSize}pt`),e.borders!==void 0)for(const s of Hc){const l=e.borders[s];if(l===void 0||!Object.hasOwn(ri,l.style))continue;const c=l.color===void 0?"windowtext":Ze(l.color);c!==null&&t.push(`border-${s}:${ri[l.style]} ${c}`)}if(e.value!==void 0){const s=Ic(e.value);s!==null&&t.push(`mso-number-format:"${Op(s)}"`)}return t},Pp={value:void 0,style:"white-space:pre",numberFormatAttribute:null},_p=e=>{const t=e.value,n=e.wrap===!0?"white-space:pre-wrap;word-wrap:break-word":"white-space:pre",r=Kc([n,...Fp(e)].join(";"));let o=null;if(t!==void 0){const s=zp(t);s!==null&&(o=Jr("data-sheets-numberformat",s))}return{value:t,style:r,numberFormatAttribute:o}},qp=(e,t,n,r)=>{const o=t.value,s=o===void 0?e.t:Wn(e.t,o),l=e.t!==""&&(o!==void 0&&o.type==="text"||e.t.startsWith("=")),c=!l&&o!==void 0&&Yc(o)?Dp(e.t):null,u=!l&&c===null&&o!==void 0&&o.type==="date"?$p(e.t):null,h=[];if(l?h.push(Jr("data-sheets-value",{1:2,2:e.t})):c!==null?h.push(Jr("data-sheets-value",{1:3,3:c})):u!==null&&h.push(Jr("data-sheets-value",{1:3,3:u})),e.f!==void 0&&h.push(`data-sheets-formula="${pn(e.f)}"`),t.numberFormatAttribute!==null&&h.push(t.numberFormatAttribute),e.link!==void 0&&h.push(`data-sheets-hyperlink="${pn(e.link)}"`),e.note!==void 0&&h.push(`data-sheets-note="${pn(e.note)}"`),l?h.push("x:str"):c!==null?h.push(`x:num="${pn(e.t)}"`):u!==null&&h.push(`x:num="${u}"`),e.f!==void 0){const N=Rr(e.f,{row:n,col:r});N.includes("#REF!")||h.push(`x:fmla="${pn(N)}"`)}const m=Lp(s),R=e.link===void 0?m:`<a href="${pn(e.link)}">${m}</a>`;return`<td style='${t.style}'${h.map(N=>` ${N}`).join("")}>${R}</td>`},Gc=(e,t)=>{if(e.cells.length!==e.rows||e.cells.some(s=>s.length!==e.cols))throw new RangeError(`serializeHtmlTable: cells must be exactly rows × cols (${e.rows} × ${e.cols})`);const n=e.colWidths===void 0?"":`<colgroup>${e.colWidths.map(s=>`<col width="${s}">`).join("")}</colgroup>`,r=e.formats.map(_p);let o="";for(let s=0;s<e.rows;s+=1){const l=e.rowHeights===void 0?"":` height="${e.rowHeights[s]}" style="height:${e.rowHeights[s]}px;"`;let c="";for(let u=0;u<e.cols;u+=1){const h=e.cells[s][u],m=h.fmt===void 0?void 0:r[h.fmt];c+=qp(h,m===void 0?Pp:m,s,u)}o+=`<tr${l}>${c}</tr>`}return`<${ni}><style type="text/css">br{mso-data-placement:same-cell;}</style><table ${oc}='${Kc(t)}' data-sheets-root="1" cellspacing="0" cellpadding="0" border="1" style="table-layout:fixed;border-collapse:collapse">${n}<tbody>${o}</tbody></table></${ni}>`},hs=(e,t)=>{for(const[n,r]of t)e.set(n,r)},Zc=(e,t)=>{const n=new Map,r=e.getAttribute("bgcolor");r!==null&&r.trim()!==""&&n.set("background",r);for(const s of e.classList){const l=t.classes.get(s);l!==void 0&&hs(n,l)}const o=e.getAttribute("style");return o!==null&&hs(n,po(o)),n},Ip=e=>{const t=e.toLowerCase();if(t==="thin")return{pt:.75,unit:"px"};if(t==="medium")return{pt:1.5,unit:"px"};if(t==="thick")return{pt:3,unit:"px"};const n=/^(\d*\.?\d+)(pt|px)$/.exec(t);if(n===null)return null;const r=Number(n[1]);return n[2]==="pt"?{pt:r,unit:"pt"}:{pt:r*.75,unit:"px"}},jp=e=>{if(e.unit==="px"){const t=e.pt/.75;return t<=1?"thin":t<3?"medium":"thick"}return e.pt<.75?"thin":e.pt<1.25?"medium":"thick"},Hp=new Map([["dashed","dashed"],["dotted","dotted"],["double","double"],["hairline","hair"]]),Bp={pt:1.5,unit:"px"},si=e=>{let t=null,n=null;const r=[];for(const u of Ns(e)){const h=u.toLowerCase(),m=Ip(u);fp.has(h)?n=h:m!==null?t=m:r.push(u)}if(n===null||n==="none"||n==="hidden")return null;const o=Hp.get(n),s=o===void 0?jp(t===null?Bp:t):o,l=r.join(" ");if(l===""||pp.has(l.toLowerCase()))return{style:s};const c=Ze(l);return c===null||c.length===9?null:{style:s,color:c}},Vp=e=>e.style==="thin"&&e.color==="#cccccc",Wp=e=>{const t=Ze(e);if(t!==null)return t;for(const n of Ns(e)){const r=Ze(n);if(r!==null)return r}return null},Kp=e=>{const t=ro(Ns(e.split(",")[0]).join(" ").trim()).trim();return t===""||hp.has(t.toLowerCase())?null:t},Yp=e=>{const t=/^(\d*\.?\d+)(pt|px)$/i.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=t[2].toLowerCase()==="pt"?n:n*.75;return Number.isFinite(r)&&r>0?r:null},Up=e=>{const t=new Set;for(const n of["text-decoration","text-decoration-line"]){const r=e.get(n);if(r!==void 0)for(const o of r.toLowerCase().split(/\s+/))t.add(o)}return t},Xp=e=>{const t=e.get("white-space"),n=t===void 0?"":t.toLowerCase();return n==="pre"||n==="pre-wrap"?"pre":n==="pre-line"?"pre-line":"collapse"},Gp=new Set(["normal","pre-wrap","pre-line"]),Zp=(e,t,n)=>{const r={},o=e.get("font-weight");if(o!==void 0){const F=o.toLowerCase();(F==="bold"||F==="bolder"||Number(F)>=600)&&(r.bold=!0)}const s=e.get("font-style");s!==void 0&&(s.toLowerCase()==="italic"||s.toLowerCase().startsWith("oblique"))&&(r.italic=!0);const l=Up(e);(t.underline||l.has("underline"))&&(r.underline=!0),(t.strikethrough||l.has("line-through"))&&(r.strikethrough=!0);const c=e.get("color"),u=c===void 0?null:Ze(c);u!==null&&u.length!==9&&(r.color=u);const h=e.has("background-color")?e.get("background-color"):e.get("background"),m=h===void 0?null:Wp(h);m!==null&&m.length!==9&&(r.background=m);const R=e.get("text-align"),N=R===void 0?"":R.toLowerCase();Uc(N)&&(r.align=N);const H=e.get("vertical-align"),L=H===void 0?"":H.toLowerCase();Xc(L)&&(r.verticalAlign=L);const _=e.get("font-family"),U=_===void 0?null:Kp(_);U!==null&&(r.fontFamily=U);const W=e.get("font-size"),k=W===void 0?null:Yp(W);k!==null&&(r.fontSize=k);const x=e.get("white-space");x!==void 0&&Gp.has(x.toLowerCase())&&(r.wrap=!0);const z={},I=e.get("border"),T=I===void 0?null:si(I);for(const F of Hc){const O=e.get(`border-${F}`),g=O===void 0?T:si(O);g!==null&&!(n==="sheets"&&Vp(g))&&(z[F]=g)}return Object.keys(z).length>0&&(r.borders=z),r},li=e=>{e.text!==""&&!e.text.endsWith(`
5
+ `,'<br style="mso-data-placement:same-cell">').replaceAll(" ","&#9;"),co=(e,t)=>`${e}="${bn(JSON.stringify(t))}"`,la=e=>e.type==="number"||e.type==="percent"||e.type==="currency"||e.type==="scientific",Hp=e=>{if(wt(e)===null)return null;const t=Number(e);return Number.isFinite(t)?t:null},Bp=e=>{const t=/yyyy|MM|dd/.test(e),n=/HH|mm|ss/.test(e);return t&&n?7:n?6:5},Wp=e=>{if(e.type==="text")return{1:1};const t=Qc(e);return t===null?null:{1:e.type==="date"?Bp(e.pattern===void 0?"yyyy/MM/dd":e.pattern):Ep[e.type],2:t,3:1}},Vp=/[;"'{}<>&\\]/,ia=e=>e==="left"||e==="center"||e==="right",ca=e=>e==="top"||e==="middle"||e==="bottom",Yp=e=>{const t=[];e.bold===!0&&t.push("font-weight:bold"),e.italic===!0&&t.push("font-style:italic");const n=[...e.underline===!0?["underline"]:[],...e.strikethrough===!0?["line-through"]:[]];n.length>0&&t.push(`text-decoration:${n.join(" ")}`);const r=typeof e.color=="string"?ot(e.color):null;r!==null&&t.push(`color:${r}`);const o=typeof e.background=="string"?ot(e.background):null;if(o!==null&&t.push(`background-color:${o}`),ia(e.align)&&t.push(`text-align:${e.align}`),ca(e.verticalAlign)&&t.push(`vertical-align:${e.verticalAlign}`),typeof e.fontFamily=="string"&&e.fontFamily.trim()!==""&&!Vp.test(e.fontFamily)&&t.push(`font-family:${e.fontFamily.trim()}`),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize>0&&t.push(`font-size:${e.fontSize}pt`),e.borders!==void 0)for(const s of ta){const l=e.borders[s];if(l===void 0||!Object.hasOwn(ci,l.style))continue;const c=l.color===void 0?"windowtext":ot(l.color);c!==null&&t.push(`border-${s}:${ci[l.style]} ${c}`)}if(e.value!==void 0){const s=Qc(e.value);s!==null&&t.push(`mso-number-format:"${Pp(s)}"`)}return t},Kp={value:void 0,style:"white-space:pre",numberFormatAttribute:null},Up=e=>{const t=e.value,n=e.wrap===!0?"white-space:pre-wrap;word-wrap:break-word":"white-space:pre",r=sa([n,...Yp(e)].join(";"));let o=null;if(t!==void 0){const s=Wp(t);s!==null&&(o=co("data-sheets-numberformat",s))}return{value:t,style:r,numberFormatAttribute:o}},Xp=(e,t,n,r)=>{const o=t.value,s=o===void 0?e.t:Xn(e.t,o),l=e.t!==""&&(o!==void 0&&o.type==="text"||e.t.startsWith("=")),c=!l&&o!==void 0&&la(o)?Hp(e.t):null,u=!l&&c===null&&o!==void 0&&o.type==="date"?jp(e.t):null,h=[];if(l?h.push(co("data-sheets-value",{1:2,2:e.t})):c!==null?h.push(co("data-sheets-value",{1:3,3:c})):u!==null&&h.push(co("data-sheets-value",{1:3,3:u})),e.f!==void 0&&h.push(`data-sheets-formula="${bn(e.f)}"`),t.numberFormatAttribute!==null&&h.push(t.numberFormatAttribute),e.link!==void 0&&h.push(`data-sheets-hyperlink="${bn(e.link)}"`),e.note!==void 0&&h.push(`data-sheets-note="${bn(e.note)}"`),l?h.push("x:str"):c!==null?h.push(`x:num="${bn(e.t)}"`):u!==null&&h.push(`x:num="${u}"`),e.f!==void 0){const N=$r(e.f,{row:n,col:r});N.includes("#REF!")||h.push(`x:fmla="${bn(N)}"`)}const m=Ip(s),y=e.link===void 0?m:`<a href="${bn(e.link)}">${m}</a>`;return`<td style='${t.style}'${h.map(N=>` ${N}`).join("")}>${y}</td>`},aa=(e,t)=>{if(e.cells.length!==e.rows||e.cells.some(s=>s.length!==e.cols))throw new RangeError(`serializeHtmlTable: cells must be exactly rows × cols (${e.rows} × ${e.cols})`);const n=e.colWidths===void 0?"":`<colgroup>${e.colWidths.map(s=>`<col width="${s}">`).join("")}</colgroup>`,r=e.formats.map(Up);let o="";for(let s=0;s<e.rows;s+=1){const l=e.rowHeights===void 0?"":` height="${e.rowHeights[s]}" style="height:${e.rowHeights[s]}px;"`;let c="";for(let u=0;u<e.cols;u+=1){const h=e.cells[s][u],m=h.fmt===void 0?void 0:r[h.fmt];c+=Xp(h,m===void 0?Kp:m,s,u)}o+=`<tr${l}>${c}</tr>`}return`<${ii}><style type="text/css">br{mso-data-placement:same-cell;}</style><table ${wc}='${sa(t)}' data-sheets-root="1" cellspacing="0" cellpadding="0" border="1" style="table-layout:fixed;border-collapse:collapse">${n}<tbody>${o}</tbody></table></${ii}>`},ys=(e,t)=>{for(const[n,r]of t)e.set(n,r)},ua=(e,t)=>{const n=new Map,r=e.getAttribute("bgcolor");r!==null&&r.trim()!==""&&n.set("background",r);for(const s of e.classList){const l=t.classes.get(s);l!==void 0&&ys(n,l)}const o=e.getAttribute("style");return o!==null&&ys(n,So(o)),n},Gp=e=>{const t=e.toLowerCase();if(t==="thin")return{pt:.75,unit:"px"};if(t==="medium")return{pt:1.5,unit:"px"};if(t==="thick")return{pt:3,unit:"px"};const n=/^(\d*\.?\d+)(pt|px)$/.exec(t);if(n===null)return null;const r=Number(n[1]);return n[2]==="pt"?{pt:r,unit:"pt"}:{pt:r*.75,unit:"px"}},Zp=e=>{if(e.unit==="px"){const t=e.pt/.75;return t<=1?"thin":t<3?"medium":"thick"}return e.pt<.75?"thin":e.pt<1.25?"medium":"thick"},Jp=new Map([["dashed","dashed"],["dotted","dotted"],["double","double"],["hairline","hair"]]),Qp={pt:1.5,unit:"px"},ui=e=>{let t=null,n=null;const r=[];for(const u of Hs(e)){const h=u.toLowerCase(),m=Gp(u);vp.has(h)?n=h:m!==null?t=m:r.push(u)}if(n===null||n==="none"||n==="hidden")return null;const o=Jp.get(n),s=o===void 0?Zp(t===null?Qp:t):o,l=r.join(" ");if(l===""||Sp.has(l.toLowerCase()))return{style:s};const c=ot(l);return c===null||c.length===9?null:{style:s,color:c}},eh=e=>e.style==="thin"&&e.color==="#cccccc",th=e=>{const t=ot(e);if(t!==null)return t;for(const n of Hs(e)){const r=ot(n);if(r!==null)return r}return null},nh=e=>{const t=ho(Hs(e.split(",")[0]).join(" ").trim()).trim();return t===""||kp.has(t.toLowerCase())?null:t},rh=e=>{const t=/^(\d*\.?\d+)(pt|px)$/i.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=t[2].toLowerCase()==="pt"?n:n*.75;return Number.isFinite(r)&&r>0?r:null},oh=e=>{const t=new Set;for(const n of["text-decoration","text-decoration-line"]){const r=e.get(n);if(r!==void 0)for(const o of r.toLowerCase().split(/\s+/))t.add(o)}return t},sh=e=>{const t=e.get("white-space"),n=t===void 0?"":t.toLowerCase();return n==="pre"||n==="pre-wrap"?"pre":n==="pre-line"?"pre-line":"collapse"},lh=new Set(["normal","pre-wrap","pre-line"]),ih=(e,t,n)=>{const r={},o=e.get("font-weight");if(o!==void 0){const _=o.toLowerCase();(_==="bold"||_==="bolder"||Number(_)>=600)&&(r.bold=!0)}const s=e.get("font-style");s!==void 0&&(s.toLowerCase()==="italic"||s.toLowerCase().startsWith("oblique"))&&(r.italic=!0);const l=oh(e);(t.underline||l.has("underline"))&&(r.underline=!0),(t.strikethrough||l.has("line-through"))&&(r.strikethrough=!0);const c=e.get("color"),u=c===void 0?null:ot(c);u!==null&&u.length!==9&&(r.color=u);const h=e.has("background-color")?e.get("background-color"):e.get("background"),m=h===void 0?null:th(h);m!==null&&m.length!==9&&(r.background=m);const y=e.get("text-align"),N=y===void 0?"":y.toLowerCase();ia(N)&&(r.align=N);const W=e.get("vertical-align"),D=W===void 0?"":W.toLowerCase();ca(D)&&(r.verticalAlign=D);const j=e.get("font-family"),U=j===void 0?null:nh(j);U!==null&&(r.fontFamily=U);const V=e.get("font-size"),O=V===void 0?null:rh(V);O!==null&&(r.fontSize=O);const T=e.get("white-space");T!==void 0&&lh.has(T.toLowerCase())&&(r.wrap=!0);const P={},H=e.get("border"),$=H===void 0?null:ui(H);for(const _ of ta){const x=e.get(`border-${_}`),g=x===void 0?$:ui(x);g!==null&&!(n==="sheets"&&eh(g))&&(P[_]=g)}return Object.keys(P).length>0&&(r.borders=P),r},di=e=>{e.text!==""&&!e.text.endsWith(`
6
6
  `)&&(e.text+=`
7
- `)},Jp=e=>{const t=e.getAttribute("style");return t!==null&&po(t).get("mso-spacerun")==="yes"},Qp=(e,t)=>{const n=[{kind:"enter",node:e}];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="exit"){Cp.has(r.element.localName)&&t.runs.push({element:r.element,before:r.before,end:t.text.length}),r.block&&li(t);continue}const o=r.node;if(o.nodeType===bp){const u=o.data;t.text+=t.mode==="collapse"?u.replace(/[\r\n\t\f]/g," "):u.replace(/\r\n?/g,`
8
- `);continue}if(o.nodeType!==yp)continue;const s=o,l=s.localName;if(gp.has(l)||Jp(s))continue;if(l==="br"){t.text+=`
9
- `;continue}const c=t.mode==="collapse"&&wp.has(l);if(c&&li(t),t.mode==="collapse"&&(l==="td"||l==="th")&&t.text!==""&&!/\s$/.test(t.text)&&(t.text+=" "),l==="a"&&t.href===null){const u=s.getAttribute("href");u!==null&&(t.href=u)}n.push({kind:"exit",element:s,before:t.text.length,block:c});for(let u=s.lastChild;u!==null;u=u.previousSibling)n.push({kind:"enter",node:u})}},eh=(e,t,n,r)=>{const o=e.text.trimEnd().length;if(o===0)return;const s=e.text.length-e.text.trimStart().length;for(const l of e.runs)l.before<=s&&l.end>=o&&nh(l.element,t,n,r)},th=(e,t)=>{const n=e.replaceAll(Sp," ");if(t==="pre")return n;const r=n.split(`
7
+ `)},ch=e=>{const t=e.getAttribute("style");return t!==null&&So(t).get("mso-spacerun")==="yes"},ah=(e,t)=>{const n=[{kind:"enter",node:e}];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="exit"){xp.has(r.element.localName)&&t.runs.push({element:r.element,before:r.before,end:t.text.length}),r.block&&di(t);continue}const o=r.node;if(o.nodeType===Tp){const u=o.data;t.text+=t.mode==="collapse"?u.replace(/[\r\n\t\f]/g," "):u.replace(/\r\n?/g,`
8
+ `);continue}if(o.nodeType!==$p)continue;const s=o,l=s.localName;if(Op.has(l)||ch(s))continue;if(l==="br"){t.text+=`
9
+ `;continue}const c=t.mode==="collapse"&&Ap.has(l);if(c&&di(t),t.mode==="collapse"&&(l==="td"||l==="th")&&t.text!==""&&!/\s$/.test(t.text)&&(t.text+=" "),l==="a"&&t.href===null){const u=s.getAttribute("href");u!==null&&(t.href=u)}n.push({kind:"exit",element:s,before:t.text.length,block:c});for(let u=s.lastChild;u!==null;u=u.previousSibling)n.push({kind:"enter",node:u})}},uh=(e,t,n,r)=>{const o=e.text.trimEnd().length;if(o===0)return;const s=e.text.length-e.text.trimStart().length;for(const l of e.runs)l.before<=s&&l.end>=o&&fh(l.element,t,n,r)},dh=(e,t)=>{const n=e.replaceAll(Mp," ");if(t==="pre")return n;const r=n.split(`
10
10
  `).map(l=>l.replace(/[ \t\f\r]+/g," ").trim());if(t==="pre-line")return r.join(`
11
11
  `);let o=0;for(;o<r.length&&r[o]==="";)o+=1;let s=r.length;for(;s>o&&r[s-1]==="";)s-=1;return r.slice(o,s).join(`
12
- `)},nh=(e,t,n,r)=>{const o=e.localName;if(o==="b"||o==="strong")t.set("font-weight","bold");else if(o==="i"||o==="em")t.set("font-style","italic");else if(o==="u")n.underline=!0;else if(o==="s"||o==="strike"||o==="del")n.strikethrough=!0;else if(o==="font"){const s=e.getAttribute("color"),l=e.getAttribute("face");s!==null&&s.trim()!==""&&t.set("color",s),l!==null&&l.trim()!==""&&t.set("font-family",l)}hs(t,Zc(e,r))},rh=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null)return null;const r=n,o=r[1];if(typeof o!="number")return null;const s=r[String(o)];if(o===2)return typeof s=="string"?s:null;if(o===3)return typeof s!="number"||!Number.isFinite(s)?null:t!==void 0&&t.type==="date"?Wc(s):String(s);if(o===4)return s===1||s===!0?"TRUE":s===0||s===!1?"FALSE":null;if(o===5&&typeof s=="object"&&s!==null){const l=s[1];return typeof l=="number"&&l>=1&&l<oi.length?oi[l]:null}return null},Jc=(e,t,n)=>t!==void 0&&Yc(t)?dp(e,t,n):e,oh=(e,t,n,r)=>{const o=e.getAttribute("x:str");if(o!==null)return o===""?t:o;const s=e.getAttribute("x:bool");if(s!==null){const u=s.toUpperCase();return u==="TRUE"||u==="FALSE"?u:t}const l=e.getAttribute("x:err");if(l!==null)return l===""?t:l;const c=e.getAttribute("x:num");if(c!==null&&c!==""&&ot(c)!==null)if(n!==void 0&&n.type==="date"){const u=Wc(Number(c));if(u!==null)return u}else return c;return Jc(t,n,r)},sh=(e,t,n,r)=>{const o=Zc(e,r.rules),s={underline:!1,strikethrough:!1},l={text:"",runs:[],href:null,mode:Xp(o)};for(const m of ah(e))Qp(m,l);eh(l,o,s,r.rules);const c=th(l.text,l.mode),u=Zp(o,s,r.kind),h={t:""};if(r.kind==="sheets"){const m=e.getAttribute("data-sheets-numberformat"),R=m===null?void 0:op(m,r.options);R!==void 0&&(u.value=R);const N=e.getAttribute("data-sheets-value"),H=N===null?null:rh(N,R);h.t=H===null?Jc(c,R,jc):H;const L=e.getAttribute("data-sheets-formula");L?.startsWith("=")&&(h.f=L);const _=e.getAttribute("data-sheets-hyperlink"),U=_!==null?_:l.href,W=U===null?null:sn(U);W!==null&&(h.link=W);const k=e.getAttribute("data-sheets-note");k!==null&&k!==""&&(h.note=k)}else{const m=o.get("mso-number-format"),R=m===void 0?void 0:zs(ps(ro(m)),r.options);R!==void 0&&(u.value=R),h.t=oh(e,c,R,r.separators);const N=e.getAttribute("x:fmla");N?.startsWith("=")&&(h.f=uo(N,{row:t,col:n}));const H=l.href===null?null:sn(l.href);H!==null&&(h.link=H)}return{cell:h,format:u}},ms=(e,t,n)=>{const r=e.getAttribute(t);if(r===null)return 1;const o=/^\s*\+?(\d+)/.exec(r);if(o===null)return 1;const s=Number(o[1]);return s<1?1:s>n?n:s},lh=e=>{const t=/^(\d*\.?\d+)(px|pt)$/i.exec(e.trim());if(t===null)return null;const n=Number(t[1]);return t[2].toLowerCase()==="pt"?Math.round(n*4/3):Math.round(n)},ih=(e,t)=>{const n=e.getAttribute(t);if(n===null)return null;const r=/^\s*\+?(\d*\.?\d+)/.exec(n);return r===null?null:Math.round(Number(r[1]))},Qc=(e,t)=>{const n=e.getAttribute("style"),r=n===null?null:po(n);if(r!==null){const s=r.get("display");if(s!==void 0&&s.toLowerCase()==="none")return 0;const l=r.get(t),c=l===void 0?null:lh(l);if(c!==null)return Math.min(c,on)}const o=ih(e,t);return o===null?null:Math.min(o,on)},ch=(e,t)=>{const n=[],r=o=>{const s=Qc(o,"width");for(let l=ms(o,"span",xs);l>0&&n.length<t;l-=1)n.push(s)};for(const o of wr(e)){if(n.length>=t)break;if(o.localName==="col")r(o);else if(o.localName==="colgroup")for(const s of wr(o))s.localName==="col"&&n.length<t&&r(s)}return n};function*wr(e){for(let t=e.firstElementChild;t!==null;t=t.nextElementSibling)yield t}function*ah(e){for(let t=e.firstChild;t!==null;t=t.nextSibling)yield t}function*uh(e){for(const t of["thead","tbody","tfoot"])for(const n of wr(e)){const r=n.localName;if(t==="tbody"&&r==="tr")yield n;else if(r===t)for(const o of wr(n))o.localName==="tr"&&(yield o)}}const Yo=()=>({t:""}),dh=(e,t,n)=>{const r=wc(),o=[],s=[],l=[];let c=0;for(const H of uh(e)){const L=o.length,_=(L+1)*Math.max(c,1);if(_>n)return{outcome:"limit",cells:_};const U=[];for(let k=0;k<l.length;k+=1)l[k]>0&&(U[k]=Yo(),l[k]-=1);let W=0;for(const k of wr(H)){const x=k.localName;if(x!=="td"&&x!=="th")continue;for(;U[W]!==void 0;)W+=1;const z=ms(k,"colspan",xs),I=ms(k,"rowspan",uc),T=(L+1)*Math.max(c,W+z);if(T>n)return{outcome:"limit",cells:T};const F=sh(k,L,W,t),O=r.intern(F.format);O!==void 0&&(F.cell.fmt=O),U[W]=F.cell;for(let g=1;g<z;g+=1)U[W+g]===void 0&&(U[W+g]=Yo());if(I>1)for(let g=0;g<z;g+=1){const p=I-1,C=W+g;l[C]=l[C]===void 0||l[C]<p?p:l[C]}W+=z}U.length>c&&(c=U.length),o.push(U),s.push(Qc(H,"height"))}if(o.length===0||c===0)return{outcome:"none"};const u=o.map(H=>{const L=[];for(let _=0;_<c;_+=1){const U=H[_];L.push(U===void 0?Yo():U)}return L}),h=ch(e,c),m=h.length===c&&h.every(H=>H!==null)?h.map(H=>H===null?0:H):void 0,R=s.every(H=>H!==null)?s.map(H=>H===null?0:H):void 0;return{outcome:"payload",payload:{v:1,rows:o.length,cols:c,clipId:As(),formats:[...r.entries],validations:[],cells:u,...m===void 0?{}:{colWidths:m},...R===void 0?{}:{rowHeights:R},wholeRows:!1,wholeCols:!1,conditionalFormats:[]}}},ea=(e,t,n,r)=>{if(!Number.isInteger(r)||r<=0)throw new RangeError(`[spreadsheet] parseHtmlTable requires a positive integer maxCells, received ${r}`);let o;try{o=new DOMParser().parseFromString(e,"text/html")}catch{return{outcome:"none"}}const s=o.querySelector("table");if(s===null)return{outcome:"none"};const l=Ep(o);return dh(s,{kind:t,rules:l,options:n,separators:l.separators},r)},Re=(e,t)=>({startRow:Math.min(e.row,t.row),endRow:Math.max(e.row,t.row),startCol:Math.min(e.col,t.col),endCol:Math.max(e.col,t.col)}),Cn=(e,t)=>t.row>=e.startRow&&t.row<=e.endRow&&t.col>=e.startCol&&t.col<=e.endCol,st=e=>({rows:e.endRow-e.startRow+1,cols:e.endCol-e.startCol+1}),At=e=>e.reduce((t,n)=>t+st(n).rows*st(n).cols,0),Jt=(e,t)=>{if(e.length===1){const r=e[0];for(let o=r.startRow;o<=r.endRow;o+=1)for(let s=r.startCol;s<=r.endCol;s+=1)t({row:o,col:s});return}const n=new Set;for(const r of e)for(let o=r.startRow;o<=r.endRow;o+=1)for(let s=r.startCol;s<=r.endCol;s+=1){const l=`${o}:${s}`;n.has(l)||(n.add(l),t({row:o,col:s}))}},ln=(e,t,n)=>{if(t<=0||n<=0)throw new RangeError(`[spreadsheet] clampCoord requires a non-empty grid, received ${t} x ${n}`);return{row:Math.min(Math.max(Math.trunc(e.row),0),t-1),col:Math.min(Math.max(Math.trunc(e.col),0),n-1)}},It=(e,t)=>e.row===t.row&&e.col===t.col,ta=(e,t)=>e===void 0?Fl(void 0,void 0,t()):Fl(e.align,e.value,e.align===void 0?t():""),Qr=(e,t,n)=>{let r=null;return()=>(r===null&&(r=e.getCellText(t,n)),r)},Yn=(e,t,n)=>{if(e.getCellFormula!==void 0){const r=e.getCellFormula(t,n);if(r!==void 0){if(typeof r!="string"||!r.startsWith("="))throw new RangeError(`[spreadsheet] getCellFormula(${t}, ${n}) must return a string starting with "=", received ${JSON.stringify(r)}`);return{text:r,isFormula:!0}}}return{text:e.getCellText(t,n),isFormula:!1}},eo=e=>({format:e.getCellFormat!==void 0,note:e.getCellNote!==void 0,comments:e.getCellComments!==void 0,hyperlink:e.getCellHyperlink!==void 0,validation:e.getCellValidation!==void 0,cf:e.getConditionalFormats!==void 0,formula:e.getCellFormula!==void 0}),na=e=>e.isCellReadOnly!==void 0,Ye=(e,t,n)=>e.isCellReadOnly?.(t,n)===!0,fh=["rowCount","colCount","getCellText","applyEdits","findDataEdge","getCellFormat","getCellFormula","getCellNote","getCellComments","getCellHyperlink","getCellValidation","getConditionalFormats","isCellReadOnly","getCellAttributes","getRangeExtrema","evaluateFormula"],ph=()=>!0,hh=e=>{const t=new WeakMap,n={};for(const r of fh)r!=="isCellReadOnly"&&Object.defineProperty(n,r,{enumerable:!0,get:()=>{const o=Reflect.get(e,r,e);if(typeof o!="function")return o;const s=t.get(o);if(s!==void 0)return s;const l=o.bind(e);return t.set(o,l),l}});return Object.defineProperty(n,"isCellReadOnly",{enumerable:!0,value:ph}),n},mh=/^data-[a-z0-9-]+$/,gh=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},wh=(e,t,n)=>{if(e.getCellAttributes===void 0)return null;const r=e.getCellAttributes(t,n);if(r===null)return null;if(!gh(r))throw new RangeError(`[spreadsheet] getCellAttributes must return a plain data-* record or null (got ${Object.prototype.toString.call(r)})`);for(const[o,s]of Object.entries(r)){if(!mh.test(o))throw new RangeError(`[spreadsheet] getCellAttributes key must be a lowercase data-* name (got ${JSON.stringify(o)})`);if(o.startsWith("data-aqsp")||o.startsWith("data-aqvs")||o==="data-row"||o==="data-col")throw new RangeError(`[spreadsheet] getCellAttributes key ${JSON.stringify(o)} shadows a package- or engine-emitted cell attribute`);if(typeof s!="string")throw new RangeError(`[spreadsheet] getCellAttributes value for ${JSON.stringify(o)} must be a string (got ${typeof s})`)}return r},ur=(e,t)=>{const n=e.isCellReadOnly;if(n===void 0)return!1;for(let r=t.startRow;r<=t.endRow;r+=1)for(let o=t.startCol;o<=t.endCol;o+=1)if(n(r,o))return!0;return!1},qn=(e,t)=>{for(const n of t)if(ur(e,n))return!0;return!1},Ch=(e,t)=>{const n=e.length,r=e[0]?.length??0;if(n===0||r===0)return 0;const o=st(t);return!(o.rows===1&&o.cols===1)&&o.rows%n===0&&o.cols%r===0?o.rows*o.cols:n*r},gs=(e,t,n,r,o)=>{if(e.rows===0||e.cols===0)return null;const s=st(t),l=s.rows===1&&s.cols===1,c=!l&&s.rows%e.rows===0&&s.cols%e.cols===0,u=c?s.rows:e.rows,h=c?s.cols:e.cols,m=l?n:{row:t.startRow,col:t.startCol},R=Math.min(u,r-m.row),N=Math.min(h,o-m.col);return R<=0||N<=0?null:Re(m,{row:m.row+R-1,col:m.col+N-1})},ra=(e,t,n,r,o,s)=>{const l=e.length,c=e[0]?.length??0,u=gs({rows:l,cols:c},t,n,r,o);if(u===null)return[];const h={row:u.startRow,col:u.startCol},m=u.endRow-u.startRow+1,R=u.endCol-u.startCol+1,N=[];for(let H=0;H<m;H+=l){const L=[];for(let U=0;U<R;U+=c){const W={row:h.row+H,col:h.col+U};L.push(W),N.push(W)}const _=Math.min(l,m-H);for(let U=0;U<_;U+=1){const W=h.row+H+U,k=e[U];for(let x=0;x<L.length;x+=1){const z=x*c,I=Math.min(c,R-z);for(let T=0;T<I;T+=1)s(W,h.col+z+T,k[T],L[x])}}}return N},bh=(e,t,n,r,o)=>{const s=[];return ra(e,t,n,r,o,(l,c,u)=>{s.push({row:l,col:c,text:u})}),s},ii=(e,t,n,r,o,s)=>{const l=[],c=ra(e,t,n,r,o,(u,h,m,R)=>{const N=s(m,u,h,R);N!==null&&l.push({...N,row:u,col:h})});return{edits:l,tiles:c}},oa=(e,t)=>{const n=t.startRow<=e.startRow&&t.endRow>=e.endRow&&t.startCol<=e.startCol&&t.endCol>=e.endCol,r=t.startRow!==e.startRow||t.endRow!==e.endRow||t.startCol!==e.startCol||t.endCol!==e.endCol;if(!(n&&r))throw new RangeError(`[spreadsheet] expandFill requires a box strictly containing the source (source ${JSON.stringify(e)}, box ${JSON.stringify(t)})`)},yh=(e,t)=>{oa(e,t);const n=st(t),r=st(e),o=n.rows-r.rows,s=n.cols-r.cols,l=s>0?r.rows:Math.min(r.rows,o),c=o>0?r.cols:Math.min(r.cols,s);return n.rows*n.cols-r.rows*r.cols+l*c},Rh=(e,t)=>{if(!(t.startRow<=e.startRow&&t.endRow>=e.endRow&&t.startCol<=e.startCol&&t.endCol>=e.endCol))throw new RangeError(`[spreadsheet] fillExtensionRects requires a box containing the source (source ${JSON.stringify(e)}, box ${JSON.stringify(t)})`);const r=[];return t.startRow<e.startRow&&r.push(Re({row:t.startRow,col:t.startCol},{row:e.startRow-1,col:t.endCol})),t.endRow>e.endRow&&r.push(Re({row:e.endRow+1,col:t.startCol},{row:t.endRow,col:t.endCol})),t.startCol<e.startCol&&r.push(Re({row:e.startRow,col:t.startCol},{row:e.endRow,col:e.startCol-1})),t.endCol>e.endCol&&r.push(Re({row:e.startRow,col:e.endCol+1},{row:e.endRow,col:t.endCol})),r},vh=(e,t,n,r)=>{oa(t,n);const o=st(t).rows,s=st(t).cols,l=[],c=new Map;for(let u=n.startRow;u<=n.endRow;u+=1){const h=t.startRow+((u-t.startRow)%o+o)%o,m=u>=t.startRow&&u<=t.endRow;for(let R=n.startCol;R<=n.endCol;R+=1){if(m&&R>=t.startCol&&R<=t.endCol)continue;const N=t.startCol+((R-t.startCol)%s+s)%s,H=h*2**21+N;let L=c.get(H);L===void 0&&(L={value:e(h,N),origin:{row:h,col:N}},c.set(H,L)),l.push(r(L.value,L.origin,{row:u,col:R}))}}return l},sa=(e,t,n)=>{const r=Yn(e,t,n),o={text:r.text,isFormula:r.isFormula};if(e.getCellFormat!==void 0){const s=e.getCellFormat(t,n);o.format=s===void 0?null:gt(s)}if(e.getCellValidation!==void 0){const s=e.getCellValidation(t,n);o.validation=s===void 0?null:s}if(e.getCellHyperlink!==void 0){const s=Un(e.getCellHyperlink(t,n));o.hyperlink=s===void 0?null:s}if(e.getCellNote!==void 0){const s=e.getCellNote(t,n);o.note=s===void 0?null:s}return o},la=(e,t,n)=>{const r={row:n.row,col:n.col,text:e.isFormula?Mc(e.text,n.row-t.row,n.col-t.col):e.text};return e.format!==void 0&&(r.format=e.format),e.validation!==void 0&&(r.validation=e.validation),e.hyperlink!==void 0&&(r.hyperlink=e.hyperlink),e.note!==void 0&&(r.note=e.note),r},ho=["bold","italic","underline","strikethrough","clearFormatting","alignLeft","alignCenter","alignRight","formatNumber","formatTime","formatDate","formatCurrency","formatPercent","formatScientific","bordersOuter","bordersClear","borderTop","borderRight","borderBottom","borderLeft","insertLink","insertNote","insertComment","openHyperlink","openValidationList","pasteSpecial","fillDown","fillRight","fillSelection","insertDate","insertTime","hideRows","hideColumns","unhideRows","unhideColumns","increaseColumnWidth","decreaseColumnWidth","increaseRowHeight","decreaseRowHeight","autoFitColumnWidth","formatGeneral","bordersAll","pasteFormats","pasteFormulas","pasteAdd","pasteSubtract","pasteMultiply","pasteDivide","multiplyBy100","multiplyBy1000","divideBy100","divideBy1000","signReversal","fillColorYellow","fillColorBlue","fillColorGreen","fillColorRed","fillColorCustom1","fillColorCustom2","fillColorCustom3","fillColorCustom4","fillColorCustom5","fontColorYellow","fontColorBlue","fontColorGreen","fontColorRed","fontColorCustom1","fontColorCustom2","fontColorCustom3","fontColorCustom4","fontColorCustom5","toggleRowHighlight","toggleColumnHighlight","toggleBothHighlight","toggleIntersectionHighlight"],Sh=/^[A-Z]$/,kh=/^[A-Za-z]$/,Eh=/^Key([A-Z])$/,ia=new Set([...Array.from({length:10},(e,t)=>`Digit${t}`),...Array.from({length:10},(e,t)=>`Numpad${t}`),"NumpadAdd","NumpadSubtract","NumpadMultiply","NumpadDivide","NumpadDecimal","NumpadEnter",...Array.from({length:12},(e,t)=>`F${t+1}`),"Semicolon","Quote","Comma","Period","Slash","Backslash","BracketLeft","BracketRight","Backquote","Minus","Equal","IntlYen","IntlRo","IntlBackslash","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","Enter","Escape","Space","Tab","Delete","Backspace","Insert","ContextMenu"]),Ah=e=>Sh.test(e)||ia.has(e),Qt=e=>{const t=e.split("+");let n=0;const r=t[n]==="Ctrl";r&&(n+=1);const o=t[n]==="Alt";o&&(n+=1);const s=t[n]==="Shift";s&&(n+=1);const l=t[n];if(n!==t.length-1||l===void 0||!Ah(l))throw new RangeError(`[spreadsheet] shortcut ${JSON.stringify(e)} is not canonical (expected Ctrl+Alt+Shift+KEY with used modifiers only, KEY = A-Z or a code name such as Digit1 / Semicolon / F2)`);return{ctrl:r,alt:o,shift:s,key:l}},Oh=e=>`${e.ctrl?"Ctrl+":""}${e.alt?"Alt+":""}${e.shift?"Shift+":""}${e.key}`,ca=e=>{if(kh.test(e.key))return e.key.toUpperCase();const t=Eh.exec(e.code);return t!==null?t[1]:ia.has(e.code)?e.code:null},or=(e,t)=>e.ctrl!==(t.ctrlKey||t.metaKey)||e.alt!==t.altKey||e.shift!==t.shiftKey||e.alt&&t.getModifierState("AltGraph")?!1:ca(t)===e.key,we=(e,t,n)=>({chord:e,column:t,rebindable:!1,note:n}),ye=(e,t,n,r)=>({chord:t,column:n,rebindable:!0,command:e,note:r}),xh=()=>{const e=[];for(const t of["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"])e.push(we(t,"both","move active (idle) / commit + move in replace mode, caret in edit mode, reference cursor while pointing")),e.push(we(`Shift+${t}`,"both","extend selection (idle) / commit + extend in replace mode, text selection in edit mode")),e.push(we(`Ctrl+${t}`,"both","data-edge jump (idle) / native word caret (editing), Ctrl reference cursor while pointing")),e.push(we(`Ctrl+Shift+${t}`,"both","extend to data edge (idle) / consume + no-op (editing)"));return e},Th=()=>{const e=[];for(const t of["Equal","Minus","Digit0","NumpadAdd","NumpadSubtract","Numpad0"])e.push(we(`Ctrl+Alt+${t}`,"both","zoom token space (root capture listener, produced-character matching — v0.3.3 contract)")),e.push(we(`Ctrl+Alt+Shift+${t}`,"both","zoom token space, Shift-independent (JIS `=` is Shift+Minus, AZERTY `0` is Shift+Digit0)"));return e},vr=[...xh(),we("Home","idle","row start (first visible column)"),we("Ctrl+Home","idle","first visible cell"),we("Shift+Home","idle","extend to row start"),we("Ctrl+Shift+Home","idle","extend to first visible cell"),we("End","idle","row end (last visible column)"),we("Ctrl+End","idle","last visible cell"),we("Shift+End","idle","extend to row end"),we("Ctrl+Shift+End","idle","extend to last visible cell"),we("PageUp","both","page up (idle) / commit + page up (editing)"),we("PageDown","both","page down (idle) / commit + page down (editing)"),we("Shift+PageUp","idle","extend one page up"),we("Shift+PageDown","idle","extend one page down"),we("Ctrl+Shift+PageUp","idle","consume + no-op (sheet-switch class)"),we("Ctrl+Shift+PageDown","idle","consume + no-op (sheet-switch class)"),we("Tab","both","cycle right (idle) / commit + cycle right (editing)"),we("Shift+Tab","both","cycle left (idle) / commit + cycle left (editing)"),we("Enter","both","cycle down (idle) / commit + cycle down (editing)"),we("Shift+Enter","both","cycle up (idle) / commit + cycle up (editing)"),we("Alt+Enter","editing","newline at the caret (editing column only — coexists with the idle openHyperlink default)"),we("F2","both","start editing (idle) / toggle the pointing arm (editing)"),we("F4","editing","cycle the reference anchor under the caret (formula session)"),we("Delete","idle","clear every selected cell"),we("Backspace","idle","clear every selected cell"),we("Escape","both","abort drag > hide note tip > close rejected message > discard clip > hand off focus (idle) / cancel editing"),we("Ctrl+A","idle","select all"),we("Ctrl+Z","idle","undo request"),we("Ctrl+Y","idle","redo request"),we("Ctrl+Shift+Z","idle","redo request"),we("Shift+F10","idle","keyboard context menu"),we("ContextMenu","idle","keyboard context menu"),we("Ctrl+Space","idle","column bands"),we("Shift+Space","idle","row bands"),we("Ctrl+C","idle","native copy (ClipboardEvent path — never preventDefault)"),we("Ctrl+X","idle","native cut (ClipboardEvent path — never preventDefault)"),we("Ctrl+V","idle","native paste (ClipboardEvent path — never preventDefault)"),we("Ctrl+Shift+V","idle","pasteValues: arms the paste options, the native paste follows (not a command)"),{chord:"Ctrl+Alt+V",column:"idle",rebindable:!1,command:"pasteSpecial",note:"paste special (onPasteSpecialRequest / formats-only branch) — a command row that cannot be rebound"},...Th(),ye("bold","Ctrl+B","both","toggle bold"),ye("italic","Ctrl+I","both","toggle italic"),ye("underline","Ctrl+U","both","toggle underline"),ye("strikethrough","Alt+Shift+Digit5","both","toggle strikethrough"),ye("clearFormatting","Ctrl+Backslash","idle","clear formatting"),ye("clearFormatting","Ctrl+IntlYen","idle","clear formatting (JIS ¥ key)"),ye("clearFormatting","Ctrl+IntlRo","idle","clear formatting (JIS ろ key)"),ye("alignLeft","Ctrl+Shift+L","both","align left"),ye("alignCenter","Ctrl+Shift+E","both","align center"),ye("alignRight","Ctrl+Shift+R","both","align right"),ye("formatNumber","Ctrl+Shift+Digit1","both","number format"),ye("formatTime","Ctrl+Shift+Digit2","both","time format"),ye("formatDate","Ctrl+Shift+Digit3","both","date format"),ye("formatCurrency","Ctrl+Shift+Digit4","both","currency format"),ye("formatPercent","Ctrl+Shift+Digit5","both","percent format"),ye("formatScientific","Ctrl+Shift+Digit6","both","scientific format"),ye("bordersOuter","Alt+Shift+Digit7","idle","outer borders"),ye("bordersClear","Alt+Shift+Digit6","idle","clear borders"),ye("borderTop","Alt+Shift+Digit1","idle","top border"),ye("borderRight","Alt+Shift+Digit2","idle","right border"),ye("borderBottom","Alt+Shift+Digit3","idle","bottom border"),ye("borderLeft","Alt+Shift+Digit4","idle","left border"),ye("insertLink","Ctrl+K","idle","insert / edit hyperlink"),ye("insertNote","Shift+F2","idle","insert / edit note"),ye("insertComment","Ctrl+Alt+M","idle","insert comment"),ye("openHyperlink","Alt+Enter","idle","open the hyperlink (idle column — the editing Alt+Enter row is a different column)"),ye("openValidationList","Alt+ArrowDown","idle","open the validation list"),ye("fillDown","Ctrl+D","idle","fill down"),ye("fillRight","Ctrl+R","idle","fill right"),ye("fillSelection","Ctrl+Enter","both","fill the selection with the active / session text"),ye("insertDate","Ctrl+Semicolon","both","insert today's date (active cell / caret)"),ye("insertTime","Ctrl+Shift+Semicolon","both","insert the current time (active cell / caret)"),ye("hideRows","Ctrl+Alt+Digit9","idle","hide the selected rows"),ye("unhideRows","Ctrl+Shift+Digit9","idle","unhide rows"),ye("unhideColumns","Ctrl+Shift+Digit0","idle","unhide columns"),ye("increaseColumnWidth","Alt+Shift+ArrowRight","idle","widen the active column by one step (x 2^(1/4))"),ye("decreaseColumnWidth","Alt+Shift+ArrowLeft","idle","narrow the active column by one step (/ 2^(1/4), never below 1 px)"),ye("increaseRowHeight","Alt+Shift+ArrowDown","idle","make the active row taller by one step (x 2^(1/4))"),ye("decreaseRowHeight","Alt+Shift+ArrowUp","idle","make the active row shorter by one step (/ 2^(1/4), never below 1 px)"),ye("autoFitColumnWidth","Alt+Shift+Equal","idle","fit the active column to its content (the strip double-click)")],Uo=Object.freeze(["increaseColumnWidth","decreaseColumnWidth","increaseRowHeight","decreaseRowHeight","autoFitColumnWidth"]),ci=Object.freeze({Equal:"=",Minus:"-",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/",Backslash:"\\",BracketLeft:"[",BracketRight:"]",Backquote:"`",NumpadAdd:"+",NumpadSubtract:"-",NumpadMultiply:"*",NumpadDivide:"/",NumpadDecimal:".",NumpadEnter:"Enter"}),$h=e=>{const t=Qt(e);if(t.key==="IntlYen"||t.key==="IntlRo"||t.key==="IntlBackslash")return null;const n=/^(?:Digit|Numpad)(\d)$/u.exec(t.key),r=n!==null?n[1]:t.key in ci?ci[t.key]:t.key;return`${t.ctrl?"Control+":""}${t.alt?"Alt+":""}${t.shift?"Shift+":""}${r}`},oo=(e,t)=>e.column==="both"||e.column===t,Lh=Array.from(new Set(vr.filter(e=>!e.rebindable&&oo(e,"idle")).map(e=>e.chord))),Ps=new Set(vr.filter(e=>e.command!==void 0&&oo(e,"editing")).map(e=>e.command)),Dh=new Set(vr.filter(e=>e.command!==void 0&&!e.rebindable).map(e=>e.command)),aa=e=>{const t={};for(const n of ho)t[n]=e(n);return t},ua=aa(e=>vr.filter(t=>t.command===e).map(t=>t.chord)),Mh=e=>{const t=new Map;for(const n of ho){const r=e[n];if(r!=null)for(const o of r){const s=t.get(o);s===void 0?t.set(o,[n]):s.includes(n)||s.push(n)}}return t},zh=e=>{const t=new Set(ho);for(const n of Object.keys(e)){if(!t.has(n))throw new RangeError(`[spreadsheet] shortcuts.${n} is not a SpreadsheetCommand`);const r=e[n];if(r!==void 0){if(Dh.has(n))throw new RangeError(`[spreadsheet] shortcuts.${n} is not rebindable`);if(r!==null){if(!Array.isArray(r))throw new RangeError(`[spreadsheet] shortcuts.${n} must be an array or null`);for(const o of r)if(typeof o!="string")throw new RangeError(`[spreadsheet] shortcuts.${n} must be an array of chord strings`)}}}},Nh=(e,t)=>{const n=Qt(t);if(!(n.ctrl||n.alt||n.shift))throw new RangeError(`[spreadsheet] shortcut ${t} for ${e} has no modifier`);const r=Ps.has(e);for(const o of vr)if(!(o.rebindable||o.command===e||o.chord!==t)&&(oo(o,"idle")||r&&oo(o,"editing")))throw new RangeError(`[spreadsheet] shortcut ${t} for ${e} is reserved by a built-in row (${o.column} column: ${o.note})`)},Fh=e=>{e!==void 0&&zh(e);const t=aa(r=>{const o=e===void 0?void 0:e[r];return o===void 0?ua[r]:o===null?[]:o});for(const r of ho)for(const o of t[r])Nh(r,o);const n=new Map;for(const[r,o]of Mh(t)){if(o.length>1)throw new RangeError(`[spreadsheet] shortcut ${r} bound to ${o.slice(0,-1).join(", ")} and ${o[o.length-1]}`);n.set(r,o[0])}return n},ai=(e,t)=>{const n=ca(t);if(n===null)return null;const r=t.altKey;if(r&&t.getModifierState("AltGraph"))return null;const o=e.get(Oh({ctrl:t.ctrlKey||t.metaKey,alt:r,shift:t.shiftKey,key:n}));return o===void 0?null:o},_s=["sinkAriaLabel","rootAriaLabel","noteTitle","noteSave","noteEscapeHint","noteRejectedHint","noteViewerHint","commentTitle","commentReply","commentPost","commentCount","linkTitle","linkTextField","linkUrlField","linkOpen","linkSave","listTitle","listEmpty","listMore","messageTitle","popoverClose"],ui=[...Je.VIRTUAL_SCROLL_LABEL_KEYS,..._s],ws=Object.freeze({en:Object.freeze({sinkAriaLabel:"Spreadsheet grid. Press Escape to move focus out of the grid.",rootAriaLabel:"Spreadsheet",noteTitle:"Note",noteSave:"Save",noteEscapeHint:"Escape saves and closes",noteRejectedHint:"The note was rejected. Press Ctrl+Enter to retry or Escape to close without saving",noteViewerHint:"Escape closes without saving",commentTitle:"Comments",commentReply:"Reply",commentPost:"Post",commentCount:e=>e===1?"1 comment":`${e} comments`,linkTitle:"Link",linkTextField:"Text",linkUrlField:"URL",linkOpen:"Open",linkSave:"Save",listTitle:"Choose a value",listEmpty:"No matching values",listMore:e=>e===1?"1 more value — keep typing to narrow":`${e} more values — keep typing to narrow`,messageTitle:"Data validation",popoverClose:"Close"}),ja:Object.freeze({sinkAriaLabel:"スプレッドシートのグリッド。Escape キーでグリッドの外へフォーカスを移動します。",rootAriaLabel:"スプレッドシート",noteTitle:"メモ",noteSave:"保存",noteEscapeHint:"Escape で保存して閉じます",noteRejectedHint:"メモは拒否されました。Ctrl+Enter で再試行、Escape で保存せずに閉じます",noteViewerHint:"Escape で保存せずに閉じます",commentTitle:"コメント",commentReply:"返信",commentPost:"投稿",commentCount:e=>`${e} 件のコメント`,linkTitle:"リンク",linkTextField:"表示テキスト",linkUrlField:"URL",linkOpen:"開く",linkSave:"保存",listTitle:"値を選択",listEmpty:"一致する値がありません",listMore:e=>`ほかに ${e} 件 — 入力して絞り込んでください`,messageTitle:"データの入力規則",popoverClose:"閉じる"})}),da=Object.freeze({en:Object.freeze({...Je.VIRTUAL_SCROLL_LABEL_CATALOGS.en,...ws.en}),ja:Object.freeze({...Je.VIRTUAL_SCROLL_LABEL_CATALOGS.ja,...ws.ja})}),mn=e=>typeof e=="string"?JSON.stringify(e):e===null?"null":typeof e,di=e=>e==="commentCount"||e==="listMore",Ph=e=>{const t=e.sinkAriaLabel;if(typeof t!="string"||!t.includes("Escape"))throw new RangeError(`[spreadsheet] labels.sinkAriaLabel must be a string mentioning "Escape" (WCAG 2.1.2 escape advisement, spec 00 §10-4); got ${mn(t)}`);for(const n of _s){const r=e[n];if(!(di(n)&&typeof r=="function")&&(typeof r!="string"||r.trim()==="")){const o=di(n)?"a non-blank string or a function":"a non-blank string";throw new RangeError(`[spreadsheet] labels.${n} must be ${o}; got ${mn(r)}`)}}},_h=e=>{const t={};let n=!1;for(const r of Je.VIRTUAL_SCROLL_LABEL_KEYS){const o=Object.hasOwn(e,r)?e[r]:void 0;o!==void 0&&(t[r]=o,n=!0)}return n?t:void 0},qh=(e,t,n)=>{e[t]=n},fa=(e,t)=>{const n=Je.resolveVirtualScrollLocale(e);if(t===void 0)return da[n];if(t===null||typeof t!="object")throw new RangeError(`[spreadsheet] labels must be an object; got ${mn(t)}`);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new RangeError(`[spreadsheet] labels must be a plain object (prototype Object.prototype or null); got ${Array.isArray(t)?"an array":"an object with a non-plain prototype"}`);for(const l of Object.keys(t))if(!ui.includes(l))throw new RangeError(`[spreadsheet] labels.${l} is not a known label key; expected one of ${ui.join(", ")}`);const s={...Je.resolveVirtualScrollLabels(n,_h(t)),...ws[n]};for(const l of _s){const c=Object.hasOwn(t,l)?t[l]:void 0;c!==void 0&&qh(s,l,c)}return Ph(s),Object.freeze(s)},Ih=e=>{const t={};for(const n of Je.VIRTUAL_SCROLL_LABEL_KEYS)t[n]=e[n];return Object.freeze(t)},ze=(e,t,n)=>{const r=e[t];if(typeof r=="function"){if(n===void 0)throw new RangeError(`[spreadsheet] labels.${t} is count-aware; resolveLabel needs n`);return r(n)}return r},fi={gt:"greater than",gte:"greater than or equal to",lt:"less than",lte:"less than or equal to"},jh={gt:"after",gte:"on or after",lt:"before",lte:"on or before"},Hh=(e,t,n,r)=>{switch(e){case"gt":case"gte":case"lt":case"lte":return`${r[e]} ${t}`;case"eq":return`equal to ${t}`;case"neq":return`not equal to ${t}`;case"between":return`between ${t} and ${n}`;default:return`not between ${t} and ${n}`}},Xo=(e,t)=>{const n=r=>(o,s)=>`${e} ${Hh(r,o,s,t)}.`;return Object.freeze({gt:n("gt"),gte:n("gte"),lt:n("lt"),lte:n("lte"),eq:n("eq"),neq:n("neq"),between:n("between"),notBetween:n("notBetween")})},Bh=Object.freeze({list:"Value must be one of the list items.",number:Xo("Value must be a number",fi),textLength:Xo("Text length must be",fi),date:Xo("Value must be a date",jh),text:Object.freeze({contains:e=>`Value must contain "${e}".`,notContains:e=>`Value must not contain "${e}".`,startsWith:e=>`Value must start with "${e}".`,endsWith:e=>`Value must end with "${e}".`,isEmail:"Value must be a valid email address.",isUrl:"Value must be a valid URL."}),checkbox:(e,t)=>`Value must be "${e}" or "${t}".`,custom:e=>`Value does not satisfy the formula ${e}.`}),Vh=Object.freeze({list:"リストの項目のいずれかを入力してください。",number:Object.freeze({gt:e=>`${e} より大きい数値を入力してください。`,gte:e=>`${e} 以上の数値を入力してください。`,lt:e=>`${e} より小さい数値を入力してください。`,lte:e=>`${e} 以下の数値を入力してください。`,eq:e=>`${e} に等しい数値を入力してください。`,neq:e=>`${e} 以外の数値を入力してください。`,between:(e,t)=>`${e} から ${t} までの数値を入力してください。`,notBetween:(e,t)=>`${e} から ${t} までの範囲外の数値を入力してください。`}),textLength:Object.freeze({gt:e=>`${e} 文字より長いテキストを入力してください。`,gte:e=>`${e} 文字以上のテキストを入力してください。`,lt:e=>`${e} 文字より短いテキストを入力してください。`,lte:e=>`${e} 文字以下のテキストを入力してください。`,eq:e=>`${e} 文字のテキストを入力してください。`,neq:e=>`${e} 文字以外の長さのテキストを入力してください。`,between:(e,t)=>`${e} 文字から ${t} 文字までのテキストを入力してください。`,notBetween:(e,t)=>`${e} 文字から ${t} 文字までの範囲外の長さのテキストを入力してください。`}),date:Object.freeze({gt:e=>`${e} より後の日付を入力してください。`,gte:e=>`${e} 以降の日付を入力してください。`,lt:e=>`${e} より前の日付を入力してください。`,lte:e=>`${e} 以前の日付を入力してください。`,eq:e=>`${e} の日付を入力してください。`,neq:e=>`${e} 以外の日付を入力してください。`,between:(e,t)=>`${e} から ${t} までの日付を入力してください。`,notBetween:(e,t)=>`${e} から ${t} までの範囲外の日付を入力してください。`}),text:Object.freeze({contains:e=>`「${e}」を含む値を入力してください。`,notContains:e=>`「${e}」を含まない値を入力してください。`,startsWith:e=>`「${e}」で始まる値を入力してください。`,endsWith:e=>`「${e}」で終わる値を入力してください。`,isEmail:"有効なメールアドレスを入力してください。",isUrl:"有効な URL を入力してください。"}),checkbox:(e,t)=>`「${e}」または「${t}」を入力してください。`,custom:e=>`数式 ${e} を満たす値を入力してください。`}),Go=Object.freeze({en:Bh,ja:Vh}),Wh=Object.freeze({ok:!0}),Kh="TRUE",Yh="FALSE",Uh=new Set(["gt","gte","lt","lte","eq","neq","between","notBetween"]),Xh=new Set(["contains","notContains","startsWith","endsWith","isEmail","isUrl"]),Gh=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d{1,4})?$/,Zh=/^(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/,Jh=/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/,pi=e=>{const t=e.trim();if(!(Gh.test(t)&&Number.isFinite(Number(t))))return null;const n=t.startsWith("-"),r=t.replace(/^[+-]/,""),o=r.search(/[eE]/),s=o<0?r:r.slice(0,o),l=o<0?0:Number(r.slice(o+1)),c=s.indexOf("."),u=c<0?s:s.slice(0,c),h=c<0?"":s.slice(c+1),m=u+h,R=m.search(/[^0]/);return R<0?{sign:0,digits:"",point:0}:{sign:n?-1:1,digits:m.slice(R).replace(/0+$/,""),point:u.length+l-R}},Qh=e=>e===1?-1:e===-1?1:0,em=(e,t)=>{if(e.sign!==t.sign)return e.sign<t.sign?-1:1;if(e.sign===0)return 0;const n=e.point!==t.point?e.point<t.point?-1:1:e.digits===t.digits?0:e.digits<t.digits?-1:1;return e.sign===1?n:Qh(n)},tm=(e,t)=>{switch(t){case 2:return e%4===0&&e%100!==0||e%400===0?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}},hi=e=>{const t=Zh.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);return r<1||r>12||o<1||o>tm(n,r)||s>23||l>59||c>59?null:{year:n,month:r,day:o,hour:s,minute:l,second:c}},nm=(e,t)=>{const n=[e.year,e.month,e.day,e.hour,e.minute,e.second],r=[t.year,t.month,t.day,t.hour,t.minute,t.second];for(let o=0;o<n.length;o+=1)if(n[o]!==r[o])return n[o]<r[o]?-1:1;return 0},rm=(e,t)=>e<t?-1:e>t?1:0,om=e=>e==="between"||e==="notBetween",sm=(e,t,n,r)=>{const o=r(t);if(o===null)return null;if(!om(e))return{a:o,b:null};const s=n===void 0?null:r(n);return s===null?null:{a:o,b:s}},lm=(e,t,n)=>{switch(e){case"gt":return t===1;case"gte":return t!==-1;case"lt":return t===-1;case"lte":return t!==1;case"eq":return t===0;case"neq":return t!==0;case"between":return t!==-1&&n!==1;default:return t===-1||n===1}},Zo=(e,t,n,r,o,s)=>{const l=sm(e,t,n,r);return l===null?!0:o===null?!1:lm(e,s(o,l.a),l.b===null?0:s(o,l.b))},im=e=>Number.isFinite(e)?e:null,cm=e=>{let t=0;for(const n of e)t+=1;return t},am=e=>URL.canParse(e)&&/^https?:$/.test(new URL(e).protocol),um=(e,t)=>{switch(e.op){case"isEmail":return Jh.test(t);case"isUrl":return am(t)}if(e.value===void 0)return!0;switch(e.op){case"contains":return t.includes(e.value);case"notContains":return!t.includes(e.value);case"startsWith":return t.startsWith(e.value);default:return t.endsWith(e.value)}},dm=e=>e===!0||typeof e=="number"&&Number.isFinite(e)&&e!==0,pa=e=>({checked:e.checked===void 0?Kh:e.checked,unchecked:e.unchecked===void 0?Yh:e.unchecked}),fm=e=>{switch(e.type){case"list":case"checkbox":case"custom":return;case"number":case"textLength":case"date":if(!Uh.has(e.op))throw new RangeError(`[spreadsheet] unknown data-validation op ${mn(e.op)} for type "${e.type}"`);return;case"text":if(!Xh.has(e.op))throw new RangeError(`[spreadsheet] unknown data-validation op ${mn(e.op)} for type "text"`);return;default:throw new RangeError(`[spreadsheet] unknown data-validation rule type ${mn(e.type)}`)}},pm=(e,t,n)=>{switch(e.type){case"list":return gm(e).has(t);case"number":return Zo(e.op,e.a,e.b,pi,pi(t),em);case"textLength":return Zo(e.op,e.a,e.b,im,cm(t),rm);case"date":return Zo(e.op,e.a,e.b,hi,hi(t),nm);case"text":return um(e,t);case"checkbox":{const r=pa(e);return t===r.checked||t===r.unchecked}default:return n===void 0||dm(n(e.formula))}},ha=(e,t,n)=>(fm(e),t===""||pm(e,t,n)),mi=e=>e===void 0?void 0:e.trim(),hm=(e,t)=>{switch(e.type){case"list":return t.list;case"number":return t.number[e.op](e.a.trim(),mi(e.b));case"textLength":return t.textLength[e.op](String(e.a),e.b===void 0?void 0:String(e.b));case"date":return t.date[e.op](e.a.trim(),mi(e.b));case"text":return mm(e,t.text);case"checkbox":{const n=pa(e);return t.checkbox(n.checked,n.unchecked)}default:return t.custom(e.formula)}},mm=(e,t)=>{switch(e.op){case"isEmail":return t.isEmail;case"isUrl":return t.isUrl;default:return t[e.op](e.value)}},gi=new WeakMap,gm=e=>{const t=gi.get(e);if(t!==void 0)return t;const n=new Set(e.values);return gi.set(e,n),n},ma=(e,t,n,r)=>{if(typeof n!="string"||!Object.hasOwn(Go,n)){const o=Object.keys(Go).map(s=>JSON.stringify(s)).join(", ");throw new RangeError(`[spreadsheet] validateCellText locale must be one of ${o}; got ${mn(n)}`)}return ha(e,t,r)?Wh:{ok:!1,message:e.errorMessage===void 0?hm(e,Go[n]):e.errorMessage}},wm=e=>e.type!=="custom",Cm=(e,t)=>wm(e)&&!ha(e,t,void 0),ga=(e,t)=>t<=0||e.count===0?0:t>=e.count?e.totalSize():e.offsetOf(t),wa=(e,t)=>t<=0||e.count===0?0:t>=e.count?e.totalSize():e.totalSize()-e.offsetOf(e.count-t),Ca=(e,t,{scroll:n,frozenCount:r,trailingCount:o,extent:s})=>t<r?e.offsetOf(t):o>0&&s>0&&t>=e.count-o?s-(e.totalSize()-e.offsetOf(t)):e.offsetOf(t)-n,ba=(e,t,{scroll:n,frozenSize:r,trailingSize:o,extent:s})=>r>0&&t<r?e.indexAt(t):o>0&&s>0&&t>=s-o?e.indexAt(e.totalSize()-(s-t)):e.indexAt(t+n),ya=(e,t)=>ga(e,t),Ra=(e,t)=>ga(e,t),va=(e,t)=>wa(e,t),Sa=(e,t)=>wa(e,t),gn=(e,t,n)=>Ca(e,t,n),wn=(e,t,n)=>Ca(e,t,n),Sr=(e,t,n)=>ba(e,t,n),kr=(e,t,n)=>ba(e,t,n),bm=Object.freeze({cols:0,width:0,rows:0,height:0,trailingCols:0,trailingRows:0,trailingWidth:0,trailingHeight:0,trailingVisibleWidth:0,trailingVisibleHeight:0}),Zt=1,dr=3,Ir=e=>`${-Math.min(dr,Math.max(0,Math.floor(e)))}px`,ka=Object.freeze({row:"#0084FF",column:"#42FF4F",intersection:"#E1FF00",opacity:.2}),ym=16,Rm=450,vm=e=>e>4?Math.floor(Rm/(5*e)):ym,sr=(e,t)=>{const n=document.createElement("div");return n.className="aqsp-band",n.setAttribute("data-aqsp-band",e),t!==null&&n.setAttribute("data-aqsp-band-edge",t),n.style.display="none",n},wi=()=>({rowLeft:sr("row","left"),rowRight:sr("row","right"),colAbove:sr("column","above"),colBelow:sr("column","below"),cross:sr("intersection",null),last:{rowShown:!1,colShown:!1,crossShown:!1,crossTint:"intersection",rowHeight:-1,colWidth:-1,crossWidth:-1,crossHeight:-1,rowLeftTransform:"",rowRightTransform:"",colAboveTransform:"",colBelowTransform:"",crossTransform:""}}),Ea=e=>[e.rowLeft,e.rowRight,e.colAbove,e.colBelow,e.cross],jr=(e,t,n)=>{const r=`${t}px`,o=`${n}px`;e.rowLeft.style.width=r,e.rowRight.style.width=r,e.colAbove.style.height=o,e.colBelow.style.height=o},Hr=(e,t)=>Math.min(Math.max(e,0),t),Ci="inset(100%)",Hn=(e,t)=>{for(const n of e)n.style.display=t?"block":"none"},Sm=(e,t,n,r,o)=>{const s=e.last,l=r.row&&!o;if(l!==s.rowShown&&(s.rowShown=l,Hn([e.rowLeft,e.rowRight],l)),l){if(t.height!==s.rowHeight){s.rowHeight=t.height;const N=`${t.height}px`;e.rowLeft.style.height=N,e.rowRight.style.height=N}const m=`translate(${Hr(t.left,n.clampWidth)-n.clampWidth}px, ${t.top}px)`;m!==s.rowLeftTransform&&(s.rowLeftTransform=m,e.rowLeft.style.transform=m);const R=`translate(${Hr(t.left+t.width,n.clampWidth)}px, ${t.top}px)`;R!==s.rowRightTransform&&(s.rowRightTransform=R,e.rowRight.style.transform=R)}const c=r.column&&!o;if(c!==s.colShown&&(s.colShown=c,Hn([e.colAbove,e.colBelow],c)),c){if(t.width!==s.colWidth){s.colWidth=t.width;const N=`${t.width}px`;e.colAbove.style.width=N,e.colBelow.style.width=N}const m=`translate(${t.left}px, ${Hr(t.top,n.clampHeight)-n.clampHeight}px)`;m!==s.colAboveTransform&&(s.colAboveTransform=m,e.colAbove.style.transform=m);const R=`translate(${t.left}px, ${Hr(t.top+t.height,n.clampHeight)}px)`;R!==s.colBelowTransform&&(s.colBelowTransform=R,e.colBelow.style.transform=R)}const u=r.intersection?"intersection":l!==c?l?"row":"column":null,h=u!==null;if(h!==s.crossShown&&(s.crossShown=h,Hn([e.cross],h)),u!==null){u!==s.crossTint&&(s.crossTint=u,e.cross.style.background=u==="intersection"?"":`var(--_aqsp-band-${u})`),(t.width!==s.crossWidth||t.height!==s.crossHeight)&&(s.crossWidth=t.width,s.crossHeight=t.height,e.cross.style.width=`${t.width}px`,e.cross.style.height=`${t.height}px`);const m=`translate(${t.left}px, ${t.top}px)`;m!==s.crossTransform&&(s.crossTransform=m,e.cross.style.transform=m)}},bi=e=>{const t=e.last;t.rowShown&&(t.rowShown=!1,Hn([e.rowLeft,e.rowRight],!1)),t.colShown&&(t.colShown=!1,Hn([e.colAbove,e.colBelow],!1)),t.crossShown&&(t.crossShown=!1,Hn([e.cross],!1))},yi=e=>{for(const t of Ea(e))t.remove()},km=(e,t)=>{const n=e-1-t.lineBoxPx;return t.verticalAlign==="top"?0:t.verticalAlign==="bottom"?Math.max(0,n):Math.max(0,n/2)},Em=Object.freeze([]),Ri=e=>e.dividers[0]??e.active,Am={left:"0px",right:"0px",width:""},Om={top:"0px",bottom:"0px",height:""},vi=()=>({container:null,active:null,dragRect:null,marquee:null,fillPreview:null,resizeGuide:null,fillPool:[],bandPool:[],dragBand:null,bandClampWidth:-1,bandClampHeight:-1,dividerSlots:[null,null,null,null],dividerShown:[!1,!1,!1,!1],dividers:[]}),Si=["mm","mf","ms","mt","fm","ff","fs","ft","sm","sf","ss","st","tm","tf","ts","tt"],ki=6,xm=({rowAxis:e,colAxis:t,handleRef:n,sinkRef:r,getSelection:o,editing:s,virtualKeyboard:l,repaintRef:c,dragFrameRef:u,getClip:h,getIsDraggingAny:m,getIsFillDragging:R,fillFrameRef:N,resizeGuideFrameRef:H,fillHandleNodeRef:L,enableFillHandle:_,frozenCols:U,frozenRows:W,trailingCols:k,trailingRows:x,sinkAriaLabel:z,sinkReadOnly:I,sinkKeyShortcuts:T,onSinkMouseDown:F,editPaintRef:O,highlightRef:g,highlightColors:p,popoverAnchors:C,interactiveAnchorRef:v,tipAnchorRef:S})=>{const b=i.useRef(null),y=i.useRef(null),a=i.useRef(null),f=i.useRef(new Map(Si.map(M=>[M,vi()]))),E=i.useCallback(M=>{const B=f.current.get(M);if(B!==void 0)return B;const X=vi();return f.current.set(M,X),X},[]),d=i.useCallback((M,B,X)=>{if(M===null)return;const V=M.style;V.left!==B.left&&(V.left=B.left),V.right!==B.right&&(V.right=B.right),V.width!==B.width&&(V.width=B.width),V.top!==X.top&&(V.top=X.top),V.bottom!==X.bottom&&(V.bottom=X.bottom),V.height!==X.height&&(V.height=X.height)},[]),$=i.useCallback((M,B,X)=>{if(!(M.bandClampWidth===B&&M.bandClampHeight===X)){M.bandClampWidth=B,M.bandClampHeight=X;for(const V of M.bandPool)jr(V,B,X);M.dragBand!==null&&jr(M.dragBand,B,X)}},[]),A=i.useRef({rowAxis:e,colAxis:t});A.current={rowAxis:e,colAxis:t};const D=i.useCallback((M,B,X)=>{const V=M.dividerSlots[B];V===null||M.dividerShown[B]===X||(M.dividerShown[B]=X,V.style.display=X?"":"none")},[]),q=i.useRef({x:0,y:0}),j=i.useRef(null),K=i.useCallback((M,B)=>{const X=n.current,V=X?.getFrozenSize()??bm,ee=X?.getViewportSize(),se=ee?.width??-1,ne=ee?.height??-1,Oe=q.current;Oe.x=M,Oe.y=B;let Se=j.current;if(Se===null||Se.frozenCols!==V.cols||Se.frozenWidth!==V.width||Se.frozenRows!==V.rows||Se.frozenHeight!==V.height||Se.trailingCols!==V.trailingCols||Se.trailingWidth!==V.trailingWidth||Se.trailingVisibleWidth!==V.trailingVisibleWidth||Se.trailingRows!==V.trailingRows||Se.trailingHeight!==V.trailingHeight||Se.trailingVisibleHeight!==V.trailingVisibleHeight||Se.bodyWidth!==se||Se.bodyHeight!==ne){const ie=V.trailingVisibleWidth,ce=V.trailingVisibleHeight,ge=V.cols<=0&&V.trailingCols<=0?[{kind:"m",map:re=>re-Oe.x,clamp:se,style:Am,seamLead:!1,seamTrail:!1}]:[...V.cols>0?[{kind:"f",map:re=>re,clamp:V.width,style:{left:"0px",width:`${V.width}px`,right:""},seamLead:!1,seamTrail:!0}]:[],{kind:"s",map:re=>re-Oe.x-V.width,clamp:Math.max(0,se-V.width-ie),style:{left:`${V.width}px`,right:`${ie}px`,width:""},seamLead:V.cols>0,seamTrail:V.trailingCols>0},...V.trailingCols>0?[{kind:"t",map:re=>re-A.current.colAxis.totalSize()+ie,clamp:ie,style:{left:"",right:"0px",width:`${ie}px`},seamLead:!0,seamTrail:!1}]:[]],Ce=V.rows<=0&&V.trailingRows<=0?[{kind:"m",map:re=>re-Oe.y,clamp:ne,style:Om,seamLead:!1,seamTrail:!1}]:[...V.rows>0?[{kind:"f",map:re=>re,clamp:V.height,style:{top:"0px",height:`${V.height}px`,bottom:""},seamLead:!1,seamTrail:!0}]:[],{kind:"s",map:re=>re-Oe.y-V.height,clamp:Math.max(0,ne-V.height-ce),style:{top:`${V.height}px`,bottom:`${ce}px`,height:""},seamLead:V.rows>0,seamTrail:V.trailingRows>0},...V.trailingRows>0?[{kind:"t",map:re=>re-A.current.rowAxis.totalSize()+ce,clamp:ce,style:{top:"",bottom:"0px",height:`${ce}px`},seamLead:!0,seamTrail:!1}]:[]],he=[];for(const re of ge)for(const ke of Ce)he.push({nodes:E(`${re.kind}${ke.kind}`),xKind:re.kind,yKind:ke.kind,mapX:re.map,clampWidth:re.clamp,xStyle:re.style,xSeamLead:re.seamLead,xSeamTrail:re.seamTrail,mapY:ke.map,clampHeight:ke.clamp,yStyle:ke.style,ySeamLead:ke.seamLead,ySeamTrail:ke.seamTrail});Se={frozenCols:V.cols,frozenWidth:V.width,frozenRows:V.rows,frozenHeight:V.height,trailingCols:V.trailingCols,trailingWidth:V.trailingWidth,trailingVisibleWidth:V.trailingVisibleWidth,trailingRows:V.trailingRows,trailingHeight:V.trailingHeight,trailingVisibleHeight:V.trailingVisibleHeight,bodyWidth:se,bodyHeight:ne,ctxs:he},j.current=Se}const Be=V.width>0,Ve=V.trailingWidth>0,_e=V.height>0,ve=V.trailingHeight>0;for(const ie of Se.ctxs)d(ie.nodes.container,ie.xStyle,ie.yStyle),$(ie.nodes,ie.clampWidth,ie.clampHeight),D(ie.nodes,0,Be),D(ie.nodes,1,Ve),D(ie.nodes,2,_e),D(ie.nodes,3,ve);return Se.ctxs},[n,E,d,$,D]),G=i.useCallback((M,B,X)=>{M.dividerSlots[B]=X,M.dividerShown[B]=!1,M.dividers.length=0;for(const V of M.dividerSlots)V!==null&&M.dividers.push(V)},[]),J=i.useCallback(M=>{const B=()=>E(M);return{container:X=>{const V=B();V.container=X,X===null&&(V.fillPool.length=0,V.bandPool.length=0,V.dragBand=null,V.bandClampWidth=-1,V.bandClampHeight=-1)},dividerXLeading:X=>G(B(),0,X),dividerXTrailing:X=>G(B(),1,X),dividerYLeading:X=>G(B(),2,X),dividerYTrailing:X=>G(B(),3,X),active:X=>{B().active=X},dragRect:X=>{B().dragRect=X},marquee:X=>{B().marquee=X},fillPreview:X=>{B().fillPreview=X},resizeGuide:X=>{B().resizeGuide=X}}},[E,G]),te=i.useMemo(()=>Object.fromEntries(Si.map(M=>[M,J(M)])),[J]),le=Math.min(Math.max(0,U),t.count),me=ya(t,le),Ee=Math.min(Math.max(0,W),e.count),xe=Ra(e,Ee),De=k===void 0?0:Math.min(Math.max(0,k),t.count-le),Pe=va(t,De),ue=x===void 0?0:Math.min(Math.max(0,x),e.count-Ee),Ne=Sa(e,ue),Ue=i.useRef(null),je=i.useRef("add"),Ot=i.useRef(s);Ot.current=s;const xt=i.useRef(!1),He=Je.useWheelBridge(n,{enableBridge:!s}),wt=i.useCallback(M=>(r.current=M,He(M)),[r,He]),bn=i.useCallback((M,B)=>({top:B.mapY(e.offsetOf(M.startRow)),bottom:B.mapY(e.offsetOf(M.endRow)+e.sizeOf(M.endRow)),left:B.mapX(t.offsetOf(M.startCol)),right:B.mapX(t.offsetOf(M.endCol)+t.sizeOf(M.endCol))}),[e,t]),lt=i.useCallback((M,B)=>{if(B.clampHeight<=0||B.clampWidth<=0)return null;const{top:X,bottom:V,left:ee,right:se}=bn(M,B),ne=-B.clampHeight*Zt,Oe=B.clampHeight*(1+Zt),Se=-B.clampWidth*Zt,Be=B.clampWidth*(1+Zt);if(V<ne||X>Oe||se<Se||ee>Be)return null;const Ve=Math.max(X,ne),_e=Math.max(ee,Se);return{top:Ve,left:_e,width:Math.min(se,Be)-_e,height:Math.min(V,Oe)-Ve}},[bn]),Er=i.useCallback((M,B)=>{if(B.clampHeight<=0||B.clampWidth<=0)return null;const X=bn(M,B),V=-B.clampHeight*Zt,ee=B.clampHeight*(1+Zt),se=-B.clampWidth*Zt,ne=B.clampWidth*(1+Zt),Oe=Math.min(Math.max(X.top,V),ee),Se=Math.min(Math.max(X.left,se),ne);return{top:Oe,left:Se,width:Math.min(Math.max(X.right,se),ne)-Se,height:Math.min(Math.max(X.bottom,V),ee)-Oe}},[bn]),yn=i.useCallback(()=>{if(g===void 0)return null;const M=g.current;return M.row||M.column||M.intersection?M:null},[g]),oe=i.useCallback((M,B,X)=>{const V=B.fillPool[0]?.node??Ri(B);for(const ee of Ea(X))M.insertBefore(ee,V)},[]),fe=i.useCallback((M,B,X,V)=>{const ee=Er(B,X);if(ee===null){bi(M);return}Sm(M,ee,X,V,Cc(B,t.count)||bc(B,e.count))},[Er,e,t]),pe=i.useCallback((M,B,X,V)=>{const ee=M.nodes.bandPool;for(;ee.length>X.length;){const se=ee.pop();se!==void 0&&yi(se)}if(V===null){M.nodes.dragBand!==null&&(yi(M.nodes.dragBand),M.nodes.dragBand=null);return}for(let se=0;se<X.length;se+=1){let ne=ee[se];ne===void 0&&(ne=wi(),jr(ne,M.clampWidth,M.clampHeight),oe(B,M.nodes,ne),ee.push(ne)),fe(ne,X[se],M,V)}},[oe,fe]),Ht=i.useCallback((M,B,X)=>{const V=M.nodes.container;if(V===null)return;if(B===null||X===null){M.nodes.dragBand!==null&&bi(M.nodes.dragBand);return}let ee=M.nodes.dragBand;ee===null&&(ee=wi(),jr(ee,M.clampWidth,M.clampHeight),oe(V,M.nodes,ee),M.nodes.dragBand=ee),fe(ee,B,M,X)},[oe,fe]),Ae=i.useCallback((M,B)=>{if(M!==null){if(B===null){M.style.display="none";return}M.style.display="block",M.style.transform=`translate(${B.left}px, ${B.top}px)`,M.style.width=`${B.width}px`,M.style.height=`${B.height}px`}},[]),Bt=i.useCallback((M,B,X,V)=>{const ee=V==="point"?null:yn();for(const se of K(X,B))Ae(se.nodes.dragRect,lt(M,se)),Ht(se,M,ee)},[lt,K,Ae,yn,Ht]),it=i.useCallback((M,B,X)=>{for(const V of K(X,B))Ae(V.nodes.fillPreview,M===null?null:lt(M,V))},[lt,K,Ae]),Rn=i.useCallback((M,B,X)=>{for(const V of K(X,B)){const ee=V.nodes.resizeGuide;if(ee===null)continue;if(M===null){ee.style.display="none";continue}const se=M.anchor==="trailing";if(M.axis==="col"){if(se&&V.xKind!=="t"){ee.style.display="none";continue}ee.style.display="block";const ne=V.mapX(M.position);ee.style.transform=`translate(${se?Math.max(0,ne):ne}px, 0px)`,ee.style.width="1px",ee.style.height="100%"}else{if(se&&V.yKind!=="t"){ee.style.display="none";continue}ee.style.display="block";const ne=V.mapY(M.position);ee.style.transform=`translate(0px, ${se?Math.max(0,ne):ne}px)`,ee.style.width="100%",ee.style.height="1px"}}},[K]),Vt=i.useCallback((M,B,X,V,ee,se,ne)=>{if(M===null)return;if(B===null||ne<=0||se<=0){M.style.clipPath=Ci;return}const Oe=wn(e,B.row,V),Se=gn(t,B.col,X),Be=t.sizeOf(B.col),Ve=e.sizeOf(B.row),_e=Se>=se||Oe>=ne,ve=B.col>=ee.cols&&Se<ee.width,ie=B.row>=ee.rows&&Oe<ee.height,ce=ee.trailingWidth>0&&B.col<t.count-ee.trailingCols&&Se+Be>se-ee.trailingVisibleWidth,ge=ee.trailingHeight>0&&B.row<e.count-ee.trailingRows&&Oe+Ve>ne-ee.trailingVisibleHeight;if(_e||ve||ie||ce||ge){M.style.clipPath=Ci;return}M.style.clipPath="",M.style.transform=`translate(${Se}px, ${Oe}px)`;const Ce=`${Be} ${Ve}`;M.dataset.aqspAnchorSig!==Ce&&(M.dataset.aqspAnchorSig=Ce,M.style.width=`${Be}px`,M.style.height=`${Ve}px`)},[e,t]),Ar=i.useCallback((M,B,X)=>{if(C===void 0)return;const V=C.current,{width:ee,height:se}=M.getViewportSize(),ne=M.getFrozenSize(),Oe={scroll:X,frozenCount:ne.cols,trailingCount:ne.trailingCols,extent:ee},Se={scroll:B,frozenCount:ne.rows,trailingCount:ne.trailingRows,extent:se};Vt(v===void 0?null:v.current,V.interactive,Oe,Se,ne,ee,se),Vt(S===void 0?null:S.current,V.tip,Oe,Se,ne,ee,se)},[C,v,S,Vt]),Xn=i.useCallback(()=>{const M=b.current,B=n.current;if(M===null||B===null)return;const X=B.getScrollPosition(),V=Math.max(0,X.y),ee=Math.max(0,X.x),se=o(),ne=K(ee,V),Oe=yn(),Se=Oe===null?Em:se.ranges.slice(-vm(ne.length));for(const ie of ne){const ce=ie.nodes.container;if(ce===null)continue;const ge=ie.nodes.fillPool;for(let Ce=0;Ce<Math.max(ge.length,se.ranges.length);Ce+=1){let he=ge[Ce];if(he===void 0){const Me=document.createElement("div");Me.className="aqsp-selection-fill",Me.setAttribute("data-aqsp-fill",""),Me.style.display="none",ce.insertBefore(Me,Ri(ie.nodes)),he={node:Me,last:{shown:!1,width:-1,height:-1,transform:""}},ge.push(he)}const re=se.ranges[Ce],ke=re===void 0?null:lt(re,ie);if(ke===null)he.last.shown&&(he.last.shown=!1,he.node.style.display="none");else{he.last.shown||(he.last.shown=!0,he.node.style.display="block");const Me=`translate(${ke.left}px, ${ke.top}px)`;Me!==he.last.transform&&(he.last.transform=Me,he.node.style.transform=Me),ke.width!==he.last.width&&(he.last.width=ke.width,he.node.style.width=`${ke.width}px`),ke.height!==he.last.height&&(he.last.height=ke.height,he.node.style.height=`${ke.height}px`)}}for(;ge.length>se.ranges.length;)ge.pop()?.node.remove();Ae(ie.nodes.active,lt(Re(se.active,se.active),ie)),pe(ie,ce,Se,Oe)}const Be=h(),Ve=Be===null||Be.foreign?null:Be;for(const ie of ne){const ce=ie.nodes.marquee;if(ce===null)continue;const ge=Ve===null?null:lt(Ve.range,ie),Ce=ge!==null&&(ie.xSeamTrail&&ge.left>=ie.clampWidth&&ge.left<ie.clampWidth+dr||ie.xSeamLead&&ge.left+ge.width<=0&&ge.left+ge.width>-dr||ie.ySeamTrail&&ge.top>=ie.clampHeight&&ge.top<ie.clampHeight+dr||ie.ySeamLead&&ge.top+ge.height<=0&&ge.top+ge.height>-dr)?null:ge;if(Ce===null)ce.style.display="none";else{ce.style.display="block",ce.style.transform=`translate(${Ce.left}px, ${Ce.top}px)`,ce.style.width=`${Ce.width}px`,ce.style.height=`${Ce.height}px`;const ke=Ir(Ce.top),Me=Ir(Ce.left),Ct=Ir(ie.clampHeight-(Ce.top+Ce.height)),ct=Ir(ie.clampWidth-(Ce.left+Ce.width)),bt=`${ke} ${ct} ${Ct} ${Me}`;bt!==ce.dataset.aqspOutsetSig&&(ce.dataset.aqspOutsetSig=bt,ce.style.setProperty("--aqsp-clip-outset-top",ke),ce.style.setProperty("--aqsp-clip-outset-right",ct),ce.style.setProperty("--aqsp-clip-outset-bottom",Ct),ce.style.setProperty("--aqsp-clip-outset-left",Me))}const he=Ce===null?null:Ve?.kind??null,re=ce.dataset.aqspClipKindLast??null;he!==re&&(he===null?(delete ce.dataset.aqspClipKindLast,ce.removeAttribute("data-aqsp-clip-kind")):(ce.dataset.aqspClipKindLast=he,ce.setAttribute("data-aqsp-clip-kind",he)))}Ue.current!==null&&Bt(Ue.current,V,ee,je.current),a.current!==null&&Rn(a.current,V,ee),y.current!==null&&it(y.current,V,ee);const _e=L.current;if(_e!==null&&!R()){const{width:ie,height:ce}=B.getViewportSize(),ge=se.ranges[se.ranges.length-1];if(!(se.ranges.length===1&&!Ot.current&&!m())||ce<=0||ie<=0)_e.style.display="none";else{const he=B.getFrozenSize(),re={scroll:ee,frozenCount:he.cols,trailingCount:he.trailingCols,extent:ie},ke={scroll:V,frozenCount:he.rows,trailingCount:he.trailingRows,extent:ce},Me=ge.endCol<he.cols,Ct=ge.endRow<he.rows,ct=ge.endCol>=t.count-he.trailingCols,bt=ge.endRow>=e.count-he.trailingRows,Tt=gn(t,ge.endCol,re)+t.sizeOf(ge.endCol),$t=wn(e,ge.endRow,ke)+e.sizeOf(ge.endRow),Kt=Me||ct?0:he.width,yt=Ct||bt?0:he.height,Sn=ct?ie:ie-he.trailingVisibleWidth,kn=bt?ce:ce-he.trailingVisibleHeight;$t<=yt||$t>kn||Tt<=Kt||Tt>Sn?_e.style.display="none":(_e.style.display="block",_e.style.transform=`translate(${Tt-ki+1}px, ${$t-ki+1}px)`)}}const ve=r.current;if(ve!==null){const ie=se.active,{width:ce,height:ge}=B.getViewportSize(),Ce=B.getFrozenSize(),he={scroll:ee,frozenCount:Ce.cols,trailingCount:Ce.trailingCols,extent:ce},re={scroll:V,frozenCount:Ce.rows,trailingCount:Ce.trailingRows,extent:ge},ke=wn(e,ie.row,re),Me=gn(t,ie.col,he),Ct=ge>0?Math.min(Math.max(ke,0),Math.max(0,ge-1)):0,ct=ce>0?Math.min(Math.max(Me,0),Math.max(0,ce-1)):0;ve.style.top=`${Ct}px`,ve.style.left=`${ct}px`,Ot.current?(ve.style.width=`${t.sizeOf(ie.col)}px`,ve.style.height=`${e.sizeOf(ie.row)}px`,ve.style.paddingTop=`${km(e.sizeOf(ie.row),O===void 0?Pt:O.current)}px`):(ve.style.width="1px",ve.style.height="1px",ve.style.paddingTop="0px");const bt=ie.col>=Ce.cols&&Me<Ce.width,Tt=ie.row>=Ce.rows&&ke<Ce.height,$t=Ce.trailingWidth>0&&ie.col<t.count-Ce.trailingCols&&Me+t.sizeOf(ie.col)>ce-Ce.trailingVisibleWidth,Kt=Ce.trailingHeight>0&&ie.row<e.count-Ce.trailingRows&&ke+e.sizeOf(ie.row)>ge-Ce.trailingVisibleHeight,yt=Ot.current&&ke===Ct&&Me===ct&&!bt&&!Tt&&!$t&&!Kt;yt!==xt.current&&(xt.current=yt,yt?ve.setAttribute("data-aqsp-editing",""):ve.removeAttribute("data-aqsp-editing"))}Ar(B,V,ee)},[n,lt,K,Ae,Bt,Rn,it,h,o,m,R,L,r,e,t,yn,pe,O,Ar]),mo=i.useCallback((M,B)=>{Ue.current=M,je.current=B;const X=M===null?"add":B;for(const se of K(0,0)){const ne=se.nodes.dragRect;if(ne===null)continue;const Oe=ne.dataset.aqspDragModeLast??"add";X!==Oe&&(ne.dataset.aqspDragModeLast=X,X==="add"?ne.removeAttribute("data-aqsp-drag-mode"):ne.setAttribute("data-aqsp-drag-mode",X))}const V=n.current;if(M===null||V===null){for(const se of K(0,0))se.nodes.dragRect!==null&&(se.nodes.dragRect.style.display="none"),Ht(se,null,null);return}const ee=V.getScrollPosition();Bt(M,Math.max(0,ee.y),Math.max(0,ee.x),B)},[n,Bt,K,Ht]),Or=i.useCallback(M=>{y.current=M;const B=n.current;if(B===null){for(const V of K(0,0))V.nodes.fillPreview!==null&&(V.nodes.fillPreview.style.display="none");return}const X=B.getScrollPosition();it(M,Math.max(0,X.y),Math.max(0,X.x))},[n,it,K]),go=i.useCallback(M=>{a.current=M;const B=n.current;if(B===null){for(const V of K(0,0))V.nodes.resizeGuide!==null&&(V.nodes.resizeGuide.style.display="none");return}const X=B.getScrollPosition();Rn(M,Math.max(0,X.y),Math.max(0,X.x))},[n,Rn,K]);i.useLayoutEffect(()=>{const M=b.current;if(!(M===null||p===void 0))return M.style.setProperty("--aqsp-band-row",p.row),M.style.setProperty("--aqsp-band-column",p.column),M.style.setProperty("--aqsp-band-intersection",p.intersection),M.style.setProperty("--aqsp-band-opacity",String(p.opacity)),()=>{M.style.removeProperty("--aqsp-band-row"),M.style.removeProperty("--aqsp-band-column"),M.style.removeProperty("--aqsp-band-intersection"),M.style.removeProperty("--aqsp-band-opacity")}},[p]),i.useEffect(()=>(c.current=Xn,u.current=mo,N.current=Or,H.current=go,()=>{c.current=null,u.current=null,N.current=null,H.current=null})),i.useEffect(()=>{Xn()},[Xn,s,le,Ee,De,ue]),i.useEffect(()=>{const M=r.current;if(M===null)return;const B=X=>F(X);return M.addEventListener("mousedown",B),()=>M.removeEventListener("mousedown",B)},[r,F]);const Hs=le>0||De>0?[...le>0?[{k:"f",style:{left:0,width:me}}]:[],{k:"s",style:{left:me,right:Pe}},...De>0?[{k:"t",style:{right:0,width:Pe}}]:[]]:[{k:"m",style:{left:0,right:0}}],wo=Ee>0||ue>0?[...Ee>0?[{k:"f",style:{top:0,height:xe}}]:[],{k:"s",style:{top:xe,bottom:Ne}},...ue>0?[{k:"t",style:{bottom:0,height:Ne}}]:[]]:[{k:"m",style:{top:0,bottom:0}}],Wt=M=>M==="m"?0:M==="s"?1:M==="t"?2:3,vn=Hs.flatMap(M=>wo.map(B=>({xk:M.k,yk:B.k,key:`${M.k}${B.k}`,style:{...M.style,...B.style}}))).sort((M,B)=>Wt(M.key[0])+Wt(M.key[1])-(Wt(B.key[0])+Wt(B.key[1]))),Gn=M=>M==="mm"?{"data-aqsp-overlay-main":""}:M==="fm"?{"data-aqsp-overlay-frozen":""}:M==="sm"?{"data-aqsp-overlay-scroll":""}:{};return Y.jsxs("div",{ref:b,className:"aqsp-overlay","data-aqsp-overlay":"",style:{right:Te.SPREADSHEET_SCROLLBAR_SIZE_PX,bottom:Te.SPREADSHEET_SCROLLBAR_SIZE_PX},children:[vn.map(({xk:M,yk:B,key:X,style:V})=>{const ee=te[X];return Y.jsxs("div",{className:"aqsp-overlay-quad","data-aqsp-overlay-quad":X,...Gn(X),style:V,ref:ee.container,children:[M==="s"&&le>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-leading",style:{left:0,top:0,bottom:0,display:"none"},ref:ee.dividerXLeading}):null,M==="s"&&De>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-trailing",style:{right:0,top:0,bottom:0,display:"none"},ref:ee.dividerXTrailing}):null,B==="s"&&Ee>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-leading",style:{top:0,left:0,right:0,display:"none"},ref:ee.dividerYLeading}):null,B==="s"&&ue>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-trailing",style:{bottom:0,left:0,right:0,display:"none"},ref:ee.dividerYTrailing}):null,Y.jsx("div",{className:"aqsp-active-frame","data-aqsp-active":"",style:{display:"none"},ref:ee.active}),Y.jsx("div",{className:"aqsp-drag-rect","data-aqsp-drag-rect":"",style:{display:"none"},ref:ee.dragRect}),Y.jsx("div",{className:"aqsp-clip-marquee","data-aqsp-clip-marquee":"",style:{display:"none"},ref:ee.marquee}),Y.jsx("div",{className:"aqsp-autofill-preview","data-aqsp-autofill-preview":"",style:{display:"none"},ref:ee.fillPreview}),Y.jsx("div",{className:"aqsp-resize-guide","data-aqsp-resize-guide":"",style:{display:"none"},ref:ee.resizeGuide})]},X)}),Y.jsx("textarea",{ref:wt,className:"aqsp-sink","aria-label":z,"aria-readonly":I?"true":void 0,"aria-keyshortcuts":T,tabIndex:-1,defaultValue:" ",inputMode:l?"text":"none",spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off","data-aqsp-sink":""}),_?Y.jsx("div",{ref:L,className:"aqsp-autofill-handle","data-aqsp-autofill-handle":"",style:{display:"none"}}):null]})},Aa=({ctx:e,labels:t})=>{const[n,r]=i.useState(""),o=e.cellReadOnly===!0,s=i.useId(),l=i.useRef(!1),c=R=>{l.current=!0;try{R()}finally{l.current=!1}},u=()=>{o||n.trim()!==""&&c(()=>e.commit([...e.current,{text:n}]))},h=R=>{if(R.key==="Escape"){R.preventDefault(),c(e.close);return}R.key==="Enter"&&(R.ctrlKey||R.metaKey)&&!R.altKey&&!R.shiftKey&&(R.preventDefault(),u())},m=R=>{l.current||R.relatedTarget instanceof Node&&R.currentTarget.contains(R.relatedTarget)||e.rejected||c(e.close)};return Y.jsxs("div",{className:"aqsp-popover-comment","data-aqsp-popover":"comment","data-aqsp-popover-rejected":e.rejected?"":void 0,role:"dialog","aria-labelledby":s,onBlur:m,children:[Y.jsxs("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:s,children:[ze(t,"commentTitle"),Y.jsx("span",{className:"aqsp-popover-count","data-aqsp-comment-count":"",children:ze(t,"commentCount",e.current.length)})]}),Y.jsx("ul",{className:"aqsp-popover-thread","data-aqsp-comment-thread":"",children:e.current.map(R=>Y.jsxs("li",{className:"aqsp-popover-comment-item","data-aqsp-comment-id":R.id,children:[Y.jsx("span",{className:"aqsp-popover-comment-author",children:R.author}),Y.jsx("time",{className:"aqsp-popover-comment-time",dateTime:R.createdAt,children:R.createdAt}),Y.jsx("p",{className:"aqsp-popover-comment-text",children:R.text})]},R.id))}),Y.jsx("textarea",{className:"aqsp-popover-textarea","data-aqsp-comment-input":"","data-aqsp-popover-autofocus":"",value:n,"aria-label":ze(t,"commentReply"),"aria-invalid":e.rejected?!0:void 0,onChange:R=>r(R.currentTarget.value),onKeyDown:h}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-post":"",disabled:o,"aria-disabled":o?"true":void 0,onClick:u,children:ze(t,"commentPost")}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":ze(t,"popoverClose"),onClick:()=>c(e.close),children:"×"})]})]})},Oa=({ctx:e,labels:t})=>{const[n,r]=i.useState(e.current.text),[o,s]=i.useState(e.current.url===void 0?"":e.current.url),l=e.cellReadOnly===!0,c=i.useId(),u=i.useRef(!1),h=o.trim()===""?null:sn(o),m=o.trim()!==""&&h===null,R=_=>{u.current=!0;try{_()}finally{u.current=!1}},N=()=>{l||m||R(()=>e.commit({text:n===""&&h!==null?h:n,url:h}))},H=_=>{if(_.key==="Escape"){_.preventDefault(),R(e.close);return}_.key==="Enter"&&!_.altKey&&!_.shiftKey&&(_.preventDefault(),N())},L=_=>{u.current||_.relatedTarget instanceof Node&&_.currentTarget.contains(_.relatedTarget)||e.rejected||R(e.close)};return Y.jsxs("div",{className:"aqsp-popover-link","data-aqsp-popover":"link","data-aqsp-popover-rejected":e.rejected?"":void 0,"data-aqsp-link-invalid":m?"":void 0,role:"dialog","aria-labelledby":c,onBlur:L,children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:c,children:ze(t,"linkTitle")}),Y.jsxs("label",{className:"aqsp-popover-field",children:[Y.jsx("span",{className:"aqsp-popover-field-label",children:ze(t,"linkTextField")}),Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-link-text":"",type:"text",value:n,onChange:_=>r(_.currentTarget.value),onKeyDown:H})]}),Y.jsxs("label",{className:"aqsp-popover-field",children:[Y.jsx("span",{className:"aqsp-popover-field-label",children:ze(t,"linkUrlField")}),Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-link-url":"","data-aqsp-popover-autofocus":"",type:"url",value:o,"aria-invalid":m||e.rejected?!0:void 0,onChange:_=>s(_.currentTarget.value),onKeyDown:H})]}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-save":"",disabled:m||l,"aria-disabled":l?"true":void 0,onClick:N,children:ze(t,"linkSave")}),e.canOpen&&e.current.url!==void 0?Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-link-open":"",onClick:e.open,children:ze(t,"linkOpen")}):null,Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":ze(t,"popoverClose"),onClick:()=>R(e.close),children:"×"})]})]})},Ei=500,xa=({ctx:e,labels:t})=>{const[n,r]=i.useState(e.typed),[o,s]=i.useState(0),l=i.useId(),c=i.useRef(!1),u=i.useMemo(()=>{const W=n.toLowerCase();return e.current.filter(k=>k.toLowerCase().startsWith(W))},[e.current,n]),h=i.useMemo(()=>u.length>Ei?u.slice(0,Ei):u,[u]),m=u.length-h.length,R=h.length===0?-1:Math.min(o,h.length-1),N=W=>{c.current=!0;try{W()}finally{c.current=!1}},H=()=>{R<0||N(()=>e.commit(h[R]))},L=W=>{if(W.key==="Escape"){W.preventDefault(),N(e.close);return}if(W.key==="Enter"){W.preventDefault(),H();return}if(W.key==="ArrowDown"){W.preventDefault(),s(R+1);return}W.key==="ArrowUp"&&(W.preventDefault(),s(Math.max(R-1,0)))},_=W=>{c.current||W.relatedTarget instanceof Node&&W.currentTarget.contains(W.relatedTarget)||N(e.close)},U=W=>`${l}-${W}`;return Y.jsxs("div",{className:"aqsp-popover-list","data-aqsp-popover":"list",onBlur:_,children:[Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-list-input":"","data-aqsp-popover-autofocus":"",type:"text",role:"combobox","aria-label":ze(t,"listTitle"),"aria-expanded":"true","aria-autocomplete":"list","aria-controls":l,"aria-activedescendant":R<0?void 0:U(R),value:n,onChange:W=>{r(W.currentTarget.value),s(0)},onKeyDown:L}),Y.jsxs("div",{className:"aqsp-popover-options",id:l,role:"listbox","aria-label":ze(t,"listTitle"),children:[h.length===0?Y.jsx("div",{className:"aqsp-popover-empty","data-aqsp-list-empty":"",children:ze(t,"listEmpty")}):h.map((W,k)=>Y.jsx("div",{className:"aqsp-popover-option",id:U(k),role:"option",tabIndex:-1,"aria-selected":k===R,"data-aqsp-list-option":W,onPointerDown:x=>x.preventDefault(),onClick:()=>N(()=>e.commit(W)),children:W},U(k))),m>0?Y.jsx("div",{className:"aqsp-popover-empty","data-aqsp-list-more":"",children:ze(t,"listMore",m)}):null]})]})},Ta=({ctx:e,labels:t})=>Y.jsxs("div",{className:"aqsp-popover-message","data-aqsp-popover":"message","data-aqsp-popover-rejected":e.current.rejected?"":void 0,role:"status",children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",children:e.current.title}),Y.jsx("p",{className:"aqsp-popover-message-text","data-aqsp-popover-message-text":"",children:e.current.message}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":ze(t,"popoverClose"),onClick:e.close,children:"×"})]}),$a=({ctx:e,labels:t})=>{const n=e.current===void 0?"":e.current,[r,o]=i.useState(n),s=e.cellReadOnly===!0,l=i.useId(),c=i.useId(),u=i.useRef(!1),h=L=>{u.current=!0;try{L()}finally{u.current=!1}},m=()=>{s||h(()=>e.commit(r===""?null:r))},R=()=>{r!==n&&!s?m():h(e.close)},N=L=>{if(L.key==="Escape"){L.preventDefault(),e.rejected?h(e.close):R();return}L.key==="Enter"&&(L.ctrlKey||L.metaKey)&&!L.altKey&&!L.shiftKey&&(L.preventDefault(),m())},H=L=>{u.current||L.relatedTarget instanceof Node&&L.currentTarget.contains(L.relatedTarget)||e.rejected||R()};return Y.jsxs("div",{className:"aqsp-popover-note","data-aqsp-popover":"note","data-aqsp-popover-rejected":e.rejected?"":void 0,role:"dialog","aria-labelledby":l,onBlur:H,children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:l,children:ze(t,"noteTitle")}),Y.jsx("textarea",{className:"aqsp-popover-textarea","data-aqsp-note-input":"","data-aqsp-popover-autofocus":"",value:r,"aria-describedby":c,"aria-invalid":e.rejected?!0:void 0,onChange:L=>o(L.currentTarget.value),onKeyDown:N}),Y.jsx("p",{className:"aqsp-popover-hint",id:c,"data-aqsp-popover-hint":"",children:ze(t,s?"noteViewerHint":e.rejected?"noteRejectedHint":"noteEscapeHint")}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-save":"",disabled:s,"aria-disabled":s?"true":void 0,onClick:m,children:ze(t,"noteSave")}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":ze(t,"popoverClose"),onClick:()=>h(e.close),children:"×"})]})]})},La=({ctx:e})=>Y.jsx("div",{className:"aqsp-popover-note-tip","data-aqsp-popover":"note-tip",role:"tooltip",children:e.current}),Nt=e=>Object.freeze({text:e.includes("text"),formula:e.includes("formula"),format:e.includes("format"),borders:e.includes("borders"),cf:e.includes("cf"),note:e.includes("note"),comments:e.includes("comments"),hyperlink:e.includes("hyperlink"),validation:e.includes("validation"),sizes:e.includes("sizes")}),Ai=["text","formula","format","borders","cf","note","comments","hyperlink","validation","sizes"],Da=Object.freeze({all:Nt(Ai),values:Nt(["text"]),formats:Nt(["format","borders","cf"]),formulas:Nt(["text","formula"]),noBorders:Nt(Ai.filter(e=>e!=="borders")),columnWidths:Nt(["sizes"]),validation:Nt(["validation"]),conditionalFormats:Nt(["cf"]),commentsAndNotes:Nt(["note","comments"])}),Oi=Object.freeze({mode:"all"}),Cs=Object.freeze({t:""}),xi=Object.freeze({row:1<<30,col:1<<30}),Tm=Object.freeze({add:"+",subtract:"-",multiply:"*",divide:"/"}),$m=e=>e.t===""&&e.f===void 0,Lm=e=>e.length>1&&e.startsWith("="),Dm=(e,t,n)=>{switch(n){case"add":return e+t;case"subtract":return e-t;case"multiply":return e*t;case"divide":return e/t}},Ti=e=>Number.isFinite(e)?String(Number(e.toPrecision(15))):null,Mm=(e,t,n,r)=>{const o=Lm(e),s=e===""?"0":ot(e);if(!o&&s===null)return null;const l=Tm[n];if(t.f!==void 0){const h=Rr(t.f,r),m=h.startsWith("=")?h.slice(1):h;return`=(${o?e.slice(1):s})${l}(${m})`}if(t.t==="")return n==="multiply"||n==="divide"||o||e===""?null:Ti(Number(s));const c=ot(t.t);if(c===null)return null;const u=Number(c);return n==="divide"&&u===0?null:o?`=(${e.slice(1)})${l}(${c})`:Ti(Dm(Number(s),u,n))},$i=e=>({row:e.col,col:e.row,absRow:!1,absCol:!1}),zm=e=>{switch(e.kind){case"cell":return e.absRow||e.absCol?e:{...e,row:e.col,col:e.row};case"range":return e.start.absRow||e.start.absCol||e.end.absRow||e.end.absCol?e:{...e,start:$i(e.start),end:$i(e.end)};case"column":return e.start.abs||e.end.abs?e:{...e,kind:"row",start:{row:e.start.col,abs:!1},end:{row:e.end.col,abs:!1}};case"row":return e.start.abs||e.end.abs?e:{...e,kind:"column",start:{col:e.start.row,abs:!1},end:{col:e.end.row,abs:!1}}}},Nm=e=>{const t=Rr(e,xi),n=yr(t);let r="",o=0,s=!1;for(const l of n){const c=zm(l.token);c!==l.token&&(r+=`${t.slice(o,l.start)}${tn(c)}`,o=l.end,s=!0)}return s?uo(`${r}${t.slice(o)}`,xi):e},Fm=(e,t,n)=>{const r=e.cells[t];if(r===void 0)return Cs;const o=r[n];return o===void 0?Cs:o},Pm=e=>{const{rows:t,cols:n}=e,r=Dc(Nm);let o=t===1&&n===1&&e.colWidths===void 0&&e.rowHeights===void 0&&!e.wholeRows&&!e.wholeCols;const s=[];for(let c=0;c<n;c+=1){const u=[];for(let h=0;h<t;h+=1){const m=Fm(e,h,c);let R=m;if(m.f!==void 0){const N=r(m.f);R=N===m.f?m:{...m,f:N}}(R!==m||m===Cs)&&(o=!1),u.push(R)}s.push(u)}if(o)return e;const l=e.conditionalFormats.length===0?e.conditionalFormats:e.conditionalFormats.map(c=>({...c,ranges:c.ranges.map(u=>({startRow:u.startCol,startCol:u.startRow,endRow:u.endCol,endCol:u.endRow}))}));return{v:1,rows:n,cols:t,clipId:e.clipId,formats:e.formats,validations:e.validations,cells:s,wholeRows:!1,wholeCols:!1,conditionalFormats:l}},_m=(e,t)=>!t.formula&&e.f!==void 0||!t.format&&e.fmt!==void 0||!t.validation&&e.val!==void 0||!t.note&&e.note!==void 0||!t.comments&&e.comments!==void 0||!t.hyperlink&&e.link!==void 0,qm=(e,t)=>{const n={t:e.t};return t.formula&&e.f!==void 0&&(n.f=e.f),t.format&&e.fmt!==void 0&&(n.fmt=e.fmt),t.validation&&e.val!==void 0&&(n.val=e.val),t.note&&e.note!==void 0&&(n.note=e.note),t.comments&&e.comments!==void 0&&(n.comments=e.comments),t.hyperlink&&e.link!==void 0&&(n.link=e.link),n},Li=(e,t)=>{let n=!1;const r=[];for(const c of e.cells){let u=!1;const h=[];for(const m of c)_m(m,t)?(h.push(qm(m,t)),u=!0):h.push(m);u&&(n=!0),r.push(u?h:c)}const o=!t.format&&e.formats.length>0?[]:e.formats,s=!t.validation&&e.validations.length>0?[]:e.validations,l=!t.cf&&e.conditionalFormats.length>0?[]:e.conditionalFormats;return(o!==e.formats||s!==e.validations||l!==e.conditionalFormats)&&(n=!0),n?{...e,formats:o,validations:s,conditionalFormats:l,cells:r}:e},Di=new WeakMap,Ma=e=>{const t=Di.get(e);if(t!==void 0)return t;const n=e.formats.map(s=>gt(s)),r=n.map(s=>s===void 0||s.borders===void 0?s:gt({...s,borders:void 0})),o={canonical:n,borderless:r};return Di.set(e,o),o},so=(e,t)=>t===void 0?void 0:e[t],Im=(e,t,n,r)=>{const o=Ma(e);if(n){const h=so(o.canonical,t.fmt);return h===void 0?null:h}const s=so(o.borderless,t.fmt),l=r.readFormat(),c=l===void 0?void 0:l.borders;if(c===void 0)return s===void 0?null:s;const u=gt(s===void 0?{borders:c}:{...s,borders:c});return u===void 0?null:u},jm=(e,t,n,r)=>{const o=t||e.f===void 0?e:{t:e.t};return r!==void 0?Mm(n.readText(),o,r,n):o.f===void 0?o.t:Rr(o.f,n)},Mi=(e,t,n,r,o)=>{const s=Da[r.mode];if(r.skipBlanks===!0&&$m(e))return null;const l={};let c=!1;if(s.text){const u=jm(e,s.formula&&o.formula,n,r.operation);u!==null&&(l.text=u,c=!0)}if(o.format){if(s.format)l.format=Im(t,e,s.borders,n),c=!0;else if(r.injectIntoEmpty===!0&&e.fmt!==void 0&&n.readText()===""){const u=so(Ma(t).canonical,e.fmt);u!==void 0&&(l.format=u,c=!0)}}if(s.note&&o.note&&(l.note=e.note===void 0?null:e.note,c=!0),s.comments&&o.comments&&(l.comments=e.comments===void 0?null:e.comments,c=!0),s.hyperlink&&o.hyperlink&&(l.hyperlink=e.link===void 0?null:e.link,c=!0),s.validation&&o.validation){const u=so(t.validations,e.val);l.validation=u===void 0?null:u,c=!0}return c?l:null},zi=(e,t)=>e.length===0?e:t.length===0?[]:e.map(n=>{const r=[];for(const o of t)for(const s of n.ranges)r.push({startRow:o.row+s.startRow,startCol:o.col+s.startCol,endRow:o.row+s.endRow,endCol:o.col+s.endCol});return{...n,ranges:r}}),Hm=["text/html","text/plain"],Bm=(e,t,n)=>{if(e===0||t===0)return 0;const r=st(n);return!(r.rows===1&&r.cols===1)&&r.rows%e===0&&r.cols%t===0?r.rows*r.cols:e*t},Vm=e=>e.mode==="all"&&e.operation===void 0&&e.transpose!==!0&&e.skipBlanks!==!0,Wm=e=>e.text||e.formula||e.format||e.borders||e.note||e.comments||e.hyperlink||e.validation,Km=e=>{const t=Array.from(e.types),n=new Map;return{types:t,getData:r=>{const o=n.get(r);if(o!==void 0)return o;const s=e.getData(r);return n.set(r,s),s}}},Ni=e=>{const t=e.clipboardData;return t??null},Ym=(e,t)=>{const n=Math.max(e.startRow,t.startRow),r=Math.min(e.endRow,t.endRow),o=Math.max(e.startCol,t.startCol),s=Math.min(e.endCol,t.endCol);return n>r||o>s?null:{startRow:n,startCol:o,endRow:r,endCol:s}},Um=(e,t)=>{const n=[];for(const r of e){const o=[];for(const l of r.ranges){const c=Ym(l,t);c!==null&&o.push({startRow:c.startRow-t.startRow,startCol:c.startCol-t.startCol,endRow:c.endRow-t.startRow,endCol:c.endCol-t.startCol})}if(o.length===0)continue;const s={sourceRuleId:r.id,ranges:o,condition:r.condition,style:r.style};r.stopIfTrue!==void 0&&(s.stopIfTrue=r.stopIfTrue),n.push(s)}return n},Xm=(e,t,n,r,o)=>{const s=Yn(e,r,o),l={t:s.isFormula?e.getCellText(r,o):s.text};if(s.isFormula&&(l.f=uo(s.text,{row:r,col:o})),e.getCellFormat!==void 0){const c=e.getCellFormat(r,o);if(c!==void 0){const u=t.intern(c);u!==void 0&&(l.fmt=u)}}if(e.getCellNote!==void 0){const c=e.getCellNote(r,o);c!==void 0&&(l.note=c)}if(e.getCellComments!==void 0){const c=e.getCellComments(r,o);c!==void 0&&c.length>0&&(l.comments=c.map(({text:u,author:h,createdAt:m})=>({text:u,author:h,createdAt:m})))}if(e.getCellHyperlink!==void 0){const c=Un(e.getCellHyperlink(r,o));c!==void 0&&(l.link=c)}if(e.getCellValidation!==void 0){const c=e.getCellValidation(r,o);c!==void 0&&(l.val=n.intern(c))}return l},za=(e,t)=>{const n=wc(),r=Qd(),o=[];for(let s=t.startRow;s<=t.endRow;s+=1){const l=[];for(let c=t.startCol;c<=t.endCol;c+=1)l.push(Xm(e,n,r,s,c));o.push(l)}return{formats:n.entries,validations:r.entries,cells:o,conditionalFormats:e.getConditionalFormats===void 0?[]:Um(e.getConditionalFormats(),t)}},Fi=e=>e.kind==="cut"?{...e.payload,...za(e.sourceAdapter,e.range)}:e.payload,Gm=e=>({v:1,rows:e.length,cols:e[0].length,clipId:As(),formats:[],validations:[],cells:e.map(t=>t.map(n=>({t:n}))),wholeRows:!1,wholeCols:!1,conditionalFormats:[]}),Zm=e=>{let t=!1;const n=[];for(const r of e.cells){let o=!1;const s=[];for(const l of r){if(l.link===void 0){s.push(l);continue}const c=sn(l.link);if(c===l.link){s.push(l);continue}if(o=!0,c===null){const{link:u,...h}=l;s.push(h)}else s.push({...l,link:c})}o&&(t=!0),n.push(o?s:r)}return t?{...e,cells:n}:e},Jm=(e,t,n)=>{const r={row:e,col:t,text:""};return n.format&&(r.format=null),n.note&&(r.note=null),n.comments&&(r.comments=null),n.hyperlink&&(r.hyperlink=null),n.validation&&(r.validation=null),r},Qm=(e,t,n,r,o)=>{if(e.length===0)return null;let s=0,l=0;for(const c of e)s=Math.max(s,c.row+t-1),l=Math.max(l,c.col+n-1);return Re({row:e[0].row,col:e[0].col},{row:Math.min(s,r-1),col:Math.min(l,o-1)})},eg=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(null),r=i.useRef("none"),o=i.useCallback(()=>{n.current!==null&&(n.current=null,t.current.repaintOverlay(),t.current.onClipChange?.(null))},[]),s=i.useCallback(k=>{const x=n.current;if(x===null||k==="format"||k==="annotate")return;const z=r.current;z==="own"||z==="foreign"&&x.kind==="copy"||o()},[o]),l=i.useCallback(()=>{const k=n.current;if(k===null)return;if(k.kind==="copy"){o();return}const x=t.current;x.repaintOverlay(),x.onClipChange?.({kind:"cut",range:k.range,foreign:k.sourceAdapter!==x.adapter})},[o]),c=i.useCallback((k,x,z)=>{const I=t.current;n.current={kind:k,range:x,clipId:z.clipId,sourceAdapter:I.adapter,payload:z},I.repaintOverlay(),I.onClipChange?.({kind:k,range:x,foreign:!1})},[]),u=i.useCallback(k=>{const x=t.current,z=x.adapter,I=st(k),T={v:1,rows:I.rows,cols:I.cols,clipId:As(),...za(z,k),wholeRows:Cc(k,z.colCount),wholeCols:bc(k,z.rowCount)};if(x.resize!==void 0){if(T.wholeCols){const F=[];for(let O=k.startCol;O<=k.endCol;O+=1)F.push(Math.min(x.resize.colAxis.sizeOf(O),on));T.colWidths=F}if(T.wholeRows){const F=[];for(let O=k.startRow;O<=k.endRow;O+=1)F.push(Math.min(x.resize.rowAxis.sizeOf(O),on));T.rowHeights=F}}return T},[]),h=i.useCallback((k,x)=>{const z=t.current,I=z.getSelection(),T=I.ranges[I.ranges.length-1],F=At([T]);if(F>z.maxOperationCells)return k.preventDefault(),z.onOperationRejected?.(x,F,"limit"),null;if(x==="cut"&&ur(z.adapter,T))return k.preventDefault(),z.rejectReadOnly({kind:"operation",op:"cut",cellCount:F}),null;I.ranges.length>1&&z.onCopyMultiRange?.();const O=u(T),g=lc(O),p=Ni(k);return p!==null&&(p.setData("text/plain",qt.serializeClipboardTsv(O.cells.map(C=>C.map(v=>v.t)))),p.setData("text/html",Gc(O,g)),p.setData(no,g)),k.preventDefault(),{payload:O,range:T}},[u]),m=i.useCallback((k,x)=>t.current.commitPaste(k,x)!==null,[]),R=i.useCallback((k,x,z)=>{const I=t.current;if(!z.sizes||I.resize===void 0)return;const{rowAxis:T,colAxis:F,resizeTracks:O}=I.resize,g=(p,C,v)=>{const S=vs(C,v,null,{maxOperationCells:I.maxOperationCells,rowHiddenLimit:ys,axisKind:p});if(!S.ok){I.onOperationRejected?.("resize",S.count,S.reason);return}O(p,S.entries)};if(k.colWidths!==void 0){const p=[];for(let C=x.startCol;C<=x.endCol;C+=1)p.push({index:C,size:k.colWidths[(C-x.startCol)%k.cols]});g("col",F,p)}if(k.rowHeights!==void 0){const p=[];for(let C=x.startRow;C<=x.endRow;C+=1)p.push({index:C,size:k.rowHeights[(C-x.startRow)%k.rows]});g("row",T,p)}},[]),N=i.useCallback((k,x)=>{const z=t.current,I=z.adapter,T=k.payload,F={row:x.startRow,col:x.startCol},O=T.rows*T.cols+At([k.range]);if(O>z.maxOperationCells)return z.onOperationRejected?.("paste",O,"limit"),"rejected";if(F.row+T.rows>I.rowCount||F.col+T.cols>I.colCount||k.range.endRow>=k.sourceAdapter.rowCount||k.range.endCol>=k.sourceAdapter.colCount)return z.onOperationRejected?.("paste",O,"bounds"),"rejected";const g=gs({rows:T.rows,cols:T.cols},Re(F,F),F,I.rowCount,I.colCount);if(g!==null&&ur(I,g))return z.rejectReadOnly({kind:"operation",op:"paste",cellCount:T.rows*T.cols}),"rejected";if(ur(k.sourceAdapter,k.range))return z.rejectReadOnly({kind:"operation",op:"cut",cellCount:At([k.range])}),"rejected";const p=Fi(k),C=eo(I),v=Li(p,C),S={row:0,col:0,readText:()=>Yn(I,S.row,S.col).text,readFormat:()=>I.getCellFormat===void 0?void 0:I.getCellFormat(S.row,S.col)},{edits:b,tiles:y}=ii(v.cells,Re(F,F),F,I.rowCount,I.colCount,(E,d,$)=>(S.row=k.range.startRow+(d-F.row),S.col=k.range.startCol+($-F.col),Mi(E,v,S,Oi,C))),a=eo(k.sourceAdapter),f=[];if(Jt([k.range],E=>{f.push(Jm(E.row,E.col,a))}),k.sourceAdapter===I){if(!m([...f,...b],{sameSheet:!0,conditionalFormats:[]}))return"rejected"}else{const E=z.commitPaste(b,{sameSheet:!1,conditionalFormats:zi(v.conditionalFormats,y)});if(E===null)return"rejected";try{k.sourceAdapter.applyEdits(f,{transaction:E,source:"paste",sameSheet:!1,conditionalFormats:[]})}catch(d){z.onEditRejected?.(d,{source:"paste"})}}return z.setSelection({ranges:[Re(F,{row:F.row+p.rows-1,col:F.col+p.cols-1})],anchor:F,active:F}),"applied"},[m]),H=i.useCallback((k,x,z)=>{const I=t.current,T=I.adapter,F=K=>(I.onClipboardUnavailable?.(K),"rejected"),O=ac(k,x);if(O==="none")return x==="menu"?F("empty"):"empty";const g=I.getSelection(),p=g.ranges[g.ranges.length-1],C=z.transpose===!0,v=(K,G)=>{const J=Bm(C?G:K,C?K:G,p);return J>I.maxOperationCells?(I.onOperationRejected?.("paste",J,"limit"),!0):!1};let S,b=null;if(O==="aqsp"){const K=Ad(k,x);if(K===null)return F("unreadable");const G=n.current;if(G!==null&&K.clipId===G.clipId&&(b=G),b!==null&&b.kind==="cut"&&Vm(z))return N(b,p);if(v(K.rows,K.cols))return"rejected";if(b!==null){if(b.kind==="cut"&&(b.range.endRow>=b.sourceAdapter.rowCount||b.range.endCol>=b.sourceAdapter.colCount))return I.onOperationRejected?.("paste",b.payload.rows*b.payload.cols,"bounds"),"rejected";S=Fi(b)}else{const J=Od(k,x);if(J===null)return F("unreadable");if(v(J.rows,J.cols))return"rejected";S=Zm(J)}}else if(O==="tsv"){const K=k.getData("text/plain"),G=qt.measureTsv(K);if(v(G.rows,G.cols))return"rejected";S=Gm(qt.parseTsv(K))}else{const K=k.getData("text/html"),G=Jd(K);if(G.cols===0&&G.rows>I.maxOperationCells)return I.onOperationRejected?.("paste",G.rows,"limit"),"rejected";if(v(G.rows,G.cols))return"rejected";const J=ea(K,O,I.formats===void 0?{}:{currency:I.formats.currency,locale:I.formats.locale},I.maxOperationCells);if(J.outcome==="none")return F("unreadable");if(J.outcome==="limit")return I.onOperationRejected?.("paste",J.cells,"limit"),"rejected";if(v(J.payload.rows,J.payload.cols))return"rejected";S=J.payload}const y=eo(T),a=Li(C?Pm(S):S,y),f=Da[z.mode];if(Wm(f)){const K=gs({rows:a.rows,cols:a.cols},p,g.active,T.rowCount,T.colCount);if(K!==null&&ur(T,K))return I.rejectReadOnly({kind:"operation",op:"paste",cellCount:At([K])}),"rejected"}const E={row:0,col:0,readText:()=>Yn(T,E.row,E.col).text,readFormat:()=>T.getCellFormat===void 0?void 0:T.getCellFormat(E.row,E.col)},{edits:d,tiles:$}=ii(a.cells,p,g.active,T.rowCount,T.colCount,(K,G,J)=>(E.row=G,E.col=J,Mi(K,a,E,z,y))),A=Qm($,a.rows,a.cols,T.rowCount,T.colCount);if(A===null)return"empty";if(f.cf&&a.conditionalFormats.length>0){let K=0;for(const J of a.conditionalFormats)K+=J.ranges.length;const G=$.length*K;if(G>I.maxOperationCells)return I.onOperationRejected?.("paste",G,"limit"),"rejected"}const D=f.cf?zi(a.conditionalFormats,$):[];if(d.length===0&&D.length===0)return R(a,A,f),"empty";r.current=b===null?"foreign":"own";let q=!1;try{q=m(d,{sameSheet:b!==null&&b.sourceAdapter===T,conditionalFormats:D})}finally{r.current="none"}if(!q)return"rejected";R(a,A,f);const j={row:A.startRow,col:A.startCol};return I.setSelection({ranges:[A],anchor:j,active:j}),"applied"},[N,m,R]),L=i.useCallback(async k=>{const x=C=>(t.current.onClipboardUnavailable?.(C),"rejected"),z=navigator;if(z.clipboard===void 0)return x("insecure-origin");let I;try{I=await z.clipboard.read({unsanitized:["text/html"]})}catch{return x("permission-denied")}if(I.length===0)return x("empty");const T=I[0],F=Array.from(T.types),O=new Map;try{for(const C of Hm)F.includes(C)&&O.set(C,await(await T.getType(C)).text())}catch{return x("unreadable")}const g={types:F,getData:C=>{const v=O.get(C);if(v===void 0)throw new RangeError(`[spreadsheet] clipboard flavour ${C} was not materialised for the menu path`);return v}},p=t.current;return!p.enabled||p.isDragging()||p.isEditing()?"rejected":H(g,"menu",k)},[H]),_=i.useCallback(async k=>{const x=await L(k);return t.current.onPasteResolved?.(x,"menu"),x},[L]),{enabled:U,sinkRef:W}=e;return i.useEffect(()=>{const k=W.current;if(!U||k===null)return;const x=F=>t.current.isDragging()?(F.preventDefault(),!0):!1,z=F=>{const O=t.current;if(x(F)||O.isEditing())return;const g=h(F,"copy");g!==null&&c("copy",g.range,g.payload)},I=F=>{const O=t.current;if(x(F)||O.isEditing())return;const g=h(F,"cut");g!==null&&c("cut",g.range,g.payload)},T=F=>{const O=t.current;if(x(F)||O.isEditing())return;F.preventDefault();let g=Oi;const p=O.pendingPasteOptionsRef;p!==void 0&&p.current!==null&&(g=p.current,p.current=null);const C=Ni(F);if(C===null)return;const v=H(Km(C),"event",g);O.onPasteResolved?.(v,"event")};return k.addEventListener("copy",z),k.addEventListener("cut",I),k.addEventListener("paste",T),()=>{k.removeEventListener("copy",z),k.removeEventListener("cut",I),k.removeEventListener("paste",T)}},[U,W,h,c,H]),i.useMemo(()=>({getClip:()=>{const k=n.current;return k===null?null:{kind:k.kind,range:k.range,foreign:k.sourceAdapter!==t.current.adapter}},discardClip:o,discardClipOnCommit:s,onAdapterSwitch:l,paste:_}),[o,s,l,_])},Na=e=>{if(e!==2&&e!==3&&e!==-2&&e!==-3)throw new RangeError(`[spreadsheet] self-calc exponent must be 2, 3, -2 or -3; got ${String(e)}`)},Fa=e=>{let t=e,n=!1;t.startsWith("-")?(n=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1));const r=t.search(/[eE]/);let o=null;r>=0&&(o=Number(t.slice(r+1)),t=t.slice(0,r));const s=t.indexOf("."),l=s<0?t:t.slice(0,s),c=s<0?"":t.slice(s+1);return{negative:n,digits:l+c,point:l.length,exponent:o}},Pi=(e,t,n)=>{let r,o;return n<=0?(r="0",o="0".repeat(-n)+t):n>=t.length?(r=t+"0".repeat(n-t.length),o=""):(r=t.slice(0,n),o=t.slice(n)),r=r.replace(/^0+(?=\d)/,""),o=o.replace(/0+$/,""),r==="0"&&o===""?"0":`${e?"-":""}${r}${o===""?"":`.${o}`}`},Pa=(e,t)=>{let n;if(e.exponent===null)n=Pi(e.negative,e.digits,e.point+t);else{const r=Pi(e.negative,e.digits,e.point);n=r==="0"?"0":`${r}e${e.exponent+t}`}return ot(n)===null?null:n},tg=(e,t)=>{Na(t);const n=ot(e);return n===null?null:Pa(Fa(n),t)},ng=e=>{const t=ot(e);if(t!==null){const r=Fa(t);return Pa({...r,negative:!r.negative},0)}const n=e.trim().toUpperCase();return n==="TRUE"?"FALSE":n==="FALSE"?"TRUE":null},_a=e=>{if(!e.startsWith("=")||e.length===1)throw new RangeError(`[spreadsheet] self-calc expects a formula ("=" followed by a body); got ${JSON.stringify(e)}`);return e.slice(1)},rg=e=>{let t=0,n=null;for(let r=0;r<e.length;r++){const o=e[r];if(n!==null){o===n&&(n=null);continue}if(o==='"'||o==="'")n=o;else if(o==="(")t++;else if(o===")"&&(t--,t<0))return!1}return n===null&&t===0},qa=(e,t,n)=>{if(e.length<=t.length+n.length||!e.startsWith(t)||!e.endsWith(n))return null;const r=e.slice(t.length,e.length-n.length);return rg(r)?r:null},og=(e,t)=>{Na(t);const n=_a(e),r=Math.abs(t)===2?"100":"1000",o=t>0?"*":"/",s=t>0?"/":"*",l=qa(n,"(",`)${s}${r}`);return l===null?`=(${n})${o}${r}`:`=${l}`},sg=e=>{const t=_a(e),n=qa(t,"-(",")");return n===null?`=-(${t})`:`=${n}`},lr=(e,t,n,r)=>{const o=At(t);return o>n?(r?.(e,o,"limit"),!1):!0},Br={Yellow:"#FFFF99",Blue:"#CCFFFF",Green:"#CCFFCC",Red:"#FFCCCC"},Vr={Yellow:"#FFFF00",Blue:"#0000FF",Green:"#00FF00",Red:"#FF0000"},_i={bold:{kind:"toggle",key:"bold"},italic:{kind:"toggle",key:"italic"},underline:{kind:"toggle",key:"underline"},strikethrough:{kind:"toggle",key:"strikethrough"},clearFormatting:{kind:"clear"},alignLeft:{kind:"patch",patch:{align:"left"}},alignCenter:{kind:"patch",patch:{align:"center"}},alignRight:{kind:"patch",patch:{align:"right"}},formatNumber:{kind:"value",value:"number"},formatTime:{kind:"value",value:"time"},formatDate:{kind:"value",value:"date"},formatCurrency:{kind:"value",value:"currency"},formatPercent:{kind:"value",value:"percent"},formatScientific:{kind:"value",value:"scientific"},bordersOuter:{kind:"borders",preset:"outer"},bordersClear:{kind:"borders",preset:"clear"},borderTop:{kind:"borders",preset:"top"},borderRight:{kind:"borders",preset:"right"},borderBottom:{kind:"borders",preset:"bottom"},borderLeft:{kind:"borders",preset:"left"},insertLink:{kind:"popover",popover:"link"},insertNote:{kind:"popover",popover:"note"},insertComment:{kind:"popover",popover:"comment"},openHyperlink:{kind:"openHyperlink"},openValidationList:{kind:"popover",popover:"list"},pasteSpecial:{kind:"pasteSpecial"},fillDown:{kind:"fill",direction:"down"},fillRight:{kind:"fill",direction:"right"},fillSelection:{kind:"fill",direction:"selection"},insertDate:{kind:"insertNow",unit:"date"},insertTime:{kind:"insertNow",unit:"time"},hideRows:{kind:"hide",axis:"row",hide:!0},hideColumns:{kind:"hide",axis:"col",hide:!0},unhideRows:{kind:"hide",axis:"row",hide:!1},unhideColumns:{kind:"hide",axis:"col",hide:!1},formatGeneral:{kind:"patch",patch:{value:null}},bordersAll:{kind:"borders",preset:"all"},pasteFormats:{kind:"paste",options:{mode:"formats"}},pasteFormulas:{kind:"paste",options:{mode:"formulas"}},pasteAdd:{kind:"paste",options:{mode:"all",operation:"add"}},pasteSubtract:{kind:"paste",options:{mode:"all",operation:"subtract"}},pasteMultiply:{kind:"paste",options:{mode:"all",operation:"multiply"}},pasteDivide:{kind:"paste",options:{mode:"all",operation:"divide"}},multiplyBy100:{kind:"calc",exponent:2},multiplyBy1000:{kind:"calc",exponent:3},divideBy100:{kind:"calc",exponent:-2},divideBy1000:{kind:"calc",exponent:-3},signReversal:{kind:"sign"},fillColorYellow:{kind:"color",key:"background",preset:Br.Yellow,custom:null},fillColorBlue:{kind:"color",key:"background",preset:Br.Blue,custom:null},fillColorGreen:{kind:"color",key:"background",preset:Br.Green,custom:null},fillColorRed:{kind:"color",key:"background",preset:Br.Red,custom:null},fillColorCustom1:{kind:"color",key:"background",preset:null,custom:0},fillColorCustom2:{kind:"color",key:"background",preset:null,custom:1},fillColorCustom3:{kind:"color",key:"background",preset:null,custom:2},fillColorCustom4:{kind:"color",key:"background",preset:null,custom:3},fillColorCustom5:{kind:"color",key:"background",preset:null,custom:4},fontColorYellow:{kind:"color",key:"color",preset:Vr.Yellow,custom:null},fontColorBlue:{kind:"color",key:"color",preset:Vr.Blue,custom:null},fontColorGreen:{kind:"color",key:"color",preset:Vr.Green,custom:null},fontColorRed:{kind:"color",key:"color",preset:Vr.Red,custom:null},fontColorCustom1:{kind:"color",key:"color",preset:null,custom:0},fontColorCustom2:{kind:"color",key:"color",preset:null,custom:1},fontColorCustom3:{kind:"color",key:"color",preset:null,custom:2},fontColorCustom4:{kind:"color",key:"color",preset:null,custom:3},fontColorCustom5:{kind:"color",key:"color",preset:null,custom:4},increaseColumnWidth:{kind:"resize",axis:"col",step:1},decreaseColumnWidth:{kind:"resize",axis:"col",step:-1},increaseRowHeight:{kind:"resize",axis:"row",step:1},decreaseRowHeight:{kind:"resize",axis:"row",step:-1},autoFitColumnWidth:{kind:"resize",axis:"col",step:"fit"},toggleRowHighlight:{kind:"highlight",target:"row"},toggleColumnHighlight:{kind:"highlight",target:"column"},toggleBothHighlight:{kind:"highlight",target:"both"},toggleIntersectionHighlight:{kind:"highlight",target:"intersection"}},lg={value:null,align:null,verticalAlign:null,wrap:null,background:null,color:null,bold:null,italic:null,underline:null,strikethrough:null,fontFamily:null,fontSize:null,borders:null},mr=e=>e<10?`0${e}`:String(e),ig=e=>{const t=new Date(e);return`${t.getFullYear()}-${mr(t.getMonth()+1)}-${mr(t.getDate())}`},cg=e=>{const t=new Date(e);return`${mr(t.getHours())}:${mr(t.getMinutes())}:${mr(t.getSeconds())}`},ag=(e,t)=>(e.row===t.startRow?1:0)|(e.col===t.endCol?2:0)|(e.row===t.endRow?4:0)|(e.col===t.startCol?8:0),ug=(e,t)=>({...(e&1)!==0?{top:t}:{},...(e&2)!==0?{right:t}:{},...(e&4)!==0?{bottom:t}:{},...(e&8)!==0?{left:t}:{}}),dg=e=>e===void 0||e.borders===void 0?{}:e.borders,fg={top:1,right:2,bottom:4,left:8},pg={style:"thin",color:Ss},hg=(e,t)=>{if(e===void 0)return!1;const n=Ze(e);return n!==null&&n===Ze(t)},mg=(e,t)=>{const n=t===void 0||t.locale===void 0?{}:{locale:t.locale};switch(e){case"number":return{type:"number",decimals:2,grouping:!0,...n};case"time":return{type:"date",pattern:"HH:mm:ss"};case"date":return{type:"date"};case"currency":if(t===void 0)throw new RangeError("[spreadsheet] formatCurrency requires the formats prop (currency)");return{type:"currency",currency:t.currency,decimals:2,...n};case"percent":return{type:"percent",decimals:2,...n};default:return{type:"scientific",decimals:2,...n}}},gg=e=>{const t=i.useRef(e);t.current=e;const n=i.useCallback(()=>{const g=t.current;if(g.isEditing()){const p=g.getActive();return[Re(p,p)]}return g.getSelection().ranges},[]),r=i.useCallback(()=>{const g=t.current,p=g.getActive();return g.adapter.getCellFormat===void 0?void 0:g.adapter.getCellFormat(p.row,p.col)},[]),o=i.useCallback(g=>{const p=t.current,C=n();if(!lr("format",C,p.maxOperationCells,p.onOperationRejected))return!1;if(qn(p.adapter,C))return p.rejectReadOnly({kind:"operation",op:"format",cellCount:At(C)}),!1;const v=new Map,S=[],b=p.adapter.getCellFormat;for(const y of C)Jt([y],a=>{const f=b===void 0?void 0:b(a.row,a.col),{bucket:E,patch:d}=g(a,y,f);let $=v.get(E);$===void 0&&($=new Map,v.set(E,$));let A;$.has(f)?A=$.get(f):(A=Es(f,d),$.set(f,A)),A!==f&&S.push({row:a.row,col:a.col,format:A===void 0?null:A})});return S.length===0?!0:p.commitEdits(S,{source:"format"})===null?!1:(p.isEditing()&&p.refreshEditPaint(),!0)},[n]),s=i.useCallback(g=>o(()=>({bucket:0,patch:g})),[o]),l=i.useCallback((g,p)=>{const C=t.current;C.formatCommandAnnouncement!==void 0&&C.announce(C.formatCommandAnnouncement({command:g,state:p}))},[]),c=i.useCallback((g,p=pg)=>{if(g==="clear")return s({borders:null});if(g==="all")return s({borders:{top:p,right:p,bottom:p,left:p}});const C=g==="outer"?15:fg[g];return o((v,S,b)=>{const y=ag(v,S)&C;return{bucket:y,patch:{borders:{...dg(b),...ug(y,p)}}}})},[s,o]),u=i.useCallback((g,p,C)=>{const v=sa(t.current.adapter,g.row,g.col);for(const S of p)C.push(la(v,g,S))},[]),h=i.useCallback(g=>{const p=t.current,C=p.getSelection();if(!lr("fill",C.ranges,p.maxOperationCells,p.onOperationRejected))return!1;const v=[];if(g==="selection"){const b=C.active,y=[];Jt(C.ranges,a=>{(a.row!==b.row||a.col!==b.col)&&y.push(a)}),v.push({source:b,targets:y})}else for(const b of C.ranges)if(g==="down"){const y=b.startRow===b.endRow;if(y&&b.startRow===0)continue;const a=y?b.startRow-1:b.startRow;for(let f=b.startCol;f<=b.endCol;f+=1){const E=[];for(let d=y?b.startRow:b.startRow+1;d<=b.endRow;d+=1)E.push({row:d,col:f});v.push({source:{row:a,col:f},targets:E})}}else{const y=b.startCol===b.endCol;if(y&&b.startCol===0)continue;const a=y?b.startCol-1:b.startCol;for(let f=b.startRow;f<=b.endRow;f+=1){const E=[];for(let d=y?b.startCol:b.startCol+1;d<=b.endCol;d+=1)E.push({row:f,col:d});v.push({source:{row:f,col:a},targets:E})}}for(const b of v)for(const y of b.targets)if(Ye(p.adapter,y.row,y.col)){let a=0;for(const f of v)a+=f.targets.length;return p.rejectReadOnly({kind:"operation",op:"fill",cellCount:a}),!1}const S=[];for(const b of v)u(b.source,b.targets,S);return S.length===0?!0:p.commitEdits(S,{source:"fill"})!==null},[u]),m=i.useCallback(()=>{const g=t.current,p=g.getSessionText();if(p===null)return!1;const C=g.getSelection();if(!lr("fill",C.ranges,g.maxOperationCells,g.onOperationRejected))return!1;if(qn(g.adapter,C.ranges))return g.rejectReadOnly({kind:"operation",op:"fill",cellCount:At(C.ranges)}),!1;const v=[];let S=!1;return Jt(C.ranges,b=>{if(!S){if(!g.validateCommit(b,p).ok){S=!0;return}v.push({row:b.row,col:b.col,text:p})}}),S||g.commitEdits(v,{source:"fill"})===null?!1:(g.cancelEdit(),!0)},[]),R=i.useCallback(g=>{const p=t.current,C=p.getSelection();if(!lr("calc",C.ranges,p.maxOperationCells,p.onOperationRejected))return!1;if(qn(p.adapter,C.ranges))return p.rejectReadOnly({kind:"operation",op:"calc",cellCount:At(C.ranges)}),!1;const v=[],S=p.adapter;return Jt(C.ranges,b=>{const y=S.getCellFormula===void 0?void 0:S.getCellFormula(b.row,b.col),a=y===void 0?g.text(S.getCellText(b.row,b.col)):g.formula(y);a!==null&&v.push({row:b.row,col:b.col,text:a})}),v.length===0?!0:p.commitEdits(v,{source:"calc"})!==null},[]),N=i.useCallback((g,p)=>{const C=t.current,v=g==="row"?C.rowAxis:C.colAxis,S=C.getSelection(),b=g==="row"?Math.floor(C.maxOperationCells/Rs):C.maxOperationCells;let y=0;for(const $ of S.ranges)y+=g==="row"?$.endRow-$.startRow+1:$.endCol-$.startCol+1;if(y>b)return C.onOperationRejected?.("resize",y,"limit"),!1;const a=new Set,f=[],E=p?0:g==="row"?C.defaultRowHeight:C.defaultColumnWidth;for(const $ of S.ranges){const A=g==="row"?$.startRow:$.startCol,D=g==="row"?$.endRow:$.endCol;for(let q=A;q<=D;q+=1){if(a.has(q))continue;a.add(q),v.sizeOf(q)===0!==p&&f.push({index:q,size:E})}}const d=vs(v,f,null,{maxOperationCells:C.maxOperationCells,rowHiddenLimit:ys,axisKind:g});return d.ok?(d.entries.length>0&&C.resizeTracks(g,d.entries),!0):(C.onOperationRejected?.("resize",d.count,d.reason),!1)},[]),H=i.useCallback(()=>{const g=t.current;if(g.adapter.getCellHyperlink===void 0)return;const p=g.getActive();return Un(g.adapter.getCellHyperlink(p.row,p.col))},[]),L=i.useCallback(g=>{const p=t.current,C=p.adapter,v=_i[g],S=C.getCellFormat!==void 0,b=y=>p.popovers===void 0?!0:p.popovers[y]!==!1;switch(v.kind){case"resize":return p.trackResize!==void 0;case"toggle":case"patch":case"clear":case"borders":case"color":return S;case"value":return S&&(v.value!=="currency"||p.formats!==void 0);case"popover":switch(v.popover){case"link":return C.getCellHyperlink!==void 0&&b("link");case"note":return C.getCellNote!==void 0&&b("note");case"comment":return C.getCellComments!==void 0&&b("comment");default:return C.getCellValidation!==void 0&&b("list")}case"openHyperlink":return C.getCellHyperlink!==void 0&&(p.onHyperlinkOpen!==void 0?H()!==void 0:b("link"));case"paste":return v.options.mode==="formats"?S:v.options.mode==="formulas"?C.getCellFormula!==void 0:!0;default:return!0}},[H]),_=i.useCallback(g=>{const p=t.current,C=g.kind==="popover"?g.popover:g.kind==="openHyperlink"&&p.onHyperlinkOpen===void 0?"link":void 0;if(C===void 0)return!0;const v=p.getActive();if(!Ye(p.adapter,v.row,v.col))return!0;if(C==="list")return p.rejectReadOnly({kind:"edit",cell:v,editSession:"none"}),!1;let S;if(C==="link")S=H()!==void 0;else if(C==="note"){const b=p.adapter.getCellNote===void 0?void 0:p.adapter.getCellNote(v.row,v.col);S=b!==void 0&&b!==""}else{const b=p.adapter.getCellComments===void 0?void 0:p.adapter.getCellComments(v.row,v.col);S=b!==void 0&&b.length>0}return S?!0:(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1)},[H]),U=i.useCallback((g,p,C)=>{const v=t.current,S=v.trackResize;if(S===void 0)return!1;const b=v.getActive(),y=p==="col"?b.col:b.row,a=C==="fit"?S.autofitColumn(y):S.stepTrack(p,y,C),f=(p==="col"?v.colAxis:v.rowAxis).sizeOf(y);return a&&f>0&&v.formatResizeAnnouncement!==void 0&&v.announce(v.formatResizeAnnouncement({command:g,axis:p==="col"?"column":"row",index:y,size:f})),a},[]),W=i.useCallback(g=>{const p=t.current;if(!L(g))return!1;const C=_i[g];if(!_(C))return!1;const v=p.isEditing();if(v&&!Ps.has(g)&&!p.requestCommit())return!1;switch(C.kind){case"toggle":{const S=r(),b=S!==void 0&&S[C.key]===!0;return s({[C.key]:b?null:!0})?(l(g,!b),!0):!1}case"patch":return s(C.patch)?(l(g,null),!0):!1;case"clear":return s(lg)?(l(g,null),!0):!1;case"value":return s({value:mg(C.value,p.formats)})?(l(g,null),!0):!1;case"borders":return c(C.preset)?(l(g,null),!0):!1;case"color":{const S=C.key==="background"?p.colors.fill:p.colors.font,b=C.preset!==null?C.preset:C.custom!==null&&C.custom<S.length?S[C.custom]:void 0;if(b===void 0)return!1;const y=r(),a=hg(y===void 0?void 0:y[C.key],b);return s({[C.key]:a?null:b})?(l(g,!a),!0):!1}case"calc":return R({text:S=>tg(S,C.exponent),formula:S=>og(S,C.exponent)});case"sign":return R({text:ng,formula:sg});case"fill":return v&&C.direction==="selection"?m():h(C.direction);case"popover":return p.openPopover(C.popover),!0;case"openHyperlink":{if(p.onHyperlinkOpen!==void 0){const S=H();return S===void 0?!1:(p.onHyperlinkOpen(S,p.getActive()),!0)}return p.openPopover("link"),!0}case"pasteSpecial":return p.onPasteSpecialRequest!==void 0?(p.onPasteSpecialRequest({kind:"keyboard",cellRect:p.keyboardCellRect()}),!0):(p.paste({mode:"formats"}),!0);case"paste":return p.paste(C.options),!0;case"insertNow":{const S=C.unit==="date"?ig(p.now()):cg(p.now());if(v)return p.insertAtCaret(S),!0;const b=p.getActive();return Ye(p.adapter,b.row,b.col)?(p.rejectReadOnly({kind:"edit",cell:b,editSession:"none"}),!1):p.validateCommit(b,S).ok?p.commitEdits([{row:b.row,col:b.col,text:S}],{source:"edit",editSession:"discarded"})!==null:!1}case"hide":return N(C.axis,C.hide);case"resize":return U(g,C.axis,C.step);default:{const S=p.getHighlight();switch(C.target){case"row":return p.setHighlight({...S,row:!S.row}),!0;case"column":return p.setHighlight({...S,column:!S.column}),!0;case"both":{const b=S.row&&S.column;return p.setHighlight({...S,row:!b,column:!b}),!0}default:return p.setHighlight({...S,intersection:!S.intersection}),!0}}}},[L,_,H,r,s,l,c,R,h,m,N,U]),k=i.useCallback(()=>{const g=t.current;return!(g.isEditing()&&!g.requestCommit())},[]),x=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellHyperlink===void 0)throw new RangeError("[spreadsheet] setHyperlink requires the getCellHyperlink capability");const C=g===null?null:sn(g);if(g!==null&&C===null)throw new RangeError(`[spreadsheet] setHyperlink received an unnormalisable url ${JSON.stringify(g)}`);if(!k())return!1;const v=p.getActive();return Ye(p.adapter,v.row,v.col)?(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1):p.commitEdits([{row:v.row,col:v.col,hyperlink:C}],{source:"annotate"})!==null},[k]),z=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellNote===void 0)throw new RangeError("[spreadsheet] setNote requires the getCellNote capability");if(!k())return!1;const C=p.getActive();return Ye(p.adapter,C.row,C.col)?(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1):p.commitEdits([{row:C.row,col:C.col,note:g}],{source:"annotate"})!==null},[k]),I=i.useCallback(g=>{const p=t.current,C=p.adapter.getCellComments;if(C===void 0)throw new RangeError("[spreadsheet] addComment requires the getCellComments capability");if(!k())return!1;const v=p.getActive();if(Ye(p.adapter,v.row,v.col))return p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1;const S=C(v.row,v.col),b=S===void 0?[g]:[...S,g];return p.commitEdits([{row:v.row,col:v.col,comments:b}],{source:"annotate"})!==null},[k]),T=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellValidation===void 0)throw new RangeError("[spreadsheet] setValidation requires the getCellValidation capability");if(!k())return!1;const C=p.getSelection().ranges;if(!lr("annotate",C,p.maxOperationCells,p.onOperationRejected))return!1;if(qn(p.adapter,C))return p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:At(C)}),!1;const v=[];return Jt(C,S=>{v.push({row:S.row,col:S.col,validation:g})}),p.commitEdits(v,{source:"annotate"})!==null},[k]),F=i.useCallback(g=>{if(t.current.adapter.getCellFormat===void 0)throw new RangeError("[spreadsheet] applyFormat requires the getCellFormat capability");return s(g)},[s]),O=i.useCallback((g,p)=>{if(t.current.adapter.getCellFormat===void 0)throw new RangeError("[spreadsheet] setBorders requires the getCellFormat capability");return c(g,p)},[c]);return i.useMemo(()=>({executeCommand:W,applyFormat:F,setBorders:O,setHyperlink:x,setNote:z,addComment:I,setValidation:T,isCommandAvailable:L}),[W,F,O,x,z,I,T,L])},Wr="data-aqsp-pointing",wg=(e,t)=>{const n=Pc(e,t);return n!==null&&"insertAt"in n},Cg=(e,t)=>{Object.assign(e.style,Object.fromEntries(t.map(n=>[n,""])))},bg=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(null),[r,o]=i.useState(!1),s=i.useRef(!1),l=i.useRef(!1),c=i.useRef(!1),u=i.useRef(null),h=i.useRef(Pt),m=i.useCallback(()=>{const y=t.current,a=y.sinkRef.current;if(y.adapter.getCellFormula===void 0||n.current===null||!c.current||a===null)return null;const f=Pc(a.value,a.selectionStart);return f===null?null:{sink:a,target:f}},[]),R=i.useCallback(()=>{const y=t.current.sinkRef.current;if(y===null)return;const a=m()!==null;a!==y.hasAttribute(Wr)&&(a?y.setAttribute(Wr,""):y.removeAttribute(Wr))},[m]),N=i.useCallback((y,a)=>{const f=t.current;if(f.resolveEditPaint===void 0)return;const E=f.resolveEditPaint(a),d=E===null?Pt:E;d!==Pt&&Object.assign(y.style,d.style),h.current=d,f.editPaintRef!==void 0&&(f.editPaintRef.current=d)},[]),H=i.useCallback(y=>{Cg(y,Object.keys(h.current.style)),h.current=Pt;const a=t.current.editPaintRef;a!==void 0&&(a.current=Pt)},[]),L=i.useCallback(y=>{const a=t.current,f=n.current;if(f===null)return!0;const E=()=>{n.current=null,u.current=null;const d=a.sinkRef.current;d!==null&&(d.style.removeProperty("text-align"),H(d),d.removeAttribute(Wr)),o(!1)};if(y.commit){const d=a.sinkRef.current,$=d===null?"":d.value,A=Yn(a.adapter,f.cell.row,f.cell.col).text.replace(/\r\n?/g,`
13
- `),D=$===A;let q;if(D)q=!0;else if(Ye(a.adapter,f.cell.row,f.cell.col))a.rejectReadOnly({kind:"edit",cell:f.cell,editSession:y.onReject==="keep"?"kept":"discarded"}),q=!1;else{const j={source:"edit",editSession:y.onReject==="keep"?"kept":"discarded"};q=(a.validateCommit===void 0||a.validateCommit(f.cell,$).ok)&&a.commitEdits([{row:f.cell.row,col:f.cell.col,text:$}],j)!==null}if(!q)return y.onReject==="discard"&&(E(),a.rearmSink()),!1}return E(),y.rearm&&a.rearmSink(),!0},[H]),_=i.useCallback((y,a)=>{const f=t.current;if(f.isDragging()||n.current!==null)return;const E=f.sinkRef.current;if(E===null)return;const d=f.getActive();if(Ye(f.adapter,d.row,d.col)){f.rejectReadOnly({kind:"edit",cell:d,editSession:"none"});return}if(f.discardClip(),f.ensureCellVisible(d),y==="edit"){const{text:A,isFormula:D}=Yn(f.adapter,d.row,d.col);E.value=A;const q=a===void 0||D?A.length:Math.min(a,A.length);E.setSelectionRange(q,q)}else E.value="";const $=f.resolveEditAlign(d);$!==null&&(E.style.textAlign=$),N(E,d),c.current=!1,u.current=null,n.current={cell:d,mode:y},o(!0)},[N]),U=i.useCallback(()=>{L({rearm:!0,commit:!1})},[L]),W=i.useCallback(()=>{const y=t.current;if(n.current===null)return!0;const a=y.sinkRef.current;if(s.current&&a!==null){l.current=!0;try{a.blur()}finally{l.current=!1}return L({rearm:!1,commit:!0,onReject:"keep"})?(y.focusSink(),y.rearmSink(),!0):(y.focusSink(),!1)}return L({rearm:!0,commit:!0,onReject:"keep"})},[L]),k=i.useCallback(()=>m()!==null,[m]),x=i.useCallback(()=>t.current.adapter.getCellFormula===void 0||n.current===null?!1:(c.current=!c.current,R(),!0),[R]),z=i.useCallback(()=>{const y=m(),a=n.current;if(y===null||a===null)return null;if("insertAt"in y.target)return u.current=a.cell,{origin:a.cell,cursor:a.cell,axis:"cells"};const f=Fc(y.sink.value,y.sink.selectionStart);if(f===null)return null;const E=f.token,d=u.current;switch(E.kind){case"cell":{const $={row:E.row,col:E.col};return u.current=$,{origin:$,cursor:$,axis:"cells"}}case"range":{const $=d!==null&&(d.row===E.start.row||d.row===E.end.row)&&(d.col===E.start.col||d.col===E.end.col)?{row:d.row,col:d.col}:{row:E.start.row,col:E.start.col};return u.current=$,{origin:$,cursor:{row:$.row===E.start.row?E.end.row:E.start.row,col:$.col===E.start.col?E.end.col:E.start.col},axis:"cells"}}case"column":{const $=d!==null&&(d.col===E.start.col||d.col===E.end.col)?d.col:E.start.col,A={row:a.cell.row,col:$};return u.current=A,{origin:A,cursor:{row:a.cell.row,col:$===E.start.col?E.end.col:E.start.col},axis:"columns"}}case"row":{const $=d!==null&&(d.row===E.start.row||d.row===E.end.row)?d.row:E.start.row,A={row:$,col:a.cell.col};return u.current=A,{origin:A,cursor:{row:$===E.start.row?E.end.row:E.start.row,col:a.cell.col},axis:"rows"}}}},[m]),I=i.useCallback((y,a)=>{const f=m();if(f===null)return;const E=Mf(y,a),{sink:d}=f,[$,A]="replace"in f.target?f.target.replace:[f.target.insertAt,f.target.insertAt],D=d.value;d.value=`${D.slice(0,$)}${E}${D.slice(A)}`;const q=$+E.length;d.setSelectionRange(q,q),"row"in y&&(u.current={row:y.row,col:y.col}),R()},[m,R]),T=i.useCallback(()=>{const y=t.current.sinkRef.current;return y===null?null:{value:y.value,selectionStart:y.selectionStart,selectionEnd:y.selectionEnd}},[]),F=i.useCallback(y=>{const a=t.current.sinkRef.current;a!==null&&(a.value=y.value,a.setSelectionRange(y.selectionStart,y.selectionEnd),u.current=null,R())},[R]),O=i.useCallback(()=>{const y=t.current,a=y.sinkRef.current;if(y.adapter.getCellFormula===void 0||n.current===null||a===null)return!1;const f=Bf(a.value,a.selectionStart);return f===null?!1:(a.value=f.text,a.setSelectionRange(f.caret,f.caret),R(),!0)},[R]),g=i.useCallback(y=>{const a=t.current.sinkRef.current;if(n.current===null||a===null)return;const f=a.selectionStart,E=a.selectionEnd;a.value=`${a.value.slice(0,f)}${y}${a.value.slice(E)}`;const d=f+y.length;a.setSelectionRange(d,d),u.current=null,R()},[R]),p=i.useCallback(()=>{const y=t.current.sinkRef.current;return n.current===null||y===null?null:y.value},[]),C=i.useCallback(()=>n.current===null?null:n.current.cell,[]),v=i.useCallback(()=>{const y=t.current,a=n.current,f=y.sinkRef.current;a===null||f===null||(H(f),N(f,a.cell),y.repaintOverlay?.())},[H,N]),{enabled:S,sinkRef:b}=e;return i.useEffect(()=>{const y=b.current;if(!S||y===null)return;const a=()=>{s.current=!0},f=()=>{s.current=!1},E=A=>{const D=t.current;if(l.current||n.current===null)return;const q=D.rootRef.current,j=A.relatedTarget;q!==null&&j instanceof Node&&q.contains(j)||L({rearm:!1,commit:!0,onReject:"discard"})},d=()=>{const A=t.current;u.current=null,A.adapter.getCellFormula!==void 0&&n.current!==null&&!c.current&&wg(y.value,y.selectionStart)&&(c.current=!0),R()},$=()=>{n.current!==null&&R()};return y.addEventListener("compositionstart",a),y.addEventListener("compositionend",f),y.addEventListener("focusout",E),y.addEventListener("input",d),document.addEventListener("selectionchange",$),()=>{y.removeEventListener("compositionstart",a),y.removeEventListener("compositionend",f),y.removeEventListener("focusout",E),y.removeEventListener("input",d),document.removeEventListener("selectionchange",$)}},[S,b,L,R]),i.useMemo(()=>({isEditing:()=>n.current!==null,getEditingMode:()=>n.current?.mode??null,isFocusoutSuppressed:()=>l.current,requestCommit:W,cancelEdit:U,startEdit:_,getPointing:k,togglePointingArm:x,getReferenceCursor:z,insertReference:I,captureSink:T,restoreSink:F,cycleAnchorAtCaret:O,insertAtCaret:g,getSessionText:p,getSessionCell:C,refreshPaint:v,editing:r}),[W,U,_,k,x,z,I,T,F,O,g,p,C,v,r])},yg=(e,t,n)=>{const r=new Je.FenwickMapTree(e,t);let o=0;if(n)for(let s=0;s<e;s+=1){const l=Math.round(n(s));l!==t&&r.update(s,l),l===0&&(o+=1)}return{tree:r,initialHidden:o}},Rg=(e,t,n)=>{const{tree:r,initialHidden:o}=yg(e,t,n);let s=o;const u={count:e,sizeOf:h=>r.get(h),offsetOf:h=>{const{cumulative:m,currentValue:R}=r.prefixSum(h);return m-R},indexAt:h=>{if(e===0||r.getTotal()===0)throw new RangeError("[spreadsheet] indexAt requires a non-empty axis with positive total size");const m=Math.floor(h),R=Math.min(Math.max(m,0),r.getTotal()-1);return r.findIndexAtOrAfter(R+.5).index},totalSize:()=>r.getTotal(),resize:(h,m)=>{if(!(Number.isFinite(m)&&m>=0))throw new RangeError(`[spreadsheet] resize requires a finite size >= 0, received ${m}`);const R=Math.round(m);r.get(h)===0!=(R===0)&&(s+=R===0?1:-1),r.update(h,R)},hiddenCount:()=>s};return{key:`${e}:${t}`,model:u}},nn=(e,t,n)=>{if(n>0){const o=e.offsetOf(t)+e.sizeOf(t);return o>=e.totalSize()?null:e.indexAt(o)}const r=e.offsetOf(t)-1;return r<0?null:e.indexAt(r)},Bn=(e,t,n)=>{if(t>n||e.count===0||e.totalSize()===0)return[];const r=[];let o=e.sizeOf(t)>0?t:nn(e,t,1);for(;o!==null&&o<=n;)r.push(o),o=nn(e,o,1);return r},qi=(e,t,n)=>{if(!(Number.isInteger(t)&&t>0))throw new TypeError(`[spreadsheet] useAxisModel requires a positive integer defaultSize, received ${t}`);const r=i.useRef(n).current,o=i.useRef(null),s=`${e}:${t}`;return(o.current===null||o.current.key!==s)&&(o.current=Rg(e,t,r)),o.current.model},Vn=256,Jo=256,vg=2**32,Sg=4096,Ia=Object.freeze([]),ja=["background","color","bold","italic","underline","strikethrough"],Ha=(e,t)=>{if(!Array.isArray(e))throw new RangeError(`[spreadsheet] ${t} requires an array of conditional-format rules, received ${typeof e}`)},rn=(e,t,n)=>(e.size>=Sg&&e.clear(),e.set(t,n),n),Ba=e=>(Ha(e,"buildCfIndex"),{rules:e,buckets:new Map,columns:new Map}),Va=(e,t,n,r,o)=>{for(const s of e)if(s.startRow<=n&&s.endRow>=t&&s.startCol<=o&&s.endCol>=r)return!0;return!1},kg=(e,t,n)=>{const r=Math.floor(t/Vn),o=Math.floor(n/Jo),s=r*65536+o,l=e.buckets.get(s);if(l!==void 0)return l;const c=r*Vn,u=o*Jo,h=[];for(const m of e.rules)Va(m.ranges,c,c+Vn-1,u,u+Jo-1)&&h.push(m);return rn(e.buckets,s,h.length===0?Ia:h)},Eg=(e,t,n)=>{const r=Math.floor(t/Vn),o=r*vg+n,s=e.columns.get(o);if(s!==void 0)return s;const l=kg(e,t,n),c=r*Vn,u=[];for(const h of l)Va(h.ranges,c,c+Vn-1,n,n)&&u.push(h);return rn(e.columns,o,u.length===0?Ia:u)},Ag=(e,t)=>{for(const n of e)if(Cn(n,t))return!0;return!1},qs=()=>({extrema:new Map,formulas:new Map,numbers:new Map}),Kr=(e,t)=>e<t?-1:e>t?1:0,Ii=(e,t,n)=>{switch(e){case"eq":return t===0;case"neq":return t!==0;case"gt":return t>0;case"gte":return t>=0;case"lt":return t<0;case"lte":return t<=0;case"between":return n!==null&&t>=0&&n<=0;case"notBetween":return n!==null&&(t<0||n>0);default:return!1}},ji=new WeakMap,bs=e=>e===null?null:Number(e),Og=e=>{const t=ji.get(e);if(t!==void 0)return t;const n=e.b,r={a:bs(ot(e.a)),b:n===void 0?null:bs(ot(n))};return ji.set(e,r),r},Wa=(e,t,n)=>{const r=`${t.row}\0${t.col}`,o=e.numbers.get(r);return o!==void 0?o:rn(e.numbers,r,bs(ot(n())))},xg=(e,t,n,r)=>{const o=e.op==="between"||e.op==="notBetween",s=Og(e),l=Wa(r,t,n),c=o?s.b:null;if(l!==null&&s.a!==null&&(!o||c!==null))return Ii(e.op,Kr(l,s.a),c===null?null:Kr(l,c));const u=n(),h=e.b;return Ii(e.op,Kr(u,e.a),h===void 0?null:Kr(u,h))},Tg=(e,t)=>{switch(e.op){case"contains":return t.includes(e.value);case"notContains":return!t.includes(e.value);case"startsWith":return t.startsWith(e.value);case"endsWith":return t.endsWith(e.value);default:return!1}},Qo=e=>{const t=Ze(e);if(t===null)return null;const n=r=>Number.parseInt(t.slice(r,r+2),16);return[n(1),n(3),n(5),t.length===9?n(7):255]},Yr=e=>e.toString(16).padStart(2,"0"),es=(e,t,n)=>{const r=l=>Math.round(e[l]+(t[l]-e[l])*n),o=`#${Yr(r(0))}${Yr(r(1))}${Yr(r(2))}`,s=r(3);return s===255?o:`${o}${Yr(s)}`},ts=(e,t,n)=>t===n?e<=t?0:1:Math.min(1,Math.max(0,(e-t)/(n-t))),$g=(e,t,n,r,o)=>{let s=t.value===void 0?o.min:t.value,l=r.value===void 0?o.max:r.value,c=Qo(t.color),u=Qo(r.color);const h=n===void 0?void 0:Qo(n.color);if(!(Number.isFinite(e)&&Number.isFinite(s)&&Number.isFinite(l))||c===null||u===null||h===null)return null;if(s>l){const R=s;s=l,l=R;const N=c;c=u,u=N}if(n!==void 0&&h!==void 0){const R=n.value===void 0?(s+l)/2:n.value;if(s<R&&R<l)return e<=R?es(c,h,ts(e,s,R)):es(h,u,ts(e,R,l))}return es(c,u,ts(e,s,l))},Lg=(e,t,n,r)=>{const o=r.extrema.get(e.id);if(o!==void 0)return o;const{min:s,max:l}=t;if(s.value!==void 0&&l.value!==void 0)return rn(r.extrema,e.id,{min:s.value,max:l.value});if(n.getRangeExtrema===void 0)return null;let c=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(const h of e.ranges){const m=n.getRangeExtrema(h);if(m===null)return rn(r.extrema,e.id,null);c=Math.min(c,m.min),u=Math.max(u,m.max)}return rn(r.extrema,e.id,{min:c,max:u})},Dg=(e,t,n,r,o,s)=>{const l=Wa(s,n,r);if(l===null)return null;const c=Lg(e,t,o,s);return c===null?null:$g(l,t.min,t.mid,t.max,c)},Mg=(e,t,n,r,o)=>{if(r.evaluateFormula===void 0)return!1;const s=`${e.id}\0${n.row}\0${n.col}`,l=o.formulas.get(s),c=l!==void 0?l:rn(o.formulas,s,r.evaluateFormula(t.formula,n));return c===!0||typeof c=="number"&&Number.isFinite(c)&&c!==0},zg=(e,t,n,r,o)=>{const s=e.condition;switch(s.type){case"cellValue":return xg(s,t,n,o)?e.style:null;case"text":return Tg(s,n())?e.style:null;case"empty":return n()===""?e.style:null;case"notEmpty":return n()!==""?e.style:null;case"colorScale":{const l=Dg(e,s,t,n,r,o);return l===null?null:{...e.style,background:l}}case"customFormula":return Mg(e,s,t,r,o)?e.style:null;default:return null}},Hi=(e,t)=>Es(e,t),Ng=(e,t,n)=>{e[t]=n},Fg=(e,t)=>{let n=e;for(const r of ja)e[r]===void 0&&t[r]!==void 0&&(n===e&&(n={...e}),Ng(n,r,t[r]));return n},Pg=e=>{let t="";for(const n of ja){const r=e[n];t+=r===void 0?"":typeof r=="boolean"?r?"t":"f":`s${r.length}:${r}`,t+="\0"}return t},Bi=new WeakMap,_g=Object.freeze({}),qg=e=>{const t=e===void 0?_g:e,n=Bi.get(t);if(n!==void 0)return n;const r={byStyle:new WeakMap,byKey:new Map};return Bi.set(t,r),r},Ig=(e,t,n)=>{const r=qg(e);if(n){const c=r.byStyle.get(t);if(c!==void 0)return c;const u=Hi(e,t);return u!==void 0&&r.byStyle.set(t,u),u}const o=Pg(t),s=r.byKey.get(o);if(s!==void 0)return s;const l=Hi(e,t);return l!==void 0&&rn(r.byKey,o,l),l},Is=(e,t,n,r,o,s)=>{if(e.getCellFormat===void 0)return;const l=e.getCellFormat(r,o);if(t===null)return l;const c=Eg(t,r,o);if(c.length===0)return l;const u={row:r,col:o};let h=null,m=!0;for(const R of c){if(!Ag(R.ranges,u))continue;const N=zg(R,u,s,e,n);if(N!==null){if(N!==R.style&&(m=!1),h===null)h=N;else{const H=Fg(h,N);H!==h&&(m=!1,h=H)}if(R.stopIfTrue===!0)break}}return h===null?l:Ig(l,h,m)},Vi=new WeakMap,jg=e=>{Ha(e,"widthRelevantRules");const t=Vi.get(e);if(t!==void 0)return t;const n=e.filter(o=>o.style.bold!==void 0||o.style.italic!==void 0||o.stopIfTrue===!0),r=n.length===e.length?e:n;return Vi.set(e,r),r},Hg=({row:e,col:t,text:n,display:r,renderCell:o,__onCellRender:s})=>{const l=i.useRef(!1);if(i.useEffect(()=>{const c=l.current?"update":"mount";l.current=!0,s?.(`cell-${e}-${t}`,c,0,0,0,0)}),o!==void 0){const c=o({row:e,col:t,text:n,displayText:r});return c===void 0?r:c}return r},Bg=i.memo(Hg),Vg=Object.freeze({left:Object.freeze({justifyContent:fr("left")}),center:Object.freeze({justifyContent:fr("center")}),right:Object.freeze({justifyContent:fr("right")})}),Wg=Object.freeze({role:"rowgroup"}),Kg=4096,Wi=new WeakMap,Ur=new Map,Yg=(e,t)=>{if(e===null)return Vg[t];let n=Wi.get(e);n===void 0&&(n={},Wi.set(e,n));const r=n[t];if(r!==void 0)return r;const o={...e.style,justifyContent:fr(t)},s=JSON.stringify(o);let l=Ur.get(s);return l===void 0&&(Ur.size>=Kg&&Ur.clear(),l=Object.freeze(o),Ur.set(s,l)),n[t]=l,l},Ug=qs(),Xg=(e,t,n)=>{if(e.row!==t||e.col!==n)throw new RangeError(`[spreadsheet] cell renderer (${t}, ${n}) ran without its getCellProps (latched ${e.row}, ${e.col})`);return e.value},Gg=(e,t,n,r,o,s)=>{if(e.getCellFormat===void 0&&e.getCellNote===void 0&&e.getCellComments===void 0&&e.getCellHyperlink===void 0&&e.getCellValidation===void 0)return null;const l=Qr(e,o,s),c={};let u=null,h;if(e.getCellFormat!==void 0){const m=Is(e,r===null?null:r.indexRef.current,r===null?Ug:r.memoRef.current,o,s,l);h=m===void 0?void 0:m.value;const R=ta(m,l),N=nn(n,s,1),H=nn(t,o,1),L=uf(m,N===null?void 0:e.getCellFormat(o,N),H===null?void 0:e.getCellFormat(H,s),n.offsetOf(s)===0,t.offsetOf(o)===0);L!==null&&Object.assign(c,L.attrs),c["data-aqsp-align"]=R,u=Yg(L,R)}if(e.getCellNote!==void 0&&e.getCellNote(o,s)!==void 0&&(c["data-aqsp-note"]=""),e.getCellComments!==void 0){const m=e.getCellComments(o,s);m!==void 0&&m.length>0&&(c["data-aqsp-comment"]="")}if(e.getCellHyperlink!==void 0&&Un(e.getCellHyperlink(o,s))!==void 0&&(c["data-aqsp-link"]=""),e.getCellValidation!==void 0){const m=e.getCellValidation(o,s);m!==void 0&&Cm(m,l())&&(c["data-aqsp-invalid"]="")}return{attrs:c,style:u,value:h}},Zg=({adapter:e,rowAxis:t,colAxis:n,viewStore:r,handleRef:o,bodyRef:s,dataVersion:l,defaultColumnWidth:c,frozenColumns:u,frozenRows:h,frozenTrailingColumns:m,frozenTrailingRows:R,headerRows:N,labelledBy:H,gridLabel:L,readOnly:_,renderCell:U,onScroll:W,onRangeChange:k,focusSink:x,isEditing:z,requestCommit:I,testId:T,__onCellRender:F,__maxRenderedCells:O,cfIndexRef:g,cfMemoRef:p,isPointing:C,tapScrollCircleOptions:v,overscanRows:S,overscanCols:b,background:y,onRenderTruncated:a,locale:f,scrollLabels:E})=>{const d=i.useRef(null),$=s??d;if(g===void 0!=(p===void 0))throw new RangeError("[spreadsheet] cfIndexRef and cfMemoRef must be passed together");const A=i.useMemo(()=>g===void 0||p===void 0?null:{indexRef:g,memoRef:p},[g,p]),D=i.useCallback(()=>r.get().editVersion,[r]),q=i.useCallback(ue=>r.subscribeCoalesced(ue),[r]),K=i.useSyncExternalStore(q,D,D)+(l??0),G=i.useCallback(ue=>t.sizeOf(ue),[t]),J=i.useCallback(ue=>n.sizeOf(ue),[n]),te=i.useCallback((ue,Ne)=>e.getCellText(ue,Ne),[e]),le=i.useMemo(()=>({enableKeyboardNavigation:!1,pointerDragInputs:["pen","touch"],resetOnGetItemHeightChange:!0,resetOnGetColWidthChange:!0,defaultColWidth:c}),[c]),me=i.useMemo(()=>({width:Te.SPREADSHEET_SCROLLBAR_SIZE_PX,tapScrollCircleOptions:v,enableArrowButtonTabStops:!1}),[v]),Ee=i.useRef({row:-1,col:-1,value:void 0}),xe=i.useCallback((ue,Ne)=>{const Ue=ue<N,je={role:Ue?"columnheader":"gridcell","aria-rowindex":ue+1,"aria-colindex":Ne+1,"data-aqsp-cell":"","data-row":ue,"data-col":Ne,className:"aqsp-cell",...Ye(e,ue,Ne)?{"aria-readonly":"true","data-aqsp-readonly":""}:{},...Ue?{"data-aqsp-header-row":""}:{}},Ot=wh(e,ue,Ne),xt=Ot===null?je:{...je,...Ot},He=Gg(e,t,n,A,ue,Ne),wt=Ee.current;return wt.row=ue,wt.col=Ne,wt.value=He===null?void 0:He.value,He===null?xt:He.style===null?{...xt,...He.attrs}:{...xt,...He.attrs,style:He.style}},[e,t,n,A,N]),De=i.useCallback(ue=>({role:"row","aria-rowindex":ue+1,"data-aqsp-row":ue,"data-aqsp-cells":"",className:"aqsp-row"}),[]),Pe=i.useCallback((ue,Ne,Ue)=>{let je=ue;return e.getCellFormat!==void 0&&(je=Wn(ue,Xg(Ee.current,Ne,Ue))),Y.jsx(Bg,{row:Ne,col:Ue,text:ue,display:je,renderCell:U,__onCellRender:F})},[K,U,F,e]);return Y.jsx("div",{ref:$,className:"aqsp-body","data-aqsp-body":"","data-testid":T?`${T}-body`:void 0,role:"grid","aria-rowcount":e.rowCount,"aria-colcount":e.colCount,"aria-label":L,"aria-labelledby":H,"aria-readonly":_?"true":void 0,onPointerDownCapture:ue=>{if(!(ue.target instanceof Element&&ue.target.closest("[data-aqsp-cells]")!==null)&&ue.pointerType==="mouse"){if(ue.button!==0){ue.preventDefault();return}if(ue.preventDefault(),C?.()===!0){ue.stopPropagation(),x();return}if(z()&&!I()){ue.stopPropagation(),x();return}x()}},children:Y.jsx(Je.VirtualGrid,{ref:o,rowCount:e.rowCount,colCount:e.colCount,frozenLeadingCols:u,frozenLeadingRows:h,frozenTrailingCols:m,frozenTrailingRows:R,getRowHeight:G,getColWidth:J,getCell:te,getCellProps:xe,getRowProps:De,contentProps:Wg,behaviorOptions:le,scrollBarOptions:me,overscanRows:S,overscanCols:b,background:y,onRenderTruncated:a,__maxRenderedCells:O,locale:f,labels:E,callbackThrottleMs:0,onScroll:W,onRangeChange:k,testId:T,children:Pe})})},Jg=i.memo(Zg),In=6,rt=3,lo=(e,t)=>{const n=[],r=[];if(t.length===0)return n;const o=t[0];o>0&&e.sizeOf(o-1)===0&&r.push({kind:"unhide",index:o-1,start:e.offsetOf(o),length:rt});for(const s of t){const l=e.sizeOf(s),c=e.offsetOf(s)+l,u=nn(e,s,1);s<e.count-1&&(u===null||u>s+1)?(n.push({kind:"resize",index:s,start:c-In,length:rt}),r.push({kind:"unhide",index:s+1,start:c-rt,length:rt})):l>=2*In?n.push({kind:"resize",index:s,start:c-In,length:In}):n.push({kind:"resize",index:s,start:c-rt,length:rt})}return[...n,...r]},Ka=(e,t)=>{const n=[],r=[];if(t.length===0)return n;const o=e.offsetOf(t[0]),s=e.totalSize()-o;for(const c of t){const u=e.sizeOf(c),h=e.offsetOf(c)-o;c>0&&e.sizeOf(c-1)===0?(r.push({kind:"unhide",index:c-1,start:h,length:rt}),n.push({kind:"resize",index:c,start:h+rt,length:rt})):u>=2*In?n.push({kind:"resize",index:c,start:h,length:In}):n.push({kind:"resize",index:c,start:h,length:rt})}const l=t[t.length-1];return l<e.count-1&&e.sizeOf(l+1)===0&&r.push({kind:"unhide",index:l+1,start:s-rt,length:rt}),[...n.reverse(),...r]},Qg=({viewStore:e,colAxis:t,frozenCols:n,frozenTrailingCols:r,handleRef:o,bandRef:s,colTrackRef:l,windowOriginXRef:c,repaintColHeaders:u,selectionRanges:h,enableResizeUI:m,dividerLeadingRef:R,dividerTrailingRef:N})=>{const H=Je.useWheelBridge(o),L=i.useCallback(d=>(s.current=d,H(d)),[s,H]),_=i.useCallback(()=>{const{colStart:d,colEnd:$,colVersion:A}=e.get();return`${d}:${$}:${A}`},[e]),U=i.useCallback(d=>e.subscribeCoalesced(d),[e]);i.useSyncExternalStore(U,_,_);const{colStart:W,colEnd:k}=e.get(),x=t.count===0?0:t.offsetOf(Math.min(W,t.count-1));i.useLayoutEffect(()=>{c.current=x,u()},[x,c,u]);const z=d=>h.some($=>d>=$.startCol&&d<=$.endCol),I=Math.min(Math.max(0,n),t.count),T=ya(t,I),F=I>0?Bn(t,0,I-1):[],O=Math.min(Math.max(0,r),t.count-I),g=va(t,O),p=t.totalSize()-g,C=O>0?Bn(t,t.count-O,t.count-1):[],v=Bn(t,Math.max(W,I),Math.min(k,Math.max(0,t.count-1)-O)),S=[];for(const d of v)S.push(Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-in-selection":z(d)?"":void 0,style:{left:t.offsetOf(d)-x,width:t.sizeOf(d)},children:Te.columnIndexToName(d)},d));const b=m?lo(t,v):null,y=b===null?null:b.filter(d=>!(d.kind==="unhide"&&d.index<I&&T>0||d.kind==="unhide"&&d.index>=t.count-O&&g>0)),a=m&&I>0?lo(t,F):null,f=m&&O>0?Ka(t,C):null,E=Y.jsxs("div",{ref:l,className:"aqsp-col-header-track",children:[S,y?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,style:{left:d.start-x,width:d.length}},`r${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{left:d.start-x,width:d.length}},`u${d.index}`))]});return Y.jsx("div",{ref:L,className:"aqsp-col-header","aria-hidden":"true","data-aqsp-col-header":"",children:I===0&&O===0?E:Y.jsxs(Y.Fragment,{children:[F.map(d=>Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-frozen-header":"","data-aqsp-in-selection":z(d)?"":void 0,style:{left:t.offsetOf(d),width:t.sizeOf(d)},children:Te.columnIndexToName(d)},d)),a?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,style:{left:d.start,width:d.length}},`fr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{left:d.start,width:d.length}},`fu${d.index}`)),Y.jsxs("div",{className:"aqsp-col-header-scroll","data-aqsp-col-header-scroll":"",style:{left:T,right:O>0?`calc(${Te.SPREADSHEET_SCROLLBAR_SIZE_PX}px + min(${g}px, max(0px, 100% - ${Te.SPREADSHEET_SCROLLBAR_SIZE_PX+T}px)))`:void 0},children:[E,I>0?Y.jsx("div",{ref:R,className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-leading",style:{left:0,top:0,bottom:0}}):null,O>0?Y.jsx("div",{ref:N,className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-trailing",style:{right:0,top:0,bottom:0}}):null]}),O>0?Y.jsx("div",{className:"aqsp-col-header-scroll","data-aqsp-col-header-trailing":"",style:{left:`max(${T}px, calc(100% - ${g+Te.SPREADSHEET_SCROLLBAR_SIZE_PX}px))`,right:Te.SPREADSHEET_SCROLLBAR_SIZE_PX},children:Y.jsxs("div",{style:{position:"absolute",top:0,height:"100%",right:0,width:g},children:[C.map(d=>Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-trailing-header":"","data-aqsp-in-selection":z(d)?"":void 0,style:{left:t.offsetOf(d)-p,width:t.sizeOf(d)},children:Te.columnIndexToName(d)},d)),f?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,"data-aqsp-resize-anchor":"trailing",style:{left:d.start,width:d.length}},`tr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,"data-aqsp-resize-anchor":"trailing",style:{left:d.start,width:d.length}},`tu${d.index}`))]})}):null]})})},ew=({viewStore:e,rowAxis:t,handleRef:n,bandRef:r,selectionRanges:o,rowTrackRef:s,windowOriginYRef:l,repaintHeaders:c,enableResizeUI:u,frozenRows:h,frozenTrailingRows:m,dividerLeadingRef:R,dividerTrailingRef:N})=>{const H=Je.useWheelBridge(n),L=i.useCallback(d=>(r.current=d,H(d)),[r,H]),_=d=>o.some($=>d>=$.startRow&&d<=$.endRow),U=i.useCallback(()=>{const{rowStart:d,rowEnd:$,rowGeomVersion:A}=e.get();return`${d}:${$}:${A}`},[e]),W=i.useCallback(d=>e.subscribeCoalesced(d),[e]);i.useSyncExternalStore(W,U,U);const{rowStart:k,rowEnd:x}=e.get(),z=t.count===0?0:t.offsetOf(Math.min(k,t.count-1));i.useLayoutEffect(()=>{l.current=z,c()},[z,l,c]);const I=Math.min(Math.max(0,h),t.count),T=Ra(t,I),F=I>0?Bn(t,0,I-1):[],O=Math.min(Math.max(0,m),t.count-I),g=Sa(t,O),p=t.totalSize()-g,C=O>0?Bn(t,t.count-O,t.count-1):[],v=Bn(t,Math.max(k,I),Math.min(x,Math.max(0,t.count-1)-O)),S=[];for(const d of v)S.push(Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-in-selection":_(d)?"":void 0,style:{top:t.offsetOf(d)-z,height:t.sizeOf(d)},children:d+1},d));const b=u?lo(t,v):null,y=b===null?null:b.filter(d=>!(d.kind==="unhide"&&d.index<I&&T>0||d.kind==="unhide"&&d.index>=t.count-O&&g>0)),a=u&&I>0?lo(t,F):null,f=u&&O>0?Ka(t,C):null,E=Y.jsxs("div",{ref:s,className:"aqsp-row-header-track",children:[S,y?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,style:{top:d.start-z,height:d.length}},`r${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{top:d.start-z,height:d.length}},`u${d.index}`))]});return Y.jsx("div",{ref:L,className:"aqsp-row-header","aria-hidden":"true","data-aqsp-row-header":"",style:{marginBottom:Te.SPREADSHEET_SCROLLBAR_SIZE_PX},children:I===0&&O===0?E:Y.jsxs(Y.Fragment,{children:[F.map(d=>Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-frozen-row-header":"","data-aqsp-in-selection":_(d)?"":void 0,style:{top:t.offsetOf(d),height:t.sizeOf(d)},children:d+1},d)),a?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,style:{top:d.start,height:d.length}},`fr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{top:d.start,height:d.length}},`fu${d.index}`)),Y.jsxs("div",{className:"aqsp-row-header-scroll","data-aqsp-row-header-scroll":"",style:{top:T,bottom:O>0?`calc(min(${g}px, max(0px, 100% - ${T}px)))`:void 0},children:[E,I>0?Y.jsx("div",{ref:R,className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-leading",style:{top:0,left:0,right:0}}):null,O>0?Y.jsx("div",{ref:N,className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-trailing",style:{bottom:0,left:0,right:0}}):null]}),O>0?Y.jsx("div",{className:"aqsp-row-header-scroll","data-aqsp-row-header-trailing":"",style:{top:`max(${T}px, calc(100% - ${g}px))`},children:Y.jsxs("div",{style:{position:"absolute",left:0,right:0,bottom:0,height:g},children:[C.map(d=>Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-trailing-row-header":"","data-aqsp-in-selection":_(d)?"":void 0,style:{top:t.offsetOf(d)-p,height:t.sizeOf(d)},children:d+1},d)),f?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,"data-aqsp-resize-anchor":"trailing",style:{top:d.start,height:d.length}},`tr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,"data-aqsp-resize-anchor":"trailing",style:{top:d.start,height:d.length}},`tu${d.index}`))]})}):null]})})},tw=9,nw=4,Ki=(e,t,n)=>{const r=t.get(e);if(r!==void 0)return r;const o=e.italic===!0?"italic":n.fontStyle,s=e.bold===!0?"bold":n.fontWeight,l=typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize>0?`${e.fontSize*4/3}px`:n.fontSize,c=typeof e.fontFamily=="string"&&e.fontFamily!==""?e.fontFamily:n.fontFamily,u=`${o} ${s} ${l} ${c}`;return t.set(e,u),u},Yi=(e,t,n)=>e.anchor==="trailing"?t.offsetOf(e.index)+e.initialSize-n:t.offsetOf(e.index)+n,rw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(0),s=i.useRef(null),l=i.useRef(0),c=i.useRef(null),u=i.useRef(null),h=i.useRef(""),m=i.useRef(null),R=i.useCallback(g=>s.current!==null?g.pointerId===s.current:g.pointerType==="mouse",[]),N=i.useCallback(()=>{const g=t.current;n.current=!1,r.current=null,u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),g.writeResizeGuide(null);const p=m.current;p!==null&&(window.removeEventListener("pointermove",p.move),window.removeEventListener("pointerup",p.up),m.current=null);const C=c.current;C!==null&&s.current!==null&&C.hasPointerCapture?.(s.current)&&C.releasePointerCapture(s.current),c.current=null,s.current=null,g.repaintOverlay()},[]),H=i.useCallback((g,p)=>{const C=t.current;return g==="col"?p.startRow===0&&p.endRow===C.rowAxis.count-1:p.startCol===0&&p.endCol===C.colAxis.count-1},[]),L=i.useCallback((g,p)=>{const C=t.current,v=C.getSelection().ranges.filter(f=>H(g,f));if(!v.some(f=>g==="col"?p>=f.startCol&&p<=f.endCol:p>=f.startRow&&p<=f.endRow))return[p];const b=v.reduce((f,E)=>f+(g==="col"?E.endCol-E.startCol+1:E.endRow-E.startRow+1),0),y=g==="row"?Math.floor(C.maxOperationCells/Rs):C.maxOperationCells;if(b>y)return C.onOperationRejected?.("resize",b,"limit"),null;const a=new Set;for(const f of v){const E=g==="col"?f.startCol:f.startRow,d=g==="col"?f.endCol:f.endRow;for(let $=E;$<=d;$+=1)a.add($)}return[...a]},[H]),_=i.useCallback((g,p,C)=>{const v=t.current,S=g==="col"?v.colAxis:v.rowAxis,b=vs(S,p,C,{maxOperationCells:v.maxOperationCells,rowHiddenLimit:ys,axisKind:g});return b.ok?(v.resizeTracks(g,b.entries),!0):(v.onOperationRejected?.("resize",b.count,b.reason),!1)},[]),U=i.useCallback((g,p)=>{if(p===g.initialSize)return;const C=g.kind==="unhide"?[g.index]:L(g.axis,g.index);C!==null&&_(g.axis,C.map(v=>({index:v,size:p})),g.index)},[L,_]),W=i.useCallback((g,p,C,v)=>{const S=t.current,b=S.fontSourceRef.current;if(b===null)return!1;if(p.length===0)return!0;const y=g.length*p.length;if(y>C)return S.onOperationRejected?.("resize",y,"limit"),!1;const a=document.createElement("canvas").getContext("2d");if(a===null)return!0;const f=getComputedStyle(b),E=`${f.fontStyle} ${f.fontWeight} ${f.fontSize} ${f.fontFamily}`,d=f.getPropertyValue("--_aqsp-header-row-font-weight").trim(),$={fontStyle:f.fontStyle,fontWeight:d===""?f.fontWeight:d,fontSize:f.fontSize,fontFamily:f.fontFamily},A=`${$.fontStyle} ${$.fontWeight} ${$.fontSize} ${$.fontFamily}`,D=S.adapter.getConditionalFormats===void 0?null:jg(S.adapter.getConditionalFormats()),q=qs(),j=new WeakMap,K=new WeakMap,G=new Map;for(const me of g){const Ee=D===null?null:Ba(D.filter(xe=>xe.ranges.some(De=>me>=De.startCol&&me<=De.endCol)));for(const xe of p){const De=S.adapter.getCellText(xe,me),Pe=S.adapter.getCellFormat===void 0?void 0:Is(S.adapter,Ee,q,xe,me,()=>De),ue=xe<S.headerRows,Ne=Pe===void 0?ue?A:E:ue?Ki(Pe,K,$):Ki(Pe,j,f),Ue=Wn(De,Pe===void 0?void 0:Pe.value),je=G.get(Ne);je===void 0?G.set(Ne,[{col:me,text:Ue}]):je.push({col:me,text:Ue})}}const J=b.ownerDocument.createElement("span");J.setAttribute("aria-hidden","true"),J.style.position="absolute",J.style.visibility="hidden",b.append(J);const te=new Map;for(const[me,Ee]of G){a.font=me,J.style.font=me;const xe=getComputedStyle(J);a.letterSpacing=xe.letterSpacing==="normal"?"0px":xe.letterSpacing,a.wordSpacing=xe.wordSpacing==="normal"?"0px":xe.wordSpacing;for(const De of Ee){const Pe=a.measureText(De.text).width,ue=te.get(De.col);(ue===void 0||Pe>ue)&&te.set(De.col,Pe)}}J.remove();const le=[];for(const me of g){const Ee=te.get(me);Ee!==void 0&&Ee>0&&le.push({index:me,size:Math.ceil(Ee)+tw})}return le.length===0?!0:_("col",le,v)},[_]),k=i.useCallback(g=>{const p=t.current,C=L("col",g);if(C===null)return!1;const v=p.handleRef.current,S=v===null?null:v.getFrozenSize(),b=S===null?0:S.rows,y=S===null?0:S.trailingRows,{rowStart:a,rowEnd:f}=p.viewStore.get(),E=Math.min(f,p.rowAxis.count-1),d=[],$=new Set,A=D=>{!$.has(D)&&p.rowAxis.sizeOf(D)>0&&($.add(D),d.push(D))};for(let D=0;D<b;D+=1)A(D);for(let D=a;D<=E;D+=1)A(D);for(let D=p.rowAxis.count-y;D<p.rowAxis.count;D+=1)A(D);return W(C,d,Math.floor(p.maxOperationCells/nw),g)},[L,W]),x=i.useCallback((g,p,C)=>{const v=g==="col"?t.current.colAxis:t.current.rowAxis,S=Nu(v.sizeOf(p),C);if(S===v.sizeOf(p))return!0;const b=L(g,p);return b===null?!1:_(g,b.map(y=>({index:y,size:S})),p)},[L,_]),z=i.useCallback(g=>{const p=t.current;return p.autofitEnabled?p.colAxis.sizeOf(g)===0?!0:k(g):!1},[k]),I=i.useCallback(g=>{const p=t.current;if(!p.autofitEnabled)return!1;const C=[...new Set(g)].filter(S=>p.colAxis.sizeOf(S)>0);if(C.length===0)return!0;const v=[];for(let S=0;S<p.rowAxis.count;S+=1)p.rowAxis.sizeOf(S)>0&&v.push(S);return W(C,v,p.maxOperationCells,null)},[W]),{enabled:T,colBandRef:F,rowBandRef:O}=e;return i.useEffect(()=>{const g=F.current,p=O.current;if(!T||g===null||p===null)return;const C=j=>j==="col"?"[data-aqsp-col-resize], [data-aqsp-unhide]":"[data-aqsp-row-resize], [data-aqsp-unhide]",v=(j,K)=>{if(!(K instanceof Element))return null;const G=K.closest(C(j));if(G===null)return null;const J=G.hasAttribute("data-aqsp-unhide"),te=Number(G.getAttribute(J?"data-aqsp-unhide":j==="col"?"data-aqsp-col-resize":"data-aqsp-row-resize")),le=G.hasAttribute("data-aqsp-resize-anchor")?"trailing":"leading";return{kind:J?"unhide":"resize",index:te,anchor:le}},S=j=>{if(!(n.current&&R(j)))return;const K=r.current;if(K===null)return;const G=(K.axis==="col"?j.clientX-K.startClientX:j.clientY-K.startClientY)/t.current.zoomRef.current;o.current=Math.max(0,Math.round(K.anchor==="trailing"?K.initialSize-G:K.initialSize+G)),u.current===null&&(u.current=requestAnimationFrame(()=>{u.current=null;const J=r.current;if(!n.current||J===null)return;const te=t.current,le=J.axis==="col"?te.colAxis:te.rowAxis;te.writeResizeGuide({axis:J.axis,position:Yi(J,le,o.current),anchor:J.anchor})}))},b=()=>{const j=r.current,K=o.current;N(),j!==null&&U(j,K)},y=j=>{S(j),n.current&&R(j)&&(l.current&1)!==0&&(j.buttons&1)===0&&b()},a=j=>{j.button!==0||!(n.current&&R(j))||b()},f=(j,K)=>G=>{const J=t.current;if(h.current=G.pointerType,G.pointerType!=="mouse")return;if(G.button!==0){G.preventDefault();return}const te=v(j,G.target);if(te===null)return;if(G.stopPropagation(),G.preventDefault(),J.isPointing()){J.focusSink();return}if(J.isEditing()&&!J.requestCommit()){J.focusSink();return}J.focusSink();const le=j==="col"?J.colAxis:J.rowAxis,me={axis:j,kind:te.kind,index:te.index,anchor:te.anchor,initialSize:le.sizeOf(te.index),startClientX:G.clientX,startClientY:G.clientY};r.current=me,o.current=me.initialSize,l.current=G.buttons,n.current=!0,J.repaintOverlay(),s.current=G.pointerId,c.current=K;try{K.setPointerCapture(G.pointerId)}catch{s.current=null}const Ee=y,xe=a;m.current={move:Ee,up:xe},window.addEventListener("pointermove",Ee),window.addEventListener("pointerup",xe),J.writeResizeGuide({axis:j,position:Yi(me,le,o.current),anchor:me.anchor})},E=(j,K)=>G=>{const J=t.current;if(h.current!=="mouse")return;const te=K.getRootNode(),le=te instanceof ShadowRoot?te:K.ownerDocument,me=G.target instanceof Element&&G.target.closest(C(j))!==null?G.target:typeof le.elementFromPoint=="function"?le.elementFromPoint(G.clientX,G.clientY):null,Ee=v(j,me);if(Ee!==null){if(G.stopPropagation(),J.isEditing()){J.focusSink();return}if(Ee.kind==="unhide"){_(j,[{index:Ee.index,size:j==="col"?J.defaultColumnWidth:J.defaultRowHeight}],null);return}if(J.autofitEnabled){if(j==="row"){const xe=L("row",Ee.index);xe!==null&&_("row",xe.map(De=>({index:De,size:J.defaultRowHeight})),Ee.index);return}k(Ee.index)}}},d=j=>{!n.current||s.current===null||j.pointerId!==s.current||N()},$=f("col",g),A=f("row",p),D=E("col",g),q=E("row",p);return g.addEventListener("pointerdown",$,{capture:!0}),p.addEventListener("pointerdown",A,{capture:!0}),g.addEventListener("dblclick",D),p.addEventListener("dblclick",q),g.addEventListener("lostpointercapture",d),p.addEventListener("lostpointercapture",d),()=>{g.removeEventListener("pointerdown",$,{capture:!0}),p.removeEventListener("pointerdown",A,{capture:!0}),g.removeEventListener("dblclick",D),p.removeEventListener("dblclick",q),g.removeEventListener("lostpointercapture",d),p.removeEventListener("lostpointercapture",d),N()}},[T,F,O,R,N,U,_,L,k]),i.useMemo(()=>({stepTrack:x,autofitColumn:z,autofitColumnsInAllRows:I,isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:()=>{n.current&&N()},cancelDrag:N}),[N,x,z,I])},js=(e,t)=>e.startRow===t.startRow&&e.startCol===t.startCol&&e.endRow===t.endRow&&e.endCol===t.endCol,ow=(e,t)=>e.ranges.length===t.ranges.length&&e.ranges.every((n,r)=>js(n,t.ranges[r]))&&It(e.anchor,t.anchor)&&It(e.active,t.active),sw=(e,t,n)=>{const r=l=>l.row<t&&l.col<n,o=l=>l.endRow<t&&l.endCol<n;if(r(e.anchor)&&r(e.active)&&e.ranges.every(o))return e;const s=l=>ln(l,t,n);return{ranges:e.ranges.map(l=>o(l)?l:Re(s({row:l.startRow,col:l.startCol}),s({row:l.endRow,col:l.endCol}))),anchor:r(e.anchor)?e.anchor:s(e.anchor),active:r(e.active)?e.active:s(e.active)}},lw=(e,t)=>{const n=e.ranges[e.ranges.length-1];return js(n,t)?e:{...e,ranges:[...e.ranges.slice(0,-1),t]}},Cr=(e,t,n)=>n.extend?hn(e,t):n.append?{ranges:[...e.ranges,Re(t,t)],anchor:t,active:t}:e.ranges.length===1&&It(e.anchor,t)&&It(e.active,t)&&js(e.ranges[0],Re(t,t))?e:{ranges:[Re(t,t)],anchor:t,active:t},iw=(e,t)=>({row:Math.min(Math.max(e.row,t.startRow),t.endRow),col:Math.min(Math.max(e.col,t.startCol),t.endCol)}),hn=(e,t)=>{const n=lw(e,Re(e.anchor,t));return n.ranges.some(r=>Cn(r,n.active))?n:{...n,active:iw(n.active,n.ranges[n.ranges.length-1])}},Ya=(e,t,n)=>{let r=!1;const o=[];for(const c of e.ranges){if(t.startRow>c.endRow||t.endRow<c.startRow||t.startCol>c.endCol||t.endCol<c.startCol){o.push(c);continue}r=!0,t.startRow>c.startRow&&o.push(Re({row:c.startRow,col:c.startCol},{row:t.startRow-1,col:c.endCol})),t.endRow<c.endRow&&o.push(Re({row:t.endRow+1,col:c.startCol},{row:c.endRow,col:c.endCol}));const u=Math.max(c.startRow,t.startRow),h=Math.min(c.endRow,t.endRow);t.startCol>c.startCol&&o.push(Re({row:u,col:c.startCol},{row:h,col:t.startCol-1})),t.endCol<c.endCol&&o.push(Re({row:u,col:t.endCol+1},{row:h,col:c.endCol}))}if(!r)return e;if(o.length===0)return{ranges:[Re(n,n)],anchor:n,active:n};const s=o.findIndex(c=>Cn(c,e.active));if(s>=0){const[c]=o.splice(s,1);return o.push(c),{ranges:o,anchor:e.active,active:e.active}}const l={row:o[o.length-1].startRow,col:o[o.length-1].startCol};return{ranges:o,anchor:l,active:l}},cw=(e,t,n,r)=>{const o=e[t];if(r==="right"){if(n.col<o.endCol)return{rangeIndex:t,cell:{row:n.row,col:n.col+1}};if(n.row<o.endRow)return{rangeIndex:t,cell:{row:n.row+1,col:o.startCol}}}else if(r==="left"){if(n.col>o.startCol)return{rangeIndex:t,cell:{row:n.row,col:n.col-1}};if(n.row>o.startRow)return{rangeIndex:t,cell:{row:n.row-1,col:o.endCol}}}else if(r==="down"){if(n.row<o.endRow)return{rangeIndex:t,cell:{row:n.row+1,col:n.col}};if(n.col<o.endCol)return{rangeIndex:t,cell:{row:o.startRow,col:n.col+1}}}else{if(n.row>o.startRow)return{rangeIndex:t,cell:{row:n.row-1,col:n.col}};if(n.col>o.startCol)return{rangeIndex:t,cell:{row:o.endRow,col:n.col-1}}}if(r==="right"||r==="down"){const c=(t+1)%e.length,u=e[c];return{rangeIndex:c,cell:{row:u.startRow,col:u.startCol}}}const s=(t-1+e.length)%e.length,l=e[s];return{rangeIndex:s,cell:{row:l.endRow,col:l.endCol}}},Ua=(e,t)=>{const n=e.ranges.findIndex(o=>Cn(o,e.active));if(n===-1)throw new RangeError("[spreadsheet] reduceActiveCycle requires active inside some range (invariant violation)");let r={rangeIndex:n,cell:e.active};do if(r=cw(e.ranges,r.rangeIndex,r.cell,t),!It(r.cell,e.active))return{...e,active:r.cell};while(r.rangeIndex!==n);return e},Ft=24,Ui=32,io=4,zn=({handleRef:e,rowAxis:t,colAxis:n,bodyRef:r,onDragFrame:o,axis:s="both",zoomRef:l})=>{const c=i.useRef(null),u=i.useRef(null),h=i.useRef(null),m=i.useRef(null),R=i.useCallback(()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),u.current=null,m.current=null,h.current=null},[]),N=i.useCallback(()=>{const L=u.current,_=e.current,U=m.current;if(L===null||_===null||U===null){c.current=null;return}const{clientX:W,clientY:k}=L.getPointerPosition(),x=l.current,z=(W-U.left)/x,I=(k-U.top)/x,T=_.getViewportSize(),F=T.width,O=T.height;if(F<=0||O<=0){c.current=requestAnimationFrame(N);return}const g=y=>Math.min(Ui,Math.ceil(y/Ft*Ui));let p=0,C=0;if(s!=="x"){const y=_.getFrozenSize(),a=y.trailingVisibleHeight;I>O-a-Ft?L.anchorRow!==void 0&&y.trailingRows>0&&L.anchorRow>=t.count-y.trailingRows&&a>0&&I>=O-a||(p=g(I-(O-a-Ft))):I<y.height+Ft&&(L.anchorRow!==void 0&&L.anchorRow<y.rows&&y.height>0&&I<y.height||(p=-g(y.height+Ft-I)))}if(s!=="y"){const y=_.getFrozenSize(),a=y.trailingVisibleWidth;z>F-a-Ft?L.anchorCol!==void 0&&y.trailingCols>0&&L.anchorCol>=n.count-y.trailingCols&&a>0&&z>=F-a||(C=g(z-(F-a-Ft))):z<y.width+Ft&&(L.anchorCol!==void 0&&L.anchorCol<y.cols&&y.width>0&&z<y.width||(C=-g(y.width+Ft-z)))}const v=C!==0||p!==0?_.scrollBy({x:C!==0?C:void 0,y:p!==0?p:void 0}):_.getScrollPosition(),S=v.y,b=v.x;if(S>=0&&b>=0&&t.totalSize()>0&&n.totalSize()>0){const y=_.getFrozenSize(),a=ln({row:kr(t,I,{scroll:S,frozenSize:y.height,trailingSize:y.trailingHeight,extent:T.height}),col:Sr(n,z,{scroll:b,frozenSize:y.width,trailingSize:y.trailingWidth,extent:T.width})},t.count,n.count),f=h.current;(p!==0||C!==0||f===null||f.row!==a.row||f.col!==a.col)&&(h.current=a,o(L.buildRange(a)))}c.current=requestAnimationFrame(N)},[e,t,n,s,o]),H=i.useCallback(L=>{R(),u.current=L,m.current=r.current?.getBoundingClientRect()??null,c.current=requestAnimationFrame(N)},[R,N,r]);return i.useEffect(()=>{const L=()=>{document.visibilityState==="hidden"&&R()};return document.addEventListener("visibilitychange",L),()=>{document.removeEventListener("visibilitychange",L),R()}},[R]),i.useMemo(()=>({start:H,stop:R}),[H,R])},Xi=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(0),s=i.useRef(null),l=i.useRef({clientX:0,clientY:0}),c=i.useRef(null),u=i.useRef(null),h=i.useRef(0),m=i.useRef(null),R=i.useRef(!1),N=i.useRef(0),H=i.useCallback((T,F)=>{const{axis:O,mainAxis:g,handleRef:p,zoomRef:C}=t.current,v=s.current;if(v===null||g.totalSize()===0)return null;const S=C.current,b=p.current;if(b===null)return null;if(O==="col"){const E=b.getScrollPosition().x;if(E<0)return null;const d=b.getFrozenSize(),$=b.getViewportSize();return Math.min(Math.max(Sr(g,(T-v.left)/S,{scroll:E,frozenSize:d.width,trailingSize:d.trailingWidth,extent:$.width}),0),g.count-1)}const y=b.getScrollPosition().y;if(y<0)return null;const a=b.getFrozenSize(),f=b.getViewportSize();return Math.min(Math.max(kr(g,(F-v.top)/S,{scroll:y,frozenSize:a.height,trailingSize:a.trailingHeight,extent:f.height}),0),g.count-1)},[]),L=i.useCallback((T,F)=>{const{axis:O,crossCount:g}=t.current;return O==="col"?{press:{row:0,col:T},extend:{row:g-1,col:F}}:{press:{row:T,col:0},extend:{row:F,col:g-1}}},[]),_=i.useCallback((T,F)=>{const{axis:O,crossCount:g}=t.current;return T.ranges.some(p=>O==="col"?p.startRow===0&&p.endRow===g-1&&F>=p.startCol&&F<=p.endCol:p.startCol===0&&p.endCol===g-1&&F>=p.startRow&&F<=p.endRow)},[]),U=i.useRef(!1),W=i.useRef({clientX:0,clientY:0}),k=i.useCallback(()=>{U.current=!1;const{autoScroller:T,headerRef:F,onDragFrame:O}=t.current;n.current=!1,r.current=null,m.current=null,R.current=!1,N.current=0,c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),T.stop();const g=F.current;g!==null&&u.current!==null&&g.hasPointerCapture?.(u.current)&&g.releasePointerCapture(u.current),u.current=null,O(null),t.current.repaintOverlay()},[]),x=i.useCallback(()=>{if(!n.current)return;const T=r.current;T!==null&&t.current.setSelection(T),k()},[k]),{enabled:z,headerRef:I}=e;return i.useEffect(()=>{const T=I.current;if(!z||T===null)return;const F=b=>{const y=t.current;if(b.pointerType!=="mouse")return;if(b.button!==0){b.preventDefault();return}if(R.current=!1,y.pointing?.getPointing()){s.current=T.getBoundingClientRect();const d=H(b.clientX,b.clientY);if(d===null)return;b.preventDefault(),y.focusSink(),y.pointing.insertReference(y.axis==="col"?{row:0,col:d}:{row:d,col:0},y.axis==="col"?"columns":"rows");return}if(y.isEditing()&&!y.requestCommit()){b.preventDefault(),y.focusSink();return}s.current=T.getBoundingClientRect();const a=H(b.clientX,b.clientY);if(a===null)return;b.preventDefault(),y.focusSink();const f=y.getSelection();r.current=f;const E=b.ctrlKey||b.metaKey;if(b.shiftKey){const d=y.axis==="col"?{row:0,col:f.anchor.col}:{row:f.anchor.row,col:0},{extend:$}=L(a,a),A={...f,anchor:d};y.setSelection(hn(A,$)),o.current=y.axis==="col"?d.col:d.row}else if(E&&_(f,a))R.current=!0,N.current=a,o.current=a;else{const{press:d,extend:$}=L(a,a),A=Cr(f,d,{extend:!1,append:E});y.setSelection(hn(A,$)),o.current=a}n.current=!0,y.repaintOverlay(),l.current={clientX:b.clientX,clientY:b.clientY},u.current=b.pointerId,h.current=b.buttons;try{T.setPointerCapture(b.pointerId)}catch{u.current=null}m.current=d=>{const $=t.current.axis==="col"?d.col:d.row,{press:A}=L(o.current,o.current),{extend:D}=L(o.current,$);return Re(A,D)},y.autoScroller.stop(),U.current=!1,W.current={clientX:b.clientX,clientY:b.clientY}},O=b=>u.current!==null?b.pointerId===u.current:b.pointerType==="mouse",g=b=>{if(n.current&&O(b)){if(R.current){const y=b.clientX!==l.current.clientX||b.clientY!==l.current.clientY;if(l.current={clientX:b.clientX,clientY:b.clientY},!y)return;const a=H(b.clientX,b.clientY);if(a===null||a===N.current)return;R.current=!1;const f=t.current,{press:E,extend:d}=L(N.current,N.current),$=Cr(f.getSelection(),E,{extend:!1,append:!0});f.setSelection(hn($,d));const A=m.current,D=Math.abs(b.clientX-W.current.clientX),q=Math.abs(b.clientY-W.current.clientY);A!==null&&Math.max(D,q)>=io&&(U.current=!0,f.autoScroller.start({getPointerPosition:()=>l.current,buildRange:A,anchorCol:f.axis==="col"?o.current:void 0,anchorRow:f.axis==="row"?o.current:void 0}))}else if(l.current={clientX:b.clientX,clientY:b.clientY},!U.current&&m.current!==null){const y=Math.abs(b.clientX-W.current.clientX),a=Math.abs(b.clientY-W.current.clientY);Math.max(y,a)>=io&&(U.current=!0,t.current.autoScroller.start({getPointerPosition:()=>l.current,buildRange:m.current,anchorCol:t.current.axis==="col"?o.current:void 0,anchorRow:t.current.axis==="row"?o.current:void 0}))}c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null;const y=m.current;if(!n.current||y===null)return;const a=H(l.current.clientX,l.current.clientY);a!==null&&t.current.onDragFrame(y(t.current.axis==="col"?{row:0,col:a}:{row:a,col:0}))}))}},p=b=>{g(b),n.current&&O(b)&&(h.current&1)!==0&&(b.buttons&1)===0&&v(b)},C=b=>{b.button!==0||!(n.current&&O(b))||v(b)},v=b=>{const y=t.current;if(R.current){const{press:f,extend:E}=L(N.current,N.current);y.setSelection(Ya(y.getSelection(),Re(f,E),f)),k();return}const a=H(b.clientX,b.clientY);if(a!==null){const{extend:f}=L(o.current,a);y.setSelection(hn(y.getSelection(),f))}k()},S=b=>{!n.current||u.current===null||b.pointerId!==u.current||x()};return T.addEventListener("pointerdown",F),T.addEventListener("pointermove",p),T.addEventListener("pointerup",C),T.addEventListener("lostpointercapture",S),()=>{T.removeEventListener("pointerdown",F),T.removeEventListener("pointermove",p),T.removeEventListener("pointerup",C),T.removeEventListener("lostpointercapture",S),k()}},[z,I,H,L,k,x]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:x,cancelDrag:k}),[x,k])},aw=({handleRef:e,rowAxis:t,colAxis:n})=>r=>{const o=e.current;if(o===null)return;const{x:s,y:l}=o.getScrollPosition(),{width:c,height:u}=o.getViewportSize();if(l<0||s<0)return;const h=o.getFrozenSize();if(u>0&&r.row>=h.rows&&r.row<t.count-h.trailingRows){const m=t.offsetOf(r.row),R=m+t.sizeOf(r.row);m<h.height+l?o.scrollBy({y:m-(h.height+l)}):R>l+u-h.trailingVisibleHeight&&o.scrollBy({y:R-(l+u-h.trailingVisibleHeight)})}if(c>0){if(r.col<h.cols||r.col>=n.count-h.trailingCols)return;const m=n.offsetOf(r.col),R=m+n.sizeOf(r.col);m<h.width+s?o.scrollBy({x:m-(h.width+s)}):R>s+c-h.trailingVisibleWidth&&o.scrollBy({x:R-(s+c-h.trailingVisibleWidth)})}},uw=50,dw=100,Xa=(e,t)=>e.isComposing||e.keyCode===229?!0:(e.key==="Enter"||e.key==="Escape")&&t!==null?e.timeStamp-t<uw:!1,ir={selectAll:Qt("Ctrl+A"),undo:Qt("Ctrl+Z"),redo:Qt("Ctrl+Y"),redoShiftZ:Qt("Ctrl+Shift+Z"),pasteValues:Qt("Ctrl+Shift+V")},fw=new Set(["Shift","Control","Alt","Meta","AltGraph"]),pw={ArrowRight:"right",ArrowLeft:"left",ArrowDown:"down",ArrowUp:"up"},hw=e=>!e.shiftKey||e.altKey||!(e.ctrlKey||e.metaKey)?!1:e.key==="PageUp"||e.key==="PageDown",mw=e=>{const t=i.useRef(null),n=i.useRef(null),r=i.useRef(!1),o=i.useRef(!1),s=i.useRef(e);s.current=e;const{enabled:l,sinkRef:c,rootRef:u,handleRef:h}=e;i.useEffect(()=>{const m=c.current,R=u.current;if(!l||m===null||R===null)return;const N=()=>{o.current&&(o.current=!1,s.current.onPointFrame?.(null))},H=(a,f,E)=>nn(a,f,E)??f,L=(a,f)=>{const E=s.current;return f==="left"||f==="right"?{row:a.row,col:H(E.colAxis,a.col,f==="right"?1:-1)}:{row:H(E.rowAxis,a.row,f==="down"?1:-1),col:a.col}},_=a=>a.indexAt(0),U=a=>a.indexAt(a.totalSize()-1),W=(a,f,E,d)=>{if(a.sizeOf(f)>0)return f;const $=nn(a,f,E);if($!==null)return $;const A=nn(a,f,E===1?-1:1);return A!==null?A:d},k=()=>{const a=s.current.getSelection(),f=a.ranges[a.ranges.length-1];return{row:a.anchor.row===f.startRow?f.endRow:f.startRow,col:a.anchor.col===f.startCol?f.endCol:f.startCol}},x=a=>L(k(),a),z=(a,f)=>{const E=s.current,d=f==="left"||f==="right",$=f==="right"||f==="down"?1:-1;let A;return E.findDataEdge!==void 0?(A=E.findDataEdge({row:a.row,col:a.col},f),I(A,a,f)):A={row:f==="down"?E.rowAxis.count-1:f==="up"?0:a.row,col:f==="right"?E.colAxis.count-1:f==="left"?0:a.col},d?{row:A.row,col:W(E.colAxis,A.col,$,a.col)}:{row:W(E.rowAxis,A.row,$,a.row),col:A.col}},I=(a,f,E)=>{const d=s.current;if(!(Number.isInteger(a.row)&&Number.isInteger(a.col)&&a.row>=0&&a.row<d.rowAxis.count&&a.col>=0&&a.col<d.colAxis.count))throw new RangeError(`[spreadsheet] findDataEdge returned an out-of-grid coordinate {row: ${a.row}, col: ${a.col}} for a ${d.rowAxis.count} x ${d.colAxis.count} grid`);const $=E==="left"||E==="right";if($?a.row!==f.row:a.col!==f.col)throw new RangeError(`[spreadsheet] findDataEdge must stay on the origin ${$?"row":"column"} (received {row: ${a.row}, col: ${a.col}} from {row: ${f.row}, col: ${f.col}})`)},T=(a,f,E)=>{if(!(Number.isInteger(a)&&a>=0&&a<f))throw new RangeError(`[spreadsheet] findDataEdge returned an out-of-axis ${E} component ${a} (count ${f})`)},F=a=>{const f=s.current,E=f.getSelection();if(Ua(E,a)===E){f.moveActive({mode:"reset",cell:L(E.active,a)});return}f.moveActive({mode:"cycle",direction:a})},O=()=>{const a=c.current;if(a===null)return;const f=a.selectionStart??a.value.length,E=a.selectionEnd??f;a.value=`${a.value.slice(0,f)}
14
- ${a.value.slice(E)}`,a.setSelectionRange(f+1,f+1)},g=(a,f)=>{const E=s.current,d=E.pageExtent();if(d<=0)return H(E.rowAxis,a,f==="down"?1:-1);const $=E.rowAxis.indexAt(E.rowAxis.offsetOf(a)+(f==="down"?d:-d));return $===a?H(E.rowAxis,a,f==="down"?1:-1):$},p=a=>{const f=s.current;if(r.current=!1,Xa(a,t.current))return;const E=a.ctrlKey||a.metaKey,d=a.altKey,$=pw[a.key];if(o.current&&!fw.has(a.key)&&!f.isDragging()&&N(),f.isEditing()){const D=f.getEditingMode();if(f.isDragging()){a.preventDefault(),a.key==="Escape"&&!E&&!a.shiftKey&&!d&&f.abortDrag();return}const q=f.pointing;if(q!==void 0){if($!==void 0&&!d){const K=q.getReferenceCursor();if(K!==null){a.preventDefault();const G=ln(K.cursor,f.rowAxis.count,f.colAxis.count),J=ln(K.origin,f.rowAxis.count,f.colAxis.count),te=E?z(G,$):L(G,$);if(f.ensureCellVisible(te),q.insertReference(a.shiftKey?Re(J,te):te,K.axis),f.onPointFrame!==void 0){const le=a.shiftKey?Re(J,te):Re(te,te);f.onPointFrame(K.axis==="columns"?Re({row:0,col:le.startCol},{row:f.rowAxis.count-1,col:le.endCol}):K.axis==="rows"?Re({row:le.startRow,col:0},{row:le.endRow,col:f.colAxis.count-1}):le),o.current=!0}return}}if(a.key==="F2"&&!E&&!a.shiftKey&&!d&&q.togglePointingArm()){a.preventDefault();return}if(a.key==="F4"&&!E&&!a.shiftKey&&!d&&q.cycleAnchorAtCaret()){a.preventDefault();return}}const j=f.commands;if(j!==void 0){const K=ai(j.table,a);if(K!==null&&Ps.has(K)&&j.isAvailable(K)){a.preventDefault(),j.execute(K);return}}if($!==void 0&&!d){if(E&&a.shiftKey){a.preventDefault();return}if(E)return;if(D==="replace"){if(a.preventDefault(),!f.requestCommit())return;a.shiftKey?f.moveActive({mode:"extend",cell:x($)}):f.moveActive({mode:"reset",cell:L(f.getSelection().active,$)});return}return}if(a.key==="Enter"&&d&&!E&&!a.shiftKey){a.preventDefault(),O();return}if((a.key==="Enter"||a.key==="Tab")&&!E&&!d){if(a.preventDefault(),!f.requestCommit())return;const K=!a.shiftKey;F(a.key==="Tab"?K?"right":"left":K?"down":"up");return}if((a.key==="PageUp"||a.key==="PageDown")&&!a.shiftKey&&!E&&!d){if(a.preventDefault(),!f.requestCommit())return;const K=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:g(K.row,a.key==="PageDown"?"down":"up"),col:K.col}});return}if(a.key==="Escape"&&!E&&!a.shiftKey&&!d){a.preventDefault(),f.cancelEdit();return}return}if(a.defaultPrevented)return;if(f.isDragging()&&a.key!=="Escape"){a.preventDefault();return}const A=f.commands;if(A!==void 0){const D=ai(A.table,a);if(D!==null&&A.isAvailable(D)){a.preventDefault(),A.execute(D);return}}if($!==void 0&&!d){const D=$==="left"||$==="right",q=$==="right"||$==="down"?1:-1;if(E&&a.shiftKey){a.preventDefault();const j=f.getSelection(),K=k();let G;if(f.findDataEdge!==void 0){const J=D?{row:j.active.row,col:K.col}:{row:K.row,col:j.active.col},te=f.findDataEdge(J,$);G=D?te.col:te.row,T(G,D?f.colAxis.count:f.rowAxis.count,D?"col":"row"),G=W(D?f.colAxis:f.rowAxis,G,q,D?K.col:K.row)}else{const J=D?f.colAxis:f.rowAxis;G=q===1?U(J):_(J)}f.moveActive({mode:"extend",cell:D?{row:K.row,col:G}:{row:G,col:K.col}});return}if(E){a.preventDefault(),f.moveActive({mode:"reset",cell:z(f.getSelection().active,$)});return}if(a.shiftKey){a.preventDefault(),f.moveActive({mode:"extend",cell:x($)});return}a.preventDefault(),f.moveActive({mode:"reset",cell:L(f.getSelection().active,$)});return}if(hw(a)){a.preventDefault();return}if((a.key==="Tab"||a.key==="Enter")&&!E&&!d){a.preventDefault();const D=!a.shiftKey;F(a.key==="Tab"?D?"right":"left":D?"down":"up");return}if(a.key==="Home"&&!d){if(a.preventDefault(),a.shiftKey){const q=k();f.moveActive({mode:"extend",cell:{row:E?_(f.rowAxis):q.row,col:_(f.colAxis)}});return}const D=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:E?_(f.rowAxis):D.row,col:_(f.colAxis)}});return}if(a.key==="End"&&!d){if(a.preventDefault(),a.shiftKey){const q=k();f.moveActive({mode:"extend",cell:{row:E?U(f.rowAxis):q.row,col:U(f.colAxis)}});return}const D=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:E?U(f.rowAxis):D.row,col:U(f.colAxis)}});return}if((a.key==="PageUp"||a.key==="PageDown")&&!E&&!d){a.preventDefault();const D=a.key==="PageDown"?"down":"up";if(a.shiftKey){const j=k();f.moveActive({mode:"extend",cell:{row:g(j.row,D),col:j.col}});return}const q=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:g(q.row,D),col:q.col}});return}if(a.key==="F2"&&!E&&!a.shiftKey&&!d){a.preventDefault(),f.startEdit("edit");return}if((a.key==="Delete"||a.key==="Backspace")&&!E&&!a.shiftKey&&!d){a.preventDefault();const D=f.getSelection(),q=At(D.ranges);if(q>f.maxOperationCells){f.onOperationRejected?.("delete",q,"limit");return}if(f.adapter!==void 0&&qn(f.adapter,D.ranges)){f.rejectReadOnly({kind:"operation",op:"delete",cellCount:q});return}const j=[],K=f.adapter!==void 0&&eo(f.adapter).hyperlink;Jt(D.ranges,G=>{j.push(K?{row:G.row,col:G.col,text:"",hyperlink:null}:{row:G.row,col:G.col,text:""})}),f.commitEdits(j,{source:"delete"});return}if(a.key==="Escape"){if(f.isDragging()){a.preventDefault(),f.abortDrag();return}if(E||a.shiftKey||d||(a.preventDefault(),f.hideNoteTip?.())||f.closeRejectedMessage?.())return;if(f.getClip()!==null){f.discardClip();return}f.handOffFocusToRoot();return}if(or(ir.selectAll,a)){a.preventDefault();const D=f.getSelection(),q=Re({row:0,col:0},{row:f.rowAxis.count-1,col:f.colAxis.count-1});f.setSelection({ranges:[q],anchor:D.anchor,active:D.active});return}if(or(ir.undo,a)){a.preventDefault(),f.onUndoRequest?.();return}if(or(ir.redo,a)||or(ir.redoShiftZ,a)){a.preventDefault(),f.onRedoRequest?.();return}if(a.key==="F10"&&a.shiftKey&&!E&&!d||a.key==="ContextMenu"&&!E&&!a.shiftKey&&!d){a.preventDefault();const D=f.getSelection().active;f.ensureCellVisible(D);const q=h.current,j=q===null?{x:0,y:0}:q.getScrollPosition(),K=Math.max(0,j.y),G=Math.max(0,j.x),J=q===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:q.getFrozenSize(),te=q===null?{width:0,height:0}:q.getViewportSize(),le=f.zoomRef.current;f.onCellContextMenu?.(D,{kind:"keyboard",cellRect:{top:wn(f.rowAxis,D.row,{scroll:K,frozenCount:J.rows,trailingCount:J.trailingRows,extent:te.height})*le,left:gn(f.colAxis,D.col,{scroll:G,frozenCount:J.cols,trailingCount:J.trailingCols,extent:te.width})*le,width:f.colAxis.sizeOf(D.col)*le,height:f.rowAxis.sizeOf(D.row)*le}});return}if(a.key===" "&&!d&&E!==a.shiftKey){a.preventDefault();const D=f.getSelection(),q=D.ranges.map(j=>E?Re({row:0,col:j.startCol},{row:f.rowAxis.count-1,col:j.endCol}):Re({row:j.startRow,col:0},{row:j.endRow,col:f.colAxis.count-1}));f.setSelection({ranges:q,anchor:D.anchor,active:D.active});return}if(f.pendingPasteOptionsRef!==void 0&&or(ir.pasteValues,a)){f.pendingPasteOptionsRef.current={mode:"values"};return}if(a.key.length===1&&!a.metaKey&&a.ctrlKey===a.altKey){if(a.ctrlKey&&a.altKey){r.current=!0;return}f.startEdit("replace");return}},C=()=>{const a=s.current;a.isEditing()||a.startEdit("replace")},v=a=>{t.current=a.timeStamp,n.current!==null&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current=null,n.current=null},dw)},S=()=>{const a=s.current;if(N(),!a.isEditing()){if(r.current){r.current=!1;const f=m.value;if(f!==""&&(a.startEdit("replace"),a.isEditing())){m.value=f,m.setSelectionRange(f.length,f.length);return}}a.rearmSink()}},b=()=>{r.current=!1;const a=s.current.pendingPasteOptionsRef;a!==void 0&&(a.current=null)},y=()=>{r.current=!1;const a=s.current.pendingPasteOptionsRef;a!==void 0&&(a.current=null),N()};return m.addEventListener("keydown",p),m.addEventListener("keyup",b),m.addEventListener("blur",y),m.addEventListener("compositionstart",C),m.addEventListener("compositionend",v),m.addEventListener("input",S),()=>{m.removeEventListener("keydown",p),m.removeEventListener("keyup",b),m.removeEventListener("blur",y),m.removeEventListener("compositionstart",C),m.removeEventListener("compositionend",v),m.removeEventListener("input",S),n.current!==null&&window.clearTimeout(n.current),N()}},[l,c,u,h])},gw=()=>{let e={vy:0,rowStart:0,rowEnd:0,colStart:0,colEnd:0,colVersion:0,rowGeomVersion:0,editVersion:0};const t=new Set;let n=null;const r=()=>{n=null;for(const l of[...t])l()},o=()=>{t.size!==0&&n===null&&(n=requestAnimationFrame(r))},s=l=>{e={...e,...l},o()};return{get:()=>e,setVy:l=>{l!==e.vy&&s({vy:l})},setRowRange:(l,c)=>{(l!==e.rowStart||c!==e.rowEnd)&&s({rowStart:l,rowEnd:c})},setColRange:(l,c)=>{(l!==e.colStart||c!==e.colEnd)&&s({colStart:l,colEnd:c})},bumpColVersion:()=>s({colVersion:e.colVersion+1}),bumpRowGeometry:()=>s({rowGeomVersion:e.rowGeomVersion+1}),bumpEdit:()=>s({editVersion:e.editVersion+1}),subscribeCoalesced:l=>(t.add(l),()=>{t.delete(l),t.size===0&&n!==null&&(cancelAnimationFrame(n),n=null)})}},ww=4,Cw=Object.freeze({cols:0,width:0,rows:0,height:0,trailingCols:0,trailingRows:0,trailingWidth:0,trailingHeight:0,trailingVisibleWidth:0,trailingVisibleHeight:0}),bw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef(null),l=i.useRef({clientX:0,clientY:0}),c=i.useRef({clientX:0,clientY:0}),u=i.useRef(!1),h=i.useRef({dx:0,dy:0}),m=i.useRef(null),R=i.useRef(0),N=i.useRef(null),H=i.useRef(null),L=i.useRef(!1),_=i.useCallback(T=>m.current!==null?T.pointerId===m.current:T.pointerType==="mouse",[]),U=i.useCallback((T,F)=>{const{handleRef:O,rowAxis:g,colAxis:p}=t.current,C=O.current,v=s.current;if(C===null||v===null)return null;const{x:S,y:b}=C.getScrollPosition();if(b<0||S<0||g.totalSize()===0||p.totalSize()===0)return null;const y=t.current.zoomRef.current,a=C.getFrozenSize(),f=C.getViewportSize();return ln({row:kr(g,(F-v.top)/y,{scroll:b,frozenSize:a.height,trailingSize:a.trailingHeight,extent:f.height}),col:Sr(p,(T-v.left)/y,{scroll:S,frozenSize:a.width,trailingSize:a.trailingWidth,extent:f.width})},g.count,p.count)},[]),W=i.useCallback(T=>{const F=r.current;if(F===null)return Re(T,T);const O=Re({row:Math.min(F.startRow,T.row),col:Math.min(F.startCol,T.col)},{row:Math.max(F.endRow,T.row),col:Math.max(F.endCol,T.col)}),g=O.startRow!==F.startRow||O.endRow!==F.endRow||O.startCol!==F.startCol||O.endCol!==F.endCol;return o.current=g?O:null,g?O:F},[]),k=i.useCallback(()=>{const T=t.current;n.current=!1,r.current=null,o.current=null,s.current=null,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),T.xAutoScroller.stop(),T.yAutoScroller.stop(),L.current=!1,u.current=!1,h.current={dx:0,dy:0},T.writeFillPreview(null);const F=H.current;F!==null&&(window.removeEventListener("pointermove",F.move),window.removeEventListener("pointerup",F.up),H.current=null);const O=t.current.handleNodeRef.current;O!==null&&m.current!==null&&O.hasPointerCapture?.(m.current)&&O.releasePointerCapture(m.current),m.current=null,T.repaintOverlay()},[]),x=i.useCallback(()=>{const T=t.current,F=r.current,O=o.current;if(k(),F===null||O===null)return;const g=yh(F,O);if(g>T.maxOperationCells){T.onOperationRejected?.("fill",g,"limit");return}if(qn(T.adapter,Rh(F,O))){const v=(O.endRow-O.startRow+1)*(O.endCol-O.startCol+1),S=(F.endRow-F.startRow+1)*(F.endCol-F.startCol+1);T.rejectReadOnly({kind:"operation",op:"fill",cellCount:v-S});return}const p=vh((v,S)=>sa(T.adapter,v,S),F,O,la);if(T.commitEdits(p,{source:"fill"})===null)return;const C=T.getSelection();T.setSelection({ranges:[O],anchor:C.anchor,active:C.active})},[k]),{enabled:z,handleNodeRef:I}=e;return i.useEffect(()=>{const T=I.current;if(!z||T===null)return;const F=v=>{O(v),n.current&&_(v)&&(R.current&1)!==0&&(v.buttons&1)===0&&x()},O=v=>{if(!(n.current&&_(v)))return;l.current={clientX:v.clientX,clientY:v.clientY};const S=Math.abs(v.clientX-c.current.clientX),b=Math.abs(v.clientY-c.current.clientY);if(!u.current&&Math.max(S,b)>=ww&&(u.current=!0),!!u.current){if(!L.current){const y=t.current,a={getPointerPosition:()=>({clientX:l.current.clientX-h.current.dx,clientY:l.current.clientY-h.current.dy}),buildRange:W,anchorCol:r.current?.endCol,anchorRow:r.current?.endRow};y.xAutoScroller.start(a),y.yAutoScroller.start(a),L.current=!0}N.current===null&&(N.current=requestAnimationFrame(()=>{if(N.current=null,!(n.current&&u.current))return;const y=U(l.current.clientX-h.current.dx,l.current.clientY-h.current.dy);y!==null&&t.current.writeFillPreview(W(y))}))}},g=v=>{v.button!==0||!(n.current&&_(v))||x()},p=v=>{const S=t.current;if(v.pointerType!=="mouse")return;if(v.button!==0){v.preventDefault();return}v.preventDefault(),v.stopPropagation(),S.focusSink();const b=S.getSelection(),y=b.ranges[b.ranges.length-1];r.current=y,o.current=null,u.current=!1,S.xAutoScroller.stop(),S.yAutoScroller.stop(),L.current=!1,c.current={clientX:v.clientX,clientY:v.clientY},l.current=c.current,R.current=v.buttons,n.current=!0,S.repaintOverlay(),s.current=S.bodyRef.current?.getBoundingClientRect()??null;const a=s.current,f=S.handleRef.current?.getScrollPosition()??{x:-1,y:-1},E=f.y;if(a!==null&&E>=0&&f.x>=0){const A=f.x,D=S.zoomRef.current,q=S.handleRef.current?.getFrozenSize()??Cw,j=S.handleRef.current?.getViewportSize()??{width:0,height:0},K={scroll:A,frozenCount:q.cols,trailingCount:q.trailingCols,extent:j.width},G={scroll:E,frozenCount:q.rows,trailingCount:q.trailingRows,extent:j.height},J=gn(S.colAxis,y.endCol,K)+S.colAxis.sizeOf(y.endCol),te=wn(S.rowAxis,y.endRow,G)+S.rowAxis.sizeOf(y.endRow),le=J-1,me=y.endCol>=q.cols&&q.width>0?Math.max(le,q.width):le,xe=!(y.endCol>=S.colAxis.count-q.trailingCols)&&q.trailingWidth>0?Math.min(me,j.width-q.trailingVisibleWidth-1):me,De=te-1,Pe=y.endRow>=q.rows&&q.height>0?Math.max(De,q.height):De,Ne=!(y.endRow>=S.rowAxis.count-q.trailingRows)&&q.trailingHeight>0?Math.min(Pe,j.height-q.trailingVisibleHeight-1):Pe;h.current={dx:v.clientX-(a.left+xe*D),dy:v.clientY-(a.top+Ne*D)}}else h.current={dx:0,dy:0};m.current=v.pointerId;try{T.setPointerCapture(v.pointerId)}catch{m.current=null}const d=F,$=g;H.current={move:d,up:$},window.addEventListener("pointermove",d),window.addEventListener("pointerup",$),S.writeFillPreview(r.current)},C=v=>{!n.current||m.current===null||v.pointerId!==m.current||k()};return T.addEventListener("pointerdown",p),T.addEventListener("lostpointercapture",C),()=>{T.removeEventListener("pointerdown",p),T.removeEventListener("lostpointercapture",C),k()}},[z,I,_,U,W,k,x]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:()=>{n.current&&k()},cancelDrag:k}),[k])},yw=320,to=8,Rw=64,vw=150,Ga=e=>Math.max(0,Math.min(yw,e.width-Te.SPREADSHEET_SCROLLBAR_SIZE_PX-to)),Sw=(e,t,n)=>{const r=n.width-Te.SPREADSHEET_SCROLLBAR_SIZE_PX,o=n.height-Te.SPREADSHEET_SCROLLBAR_SIZE_PX,s=Ga(n),l=Math.max(0,Math.min(t,o-to)),c=e.left+e.width,u=e.top+e.height,h=_=>_>=0&&_+s<=r,m=[e.left,c-s],R=[{left:e.left,top:u},{left:c-s,top:u},{left:e.left,top:e.top-l},{left:c-s,top:e.top-l}];for(const _ of R)if(h(_.left)&&_.top>=0&&_.top+l<=o)return{left:_.left,top:_.top,width:s,height:l};const N=o-u,H=e.top,L=Math.min(l,Math.max(N,H));if(L>=Rw){const _=N>=H?u:e.top-L;for(const U of m)if(h(U))return{left:U,top:_,width:s,height:L}}return{left:to,top:to,width:s,height:l}},kw=(e,t,n,r)=>t===null||e!==null&&It(e,t)||n?!1:r(t),Ew=(e,t)=>{switch(e.kind){case"note":return Y.jsx($a,{ctx:e,labels:t});case"note-tip":return Y.jsx(La,{ctx:e,labels:t});case"comment":return Y.jsx(Aa,{ctx:e,labels:t});case"link":return Y.jsx(Oa,{ctx:e,labels:t});case"list":return Y.jsx(xa,{ctx:e,labels:t});default:return Y.jsx(Ta,{ctx:e,labels:t})}},ns=e=>e===null?null:`${e.kind}:${e.cell.row}:${e.cell.col}`,Aw=({controller:e,renderPopover:t,labels:n,interactiveAnchorRef:r,tipAnchorRef:o})=>{const{context:s,tipContext:l}=e,c=i.useRef(null),u=i.useRef(null),h=i.useRef(l);h.current=l;const m=i.useRef(e);m.current=e;const R=ns(s),N=ns(l),H=i.useRef(null),L=(x,z)=>{const I=m.current.getLayerSize();x.style.width=`${Ga(I)}px`,x.style.maxHeight="";const T=Sw(z,x.offsetHeight,I);x.style.left=`${T.left-z.left}px`,x.style.top=`${T.top-z.top}px`,x.style.maxHeight=`${T.height}px`};i.useLayoutEffect(()=>{const x=c.current;if(x===null||s===null){H.current=null;return}if(L(x,s.anchorRect),s.kind==="message")return;const z=ns(s);if(H.current===z)return;H.current=z;const I=x.querySelector("[data-aqsp-popover-autofocus]");I!==null?I.focus({preventScroll:!0}):x.focus({preventScroll:!0})},[s]),i.useLayoutEffect(()=>{const x=u.current,z=h.current;x===null||z===null||L(x,z.anchorRect)},[N]);const _=x=>t===void 0?Ew(x,n):t(x),U=x=>{e.isCompositionKey(x.nativeEvent)&&x.stopPropagation()},W=x=>{x.key==="Escape"&&!x.defaultPrevented&&(x.preventDefault(),e.close())},k=x=>{e.registerCompositionEnd(x.timeStamp)};return Y.jsxs("div",{className:"aqsp-popover-layer","data-aqsp-popover-layer":"",onKeyDownCapture:U,onKeyDown:W,onCompositionEnd:k,children:[Y.jsx("div",{ref:r,className:"aqsp-popover-anchor","data-aqsp-popover-anchor":"interactive","data-aqsp-popover-open":s===null?void 0:"",inert:s===null,children:s===null?null:Y.jsx("div",{ref:c,className:"aqsp-popover","data-aqsp-popover-frame":s.kind,tabIndex:-1,children:_(s)},R)}),Y.jsx("div",{ref:o,className:"aqsp-popover-anchor","data-aqsp-popover-anchor":"tip","data-aqsp-popover-open":l===null?void 0:"",inert:l===null,onPointerEnter:e.onTipPointerEnter,onPointerLeave:e.onTipPointerLeave,children:l===null?null:Y.jsx("div",{ref:u,id:e.tipId,className:"aqsp-popover","data-aqsp-popover-frame":"note-tip",children:_(l)})})]})},Ow=["note","note-tip","comment","link","list","message"],xw=(e,t)=>{switch(t){case"note":case"note-tip":return e.getCellNote!==void 0;case"comment":return e.getCellComments!==void 0;case"link":return e.getCellHyperlink!==void 0;default:return e.getCellValidation!==void 0}},cr=(e,t,n)=>(t===void 0?!0:t[n]!==!1)&&xw(e,n),Tw=e=>{const t=i.useRef(e);t.current=e;const[n,r]=i.useState(null),[o,s]=i.useState(null),l=i.useRef(null),c=i.useRef(null),u=i.useRef(null),h=i.useRef(!1),m=i.useRef(null),R=i.useRef(null),N=i.useRef(null),H=i.useRef(null),L=i.useId(),_=i.useCallback(A=>{const D=t.current,q=D.handleRef.current,j=q===null?{x:0,y:0}:q.getScrollPosition(),K=q===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:q.getFrozenSize(),G=q===null?{width:0,height:0}:q.getViewportSize();return{top:wn(D.rowAxis,A.row,{scroll:Math.max(0,j.y),frozenCount:K.rows,trailingCount:K.trailingRows,extent:G.height}),left:gn(D.colAxis,A.col,{scroll:Math.max(0,j.x),frozenCount:K.cols,trailingCount:K.trailingCols,extent:G.width}),width:D.colAxis.sizeOf(A.col),height:D.rowAxis.sizeOf(A.row)}},[]),U=i.useCallback(A=>{const D=t.current;D.anchors.current={...D.anchors.current,...A},D.repaintOverlay()},[]),W=i.useCallback(()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)},[]),k=i.useCallback(()=>{const A=t.current.sinkRef.current;if(A===null)return;const D=c.current;D!==null&&It(D,t.current.getActive())?A.setAttribute("aria-describedby",L):A.getAttribute("aria-describedby")===L&&A.removeAttribute("aria-describedby")},[L]),x=i.useCallback(()=>(W(),h.current=!1,c.current===null?!1:(c.current=null,s(null),U({tip:null}),k(),!0)),[W,U,k]),z=i.useCallback(()=>{W(),m.current=window.setTimeout(()=>{m.current=null,x()},vw)},[W,x]),I=i.useCallback(A=>{const D=t.current;W();const q=D.adapter.getCellNote===void 0?void 0:D.adapter.getCellNote(A.row,A.col);q===void 0||q===""||(c.current=A,s({kind:"note-tip",cell:A,anchorRect:_(A),current:q,close:x}),U({tip:A}),k())},[_,W,x,U,k]),T=i.useCallback(A=>{const D=t.current;if(A===null&&h.current)return;const q=u.current;u.current=A;const j=c.current;if(j!==null&&A!==null&&It(j,A)){W();return}const K=G=>{const J=D.adapter.getCellNote===void 0?void 0:D.adapter.getCellNote(G.row,G.col);return J!==void 0&&J!==""};if(kw(q,A,D.isDraggingAny(),K)){A!==null&&I(A);return}j!==null&&z()},[I,W,z]),F=i.useCallback((A,D)=>{const q=t.current,j=q.bodyRef.current,K=q.handleRef.current;if(j===null||K===null)return null;const G=j.getBoundingClientRect(),J=q.zoomRef.current,te=K.getScrollPosition(),le=K.getFrozenSize(),me=K.getViewportSize();return ln({row:kr(q.rowAxis,(D-G.top)/J,{scroll:Math.max(0,te.y),frozenSize:le.height,trailingSize:le.trailingHeight,extent:me.height}),col:Sr(q.colAxis,(A-G.left)/J,{scroll:Math.max(0,te.x),frozenSize:le.width,trailingSize:le.trailingWidth,extent:me.width})},q.rowAxis.count,q.colAxis.count)},[]),O=i.useCallback(A=>{N.current=A,R.current===null&&(R.current=requestAnimationFrame(()=>{R.current=null;const D=N.current;T(D===null?null:"cell"in D?D.cell:F(D.clientX,D.clientY))}))},[T,F]),g=i.useCallback(A=>O({cell:A}),[O]),p=i.useCallback(()=>x(),[x]),C=i.useCallback(A=>{if(l.current===null)return;const D=t.current;l.current=null,r(null),U({interactive:null}),(A===void 0||A.restoreFocus)&&D.focusSink({preventScroll:!0}),D.isEditing()||D.rearmSink()},[U]),v=i.useCallback(A=>{l.current=A.kind,r(A),U({interactive:A.cell})},[U]),S=i.useCallback(A=>{const D=t.current;return na(D.adapter)?{cellReadOnly:Ye(D.adapter,A.row,A.col)}:{}},[]),b=i.useCallback((A,D)=>{const q=t.current;if(Ye(q.adapter,A.cell.row,A.cell.col)){q.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),v({...A,...S(A.cell)});return}if(q.commitEdits(D,{source:"annotate"})===null){v({...A,rejected:!0});return}C()},[v,C,S]),y=i.useCallback((A,D)=>{const q=t.current;if(!cr(q.adapter,q.popovers,A))throw new RangeError(`[spreadsheet] openPopover("${A}") is unavailable: the kind is disabled by the popovers prop or its adapter capability is undeclared`);const j=q.getActive();if(A==="list"&&Ye(q.adapter,j.row,j.col)){q.rejectReadOnly({kind:"edit",cell:j,editSession:"none"});return}if(A==="note-tip"){I(j);return}if(A==="message"){if(l.current!==null&&l.current!=="message")return;const te=D!==void 0&&D.message!==void 0?D.message:void 0,le=q.adapter.getCellValidation===void 0?void 0:q.adapter.getCellValidation(j.row,j.col),me=te!==void 0?te:le===void 0?void 0:le.inputMessage;if(me===void 0)return;const Ee=D!==void 0&&D.rejected===!0;v({kind:"message",cell:j,anchorRect:_(j),current:{title:ze(q.labels,"messageTitle"),message:me,rejected:Ee},close:C});return}if(q.isEditing()&&!q.requestCommit())return;if(A==="list"){const te=q.adapter.getCellValidation===void 0?void 0:q.adapter.getCellValidation(j.row,j.col);if(te===void 0||te.type!=="list")return;const le=D!==void 0&&D.typed!==void 0?D.typed:"";x(),q.focusSink({preventScroll:!0}),v({kind:"list",cell:j,anchorRect:_(j),current:te.values,typed:le,commit:me=>{if(Ye(t.current.adapter,j.row,j.col)){t.current.rejectReadOnly({kind:"edit",cell:j,editSession:"none"}),C();return}t.current.commitEdits([{row:j.row,col:j.col,text:me}],{source:"edit",editSession:"discarded"}),C()},close:C});return}if(x(),q.focusSink({preventScroll:!0}),A==="note"){const te=q.adapter.getCellNote===void 0?void 0:q.adapter.getCellNote(j.row,j.col),le={kind:"note",cell:j,anchorRect:_(j),current:te,commit:me=>{b(le,[{row:j.row,col:j.col,note:me}])},close:C,rejected:!1,...S(j)};v(le);return}if(A==="comment"){const te=q.adapter.getCellComments===void 0?void 0:q.adapter.getCellComments(j.row,j.col),le={kind:"comment",cell:j,anchorRect:_(j),current:te===void 0?[]:te,commit:me=>{b(le,[{row:j.row,col:j.col,comments:me}])},close:C,rejected:!1,...S(j)};v(le);return}const K=q.adapter.getCellHyperlink===void 0?void 0:Un(q.adapter.getCellHyperlink(j.row,j.col)),G=q.adapter.getCellText(j.row,j.col),J={kind:"link",cell:j,anchorRect:_(j),current:{text:G,url:K},commit:te=>{const le=te.url===null?null:sn(te.url);if(le===null&&te.url!==null)throw new RangeError(`[spreadsheet] link commit received an unnormalisable url ${JSON.stringify(te.url)}`);const me=te.text===G?{row:j.row,col:j.col,hyperlink:le}:{row:j.row,col:j.col,text:te.text,hyperlink:le};b(J,[me])},close:C,canOpen:q.onHyperlinkOpen!==void 0,open:()=>{const te=t.current.onHyperlinkOpen;te!==void 0&&K!==void 0&&te(K,j)},rejected:!1,...S(j)};v(J)},[_,C,b,x,v,I,S]),{enabled:a,bodyRef:f}=e;i.useEffect(()=>{const A=f.current;if(!a||A===null)return;const D=j=>{const K=t.current;cr(K.adapter,K.popovers,"note-tip")&&O({clientX:j.clientX,clientY:j.clientY})},q=()=>{cr(t.current.adapter,t.current.popovers,"note-tip")&&O({cell:null})};return A.addEventListener("pointermove",D),A.addEventListener("pointerleave",q),()=>{A.removeEventListener("pointermove",D),A.removeEventListener("pointerleave",q)}},[a,f,O]),i.useEffect(()=>()=>{R.current!==null&&cancelAnimationFrame(R.current),m.current!==null&&window.clearTimeout(m.current)},[]);const{adapter:E,popovers:d}=e,$=i.useMemo(()=>Ow.some(A=>cr(E,d,A)),[E,d]);return i.useMemo(()=>({layerEnabled:$,isKindEnabled:A=>cr(t.current.adapter,t.current.popovers,A),open:y,close:C,isOpen:()=>l.current,onCellHover:g,hideTip:p,onTipPointerEnter:()=>{h.current=!0,W()},onTipPointerLeave:()=>{h.current=!1,c.current!==null&&z()},syncTipAriaDescribedBy:k,context:n,tipContext:o,registerCompositionEnd:A=>{H.current=A},isCompositionKey:A=>Xa(A,H.current),getLayerSize:()=>{const A=t.current.handleRef.current;return A===null?{width:0,height:0}:A.getViewportSize()},tipId:L}),[$,y,C,g,p,W,z,k,n,o,L])},$w=(e,t,n)=>{let r=null,o=0;if(typeof document.caretPositionFromPoint=="function"){const l=document.caretPositionFromPoint(e,t);if(l===null)return;r=l.offsetNode,o=l.offset}else if(typeof document.caretRangeFromPoint=="function"){const l=document.caretRangeFromPoint(e,t);if(l===null)return;r=l.startContainer,o=l.startOffset}else return;if(r===null||r.nodeType!==Node.TEXT_NODE)return;const s=r.parentElement?.closest("[data-aqsp-cell]")??null;if(!(s===null||Number(s.getAttribute("data-row"))!==n.row||Number(s.getAttribute("data-col"))!==n.col))return o},Za=(e,t,n,r,o,s,l)=>{if(e===null||t===null)return null;const{x:c,y:u}=e.getScrollPosition();if(u<0||c<0||n.totalSize()===0||r.totalSize()===0)return null;const h=e.getFrozenSize(),m=e.getViewportSize();return ln({row:kr(n,(l-t.top)/o,{scroll:u,frozenSize:h.height,trailingSize:h.trailingHeight,extent:m.height}),col:Sr(r,(s-t.left)/o,{scroll:c,frozenSize:h.width,trailingSize:h.trailingWidth,extent:m.width})},n.count,r.count)},Lw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef({clientX:0,clientY:0}),l=i.useRef(null),c=i.useRef(null),u=i.useRef(0),h=i.useRef(null),m=i.useRef(!1),R=i.useRef(null),N=i.useRef(""),H=i.useRef(!1),L=i.useRef(!1),_=i.useCallback((O,g)=>{const{handleRef:p,rowAxis:C,colAxis:v,zoomRef:S}=t.current;return Za(p.current,o.current,C,v,S.current,O,g)},[]),U=i.useRef(!1),W=i.useRef(null),k=i.useRef(null),x=i.useRef({clientX:0,clientY:0}),z=i.useCallback(()=>{const{autoScroller:O,bodyRef:g,onDragFrame:p}=t.current;n.current=!1,r.current=null,h.current=null,U.current=!1,W.current=null,k.current=null,m.current=!1,R.current=null,l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),O.stop();const C=g.current;C!==null&&c.current!==null&&C.hasPointerCapture?.(c.current)&&C.releasePointerCapture(c.current),c.current=null,p(null),t.current.repaintOverlay()},[]),I=i.useCallback(()=>{if(!n.current)return;const O=r.current;O!==null&&t.current.setSelection(O),z()},[z]),{enabled:T,bodyRef:F}=e;return i.useEffect(()=>{const O=F.current;if(!T||O===null)return;const g=d=>d instanceof Element&&d.closest("[data-aqsp-cells]")!==null,p=d=>{const $=t.current;if(d.pointerType==="mouse"&&d.button===0&&(m.current=!1,R.current=null,L.current=!1),H.current=g(d.target),!H.current){if(d.pointerType==="mouse"){if(d.preventDefault(),d.button!==0)return;if($.getPointing?.()){$.focusSink();return}if($.isEditing()&&!$.requestCommit()){d.stopPropagation(),$.focusSink();return}$.focusSink()}return}if(N.current=d.pointerType,d.pointerType!=="mouse")return;if(d.button!==0){d.preventDefault();return}if(($.pointDragRef===void 0?null:$.pointDragRef.current)?.onPointerDown(d))return;if($.isEditing()&&!$.requestCommit()){d.preventDefault(),$.focusSink();return}o.current=O.getBoundingClientRect();const D=_(d.clientX,d.clientY);if(D===null)return;if(d.preventDefault(),$.focusSink(),(d.ctrlKey||d.metaKey)&&!d.shiftKey&&$.openHyperlinkAt?.(D)===!0){L.current=!0;return}const q=$.getSelection();r.current=q;const j=d.shiftKey,K=d.ctrlKey||d.metaKey,G=K&&!j&&q.ranges.some(te=>Cn(te,D));m.current=G,R.current=G?D:null,G||$.setSelection(Cr(q,D,{extend:j,append:K})),n.current=!0,$.repaintOverlay(),s.current={clientX:d.clientX,clientY:d.clientY},c.current=d.pointerId,u.current=d.buttons;try{O.setPointerCapture(d.pointerId)}catch{c.current=null}const J=G?D:$.getSelection().anchor;h.current=te=>Re(J,te),W.current=J.col,k.current=J.row,$.autoScroller.stop(),U.current=!1,x.current={clientX:d.clientX,clientY:d.clientY}},C=d=>c.current!==null?d.pointerId===c.current:d.pointerType==="mouse",v=d=>{if(n.current&&C(d)){if(s.current={clientX:d.clientX,clientY:d.clientY},!U.current&&h.current!==null){const $=Math.abs(d.clientX-x.current.clientX),A=Math.abs(d.clientY-x.current.clientY);Math.max($,A)>=io&&(U.current=!0,t.current.autoScroller.start({getPointerPosition:()=>s.current,buildRange:h.current,anchorCol:W.current??void 0,anchorRow:k.current??void 0}))}l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const $=h.current;if(!n.current||$===null)return;const A=t.current,D=_(s.current.clientX,s.current.clientY);D!==null&&A.onDragFrame($(D))}))}},S=d=>{v(d),n.current&&C(d)&&(u.current&1)!==0&&(d.buttons&1)===0&&y(d)},b=d=>{d.button!==0||!(n.current&&C(d))||y(d)},y=d=>{const $=t.current,A=_(d.clientX,d.clientY);if(A!==null){const D=R.current;m.current&&D!==null?$.setSelection(Ya($.getSelection(),Re(D,A),D)):$.setSelection(hn($.getSelection(),A))}z()},a=d=>{!n.current||c.current===null||d.pointerId!==c.current||I()},f=d=>{const $=t.current;if(!g(d.target)||N.current!=="mouse"||$.isAnyDragging())return;if($.isEditing()&&!$.requestCommit()){$.focusSink();return}$.focusSink(),o.current=O.getBoundingClientRect();const A=_(d.clientX,d.clientY);if(A===null)return;const D=$.getSelection();D.ranges.some(j=>Cn(j,A))||$.setSelection(Cr(D,A,{extend:!1,append:!1})),$.onContextMenuSelect(A,d)},E=d=>{const $=t.current;if(!H.current||N.current!=="mouse"||$.getPointing?.()||L.current)return;o.current=O.getBoundingClientRect();const A=_(d.clientX,d.clientY);A!==null&&It($.getSelection().active,A)&&$.onRequestEdit(A,$.caretFromPointEnabled(A)?$w(d.clientX,d.clientY,A):void 0)};return O.addEventListener("pointerdown",p),O.addEventListener("pointermove",S),O.addEventListener("pointerup",b),O.addEventListener("lostpointercapture",a),O.addEventListener("contextmenu",f),O.addEventListener("dblclick",E),()=>{O.removeEventListener("pointerdown",p),O.removeEventListener("pointermove",S),O.removeEventListener("pointerup",b),O.removeEventListener("lostpointercapture",a),O.removeEventListener("contextmenu",f),O.removeEventListener("dblclick",E),z()}},[T,F,_,z,I]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>m.current?"subtract":"add",abortDrag:I,cancelDrag:z}),[I,z])},Dw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef({clientX:0,clientY:0}),l=i.useRef({clientX:0,clientY:0}),c=i.useRef(null),u=i.useRef(null),h=i.useRef(0),m=i.useRef(null),R=i.useRef(null),N=i.useRef(!1),H=i.useCallback((x,z)=>{const{handleRef:I,rowAxis:T,colAxis:F,zoomRef:O}=t.current;return Za(I.current,o.current,T,F,O.current,x,z)},[]),L=i.useCallback(()=>{const{autoScroller:x,bodyRef:z,onDragFrame:I}=t.current;n.current=!1,r.current=null,m.current=null,R.current=null,N.current=!1,o.current=null,c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),x.stop();const T=z.current;T!==null&&u.current!==null&&T.hasPointerCapture?.(u.current)&&T.releasePointerCapture(u.current),u.current=null,I(null)},[]),_=i.useCallback(()=>{if(!n.current)return;const x=r.current;x!==null&&t.current.restoreSink(x),L()},[L]),U=i.useCallback(x=>{const z=t.current,I=z.bodyRef.current;if(!z.enabled||I===null||!z.getPointing())return!1;o.current=I.getBoundingClientRect();const T=H(x.clientX,x.clientY);if(T===null)return o.current=null,!1;const F=z.captureSink();if(F===null)return o.current=null,!1;x.preventDefault(),z.focusSink(),r.current=F,R.current=T,z.insertReference(T,"cells"),n.current=!0,s.current={clientX:x.clientX,clientY:x.clientY},l.current={clientX:x.clientX,clientY:x.clientY},u.current=x.pointerId,h.current=x.buttons;try{I.setPointerCapture(x.pointerId)}catch{u.current=null}return m.current=O=>{const g=Re(T,O);return t.current.insertReference(g,"cells"),g},z.autoScroller.stop(),N.current=!1,z.onDragFrame(Re(T,T)),!0},[H]),{enabled:W,bodyRef:k}=e;return i.useEffect(()=>{const x=k.current;if(!W||x===null)return;const z=O=>u.current!==null?O.pointerId===u.current:O.pointerType==="mouse",I=O=>{if(!(n.current&&z(O)))return;s.current={clientX:O.clientX,clientY:O.clientY};const g=m.current,p=R.current;if(!N.current&&g!==null&&p!==null){const C=Math.abs(O.clientX-l.current.clientX),v=Math.abs(O.clientY-l.current.clientY);Math.max(C,v)>=io&&(N.current=!0,t.current.autoScroller.start({getPointerPosition:()=>s.current,buildRange:g,anchorCol:p.col,anchorRow:p.row}))}c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null;const C=m.current;if(!n.current||C===null)return;const v=H(s.current.clientX,s.current.clientY);v!==null&&t.current.onDragFrame(C(v))})),(h.current&1)!==0&&(O.buttons&1)===0&&L()},T=O=>{O.button!==0||!(n.current&&z(O))||L()},F=O=>{!n.current||u.current===null||O.pointerId!==u.current||L()};return x.addEventListener("pointermove",I),x.addEventListener("pointerup",T),x.addEventListener("lostpointercapture",F),()=>{x.removeEventListener("pointermove",I),x.removeEventListener("pointerup",T),x.removeEventListener("lostpointercapture",F),L()}},[W,k,H,L]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"point",abortDrag:_,cancelDrag:L,onPointerDown:U}),[_,L,U])},Mw=Object.freeze({width:0,height:0}),rs=33,zw=e=>e.nodeType===Node.DOCUMENT_NODE||e.nodeType===Node.DOCUMENT_FRAGMENT_NODE,Nw=(e,t,n)=>{const r=(n-t)/(rs-1);let o=-1,s=-1;for(let c=0;c<rs;c++)e(t+r*c)&&(o===-1&&(o=c),s=c);if(o===-1)return null;const l=(c,u)=>{let h=c,m=u;for(;Math.abs(m-h)>1;){const R=(h+m)/2;e(R)?m=R:h=R}return m};return{top:o===0?t:l(t+r*(o-1),t+r*o),bottom:s===rs-1?n:l(t+r*(s+1),t+r*s)}},Fw=(e,t)=>{if(!Number.isInteger(e)||e<0||e>0&&e>t)throw new RangeError(`[spreadsheet] headerRows must be a whole number from 0 to frozenRows = ${t} (got ${e})`)},Pw=e=>{if(e!==void 0&&(typeof e!="string"||e===""||/\s/u.test(e)))throw new RangeError(`[spreadsheet] labelledBy must be one non-empty id without whitespace (got ${JSON.stringify(e)})`)},Gi=(e,t)=>{if(t!==void 0&&!(Number.isInteger(t)&&t>=0))throw new RangeError(`[spreadsheet] ${e} must be a non-negative integer (got ${typeof t=="string"?JSON.stringify(t):String(t)})`);return t},_w=24,qw=200,Ja=Object.freeze(["#FF0000","#00FF00","#0000FF","#FFFF00","#FF00FF"]),Zi=5,Iw=/^#[0-9A-Fa-f]{6}$/,jw=Object.freeze({row:!1,column:!1,intersection:!1}),Ji=Object.freeze({ok:!0}),Qi=(e,t)=>{if(t===void 0)return Ja;if(t.length!==Zi)throw new RangeError(`[spreadsheet] colors.${e} must contain exactly ${Zi} colours (got ${t.length})`);for(const n of t)if(typeof n!="string"||!Iw.test(n))throw new RangeError(`[spreadsheet] colors.${e} entries must be #rrggbb strings (got ${JSON.stringify(n)})`);return t},Hw=e=>{for(const t of["row","column","intersection"])if(Ze(e[t])===null)throw new RangeError(`[spreadsheet] highlightColors.${t} is not a colour (got ${JSON.stringify(e[t])})`);if(!(Number.isFinite(e.opacity)&&e.opacity>=0&&e.opacity<=1))throw new RangeError(`[spreadsheet] highlightColors.opacity must be a number in [0, 1] (got ${e.opacity})`);return e},Bw=(e,t)=>{if(e!==void 0)return e;if(t.row||t.column||t.intersection)return ka},Vw=e=>{if(e===void 0)throw new RangeError("[spreadsheet] commitEdits: a paste commit requires its sheet context (sameSheet / conditionalFormats)");return e},Ww=e=>{const t=i.useRef(null),n=t.current;return n!==null&&Je.VIRTUAL_SCROLL_LABEL_KEYS.every(r=>n[r]===e[r])?n:(t.current=e,e)},Nn={ranges:[Re({row:0,col:0},{row:0,col:0})],anchor:{row:0,col:0},active:{row:0,col:0}},Kw=i.forwardRef(function({adapter:t,headerRows:n=0,readOnly:r=!1,labelledBy:o,defaultRowHeight:s=_w,defaultColumnWidth:l=Te.SPREADSHEET_DEFAULT_COLUMN_WIDTH_PX,frozenColumns:c=0,frozenRows:u=0,frozenTrailingColumns:h=0,frozenTrailingRows:m=0,tapScrollCircleOptions:R,overscanRows:N,overscanCols:H,background:L,onRenderTruncated:_,renderCell:U,onSelectionChange:W,onCellContextMenu:k,onUndoRequest:x,onRedoRequest:z,onCopyMultiRange:I,onOperationRejected:T,onEditRejected:F,onReadOnlyRejected:O,formatReadOnlyAnnouncement:g,dataVersion:p,maxOperationCells:C=Te.SPREADSHEET_MAX_OPERATION_CELLS,enableFillHandle:v=!0,enableResizeUI:S=!0,headings:b=!0,onContentSizeChange:y,formatCellAnnouncement:a,formatSelectionAnnouncement:f,formatCommandAnnouncement:E,formatResizeAnnouncement:d,locale:$,labels:A,shortcuts:D,colors:q,formats:j,highlight:K,defaultHighlight:G,onHighlightChange:J,highlightColors:te,popovers:le,renderPopover:me,onClipChange:Ee,onHyperlinkOpen:xe,onValidationRejected:De,onPasteSpecialRequest:Pe,onClipboardUnavailable:ue,onPasteResolved:Ne,now:Ue=Date.now,zoom:je,defaultZoom:Ot,onZoomChange:xt,testId:He,className:wt,__onCellRender:bn,__onVirtualKeyboardRaise:lt,__maxRenderedCells:Er},yn){const oe=i.useMemo(()=>r?hh(t):t,[t,r]),fe=qi(oe.rowCount,s),pe=qi(oe.colCount,l),Ht=i.useRef(null);Ht.current===null&&(Ht.current=gw());const Ae=Ht.current,Bt=Je.resolveVirtualScrollLocale($),it=i.useMemo(()=>fa($,A),[$,A]),Rn=Ww(Ih(it)),Vt=i.useMemo(()=>Fh(D),[D]),Ar=i.useMemo(()=>{if(!S)return;const P=[...Vt].filter(([,Z])=>Uo.includes(Z)).sort(([,Z],[,Q])=>Uo.indexOf(Z)-Uo.indexOf(Q)).map(([Z])=>$h(Z)).filter(Z=>Z!==null);return P.length===0?void 0:P.join(" ")},[Vt,S]),Xn=i.useMemo(()=>({fill:Qi("fill",q===void 0?void 0:q.fill),font:Qi("font",q===void 0?void 0:q.font)}),[q]),mo=i.useMemo(()=>te===void 0?void 0:Hw(te),[te]);if(oe.getConditionalFormats!==void 0&&oe.getCellFormat===void 0)throw new RangeError("[spreadsheet] getConditionalFormats requires getCellFormat");Fw(n,u),Pw(o);const Or=i.useCallback(()=>Ae.get().editVersion,[Ae]),go=i.useCallback(w=>Ae.subscribeCoalesced(w),[Ae]),wo=i.useSyncExternalStore(go,Or,Or)+(p===void 0?0:p),Wt=oe.getConditionalFormats===void 0?null:oe.getConditionalFormats(),vn=i.useMemo(()=>({index:Wt===null?null:Ba(Wt),memo:qs()}),[oe,Wt,wo]),Gn=i.useRef(vn.index);Gn.current=vn.index;const M=i.useRef(vn.memo);M.current=vn.memo;const B=i.useCallback((w,P,Z)=>Is(oe,Gn.current,M.current,w,P,Z),[oe]),X=i.useRef(null),[V,ee]=i.useState(()=>Te.clampSpreadsheetZoom(Ot??1)),se=Te.clampSpreadsheetZoom(je??V),ne=i.useRef(se);ne.current=se;const Oe=i.useRef(se);Oe.current=se;const Se=i.useRef(null),Be=i.useRef(xt);Be.current=xt;const Ve=i.useRef(je!==void 0);Ve.current=je!==void 0;const _e=i.useCallback(w=>{const P=Te.clampSpreadsheetZoom(w);P!==Oe.current&&(Oe.current=P,Ve.current||ee(P),Be.current?.(P))},[]),ve=oe.rowCount===0||oe.colCount===0,ie=!ve;i.useEffect(()=>{const w=X.current;if(!ie||w===null)return;const P=Q=>{Q.defaultPrevented||!Q.altKey||Q.ctrlKey||Q.metaKey||Q.shiftKey||Q.deltaY!==0&&(Q.preventDefault(),Q.stopPropagation(),!Se.current?.()&&_e(Te.stepSpreadsheetZoom(Oe.current,Q.deltaY<0?1:-1)))},Z=Q=>{if(Q.defaultPrevented||!(Q.ctrlKey&&Q.altKey)||Q.metaKey||Q.getModifierState("AltGraph"))return;const de=Q.key==="="||Q.key==="+"?Te.stepSpreadsheetZoom(Oe.current,1):Q.key==="-"?Te.stepSpreadsheetZoom(Oe.current,-1):Q.key==="0"?1:null;de!==null&&(Q.preventDefault(),Q.stopPropagation(),!Se.current?.()&&_e(de))};return w.addEventListener("wheel",P,{passive:!1,capture:!0}),w.addEventListener("keydown",Z,!0),()=>{w.removeEventListener("wheel",P,{capture:!0}),w.removeEventListener("keydown",Z,!0)}},[_e,ie]);const ce=i.useRef(null),ge=i.useRef(null),Ce=i.useRef(null),he=i.useRef(null),re=i.useRef(null),ke=i.useRef(null),Me=i.useRef(null),Ct=i.useRef(0),ct=i.useRef(null),bt=i.useRef(0),Tt=i.useRef(null),$t=i.useRef(null),Kt=i.useRef(null),yt=i.useRef(null),Sn=i.useRef(null),kn=i.useRef(null),Bs=i.useRef(null),[En,Co]=i.useState(Nn),Rt=i.useRef(En),Lt=i.useCallback(()=>Rt.current,[]),[Qa,eu]=i.useState(()=>G===void 0?jw:G),An=K!==void 0?K:Qa,bo=i.useRef(An);bo.current=An;const tu=Bw(mo,An),Vs=i.useRef(K!==void 0);Vs.current=K!==void 0;const Ws=i.useRef(J);Ws.current=J;const nu=i.useCallback(w=>{Vs.current||eu(w),Ws.current?.(w)},[]),Ks=i.useRef(null),yo=i.useRef(null),Dt=i.useRef(null),Ro=i.useRef(()=>!1),Ys=i.useRef(()=>{}),Us=i.useRef(()=>null),Xs=i.useRef(()=>{}),cn=i.useCallback(()=>Ro.current(),[]),vo=i.useMemo(()=>({getPointing:()=>Ro.current(),insertReference:(w,P)=>Ys.current(w,P)}),[]),Gs=i.useRef(Pt),Zs=i.useRef(null),So=i.useRef({interactive:null,tip:null}),Js=i.useRef(null),Qs=i.useRef(null),xr=i.useRef(()=>{}),el=i.useRef(()=>!1),Yt=i.useRef(null),Zn=i.useCallback(()=>{const w=Yt.current;if(w===null||w.isOpen()!=="message")return!1;const P=w.context;return P===null||P.kind!=="message"||!P.current.rejected?!1:(w.close(),!0)},[]),ko=i.useRef(()=>!1),tl=i.useRef(()=>!1),nl=i.useRef(null),Eo=i.useRef(()=>Promise.resolve("rejected")),Le=i.useCallback(()=>{Ks.current?.()},[]),Mt=i.useCallback(w=>{ke.current?.focus(w)},[]),qe=i.useCallback(()=>{Mt({preventScroll:!0})},[Mt]),Ao=i.useRef(!1),ru=i.useCallback(()=>{const w=X.current;if(w!==null){Ao.current=!0;try{w.focus()}finally{Ao.current=!1}}},[]),Qe=i.useCallback(()=>{const w=ke.current;w!==null&&(w.value=" ",w.setSelectionRange(0,1))},[]),On=i.useCallback((w,P)=>{if(w===null)return;const Z=P?"":"none";w.style.display!==Z&&(w.style.display=Z)},[]),at=i.useCallback(()=>{const w=Me.current;if(w!==null){const Z=Math.max(0,re.current?.getScrollPosition().y??0),Q=re.current?.getFrozenSize().height??0;w.style.transform=`translateY(${Ct.current-Z-Q}px)`}const P=re.current;if(P!==null&&(Sn.current!==null||kn.current!==null)){const Z=P.getFrozenSize();On(Sn.current,Z.height>0),On(kn.current,Z.trailingHeight>0)}},[On]),ut=i.useCallback(()=>{const w=ct.current;if(w!==null){const Z=Math.max(0,re.current?.getScrollPosition().x??0),Q=re.current?.getFrozenSize().width??0;w.style.transform=`translateX(${bt.current-Z-Q}px)`}const P=re.current;if(P!==null&&(Kt.current!==null||yt.current!==null)){const Z=P.getFrozenSize();On(Kt.current,Z.width>0),On(yt.current,Z.trailingWidth>0)}},[On]),Jn=i.useRef(null),xn=i.useCallback(()=>{Kt.current===null&&yt.current===null&&Sn.current===null&&kn.current===null||Jn.current===null&&(Jn.current=requestAnimationFrame(()=>{Jn.current=null,at(),ut(),Le()}))},[at,ut,Le]);i.useEffect(()=>()=>{Jn.current!==null&&cancelAnimationFrame(Jn.current)},[]);const Oo=i.useRef(null),xo=i.useRef(null);(Oo.current===null||xo.current?.rowAxis!==fe||xo.current?.colAxis!==pe)&&(xo.current={rowAxis:fe,colAxis:pe},Oo.current=aw({handleRef:re,rowAxis:fe,colAxis:pe}));const Tr=i.useCallback(w=>{const P=re.current,Z=P===null?{x:0,y:0}:P.getScrollPosition(),Q=P===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:P.getFrozenSize(),de=P===null?{width:0,height:0}:P.getViewportSize(),be=ne.current;return{top:wn(fe,w.row,{scroll:Math.max(0,Z.y),frozenCount:Q.rows,trailingCount:Q.trailingRows,extent:de.height})*be,left:gn(pe,w.col,{scroll:Math.max(0,Z.x),frozenCount:Q.cols,trailingCount:Q.trailingCols,extent:de.width})*be,width:pe.sizeOf(w.col)*be,height:fe.sizeOf(w.row)*be}},[fe,pe]),rl=i.useCallback(w=>{const P=he.current,Z=X.current,Q=ge.current;if(P===null||Z===null||Q===null||re.current===null)return;const de=ne.current,be=Tr(w),Ke=Q.offsetTop*de+be.top,tt=Q.offsetLeft*de+be.left,Ie=Math.max(0,Ke),Et=Math.max(0,tt),Gt=Math.min(Z.clientHeight,Ke+be.height),Mr=Math.min(Z.clientWidth,tt+be.width);if(Gt<=Ie||Mr<=Et)return;P.style.top=`${Ie}px`,P.style.left=`${Et}px`,P.style.width=`${Mr-Et}px`,P.style.height=`${Gt-Ie}px`;const Dn=P.getBoundingClientRect();Dn.width===0&&Dn.height===0||P.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"})},[Tr]),Ut=i.useCallback(w=>{Oo.current?.(w),rl(w)},[rl]),ou=i.useCallback(()=>{const w=re.current,P=w===null?-1:w.getViewportSize().height,Z=ce.current,Q=X.current;if(P<=0||Z===null||Q===null)return P;const de=Z.getBoundingClientRect(),be=Q.getRootNode();if(de.height<=0||Z.offsetHeight<=0||!zw(be))return P;const Ke=Q.ownerDocument.documentElement,tt=Math.max(de.left,0),Ie=Math.min(de.right,Ke.clientWidth),Et=Math.max(de.top,0)+.5,Gt=Math.min(de.bottom,Ke.clientHeight)-.5,Mr=(tt+Ie)/2,Dn=Ie>tt&&Gt>=Et?Nw(zu=>{const Ml=be.elementFromPoint(Mr,zu);return Ml!==null&&Q.contains(Ml)},Et,Gt):null,Mu=Dn===null?Ke.clientHeight:Dn.bottom-Dn.top+1;return Math.min(P,Mu*(Z.offsetHeight/de.height))},[]),ol=i.useRef(y);ol.current=y;const To=i.useRef(null),zt=i.useCallback(()=>{const w=ol.current;if(w===void 0)return;const P=ge.current;let Z;if(P===null)Z=Mw;else{if(P.getClientRects().length===0)return;{const de=Ce.current,be=ne.current;Z={width:((de===null?0:de.offsetWidth)+pe.totalSize()+Te.SPREADSHEET_SCROLLBAR_SIZE_PX)*be,height:((de===null?0:de.offsetHeight)+fe.totalSize()+Te.SPREADSHEET_SCROLLBAR_SIZE_PX)*be}}}const Q=To.current;Q!==null&&Q.width===Z.width&&Q.height===Z.height||(To.current=Z,w(Z))},[fe,pe]);i.useLayoutEffect(()=>{if(y===void 0){To.current=null;return}zt()});const sl=y!==void 0;i.useEffect(()=>{const w=ge.current;if(!sl||w===null)return;const P=new ResizeObserver(()=>zt());return P.observe(w),()=>P.disconnect()},[sl,zt,ve]);const Tn=i.useRef(null),an=i.useRef(null),$n=i.useCallback(w=>{Tn.current!==null&&window.clearTimeout(Tn.current),an.current!==null&&(cancelAnimationFrame(an.current),an.current=null),Tn.current=window.setTimeout(()=>{Tn.current=null;const P=Bs.current;P!==null&&(P.textContent="",an.current=requestAnimationFrame(()=>{an.current=null,P.textContent=w}))},qw)},[]);i.useEffect(()=>()=>{Tn.current!==null&&window.clearTimeout(Tn.current),an.current!==null&&cancelAnimationFrame(an.current)},[]);const Ln=i.useCallback(w=>{O?.(w),g!==void 0&&$n(g(w))},[O,g,$n]),ll=i.useCallback((w,P)=>{if(a===void 0&&f===void 0)return;const Z=P.ranges[P.ranges.length-1],Q=st(Z),de=P.ranges.length===1&&Q.rows===1&&Q.cols===1,be=w.ranges[w.ranges.length-1],Ke=w.ranges.length!==P.ranges.length||be.startRow!==Z.startRow||be.startCol!==Z.startCol||be.endRow!==Z.endRow||be.endCol!==Z.endCol,tt=()=>{if(a!==void 0){const Ie=P.active,Et=oe.getCellText(Ie.row,Ie.col),Gt=oe.getCellFormat===void 0?void 0:B(Ie.row,Ie.col,()=>Et);$n(a({row:Ie.row,col:Ie.col,text:Et,displayText:Wn(Et,Gt===void 0?void 0:Gt.value),columnName:Te.columnIndexToName(Ie.col),...na(oe)?{readOnly:Ye(oe,Ie.row,Ie.col)}:{}}))}};if(de){tt();return}if(Ke){f!==void 0&&$n(f({range:Z,anchor:P.anchor,active:P.active,rangeRowCount:Q.rows,rangeColCount:Q.cols,rangeCount:P.ranges.length}));return}tt()},[oe,a,f,$n,B]),We=i.useCallback(w=>{const P=Rt.current;Object.is(w,P)||ow(w,P)||(Rt.current=w,Co(w),W?.(w),ll(P,w),(Dt.current?.()??!1)||Qe())},[W,ll,Qe]),su=i.useCallback(w=>{const P=Rt.current;if(w.mode==="cycle"){const Q=Ua(P,w.direction);We(Q),Ut(Q.active);return}const Z=ln(w.cell,fe.count,pe.count);if(w.mode==="extend"){We(hn(P,Z)),Ut(Z);return}We(Cr(P,Z,{extend:!1,append:!1})),Ut(Z)},[We,Ut,fe,pe]),Xe=i.useCallback(()=>Dt.current?.()??!1,[]),il=i.useRef(null),dt=i.useCallback(()=>il.current?.()??!0,[]),cl=i.useRef(null),Qn=i.useCallback((w,P)=>{const Z=Dt.current?.()??!1;cl.current?.(w,P),!Z&&(Dt.current?.()??!1)&&Zn()},[Zn]),[lu,$o]=i.useState(!1),al=i.useCallback(()=>{lt?.(),$o(!0)},[lt]),iu=i.useCallback((w,P)=>{Ye(oe,w.row,w.col)||al(),Qn("edit",P)},[oe,al,Qn]),ul=i.useRef(null),$r=i.useCallback(()=>ul.current?.()??null,[]),dl=i.useRef(null),vt=i.useCallback(()=>{dl.current?.()},[]),fl=i.useRef(null),pl=i.useCallback(w=>{fl.current?.(w)},[]),hl=i.useRef(()=>{}),Lr=i.useRef(0),un=i.useCallback((w,P,Z)=>{let Q;if(P.source==="paste"){const de=Vw(Z);if(w.length===0&&de.conditionalFormats.length===0)return null;Lr.current+=1,Q={transaction:Lr.current,source:"paste",sameSheet:de.sameSheet,conditionalFormats:de.conditionalFormats}}else{if(w.length===0)return null;Lr.current+=1,Q={transaction:Lr.current,source:P.source}}try{oe.applyEdits(w,Q)}catch(de){return F?.(de,P),null}return Ae.bumpEdit(),pl(P.source),Q.transaction},[oe,Ae,F,pl]),cu=i.useCallback((w,P)=>un(w,{source:"paste"},P),[un]),au=i.useCallback(w=>{Ae.setVy(w.y),at(),ut(),Le()},[Ae,at,ut,Le]),ml=i.useRef({rowStart:-1,rowEnd:-1,colStart:-1,colEnd:-1}),uu=i.useCallback(w=>{Ae.setRowRange(w.renderingRowStart,w.renderingRowEnd),Ae.setColRange(w.renderingColStart,w.renderingColEnd);const P=ml.current;(P.rowStart!==w.renderingRowStart||P.rowEnd!==w.renderingRowEnd||P.colStart!==w.renderingColStart||P.colEnd!==w.renderingColEnd)&&(ml.current={rowStart:w.renderingRowStart,rowEnd:w.renderingRowEnd,colStart:w.renderingColStart,colEnd:w.renderingColEnd},Le())},[Ae,Le]),gl=i.useRef(()=>"add"),Xt=i.useCallback(w=>{yo.current?.(w,gl.current())},[]),du=i.useCallback(w=>{yo.current?.(w,"point")},[]),wl=i.useRef(null),Lo=i.useCallback(w=>{wl.current?.(w)},[]),Cl=i.useRef(null),fu=i.useCallback(w=>{Cl.current?.(w)},[]),bl=i.useRef(null),Do=i.useCallback((w,P)=>{if(P.length===0)return;const Z=re.current;if(w==="col"){for(const Q of P){const de=Math.round(Q.size);pe.resize(Q.index,de),Z?.updateColSize(Q.index,de)}Ae.bumpColVersion(),ut(),Le(),xn(),zt();return}for(const Q of P){const de=Math.round(Q.size);fe.resize(Q.index,de),Z?.updateRowSize(Q.index,de)}Ae.bumpRowGeometry(),at(),Le(),xn(),zt()},[fe,pe,Ae,ut,at,Le,xn,zt]),pu=i.useCallback((w,P)=>{k?.(w,{kind:"pointer",event:P})},[k]),hu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Xt,axis:"both",zoomRef:ne}),mu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Xt,axis:"x",zoomRef:ne}),gu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Xt,axis:"y",zoomRef:ne}),wu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Lo,axis:"x",zoomRef:ne}),Cu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Lo,axis:"y",zoomRef:ne}),bu=zn({handleRef:re,rowAxis:fe,colAxis:pe,bodyRef:ce,onDragFrame:Xt,axis:"both",zoomRef:ne}),yl=i.useRef(null),Rl=i.useRef(()=>!1),Mo=i.useCallback(()=>Rl.current(),[]),ft=Lw({zoomRef:ne,enabled:!ve,rowAxis:fe,colAxis:pe,handleRef:re,bodyRef:ce,isEditing:Xe,requestCommit:dt,getSelection:Lt,setSelection:We,focusSink:qe,onDragFrame:Xt,onContextMenuSelect:pu,onRequestEdit:iu,caretFromPointEnabled:w=>{if(U!==void 0||oe.getCellFormula!==void 0&&oe.getCellFormula(w.row,w.col)!==void 0)return!1;if(oe.getCellFormat===void 0)return!0;const P=oe.getCellText(w.row,w.col);return Wn(P,oe.getCellFormat(w.row,w.col)?.value)===P},isAnyDragging:Mo,autoScroller:hu,repaintOverlay:Le,pointDragRef:yl,getPointing:cn,openHyperlinkAt:xe===void 0||oe.getCellHyperlink===void 0?void 0:w=>{const P=oe.getCellHyperlink===void 0?void 0:Un(oe.getCellHyperlink(w.row,w.col));return P===void 0?!1:(xe(P,w),!0)}}),St=Xi({zoomRef:ne,enabled:!ve&&b,axis:"col",headerRef:Tt,mainAxis:pe,crossCount:oe.rowCount,handleRef:re,isEditing:Xe,requestCommit:dt,getSelection:Lt,setSelection:We,focusSink:qe,onDragFrame:Xt,autoScroller:mu,repaintOverlay:Le,pointing:vo}),kt=Xi({zoomRef:ne,enabled:!ve&&b,axis:"row",headerRef:$t,mainAxis:fe,crossCount:oe.colCount,handleRef:re,isEditing:Xe,requestCommit:dt,getSelection:Lt,setSelection:We,focusSink:qe,onDragFrame:Xt,autoScroller:gu,repaintOverlay:Le,pointing:vo}),et=rw({zoomRef:ne,enabled:!ve&&S&&b,colBandRef:Tt,rowBandRef:$t,fontSourceRef:ce,colAxis:pe,rowAxis:fe,viewStore:Ae,handleRef:re,isEditing:Xe,requestCommit:dt,focusSink:qe,getSelection:Lt,adapter:oe,autofitEnabled:U===void 0,headerRows:n,defaultRowHeight:s,defaultColumnWidth:l,maxOperationCells:C,onOperationRejected:T,resizeTracks:Do,writeResizeGuide:fu,repaintOverlay:Le,isPointing:cn}),pt=bw({zoomRef:ne,enabled:!ve&&v,handleNodeRef:bl,bodyRef:ce,rowAxis:fe,colAxis:pe,handleRef:re,getSelection:Lt,setSelection:We,focusSink:qe,adapter:oe,commitEdits:un,maxOperationCells:C,onOperationRejected:T,rejectReadOnly:Ln,writeFillPreview:Lo,repaintOverlay:Le,xAutoScroller:wu,yAutoScroller:Cu}),nt=Dw({zoomRef:ne,enabled:!ve,bodyRef:ce,handleRef:re,rowAxis:fe,colAxis:pe,getPointing:cn,insertReference:vo.insertReference,captureSink:()=>Us.current(),restoreSink:w=>Xs.current(w),focusSink:qe,autoScroller:bu,onDragFrame:Xt});yl.current=nt;const er=i.useCallback(()=>ft.isDragging()||St.isDragging()||kt.isDragging()||et.isDragging()||pt.isDragging()||nt.isDragging(),[ft,St,kt,et,pt,nt]);Se.current=er,Rl.current=er,gl.current=()=>nt.isDragging()?"point":ft.getDragMode();const yu=i.useCallback(()=>{ft.abortDrag(),St.abortDrag(),kt.abortDrag(),et.abortDrag(),pt.abortDrag(),nt.abortDrag()},[ft,St,kt,et,pt,nt]),zo=i.useCallback(()=>Rt.current.active,[]),vl=i.useCallback((w,P)=>{const Z=oe.getCellValidation===void 0?void 0:oe.getCellValidation(w.row,w.col);if(Z===void 0)return Ji;const Q=oe.evaluateFormula,de=ma(Z,P,Bt,Q===void 0?void 0:be=>Q(be,w));return de.ok||Z.strict!==!0?Ji:(De?.({cell:w,rule:Z,text:P,message:de.message}),Yt.current?.isKindEnabled("message")&&xr.current("message",{message:de.message,rejected:!0}),de)},[oe,De,Bt]),Fe=bg({enabled:!ve,sinkRef:ke,rootRef:X,adapter:oe,commitEdits:un,getActive:zo,ensureCellVisible:Ut,focusSink:Mt,rearmSink:Qe,discardClip:vt,isDragging:Mo,rejectReadOnly:Ln,resolveEditAlign:w=>{if(oe.getCellFormat===void 0)return null;const P=Qr(oe,w.row,w.col);return ta(B(w.row,w.col,P),P)},resolveEditPaint:w=>oe.getCellFormat===void 0?null:df(B(w.row,w.col,Qr(oe,w.row,w.col))),editPaintRef:Gs,repaintOverlay:Le,validateCommit:vl});Dt.current=Fe.isEditing,il.current=Fe.requestCommit,cl.current=Fe.startEdit,Ro.current=Fe.getPointing,Ys.current=Fe.insertReference,Us.current=Fe.captureSink,Xs.current=Fe.restoreSink;const Sl=i.useCallback(()=>{Fe.cancelEdit(),Zn()},[Fe.cancelEdit,Zn]),tr=eg({enabled:!ve,sinkRef:ke,adapter:oe,isEditing:Xe,getSelection:Lt,setSelection:We,commitPaste:cu,maxOperationCells:C,onOperationRejected:T,onCopyMultiRange:I,repaintOverlay:Le,isDragging:Mo,resize:{rowAxis:fe,colAxis:pe,resizeTracks:Do},pendingPasteOptionsRef:Zs,formats:j,onClipChange:Ee,onClipboardUnavailable:ue,onEditRejected:F,rejectReadOnly:Ln,onPasteResolved:Ne});ul.current=tr.getClip,dl.current=tr.discardClip,fl.current=tr.discardClipOnCommit,hl.current=tr.onAdapterSwitch,Eo.current=tr.paste;const nr=Tw({enabled:!ve,adapter:oe,popovers:le,sinkRef:ke,bodyRef:ce,handleRef:re,rowAxis:fe,colAxis:pe,zoomRef:ne,getActive:zo,isEditing:Xe,requestCommit:dt,focusSink:Mt,rearmSink:Qe,isDraggingAny:er,commitEdits:un,labels:it,onHyperlinkOpen:xe,anchors:So,repaintOverlay:Le,rejectReadOnly:Ln});Yt.current=nr,xr.current=nr.open,el.current=nr.hideTip;const Ru=i.useCallback(()=>{const w=Rt.current.active;return Ut(w),Tr(w)},[Ut,Tr]),No=gg({adapter:oe,trackResize:S&&!ve?et:void 0,getSelection:Lt,commitEdits:un,getActive:zo,isEditing:Xe,requestCommit:dt,cancelEdit:Sl,getSessionText:Fe.getSessionText,validateCommit:vl,insertAtCaret:Fe.insertAtCaret,refreshEditPaint:Fe.refreshPaint,maxOperationCells:C,onOperationRejected:T,colors:Xn,formats:j,getHighlight:()=>bo.current,setHighlight:nu,popovers:le,openPopover:w=>xr.current(w),onHyperlinkOpen:xe,onPasteSpecialRequest:Pe,paste:w=>Eo.current(w),rowAxis:fe,colAxis:pe,resizeTracks:Do,defaultRowHeight:s,defaultColumnWidth:l,now:Ue,announce:$n,formatCommandAnnouncement:E,formatResizeAnnouncement:d,keyboardCellRect:Ru,rejectReadOnly:Ln});nl.current=No,ko.current=No.executeCommand,tl.current=No.isCommandAvailable;const vu=i.useMemo(()=>({table:Vt,execute:w=>ko.current(w),isAvailable:w=>tl.current(w)}),[Vt]),Su=i.useCallback(()=>{vt(),x?.()},[vt,x]),ku=i.useCallback(()=>{vt(),z?.()},[vt,z]);mw({zoomRef:ne,enabled:!ve,sinkRef:ke,rootRef:X,handOffFocusToRoot:ru,getSelection:Lt,setSelection:We,moveActive:su,ensureCellVisible:Ut,pageExtent:ou,isEditing:Xe,requestCommit:dt,startEdit:Qn,commitEdits:un,maxOperationCells:C,onOperationRejected:T,rejectReadOnly:Ln,getClip:$r,discardClip:vt,isDragging:er,abortDrag:yu,findDataEdge:oe.findDataEdge,getEditingMode:Fe.getEditingMode,cancelEdit:Sl,onUndoRequest:Su,onRedoRequest:ku,onCellContextMenu:k,rowAxis:fe,colAxis:pe,handleRef:re,rearmSink:Qe,commands:vu,pointing:Fe,adapter:oe,hideNoteTip:()=>el.current(),closeRejectedMessage:Zn,pendingPasteOptionsRef:Zs,onPointFrame:du});const Eu=En.active.row,Au=En.active.col;i.useLayoutEffect(()=>{const w=Yt.current;w!==null&&(w.syncTipAriaDescribedBy(),w.isKindEnabled("message")&&(w.isOpen()==="message"&&w.close(),w.open("message")))},[Eu,Au]),i.useLayoutEffect(()=>{Le()},[Le,An.row,An.column,An.intersection]);const Ou=i.useCallback(w=>{(Dt.current?.()??!1)||(w.preventDefault(),qe(),Qe())},[qe,Qe]),xu=i.useCallback(w=>{const P=X.current,Z=w.relatedTarget,Q=P!==null&&!P.matches(":focus-visible");if(P!==null&&Z instanceof Node&&P.contains(Z)){w.target===P&&Z===ke.current&&!Ao.current&&Mt({preventScroll:Q});return}(Dt.current?.()??!1)||(Mt({preventScroll:Q}),Qe())},[Mt,Qe]),Tu=i.useCallback(w=>{const P=X.current,Z=w.relatedTarget;P!==null&&Z instanceof Node&&P.contains(Z)||Fe.isFocusoutSuppressed()||$o(!1)},[Fe]),Dr=i.useRef(null),rr=i.useCallback(()=>{const w=Dr.current;w!==null&&(Dr.current=null,window.removeEventListener("pointerup",w.up,!0),window.removeEventListener("pointercancel",w.cancel,!0))},[]),Fo=i.useCallback(()=>{if(Dr.current!==null)return;const w=Z=>{Z.pointerType==="mouse"&&(rr(),Z.button===1&&Z.preventDefault())},P=Z=>{Z.pointerType==="mouse"&&rr()};Dr.current={up:w,cancel:P},window.addEventListener("pointerup",w,!0),window.addEventListener("pointercancel",P,!0)},[rr]);i.useEffect(()=>rr,[rr]),i.useEffect(()=>{const w=X.current;if(ve||w===null)return;let P=0;const Z=be=>{if(be.pointerType!=="mouse"){(Dt.current?.()??!1)||$o(!1);return}P=be.buttons,be.button===1&&(be.target===ke.current&&(Dt.current?.()??!1)||Fo())},Q=be=>{be.pointerType==="mouse"&&(P=be.buttons)},de=be=>{if(be.pointerType!=="mouse"||be.buttons===P)return;const Ke=be.buttons&~P;P=be.buttons,be.preventDefault(),(Ke&4)!==0&&Fo()};return w.addEventListener("pointerdown",Z,!0),w.addEventListener("pointerup",Q,!0),w.addEventListener("pointermove",de,!0),()=>{w.removeEventListener("pointerdown",Z,!0),w.removeEventListener("pointerup",Q,!0),w.removeEventListener("pointermove",de,!0)}},[ve,Fo]);const $u=i.useCallback(w=>{if(!(w.target!==w.currentTarget||w.pointerType!=="mouse")&&(w.preventDefault(),w.button===0)){if(cn()){qe();return}if(Xe()&&!dt()){qe();return}qe()}},[qe,Xe,dt,cn]),Po=i.useRef(!1);i.useLayoutEffect(()=>{if(ve){Po.current=!1;return}if(Po.current)return;Po.current=!0,Qe();const w=(X.current?.clientHeight??0)/ne.current;w>0&&fe.totalSize()>0&&Ae.setRowRange(0,fe.indexAt(Math.min(w-1,fe.totalSize()-1)));const P=(X.current?.clientWidth??0)/ne.current;P>0&&pe.totalSize()>0&&Ae.setColRange(0,pe.indexAt(Math.min(P-1,pe.totalSize()-1)))},[ve,Qe,Ae,fe,pe]);const kl=i.useRef(t);i.useLayoutEffect(()=>{kl.current!==t&&(kl.current=t,ft.cancelDrag(),St.cancelDrag(),kt.cancelDrag(),et.cancelDrag(),pt.cancelDrag(),nt.cancelDrag(),Fe.cancelEdit(),Yt.current?.hideTip(),Yt.current?.close(),ve?(Rt.current=Nn,Co(Nn)):We(Nn),hl.current())},[t,ve,We,ft,St,kt,et,pt,nt,Ae,Fe.cancelEdit]);const El=i.useRef({adapter:oe,rows:fe.count,cols:pe.count}),{getSessionCell:Al,cancelEdit:Ol}=Fe;i.useLayoutEffect(()=>{const w=El.current,P=fe.count,Z=pe.count;if(El.current={adapter:oe,rows:P,cols:Z},w.adapter!==oe||P>=w.rows&&Z>=w.cols)return;ve?(Rt.current=Nn,Co(Nn)):We(sw(Rt.current,P,Z)),ft.cancelDrag(),St.cancelDrag(),kt.cancelDrag(),et.cancelDrag(),pt.cancelDrag(),nt.cancelDrag();const Q=tt=>ve||tt.row>=P||tt.col>=Z,de=Al();de!==null&&Q(de)&&Ol();const be=So.current;if(be.tip!==null&&Q(be.tip)&&Yt.current?.hideTip(),be.interactive!==null&&Q(be.interactive)){const tt=X.current?.contains(document.activeElement)===!0;Yt.current?.close({restoreFocus:tt})}const Ke=$r();Ke!==null&&!Ke.foreign&&Q({row:Ke.range.endRow,col:Ke.range.endCol})&&vt()},[oe,fe.count,pe.count,ve,We,ft,St,kt,et,pt,nt,Al,Ol,$r,vt]);const xl=i.useRef(c),Tl=i.useRef(u),$l=i.useRef(h),Ll=i.useRef(m);i.useLayoutEffect(()=>{(xl.current!==c||Tl.current!==u||$l.current!==h||Ll.current!==m)&&(xl.current=c,Tl.current=u,$l.current=h,Ll.current=m,ft.cancelDrag(),St.cancelDrag(),kt.cancelDrag(),et.cancelDrag(),pt.cancelDrag(),nt.cancelDrag())},[c,u,h,m,ft,St,kt,et,pt,nt]),i.useLayoutEffect(()=>{at(),ut(),Le()},[c,u,h,m,at,ut,Le]);const Dl=i.useRef(p);i.useLayoutEffect(()=>{Dl.current!==p&&(Dl.current=p,vt())},[p,vt]),i.useLayoutEffect(()=>{Le()},[Le,En]);const dn=i.useCallback(()=>{const w=nl.current;if(w===null)throw new RangeError("[spreadsheet] the command runner is not mounted");return w},[]);if(i.useImperativeHandle(yn,()=>({resizeRow:(w,P)=>{const Z=Math.round(P);fe.resize(w,Z),re.current?.updateRowSize(w,Z),Ae.bumpRowGeometry(),at(),Le(),xn(),zt()},resizeColumn:(w,P)=>{const Z=Math.round(P);pe.resize(w,Z),re.current?.updateColSize(w,Z),Ae.bumpColVersion(),ut(),Le(),xn(),zt()},autoFitColumns:w=>{for(const P of w)if(!Number.isInteger(P)||P<0||P>=pe.count)throw new RangeError(`[spreadsheet] autoFitColumns: each column must be a whole number from 0 to ${pe.count-1} (got ${String(P)})`);return et.autofitColumnsInAllRows(w)},scrollToCell:(w,P)=>{re.current?.scrollToCell(w.row,w.col,P)},focus:w=>{Mt(w),Xe()||Qe()},executeCommand:w=>ko.current(w),applyFormat:w=>dn().applyFormat(w),setBorders:(w,P)=>dn().setBorders(w,P),setHyperlink:w=>dn().setHyperlink(w),setNote:w=>dn().setNote(w),addComment:w=>dn().addComment(w),setValidation:w=>dn().setValidation(w),paste:w=>Eo.current(w),getSelection:()=>Rt.current,getBaseFormat:w=>oe.getCellFormat===void 0?void 0:oe.getCellFormat(w.row,w.col),getPaintedFormat:w=>oe.getCellFormat===void 0?void 0:B(w.row,w.col,Qr(oe,w.row,w.col)),startEdit:w=>{Qn(w)},openPopover:w=>{xr.current(w)}}),[fe,pe,Ae,ut,at,Le,xn,zt,et,Mt,Xe,Qe,oe,B,Qn,dn]),ve)return Y.jsx("div",{className:wt?`aqsp-root ${wt}`:"aqsp-root","data-aqsp-empty":"","data-testid":He});const Lu=a!==void 0||f!==void 0||E!==void 0||g!==void 0||d!==void 0,Du=o===void 0?{"aria-label":it.rootAriaLabel}:{"aria-labelledby":o};return Y.jsxs("div",{ref:X,className:wt?`aqsp-root ${wt}`:"aqsp-root",role:"group",...Du,tabIndex:0,onFocus:xu,onBlur:Tu,"data-aqsp-root":"","data-aqsp-headings-hidden":b?void 0:"","data-testid":He,children:[Y.jsxs("div",{className:"aqsp-zoom","data-aqsp-zoom":se,onPointerDown:$u,style:se===1?void 0:{width:`${100/se}%`,height:`${100/se}%`,transform:`scale(${se})`,"--_aqsp-zoom":String(se)},children:[b?Y.jsxs(Y.Fragment,{children:[Y.jsx("div",{ref:Ce,className:"aqsp-corner","aria-hidden":"true","data-aqsp-corner":"",onPointerDown:w=>{if(w.pointerType==="mouse"&&(w.preventDefault(),w.button===0)){if(cn()){qe();return}if(Xe()&&!dt()){qe();return}qe(),We({ranges:[Re({row:0,col:0},{row:oe.rowCount-1,col:oe.colCount-1})],anchor:{row:0,col:0},active:{row:0,col:0}})}}}),Y.jsx(Qg,{viewStore:Ae,colAxis:pe,frozenCols:c,frozenTrailingCols:h,handleRef:re,bandRef:Tt,colTrackRef:ct,windowOriginXRef:bt,repaintColHeaders:ut,selectionRanges:En.ranges,enableResizeUI:S,dividerLeadingRef:Kt,dividerTrailingRef:yt}),Y.jsx(ew,{viewStore:Ae,rowAxis:fe,handleRef:re,bandRef:$t,selectionRanges:En.ranges,rowTrackRef:Me,windowOriginYRef:Ct,repaintHeaders:at,enableResizeUI:S,frozenRows:u,frozenTrailingRows:m,dividerLeadingRef:Sn,dividerTrailingRef:kn})]}):null,Y.jsxs("div",{ref:ge,className:"aqsp-body-stack","data-aqsp-body-stack":"",children:[Y.jsx(Jg,{adapter:oe,rowAxis:fe,colAxis:pe,viewStore:Ae,handleRef:re,bodyRef:ce,dataVersion:p,defaultColumnWidth:l,frozenColumns:c,frozenRows:u,frozenTrailingColumns:h,frozenTrailingRows:m,headerRows:n,labelledBy:o,gridLabel:o===void 0?it.rootAriaLabel:void 0,readOnly:r,tapScrollCircleOptions:R,overscanRows:Gi("overscanRows",N),overscanCols:Gi("overscanCols",H),background:L,onRenderTruncated:_,renderCell:U,onScroll:au,onRangeChange:uu,focusSink:qe,isEditing:Xe,requestCommit:dt,testId:He?`${He}-vs`:void 0,__onCellRender:bn,__maxRenderedCells:Er,cfIndexRef:Gn,cfMemoRef:M,isPointing:cn,locale:Bt,scrollLabels:Rn}),Y.jsx(xm,{rowAxis:fe,colAxis:pe,handleRef:re,sinkRef:ke,getSelection:Lt,editing:Fe.editing,virtualKeyboard:lu,repaintRef:Ks,dragFrameRef:yo,getClip:$r,getIsDraggingAny:er,getIsFillDragging:pt.isDragging,fillFrameRef:wl,resizeGuideFrameRef:Cl,fillHandleNodeRef:bl,enableFillHandle:v,frozenCols:c,frozenRows:u,trailingCols:h,trailingRows:m,sinkAriaLabel:it.sinkAriaLabel,sinkReadOnly:r,sinkKeyShortcuts:Ar,onSinkMouseDown:Ou,editPaintRef:Gs,highlightRef:bo,highlightColors:tu,popoverAnchors:So,interactiveAnchorRef:Js,tipAnchorRef:Qs}),nr.layerEnabled?Y.jsx(Aw,{controller:nr,labels:it,renderPopover:me,interactiveAnchorRef:Js,tipAnchorRef:Qs}):null]}),Lu?Y.jsx("div",{ref:Bs,className:"aqsp-live-region","aria-live":"polite","data-aqsp-live-region":""}):null]}),Y.jsx("div",{ref:he,className:"aqsp-reveal","aria-hidden":"true","data-aqsp-reveal":""})]})});exports.iterateTsvPrefixRows=qt.iterateTsvPrefixRows;exports.iterateTsvRows=qt.iterateTsvRows;exports.measureTsv=qt.measureTsv;exports.parseTsv=qt.parseTsv;exports.serializeClipboardTsv=qt.serializeClipboardTsv;exports.serializeTsv=qt.serializeTsv;exports.columnIndexToName=Te.columnIndexToName;exports.columnNameToIndex=Te.columnNameToIndex;exports.BORDER_DEFAULT_COLOR=Ss;exports.CommentPopover=Aa;exports.DEFAULT_CUSTOM_COLORS=Ja;exports.DEFAULT_HIGHLIGHT_COLORS=ka;exports.DEFAULT_SHORTCUTS=ua;exports.LinkPopover=Oa;exports.ListPopover=xa;exports.MessagePopover=Ta;exports.NotePopover=$a;exports.NoteTip=La;exports.SPREADSHEET_LABEL_CATALOGS=da;exports.SPREADSHEET_RESERVED_SHORTCUTS=Lh;exports.Spreadsheet=Kw;exports.canonicalizeFormat=gt;exports.detectClipSource=ac;exports.enumerateRangeCells=Jt;exports.estimatePasteCellCount=Ch;exports.expandPaste=bh;exports.formatCellValue=Wn;exports.formatEquals=Wu;exports.fromR1C1=Rr;exports.makeRange=Re;exports.mergeFormat=Es;exports.normalizeHyperlink=sn;exports.parseChord=Qt;exports.parseClipPayload=ls;exports.parseHtmlTable=ea;exports.rangeContains=Cn;exports.rangeSize=st;exports.resolveLabel=ze;exports.resolveLabels=fa;exports.serializeClipPayload=lc;exports.serializeHtmlTable=Gc;exports.shiftFormula=Mc;exports.toR1C1=uo;exports.validateCellText=ma;
12
+ `)},fh=(e,t,n,r)=>{const o=e.localName;if(o==="b"||o==="strong")t.set("font-weight","bold");else if(o==="i"||o==="em")t.set("font-style","italic");else if(o==="u")n.underline=!0;else if(o==="s"||o==="strike"||o==="del")n.strikethrough=!0;else if(o==="font"){const s=e.getAttribute("color"),l=e.getAttribute("face");s!==null&&s.trim()!==""&&t.set("color",s),l!==null&&l.trim()!==""&&t.set("font-family",l)}ys(t,ua(e,r))},ph=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null)return null;const r=n,o=r[1];if(typeof o!="number")return null;const s=r[String(o)];if(o===2)return typeof s=="string"?s:null;if(o===3)return typeof s!="number"||!Number.isFinite(s)?null:t!==void 0&&t.type==="date"?oa(s):String(s);if(o===4)return s===1||s===!0?"TRUE":s===0||s===!1?"FALSE":null;if(o===5&&typeof s=="object"&&s!==null){const l=s[1];return typeof l=="number"&&l>=1&&l<ai.length?ai[l]:null}return null},da=(e,t,n)=>t!==void 0&&la(t)?Rp(e,t,n):e,hh=(e,t,n,r)=>{const o=e.getAttribute("x:str");if(o!==null)return o===""?t:o;const s=e.getAttribute("x:bool");if(s!==null){const u=s.toUpperCase();return u==="TRUE"||u==="FALSE"?u:t}const l=e.getAttribute("x:err");if(l!==null)return l===""?t:l;const c=e.getAttribute("x:num");if(c!==null&&c!==""&&wt(c)!==null)if(n!==void 0&&n.type==="date"){const u=oa(Number(c));if(u!==null)return u}else return c;return da(t,n,r)},mh=(e,t,n,r)=>{const o=ua(e,r.rules),s={underline:!1,strikethrough:!1},l={text:"",runs:[],href:null,mode:sh(o)};for(const m of bh(e))ah(m,l);uh(l,o,s,r.rules);const c=dh(l.text,l.mode),u=ih(o,s,r.kind),h={t:""};if(r.kind==="sheets"){const m=e.getAttribute("data-sheets-numberformat"),y=m===null?void 0:hp(m,r.options);y!==void 0&&(u.value=y);const N=e.getAttribute("data-sheets-value"),W=N===null?null:ph(N,y);h.t=W===null?da(c,y,ea):W;const D=e.getAttribute("data-sheets-formula");D?.startsWith("=")&&(h.f=D);const j=e.getAttribute("data-sheets-hyperlink"),U=j!==null?j:l.href,V=U===null?null:un(U);V!==null&&(h.link=V);const O=e.getAttribute("data-sheets-note");O!==null&&O!==""&&(h.note=O)}else{const m=o.get("mso-number-format"),y=m===void 0?void 0:Is(bs(ho(m)),r.options);y!==void 0&&(u.value=y),h.t=hh(e,c,y,r.separators);const N=e.getAttribute("x:fmla");N?.startsWith("=")&&(h.f=Ro(N,{row:t,col:n}));const W=l.href===null?null:un(l.href);W!==null&&(h.link=W)}return{cell:h,format:u}},Rs=(e,t,n)=>{const r=e.getAttribute(t);if(r===null)return 1;const o=/^\s*\+?(\d+)/.exec(r);if(o===null)return 1;const s=Number(o[1]);return s<1?1:s>n?n:s},gh=e=>{const t=/^(\d*\.?\d+)(px|pt)$/i.exec(e.trim());if(t===null)return null;const n=Number(t[1]);return t[2].toLowerCase()==="pt"?Math.round(n*4/3):Math.round(n)},wh=(e,t)=>{const n=e.getAttribute(t);if(n===null)return null;const r=/^\s*\+?(\d*\.?\d+)/.exec(n);return r===null?null:Math.round(Number(r[1]))},fa=(e,t)=>{const n=e.getAttribute("style"),r=n===null?null:So(n);if(r!==null){const s=r.get("display");if(s!==void 0&&s.toLowerCase()==="none")return 0;const l=r.get(t),c=l===void 0?null:gh(l);if(c!==null)return Math.min(c,an)}const o=wh(e,t);return o===null?null:Math.min(o,an)},Ch=(e,t)=>{const n=[],r=o=>{const s=fa(o,"width");for(let l=Rs(o,"span",Fs);l>0&&n.length<t;l-=1)n.push(s)};for(const o of Or(e)){if(n.length>=t)break;if(o.localName==="col")r(o);else if(o.localName==="colgroup")for(const s of Or(o))s.localName==="col"&&n.length<t&&r(s)}return n};function*Or(e){for(let t=e.firstElementChild;t!==null;t=t.nextElementSibling)yield t}function*bh(e){for(let t=e.firstChild;t!==null;t=t.nextSibling)yield t}function*yh(e){for(const t of["thead","tbody","tfoot"])for(const n of Or(e)){const r=n.localName;if(t==="tbody"&&r==="tr")yield n;else if(r===t)for(const o of Or(n))o.localName==="tr"&&(yield o)}}const Qo=()=>({t:""}),Rh=(e,t,n)=>{const r=$c(),o=[],s=[],l=[];let c=0;for(const W of yh(e)){const D=o.length,j=(D+1)*Math.max(c,1);if(j>n)return{outcome:"limit",cells:j};const U=[];for(let O=0;O<l.length;O+=1)l[O]>0&&(U[O]=Qo(),l[O]-=1);let V=0;for(const O of Or(W)){const T=O.localName;if(T!=="td"&&T!=="th")continue;for(;U[V]!==void 0;)V+=1;const P=Rs(O,"colspan",Fs),H=Rs(O,"rowspan",Sc),$=(D+1)*Math.max(c,V+P);if($>n)return{outcome:"limit",cells:$};const _=mh(O,D,V,t),x=r.intern(_.format);x!==void 0&&(_.cell.fmt=x),U[V]=_.cell;for(let g=1;g<P;g+=1)U[V+g]===void 0&&(U[V+g]=Qo());if(H>1)for(let g=0;g<P;g+=1){const p=H-1,C=V+g;l[C]=l[C]===void 0||l[C]<p?p:l[C]}V+=P}U.length>c&&(c=U.length),o.push(U),s.push(fa(W,"height"))}if(o.length===0||c===0)return{outcome:"none"};const u=o.map(W=>{const D=[];for(let j=0;j<c;j+=1){const U=W[j];D.push(U===void 0?Qo():U)}return D}),h=Ch(e,c),m=h.length===c&&h.every(W=>W!==null)?h.map(W=>W===null?0:W):void 0,y=s.every(W=>W!==null)?s.map(W=>W===null?0:W):void 0;return{outcome:"payload",payload:{v:1,rows:o.length,cols:c,clipId:Ms(),formats:[...r.entries],validations:[],cells:u,...m===void 0?{}:{colWidths:m},...y===void 0?{}:{rowHeights:y},wholeRows:!1,wholeCols:!1,conditionalFormats:[]}}},pa=(e,t,n,r)=>{if(!Number.isInteger(r)||r<=0)throw new RangeError(`[spreadsheet] parseHtmlTable requires a positive integer maxCells, received ${r}`);let o;try{o=new DOMParser().parseFromString(e,"text/html")}catch{return{outcome:"none"}}const s=o.querySelector("table");if(s===null)return{outcome:"none"};const l=Fp(o);return Rh(s,{kind:t,rules:l,options:n,separators:l.separators},r)},ke=(e,t)=>({startRow:Math.min(e.row,t.row),endRow:Math.max(e.row,t.row),startCol:Math.min(e.col,t.col),endCol:Math.max(e.col,t.col)}),kn=(e,t)=>t.row>=e.startRow&&t.row<=e.endRow&&t.col>=e.startCol&&t.col<=e.endCol,Ct=e=>({rows:e.endRow-e.startRow+1,cols:e.endCol-e.startCol+1}),zt=e=>e.reduce((t,n)=>t+Ct(n).rows*Ct(n).cols,0),nn=(e,t)=>{if(e.length===1){const r=e[0];for(let o=r.startRow;o<=r.endRow;o+=1)for(let s=r.startCol;s<=r.endCol;s+=1)t({row:o,col:s});return}const n=new Set;for(const r of e)for(let o=r.startRow;o<=r.endRow;o+=1)for(let s=r.startCol;s<=r.endCol;s+=1){const l=`${o}:${s}`;n.has(l)||(n.add(l),t({row:o,col:s}))}},dn=(e,t,n)=>{if(t<=0||n<=0)throw new RangeError(`[spreadsheet] clampCoord requires a non-empty grid, received ${t} x ${n}`);return{row:Math.min(Math.max(Math.trunc(e.row),0),t-1),col:Math.min(Math.max(Math.trunc(e.col),0),n-1)}},Vt=(e,t)=>e.row===t.row&&e.col===t.col,ha=(e,t)=>e===void 0?Il(void 0,void 0,t()):Il(e.align,e.value,e.align===void 0?t():""),ao=(e,t,n)=>{let r=null;return()=>(r===null&&(r=e.getCellText(t,n)),r)},Zn=(e,t,n)=>{if(e.getCellFormula!==void 0){const r=e.getCellFormula(t,n);if(r!==void 0){if(typeof r!="string"||!r.startsWith("="))throw new RangeError(`[spreadsheet] getCellFormula(${t}, ${n}) must return a string starting with "=", received ${JSON.stringify(r)}`);return{text:r,isFormula:!0}}}return{text:e.getCellText(t,n),isFormula:!1}},uo=e=>({format:e.getCellFormat!==void 0,note:e.getCellNote!==void 0,comments:e.getCellComments!==void 0,hyperlink:e.getCellHyperlink!==void 0,validation:e.getCellValidation!==void 0,cf:e.getConditionalFormats!==void 0,formula:e.getCellFormula!==void 0}),ma=e=>e.isCellReadOnly!==void 0,Je=(e,t,n)=>e.isCellReadOnly?.(t,n)===!0,vh=["rowCount","colCount","getCellText","applyEdits","findDataEdge","getCellFormat","getCellFormula","getCellNote","getCellComments","getCellHyperlink","getCellValidation","getConditionalFormats","isCellReadOnly","getCellAttributes","getRangeExtrema","evaluateFormula"],Sh=()=>!0,kh=e=>{const t=new WeakMap,n={};for(const r of vh)r!=="isCellReadOnly"&&Object.defineProperty(n,r,{enumerable:!0,get:()=>{const o=Reflect.get(e,r,e);if(typeof o!="function")return o;const s=t.get(o);if(s!==void 0)return s;const l=o.bind(e);return t.set(o,l),l}});return Object.defineProperty(n,"isCellReadOnly",{enumerable:!0,value:Sh}),n},Eh=/^data-[a-z0-9-]+$/,Oh=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Ah=(e,t,n)=>{if(e.getCellAttributes===void 0)return null;const r=e.getCellAttributes(t,n);if(r===null)return null;if(!Oh(r))throw new RangeError(`[spreadsheet] getCellAttributes must return a plain data-* record or null (got ${Object.prototype.toString.call(r)})`);for(const[o,s]of Object.entries(r)){if(!Eh.test(o))throw new RangeError(`[spreadsheet] getCellAttributes key must be a lowercase data-* name (got ${JSON.stringify(o)})`);if(o.startsWith("data-aqsp")||o.startsWith("data-aqvs")||o==="data-row"||o==="data-col")throw new RangeError(`[spreadsheet] getCellAttributes key ${JSON.stringify(o)} shadows a package- or engine-emitted cell attribute`);if(typeof s!="string")throw new RangeError(`[spreadsheet] getCellAttributes value for ${JSON.stringify(o)} must be a string (got ${typeof s})`)}return r},br=(e,t)=>{const n=e.isCellReadOnly;if(n===void 0)return!1;for(let r=t.startRow;r<=t.endRow;r+=1)for(let o=t.startCol;o<=t.endCol;o+=1)if(n(r,o))return!0;return!1},Bn=(e,t)=>{for(const n of t)if(br(e,n))return!0;return!1},xh=(e,t)=>{const n=e.length,r=e[0]?.length??0;if(n===0||r===0)return 0;const o=Ct(t);return!(o.rows===1&&o.cols===1)&&o.rows%n===0&&o.cols%r===0?o.rows*o.cols:n*r},vs=(e,t,n,r,o)=>{if(e.rows===0||e.cols===0)return null;const s=Ct(t),l=s.rows===1&&s.cols===1,c=!l&&s.rows%e.rows===0&&s.cols%e.cols===0,u=c?s.rows:e.rows,h=c?s.cols:e.cols,m=l?n:{row:t.startRow,col:t.startCol},y=Math.min(u,r-m.row),N=Math.min(h,o-m.col);return y<=0||N<=0?null:ke(m,{row:m.row+y-1,col:m.col+N-1})},ga=(e,t,n,r,o,s)=>{const l=e.length,c=e[0]?.length??0,u=vs({rows:l,cols:c},t,n,r,o);if(u===null)return[];const h={row:u.startRow,col:u.startCol},m=u.endRow-u.startRow+1,y=u.endCol-u.startCol+1,N=[];for(let W=0;W<m;W+=l){const D=[];for(let U=0;U<y;U+=c){const V={row:h.row+W,col:h.col+U};D.push(V),N.push(V)}const j=Math.min(l,m-W);for(let U=0;U<j;U+=1){const V=h.row+W+U,O=e[U];for(let T=0;T<D.length;T+=1){const P=T*c,H=Math.min(c,y-P);for(let $=0;$<H;$+=1)s(V,h.col+P+$,O[$],D[T])}}}return N},Th=(e,t,n,r,o)=>{const s=[];return ga(e,t,n,r,o,(l,c,u)=>{s.push({row:l,col:c,text:u})}),s},fi=(e,t,n,r,o,s)=>{const l=[],c=ga(e,t,n,r,o,(u,h,m,y)=>{const N=s(m,u,h,y);N!==null&&l.push({...N,row:u,col:h})});return{edits:l,tiles:c}},wa=(e,t)=>{const n=t.startRow<=e.startRow&&t.endRow>=e.endRow&&t.startCol<=e.startCol&&t.endCol>=e.endCol,r=t.startRow!==e.startRow||t.endRow!==e.endRow||t.startCol!==e.startCol||t.endCol!==e.endCol;if(!(n&&r))throw new RangeError(`[spreadsheet] expandFill requires a box strictly containing the source (source ${JSON.stringify(e)}, box ${JSON.stringify(t)})`)},$h=(e,t)=>{wa(e,t);const n=Ct(t),r=Ct(e),o=n.rows-r.rows,s=n.cols-r.cols,l=s>0?r.rows:Math.min(r.rows,o),c=o>0?r.cols:Math.min(r.cols,s);return n.rows*n.cols-r.rows*r.cols+l*c},Lh=(e,t)=>{if(!(t.startRow<=e.startRow&&t.endRow>=e.endRow&&t.startCol<=e.startCol&&t.endCol>=e.endCol))throw new RangeError(`[spreadsheet] fillExtensionRects requires a box containing the source (source ${JSON.stringify(e)}, box ${JSON.stringify(t)})`);const r=[];return t.startRow<e.startRow&&r.push(ke({row:t.startRow,col:t.startCol},{row:e.startRow-1,col:t.endCol})),t.endRow>e.endRow&&r.push(ke({row:e.endRow+1,col:t.startCol},{row:t.endRow,col:t.endCol})),t.startCol<e.startCol&&r.push(ke({row:e.startRow,col:t.startCol},{row:e.endRow,col:e.startCol-1})),t.endCol>e.endCol&&r.push(ke({row:e.startRow,col:e.endCol+1},{row:e.endRow,col:t.endCol})),r},Dh=(e,t,n,r)=>{wa(t,n);const o=Ct(t).rows,s=Ct(t).cols,l=[],c=new Map;for(let u=n.startRow;u<=n.endRow;u+=1){const h=t.startRow+((u-t.startRow)%o+o)%o,m=u>=t.startRow&&u<=t.endRow;for(let y=n.startCol;y<=n.endCol;y+=1){if(m&&y>=t.startCol&&y<=t.endCol)continue;const N=t.startCol+((y-t.startCol)%s+s)%s,W=h*2**21+N;let D=c.get(W);D===void 0&&(D={value:e(h,N),origin:{row:h,col:N}},c.set(W,D)),l.push(r(D.value,D.origin,{row:u,col:y}))}}return l},Ca=(e,t,n)=>{const r=Zn(e,t,n),o={text:r.text,isFormula:r.isFormula};if(e.getCellFormat!==void 0){const s=e.getCellFormat(t,n);o.format=s===void 0?null:xt(s)}if(e.getCellValidation!==void 0){const s=e.getCellValidation(t,n);o.validation=s===void 0?null:s}if(e.getCellHyperlink!==void 0){const s=Jn(e.getCellHyperlink(t,n));o.hyperlink=s===void 0?null:s}if(e.getCellNote!==void 0){const s=e.getCellNote(t,n);o.note=s===void 0?null:s}return o},ba=(e,t,n)=>{const r={row:n.row,col:n.col,text:e.isFormula?Yc(e.text,n.row-t.row,n.col-t.col):e.text};return e.format!==void 0&&(r.format=e.format),e.validation!==void 0&&(r.validation=e.validation),e.hyperlink!==void 0&&(r.hyperlink=e.hyperlink),e.note!==void 0&&(r.note=e.note),r},ko=["bold","italic","underline","strikethrough","clearFormatting","alignLeft","alignCenter","alignRight","formatNumber","formatTime","formatDate","formatCurrency","formatPercent","formatScientific","bordersOuter","bordersClear","borderTop","borderRight","borderBottom","borderLeft","insertLink","insertNote","insertComment","openHyperlink","openValidationList","pasteSpecial","fillDown","fillRight","fillSelection","insertDate","insertTime","hideRows","hideColumns","unhideRows","unhideColumns","increaseColumnWidth","decreaseColumnWidth","increaseRowHeight","decreaseRowHeight","autoFitColumnWidth","formatGeneral","bordersAll","pasteFormats","pasteFormulas","pasteAdd","pasteSubtract","pasteMultiply","pasteDivide","multiplyBy100","multiplyBy1000","divideBy100","divideBy1000","signReversal","fillColorYellow","fillColorBlue","fillColorGreen","fillColorRed","fillColorCustom1","fillColorCustom2","fillColorCustom3","fillColorCustom4","fillColorCustom5","fontColorYellow","fontColorBlue","fontColorGreen","fontColorRed","fontColorCustom1","fontColorCustom2","fontColorCustom3","fontColorCustom4","fontColorCustom5","toggleRowHighlight","toggleColumnHighlight","toggleBothHighlight","toggleIntersectionHighlight"],Mh=/^[A-Z]$/,zh=/^[A-Za-z]$/,Fh=/^Key([A-Z])$/,ya=new Set([...Array.from({length:10},(e,t)=>`Digit${t}`),...Array.from({length:10},(e,t)=>`Numpad${t}`),"NumpadAdd","NumpadSubtract","NumpadMultiply","NumpadDivide","NumpadDecimal","NumpadEnter",...Array.from({length:12},(e,t)=>`F${t+1}`),"Semicolon","Quote","Comma","Period","Slash","Backslash","BracketLeft","BracketRight","Backquote","Minus","Equal","IntlYen","IntlRo","IntlBackslash","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown","Enter","Escape","Space","Tab","Delete","Backspace","Insert","ContextMenu"]),Nh=e=>Mh.test(e)||ya.has(e),rn=e=>{const t=e.split("+");let n=0;const r=t[n]==="Ctrl";r&&(n+=1);const o=t[n]==="Alt";o&&(n+=1);const s=t[n]==="Shift";s&&(n+=1);const l=t[n];if(n!==t.length-1||l===void 0||!Nh(l))throw new RangeError(`[spreadsheet] shortcut ${JSON.stringify(e)} is not canonical (expected Ctrl+Alt+Shift+KEY with used modifiers only, KEY = A-Z or a code name such as Digit1 / Semicolon / F2)`);return{ctrl:r,alt:o,shift:s,key:l}},Ph=e=>`${e.ctrl?"Ctrl+":""}${e.alt?"Alt+":""}${e.shift?"Shift+":""}${e.key}`,Ra=e=>{if(zh.test(e.key))return e.key.toUpperCase();const t=Fh.exec(e.code);return t!==null?t[1]:ya.has(e.code)?e.code:null},pr=(e,t)=>e.ctrl!==(t.ctrlKey||t.metaKey)||e.alt!==t.altKey||e.shift!==t.shiftKey||e.alt&&t.getModifierState("AltGraph")?!1:Ra(t)===e.key,we=(e,t,n)=>({chord:e,column:t,rebindable:!1,note:n}),Se=(e,t,n,r)=>({chord:t,column:n,rebindable:!0,command:e,note:r}),_h=()=>{const e=[];for(const t of["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"])e.push(we(t,"both","move active (idle) / commit + move in replace mode, caret in edit mode, reference cursor while pointing")),e.push(we(`Shift+${t}`,"both","extend selection (idle) / commit + extend in replace mode, text selection in edit mode")),e.push(we(`Ctrl+${t}`,"both","data-edge jump (idle) / native word caret (editing), Ctrl reference cursor while pointing")),e.push(we(`Ctrl+Shift+${t}`,"both","extend to data edge (idle) / consume + no-op (editing)"));return e},qh=()=>{const e=[];for(const t of["Equal","Minus","Digit0","NumpadAdd","NumpadSubtract","Numpad0"])e.push(we(`Ctrl+Alt+${t}`,"both","zoom token space (root capture listener, produced-character matching — v0.3.3 contract)")),e.push(we(`Ctrl+Alt+Shift+${t}`,"both","zoom token space, Shift-independent (JIS `=` is Shift+Minus, AZERTY `0` is Shift+Digit0)"));return e},Lr=[..._h(),we("Home","idle","row start (first visible column)"),we("Ctrl+Home","idle","first visible cell"),we("Shift+Home","idle","extend to row start"),we("Ctrl+Shift+Home","idle","extend to first visible cell"),we("End","idle","row end (last visible column)"),we("Ctrl+End","idle","last visible cell"),we("Shift+End","idle","extend to row end"),we("Ctrl+Shift+End","idle","extend to last visible cell"),we("PageUp","both","page up (idle) / commit + page up (editing)"),we("PageDown","both","page down (idle) / commit + page down (editing)"),we("Shift+PageUp","idle","extend one page up"),we("Shift+PageDown","idle","extend one page down"),we("Ctrl+Shift+PageUp","idle","consume + no-op (sheet-switch class)"),we("Ctrl+Shift+PageDown","idle","consume + no-op (sheet-switch class)"),we("Tab","both","cycle right (idle) / commit + cycle right (editing)"),we("Shift+Tab","both","cycle left (idle) / commit + cycle left (editing)"),we("Enter","both","cycle down (idle) / commit + cycle down (editing)"),we("Shift+Enter","both","cycle up (idle) / commit + cycle up (editing)"),we("Alt+Enter","editing","newline at the caret (editing column only — coexists with the idle openHyperlink default)"),we("F2","both","start editing (idle) / toggle the pointing arm (editing)"),we("F4","editing","cycle the reference anchor under the caret (formula session)"),we("Delete","idle","clear every selected cell"),we("Backspace","idle","clear every selected cell"),we("Escape","both","abort drag > hide note tip > close rejected message > discard clip > hand off focus (idle) / cancel editing"),we("Ctrl+A","idle","select all"),we("Ctrl+Z","idle","undo request"),we("Ctrl+Y","idle","redo request"),we("Ctrl+Shift+Z","idle","redo request"),we("Shift+F10","idle","keyboard context menu"),we("ContextMenu","idle","keyboard context menu"),we("Ctrl+Space","idle","column bands"),we("Shift+Space","idle","row bands"),we("Ctrl+C","idle","native copy (ClipboardEvent path — never preventDefault)"),we("Ctrl+X","idle","native cut (ClipboardEvent path — never preventDefault)"),we("Ctrl+V","idle","native paste (ClipboardEvent path — never preventDefault)"),we("Ctrl+Shift+V","idle","pasteValues: arms the paste options, the native paste follows (not a command)"),{chord:"Ctrl+Alt+V",column:"idle",rebindable:!1,command:"pasteSpecial",note:"paste special (onPasteSpecialRequest / formats-only branch) — a command row that cannot be rebound"},...qh(),Se("bold","Ctrl+B","both","toggle bold"),Se("italic","Ctrl+I","both","toggle italic"),Se("underline","Ctrl+U","both","toggle underline"),Se("strikethrough","Alt+Shift+Digit5","both","toggle strikethrough"),Se("clearFormatting","Ctrl+Backslash","idle","clear formatting"),Se("clearFormatting","Ctrl+IntlYen","idle","clear formatting (JIS ¥ key)"),Se("clearFormatting","Ctrl+IntlRo","idle","clear formatting (JIS ろ key)"),Se("alignLeft","Ctrl+Shift+L","both","align left"),Se("alignCenter","Ctrl+Shift+E","both","align center"),Se("alignRight","Ctrl+Shift+R","both","align right"),Se("formatNumber","Ctrl+Shift+Digit1","both","number format"),Se("formatTime","Ctrl+Shift+Digit2","both","time format"),Se("formatDate","Ctrl+Shift+Digit3","both","date format"),Se("formatCurrency","Ctrl+Shift+Digit4","both","currency format"),Se("formatPercent","Ctrl+Shift+Digit5","both","percent format"),Se("formatScientific","Ctrl+Shift+Digit6","both","scientific format"),Se("bordersOuter","Alt+Shift+Digit7","idle","outer borders"),Se("bordersClear","Alt+Shift+Digit6","idle","clear borders"),Se("borderTop","Alt+Shift+Digit1","idle","top border"),Se("borderRight","Alt+Shift+Digit2","idle","right border"),Se("borderBottom","Alt+Shift+Digit3","idle","bottom border"),Se("borderLeft","Alt+Shift+Digit4","idle","left border"),Se("insertLink","Ctrl+K","idle","insert / edit hyperlink"),Se("insertNote","Shift+F2","idle","insert / edit note"),Se("insertComment","Ctrl+Alt+M","idle","insert comment"),Se("openHyperlink","Alt+Enter","idle","open the hyperlink (idle column — the editing Alt+Enter row is a different column)"),Se("openValidationList","Alt+ArrowDown","idle","open the validation list"),Se("fillDown","Ctrl+D","idle","fill down"),Se("fillRight","Ctrl+R","idle","fill right"),Se("fillSelection","Ctrl+Enter","both","fill the selection with the active / session text"),Se("insertDate","Ctrl+Semicolon","both","insert today's date (active cell / caret)"),Se("insertTime","Ctrl+Shift+Semicolon","both","insert the current time (active cell / caret)"),Se("hideRows","Ctrl+Alt+Digit9","idle","hide the selected rows"),Se("unhideRows","Ctrl+Shift+Digit9","idle","unhide rows"),Se("unhideColumns","Ctrl+Shift+Digit0","idle","unhide columns"),Se("increaseColumnWidth","Alt+Shift+ArrowRight","idle","widen the active column by one step (x 2^(1/4))"),Se("decreaseColumnWidth","Alt+Shift+ArrowLeft","idle","narrow the active column by one step (/ 2^(1/4), never below 1 px)"),Se("increaseRowHeight","Alt+Shift+ArrowDown","idle","make the active row taller by one step (x 2^(1/4))"),Se("decreaseRowHeight","Alt+Shift+ArrowUp","idle","make the active row shorter by one step (/ 2^(1/4), never below 1 px)"),Se("autoFitColumnWidth","Alt+Shift+Equal","idle","fit the active column to its content (the strip double-click)")],es=Object.freeze(["increaseColumnWidth","decreaseColumnWidth","increaseRowHeight","decreaseRowHeight","autoFitColumnWidth"]),pi=Object.freeze({Equal:"=",Minus:"-",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/",Backslash:"\\",BracketLeft:"[",BracketRight:"]",Backquote:"`",NumpadAdd:"+",NumpadSubtract:"-",NumpadMultiply:"*",NumpadDivide:"/",NumpadDecimal:".",NumpadEnter:"Enter"}),jh=e=>{const t=rn(e);if(t.key==="IntlYen"||t.key==="IntlRo"||t.key==="IntlBackslash")return null;const n=/^(?:Digit|Numpad)(\d)$/u.exec(t.key),r=n!==null?n[1]:t.key in pi?pi[t.key]:t.key;return`${t.ctrl?"Control+":""}${t.alt?"Alt+":""}${t.shift?"Shift+":""}${r}`},mo=(e,t)=>e.column==="both"||e.column===t,Ih=Array.from(new Set(Lr.filter(e=>!e.rebindable&&mo(e,"idle")).map(e=>e.chord))),Ws=new Set(Lr.filter(e=>e.command!==void 0&&mo(e,"editing")).map(e=>e.command)),Hh=new Set(Lr.filter(e=>e.command!==void 0&&!e.rebindable).map(e=>e.command)),va=e=>{const t={};for(const n of ko)t[n]=e(n);return t},Sa=va(e=>Lr.filter(t=>t.command===e).map(t=>t.chord)),Bh=e=>{const t=new Map;for(const n of ko){const r=e[n];if(r!=null)for(const o of r){const s=t.get(o);s===void 0?t.set(o,[n]):s.includes(n)||s.push(n)}}return t},Wh=e=>{const t=new Set(ko);for(const n of Object.keys(e)){if(!t.has(n))throw new RangeError(`[spreadsheet] shortcuts.${n} is not a SpreadsheetCommand`);const r=e[n];if(r!==void 0){if(Hh.has(n))throw new RangeError(`[spreadsheet] shortcuts.${n} is not rebindable`);if(r!==null){if(!Array.isArray(r))throw new RangeError(`[spreadsheet] shortcuts.${n} must be an array or null`);for(const o of r)if(typeof o!="string")throw new RangeError(`[spreadsheet] shortcuts.${n} must be an array of chord strings`)}}}},Vh=(e,t)=>{const n=rn(t);if(!(n.ctrl||n.alt||n.shift))throw new RangeError(`[spreadsheet] shortcut ${t} for ${e} has no modifier`);const r=Ws.has(e);for(const o of Lr)if(!(o.rebindable||o.command===e||o.chord!==t)&&(mo(o,"idle")||r&&mo(o,"editing")))throw new RangeError(`[spreadsheet] shortcut ${t} for ${e} is reserved by a built-in row (${o.column} column: ${o.note})`)},Yh=e=>{e!==void 0&&Wh(e);const t=va(r=>{const o=e===void 0?void 0:e[r];return o===void 0?Sa[r]:o===null?[]:o});for(const r of ko)for(const o of t[r])Vh(r,o);const n=new Map;for(const[r,o]of Bh(t)){if(o.length>1)throw new RangeError(`[spreadsheet] shortcut ${r} bound to ${o.slice(0,-1).join(", ")} and ${o[o.length-1]}`);n.set(r,o[0])}return n},hi=(e,t)=>{const n=Ra(t);if(n===null)return null;const r=t.altKey;if(r&&t.getModifierState("AltGraph"))return null;const o=e.get(Ph({ctrl:t.ctrlKey||t.metaKey,alt:r,shift:t.shiftKey,key:n}));return o===void 0?null:o},Vs=["sinkAriaLabel","rootAriaLabel","noteTitle","noteSave","noteEscapeHint","noteRejectedHint","noteViewerHint","commentTitle","commentReply","commentPost","commentCount","linkTitle","linkTextField","linkUrlField","linkOpen","linkSave","listTitle","listEmpty","listMore","messageTitle","popoverClose"],mi=[...st.VIRTUAL_SCROLL_LABEL_KEYS,...Vs],Ss=Object.freeze({en:Object.freeze({sinkAriaLabel:"Spreadsheet grid. Press Escape to move focus out of the grid.",rootAriaLabel:"Spreadsheet",noteTitle:"Note",noteSave:"Save",noteEscapeHint:"Escape saves and closes",noteRejectedHint:"The note was rejected. Press Ctrl+Enter to retry or Escape to close without saving",noteViewerHint:"Escape closes without saving",commentTitle:"Comments",commentReply:"Reply",commentPost:"Post",commentCount:e=>e===1?"1 comment":`${e} comments`,linkTitle:"Link",linkTextField:"Text",linkUrlField:"URL",linkOpen:"Open",linkSave:"Save",listTitle:"Choose a value",listEmpty:"No matching values",listMore:e=>e===1?"1 more value — keep typing to narrow":`${e} more values — keep typing to narrow`,messageTitle:"Data validation",popoverClose:"Close"}),ja:Object.freeze({sinkAriaLabel:"スプレッドシートのグリッド。Escape キーでグリッドの外へフォーカスを移動します。",rootAriaLabel:"スプレッドシート",noteTitle:"メモ",noteSave:"保存",noteEscapeHint:"Escape で保存して閉じます",noteRejectedHint:"メモは拒否されました。Ctrl+Enter で再試行、Escape で保存せずに閉じます",noteViewerHint:"Escape で保存せずに閉じます",commentTitle:"コメント",commentReply:"返信",commentPost:"投稿",commentCount:e=>`${e} 件のコメント`,linkTitle:"リンク",linkTextField:"表示テキスト",linkUrlField:"URL",linkOpen:"開く",linkSave:"保存",listTitle:"値を選択",listEmpty:"一致する値がありません",listMore:e=>`ほかに ${e} 件 — 入力して絞り込んでください`,messageTitle:"データの入力規則",popoverClose:"閉じる"})}),ka=Object.freeze({en:Object.freeze({...st.VIRTUAL_SCROLL_LABEL_CATALOGS.en,...Ss.en}),ja:Object.freeze({...st.VIRTUAL_SCROLL_LABEL_CATALOGS.ja,...Ss.ja})}),Rn=e=>typeof e=="string"?JSON.stringify(e):e===null?"null":typeof e,gi=e=>e==="commentCount"||e==="listMore",Kh=e=>{const t=e.sinkAriaLabel;if(typeof t!="string"||!t.includes("Escape"))throw new RangeError(`[spreadsheet] labels.sinkAriaLabel must be a string mentioning "Escape" (WCAG 2.1.2 escape advisement, spec 00 §10-4); got ${Rn(t)}`);for(const n of Vs){const r=e[n];if(!(gi(n)&&typeof r=="function")&&(typeof r!="string"||r.trim()==="")){const o=gi(n)?"a non-blank string or a function":"a non-blank string";throw new RangeError(`[spreadsheet] labels.${n} must be ${o}; got ${Rn(r)}`)}}},Uh=e=>{const t={};let n=!1;for(const r of st.VIRTUAL_SCROLL_LABEL_KEYS){const o=Object.hasOwn(e,r)?e[r]:void 0;o!==void 0&&(t[r]=o,n=!0)}return n?t:void 0},Xh=(e,t,n)=>{e[t]=n},Ea=(e,t)=>{const n=st.resolveVirtualScrollLocale(e);if(t===void 0)return ka[n];if(t===null||typeof t!="object")throw new RangeError(`[spreadsheet] labels must be an object; got ${Rn(t)}`);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new RangeError(`[spreadsheet] labels must be a plain object (prototype Object.prototype or null); got ${Array.isArray(t)?"an array":"an object with a non-plain prototype"}`);for(const l of Object.keys(t))if(!mi.includes(l))throw new RangeError(`[spreadsheet] labels.${l} is not a known label key; expected one of ${mi.join(", ")}`);const s={...st.resolveVirtualScrollLabels(n,Uh(t)),...Ss[n]};for(const l of Vs){const c=Object.hasOwn(t,l)?t[l]:void 0;c!==void 0&&Xh(s,l,c)}return Kh(s),Object.freeze(s)},Gh=e=>{const t={};for(const n of st.VIRTUAL_SCROLL_LABEL_KEYS)t[n]=e[n];return Object.freeze(t)},qe=(e,t,n)=>{const r=e[t];if(typeof r=="function"){if(n===void 0)throw new RangeError(`[spreadsheet] labels.${t} is count-aware; resolveLabel needs n`);return r(n)}return r},wi={gt:"greater than",gte:"greater than or equal to",lt:"less than",lte:"less than or equal to"},Zh={gt:"after",gte:"on or after",lt:"before",lte:"on or before"},Jh=(e,t,n,r)=>{switch(e){case"gt":case"gte":case"lt":case"lte":return`${r[e]} ${t}`;case"eq":return`equal to ${t}`;case"neq":return`not equal to ${t}`;case"between":return`between ${t} and ${n}`;default:return`not between ${t} and ${n}`}},ts=(e,t)=>{const n=r=>(o,s)=>`${e} ${Jh(r,o,s,t)}.`;return Object.freeze({gt:n("gt"),gte:n("gte"),lt:n("lt"),lte:n("lte"),eq:n("eq"),neq:n("neq"),between:n("between"),notBetween:n("notBetween")})},Qh=Object.freeze({list:"Value must be one of the list items.",number:ts("Value must be a number",wi),textLength:ts("Text length must be",wi),date:ts("Value must be a date",Zh),text:Object.freeze({contains:e=>`Value must contain "${e}".`,notContains:e=>`Value must not contain "${e}".`,startsWith:e=>`Value must start with "${e}".`,endsWith:e=>`Value must end with "${e}".`,isEmail:"Value must be a valid email address.",isUrl:"Value must be a valid URL."}),checkbox:(e,t)=>`Value must be "${e}" or "${t}".`,custom:e=>`Value does not satisfy the formula ${e}.`}),em=Object.freeze({list:"リストの項目のいずれかを入力してください。",number:Object.freeze({gt:e=>`${e} より大きい数値を入力してください。`,gte:e=>`${e} 以上の数値を入力してください。`,lt:e=>`${e} より小さい数値を入力してください。`,lte:e=>`${e} 以下の数値を入力してください。`,eq:e=>`${e} に等しい数値を入力してください。`,neq:e=>`${e} 以外の数値を入力してください。`,between:(e,t)=>`${e} から ${t} までの数値を入力してください。`,notBetween:(e,t)=>`${e} から ${t} までの範囲外の数値を入力してください。`}),textLength:Object.freeze({gt:e=>`${e} 文字より長いテキストを入力してください。`,gte:e=>`${e} 文字以上のテキストを入力してください。`,lt:e=>`${e} 文字より短いテキストを入力してください。`,lte:e=>`${e} 文字以下のテキストを入力してください。`,eq:e=>`${e} 文字のテキストを入力してください。`,neq:e=>`${e} 文字以外の長さのテキストを入力してください。`,between:(e,t)=>`${e} 文字から ${t} 文字までのテキストを入力してください。`,notBetween:(e,t)=>`${e} 文字から ${t} 文字までの範囲外の長さのテキストを入力してください。`}),date:Object.freeze({gt:e=>`${e} より後の日付を入力してください。`,gte:e=>`${e} 以降の日付を入力してください。`,lt:e=>`${e} より前の日付を入力してください。`,lte:e=>`${e} 以前の日付を入力してください。`,eq:e=>`${e} の日付を入力してください。`,neq:e=>`${e} 以外の日付を入力してください。`,between:(e,t)=>`${e} から ${t} までの日付を入力してください。`,notBetween:(e,t)=>`${e} から ${t} までの範囲外の日付を入力してください。`}),text:Object.freeze({contains:e=>`「${e}」を含む値を入力してください。`,notContains:e=>`「${e}」を含まない値を入力してください。`,startsWith:e=>`「${e}」で始まる値を入力してください。`,endsWith:e=>`「${e}」で終わる値を入力してください。`,isEmail:"有効なメールアドレスを入力してください。",isUrl:"有効な URL を入力してください。"}),checkbox:(e,t)=>`「${e}」または「${t}」を入力してください。`,custom:e=>`数式 ${e} を満たす値を入力してください。`}),ns=Object.freeze({en:Qh,ja:em}),tm=Object.freeze({ok:!0}),nm="TRUE",rm="FALSE",om=new Set(["gt","gte","lt","lte","eq","neq","between","notBetween"]),sm=new Set(["contains","notContains","startsWith","endsWith","isEmail","isUrl"]),lm=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d{1,4})?$/,im=/^(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/,cm=/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/,Ci=e=>{const t=e.trim();if(!(lm.test(t)&&Number.isFinite(Number(t))))return null;const n=t.startsWith("-"),r=t.replace(/^[+-]/,""),o=r.search(/[eE]/),s=o<0?r:r.slice(0,o),l=o<0?0:Number(r.slice(o+1)),c=s.indexOf("."),u=c<0?s:s.slice(0,c),h=c<0?"":s.slice(c+1),m=u+h,y=m.search(/[^0]/);return y<0?{sign:0,digits:"",point:0}:{sign:n?-1:1,digits:m.slice(y).replace(/0+$/,""),point:u.length+l-y}},am=e=>e===1?-1:e===-1?1:0,um=(e,t)=>{if(e.sign!==t.sign)return e.sign<t.sign?-1:1;if(e.sign===0)return 0;const n=e.point!==t.point?e.point<t.point?-1:1:e.digits===t.digits?0:e.digits<t.digits?-1:1;return e.sign===1?n:am(n)},dm=(e,t)=>{switch(t){case 2:return e%4===0&&e%100!==0||e%400===0?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}},bi=e=>{const t=im.exec(e.trim());if(t===null)return null;const n=Number(t[1]),r=Number(t[3]),o=Number(t[4]),s=t[5]===void 0?0:Number(t[5]),l=t[6]===void 0?0:Number(t[6]),c=t[7]===void 0?0:Number(t[7]);return r<1||r>12||o<1||o>dm(n,r)||s>23||l>59||c>59?null:{year:n,month:r,day:o,hour:s,minute:l,second:c}},fm=(e,t)=>{const n=[e.year,e.month,e.day,e.hour,e.minute,e.second],r=[t.year,t.month,t.day,t.hour,t.minute,t.second];for(let o=0;o<n.length;o+=1)if(n[o]!==r[o])return n[o]<r[o]?-1:1;return 0},pm=(e,t)=>e<t?-1:e>t?1:0,hm=e=>e==="between"||e==="notBetween",mm=(e,t,n,r)=>{const o=r(t);if(o===null)return null;if(!hm(e))return{a:o,b:null};const s=n===void 0?null:r(n);return s===null?null:{a:o,b:s}},gm=(e,t,n)=>{switch(e){case"gt":return t===1;case"gte":return t!==-1;case"lt":return t===-1;case"lte":return t!==1;case"eq":return t===0;case"neq":return t!==0;case"between":return t!==-1&&n!==1;default:return t===-1||n===1}},rs=(e,t,n,r,o,s)=>{const l=mm(e,t,n,r);return l===null?!0:o===null?!1:gm(e,s(o,l.a),l.b===null?0:s(o,l.b))},wm=e=>Number.isFinite(e)?e:null,Cm=e=>{let t=0;for(const n of e)t+=1;return t},bm=e=>URL.canParse(e)&&/^https?:$/.test(new URL(e).protocol),ym=(e,t)=>{switch(e.op){case"isEmail":return cm.test(t);case"isUrl":return bm(t)}if(e.value===void 0)return!0;switch(e.op){case"contains":return t.includes(e.value);case"notContains":return!t.includes(e.value);case"startsWith":return t.startsWith(e.value);default:return t.endsWith(e.value)}},Rm=e=>e===!0||typeof e=="number"&&Number.isFinite(e)&&e!==0,Oa=e=>({checked:e.checked===void 0?nm:e.checked,unchecked:e.unchecked===void 0?rm:e.unchecked}),vm=e=>{switch(e.type){case"list":case"checkbox":case"custom":return;case"number":case"textLength":case"date":if(!om.has(e.op))throw new RangeError(`[spreadsheet] unknown data-validation op ${Rn(e.op)} for type "${e.type}"`);return;case"text":if(!sm.has(e.op))throw new RangeError(`[spreadsheet] unknown data-validation op ${Rn(e.op)} for type "text"`);return;default:throw new RangeError(`[spreadsheet] unknown data-validation rule type ${Rn(e.type)}`)}},Sm=(e,t,n)=>{switch(e.type){case"list":return Om(e).has(t);case"number":return rs(e.op,e.a,e.b,Ci,Ci(t),um);case"textLength":return rs(e.op,e.a,e.b,wm,Cm(t),pm);case"date":return rs(e.op,e.a,e.b,bi,bi(t),fm);case"text":return ym(e,t);case"checkbox":{const r=Oa(e);return t===r.checked||t===r.unchecked}default:return n===void 0||Rm(n(e.formula))}},Aa=(e,t,n)=>(vm(e),t===""||Sm(e,t,n)),yi=e=>e===void 0?void 0:e.trim(),km=(e,t)=>{switch(e.type){case"list":return t.list;case"number":return t.number[e.op](e.a.trim(),yi(e.b));case"textLength":return t.textLength[e.op](String(e.a),e.b===void 0?void 0:String(e.b));case"date":return t.date[e.op](e.a.trim(),yi(e.b));case"text":return Em(e,t.text);case"checkbox":{const n=Oa(e);return t.checkbox(n.checked,n.unchecked)}default:return t.custom(e.formula)}},Em=(e,t)=>{switch(e.op){case"isEmail":return t.isEmail;case"isUrl":return t.isUrl;default:return t[e.op](e.value)}},Ri=new WeakMap,Om=e=>{const t=Ri.get(e);if(t!==void 0)return t;const n=new Set(e.values);return Ri.set(e,n),n},xa=(e,t,n,r)=>{if(typeof n!="string"||!Object.hasOwn(ns,n)){const o=Object.keys(ns).map(s=>JSON.stringify(s)).join(", ");throw new RangeError(`[spreadsheet] validateCellText locale must be one of ${o}; got ${Rn(n)}`)}return Aa(e,t,r)?tm:{ok:!1,message:e.errorMessage===void 0?km(e,ns[n]):e.errorMessage}},Am=e=>e.type!=="custom",xm=(e,t)=>Am(e)&&!Aa(e,t,void 0),Ta=(e,t)=>t<=0||e.count===0?0:t>=e.count?e.totalSize():e.offsetOf(t),$a=(e,t)=>t<=0||e.count===0?0:t>=e.count?e.totalSize():e.totalSize()-e.offsetOf(e.count-t),La=(e,t,{scroll:n,frozenCount:r,trailingCount:o,extent:s})=>t<r?e.offsetOf(t):o>0&&s>0&&t>=e.count-o?s-(e.totalSize()-e.offsetOf(t)):e.offsetOf(t)-n,Da=(e,t,{scroll:n,frozenSize:r,trailingSize:o,extent:s})=>r>0&&t<r?e.indexAt(t):o>0&&s>0&&t>=s-o?e.indexAt(e.totalSize()-(s-t)):e.indexAt(t+n),Ma=(e,t)=>Ta(e,t),za=(e,t)=>Ta(e,t),Fa=(e,t)=>$a(e,t),Na=(e,t)=>$a(e,t),vn=(e,t,n)=>La(e,t,n),Sn=(e,t,n)=>La(e,t,n),Dr=(e,t,n)=>Da(e,t,n),Mr=(e,t,n)=>Da(e,t,n),Tm=Object.freeze({cols:0,width:0,rows:0,height:0,trailingCols:0,trailingRows:0,trailingWidth:0,trailingHeight:0,trailingVisibleWidth:0,trailingVisibleHeight:0}),Mt=1,yr=3,Xr=e=>`${-Math.min(yr,Math.max(0,Math.floor(e)))}px`,$m=(e,t,n)=>{const r=Math.min(e.endRow,t-1),o=Math.min(e.endCol,n-1);return e.startRow>r||e.startCol>o?null:{startRow:e.startRow,startCol:e.startCol,endRow:r,endCol:o}},vi=(e,t,n,r)=>e==="m"?t:e==="s"?Math.max(0,t-n-r):null,Si=(e,t)=>t===null?e:Math.min(e,t),ki=e=>e===null?"100%":`min(100%, ${e}px)`,Ei=e=>e===null?"0px":`max(0px, calc(100% - ${e}px))`,Oi=(e,t,n,r)=>{switch(e){case"f":return[0,n-1];case"s":return[n,t-r-1];case"t":return[t-r,t-1];case"m":return[0,t-1]}},Ai=Object.freeze([0,-1]),xi=(e,t,n,r,o,s,l)=>{if(l<=0||r<n||t<n||e>r)return null;const c=-l*Mt,u=l*(1+Mt),h=e>=n,m=t<=r,y=h?o:c,N=m?s:u;return N<=c||y>=u?null:{near:Math.max(y,c),far:Math.min(N,u),nearOpen:!h||y<c,farOpen:!m||N>u}},Lm=Object.freeze(["top","right","bottom","left"]),Dm=(e,t)=>(t.nearOpen?1:0)|(e.farOpen?2:0)|(t.farOpen?4:0)|(e.nearOpen?8:0),Mm=e=>Lm.filter((t,n)=>(e&1<<n)!==0).join(" "),Pa=Object.freeze({row:"#0084FF",column:"#42FF4F",intersection:"#E1FF00",opacity:.2}),zm=16,Fm=450,Nm=e=>e>4?Math.floor(Fm/(5*e)):zm,hr=(e,t)=>{const n=document.createElement("div");return n.className="aqsp-band",n.setAttribute("data-aqsp-band",e),t!==null&&n.setAttribute("data-aqsp-band-edge",t),n.style.display="none",n},Ti=()=>({rowLeft:hr("row","left"),rowRight:hr("row","right"),colAbove:hr("column","above"),colBelow:hr("column","below"),cross:hr("intersection",null),last:{rowShown:!1,colShown:!1,crossShown:!1,crossTint:"intersection",rowHeight:-1,colWidth:-1,crossWidth:-1,crossHeight:-1,rowLeftTransform:"",rowRightTransform:"",colAboveTransform:"",colBelowTransform:"",crossTransform:""}}),ks=e=>[e.rowLeft,e.rowRight,e.colAbove,e.colBelow,e.cross],Gr=(e,t,n)=>{const r=`${t}px`,o=`${n}px`;e.rowLeft.style.width=r,e.rowRight.style.width=r,e.colAbove.style.height=o,e.colBelow.style.height=o},Zr=(e,t)=>Math.min(Math.max(e,0),t),$i="inset(100%)",Yn=(e,t)=>{for(const n of e)n.style.display=t?"block":"none"},Pm=(e,t,n,r,o)=>{const s=e.last,l=r.row&&!o;if(l!==s.rowShown&&(s.rowShown=l,Yn([e.rowLeft,e.rowRight],l)),l){if(t.height!==s.rowHeight){s.rowHeight=t.height;const N=`${t.height}px`;e.rowLeft.style.height=N,e.rowRight.style.height=N}const m=`translate(${Zr(t.left,n.clampWidth)-n.clampWidth}px, ${t.top}px)`;m!==s.rowLeftTransform&&(s.rowLeftTransform=m,e.rowLeft.style.transform=m);const y=`translate(${Zr(t.left+t.width,n.clampWidth)}px, ${t.top}px)`;y!==s.rowRightTransform&&(s.rowRightTransform=y,e.rowRight.style.transform=y)}const c=r.column&&!o;if(c!==s.colShown&&(s.colShown=c,Yn([e.colAbove,e.colBelow],c)),c){if(t.width!==s.colWidth){s.colWidth=t.width;const N=`${t.width}px`;e.colAbove.style.width=N,e.colBelow.style.width=N}const m=`translate(${t.left}px, ${Zr(t.top,n.clampHeight)-n.clampHeight}px)`;m!==s.colAboveTransform&&(s.colAboveTransform=m,e.colAbove.style.transform=m);const y=`translate(${t.left}px, ${Zr(t.top+t.height,n.clampHeight)}px)`;y!==s.colBelowTransform&&(s.colBelowTransform=y,e.colBelow.style.transform=y)}const u=r.intersection?"intersection":l!==c?l?"row":"column":null,h=u!==null;if(h!==s.crossShown&&(s.crossShown=h,Yn([e.cross],h)),u!==null){u!==s.crossTint&&(s.crossTint=u,e.cross.style.background=u==="intersection"?"":`var(--_aqsp-band-${u})`),(t.width!==s.crossWidth||t.height!==s.crossHeight)&&(s.crossWidth=t.width,s.crossHeight=t.height,e.cross.style.width=`${t.width}px`,e.cross.style.height=`${t.height}px`);const m=`translate(${t.left}px, ${t.top}px)`;m!==s.crossTransform&&(s.crossTransform=m,e.cross.style.transform=m)}},Li=e=>{const t=e.last;t.rowShown&&(t.rowShown=!1,Yn([e.rowLeft,e.rowRight],!1)),t.colShown&&(t.colShown=!1,Yn([e.colAbove,e.colBelow],!1)),t.crossShown&&(t.crossShown=!1,Yn([e.cross],!1))},Jr=e=>{for(const t of ks(e))t.remove()},_m=(e,t)=>{const n=e-1-t.lineBoxPx;return t.verticalAlign==="top"?0:t.verticalAlign==="bottom"?Math.max(0,n):Math.max(0,n/2)},qm=Object.freeze([]),Di=e=>{const t=e.nearOpen?0:e.near;return e.farOpen?{start:`${t}px`,end:"0px",size:""}:{start:`${t}px`,end:"",size:`${e.far-t}px`}},Mi=e=>e.chrome[0]??e.active,zi=e=>{e.chrome.length=0;for(const t of e.dividerSlots)t!==null&&e.chrome.push(t);e.frame!==null&&e.chrome.push(e.frame.node)},jm={left:"0px",right:"0px",width:""},Im={top:"0px",bottom:"0px",height:""},Fi=()=>({container:null,active:null,dragRect:null,marquee:null,fillPreview:null,resizeGuide:null,fillPool:[],bandPool:[],dragBand:null,bandClampWidth:-1,bandClampHeight:-1,dividerSlots:[null,null,null,null],dividerShown:[!1,!1,!1,!1],dividerEnd:["0px","0px","0px","0px"],frame:null,bandClip:null,bandClipWidth:"",bandClipHeight:"",chrome:[]}),Ni=["mm","mf","ms","mt","fm","ff","fs","ft","sm","sf","ss","st","tm","tf","ts","tt"],Pi=6,Hm=({rowAxis:e,colAxis:t,handleRef:n,sinkRef:r,getSelection:o,editing:s,virtualKeyboard:l,repaintRef:c,dragFrameRef:u,getClip:h,getIsDraggingAny:m,getIsFillDragging:y,fillFrameRef:N,resizeGuideFrameRef:W,fillHandleNodeRef:D,enableFillHandle:j,frozenCols:U,frozenRows:V,trailingCols:O,trailingRows:T,sinkAriaLabel:P,sinkReadOnly:H,sinkKeyShortcuts:$,onSinkMouseDown:_,editPaintRef:x,highlightRef:g,frameRange:p,highlightColors:C,popoverAnchors:v,interactiveAnchorRef:k,tipAnchorRef:b})=>{const R=i.useRef(null),a=i.useRef(p);a.current=p;const f=p!==void 0,E=i.useRef(null),d=i.useRef(null),L=i.useRef(new Map(Ni.map(S=>[S,Fi()]))),A=i.useCallback(S=>{const F=L.current.get(S);if(F!==void 0)return F;const K=Fi();return L.current.set(S,K),K},[]),M=i.useCallback((S,F,K)=>{if(S===null)return;const z=S.style;z.left!==F.left&&(z.left=F.left),z.right!==F.right&&(z.right=F.right),z.width!==F.width&&(z.width=F.width),z.top!==K.top&&(z.top=K.top),z.bottom!==K.bottom&&(z.bottom=K.bottom),z.height!==K.height&&(z.height=K.height)},[]),B=i.useCallback((S,F,K)=>{if(!(S.bandClampWidth===F&&S.bandClampHeight===K)){S.bandClampWidth=F,S.bandClampHeight=K;for(const z of S.bandPool)Gr(z,F,K);S.dragBand!==null&&Gr(S.dragBand,F,K)}},[]),I=i.useRef({rowAxis:e,colAxis:t});I.current={rowAxis:e,colAxis:t};const X=i.useCallback((S,F,K)=>{const z=S.dividerSlots[F];z===null||S.dividerShown[F]===K||(S.dividerShown[F]=K,z.style.display=K?"":"none")},[]),G=i.useCallback((S,F,K)=>{const z=S.bandClip;z!==null&&(S.bandClipWidth!==F&&(S.bandClipWidth=F,z.style.width=F),S.bandClipHeight!==K&&(S.bandClipHeight=K,z.style.height=K))},[]),J=i.useCallback((S,F,K)=>{const z=S.dividerSlots[F];z===null||S.dividerEnd[F]===K||(S.dividerEnd[F]=K,F<2?z.style.bottom=K:z.style.right=K)},[]),ne=i.useRef({x:0,y:0}),ie=i.useRef(null),le=i.useCallback((S,F)=>{const K=n.current,z=K?.getFrozenSize()??Tm,Q=K?.getViewportSize(),ee=Q?.width??-1,re=Q?.height??-1,ue=ne.current;ue.x=S,ue.y=F;const be=a.current!==void 0,Te=I.current,_e=be?Te.rowAxis.count:-1,de=be?Te.colAxis.count:-1,Le=be?Te.rowAxis.totalSize():-1,fe=be?Te.colAxis.totalSize():-1;let se=ie.current;if(se===null||se.framed!==be||se.rowCount!==_e||se.colCount!==de||se.rowsTotal!==Le||se.colsTotal!==fe||se.frozenCols!==z.cols||se.frozenWidth!==z.width||se.frozenRows!==z.rows||se.frozenHeight!==z.height||se.trailingCols!==z.trailingCols||se.trailingWidth!==z.trailingWidth||se.trailingVisibleWidth!==z.trailingVisibleWidth||se.trailingRows!==z.trailingRows||se.trailingHeight!==z.trailingHeight||se.trailingVisibleHeight!==z.trailingVisibleHeight||se.bodyWidth!==ee||se.bodyHeight!==re){const ae=z.trailingVisibleWidth,Oe=z.trailingVisibleHeight,Be=z.cols<=0&&z.trailingCols<=0?[{kind:"m",map:Ee=>Ee-ue.x,clamp:ee,style:jm,seamLead:!1,seamTrail:!1}]:[...z.cols>0?[{kind:"f",map:Ee=>Ee,clamp:z.width,style:{left:"0px",width:`${z.width}px`,right:""},seamLead:!1,seamTrail:!0}]:[],{kind:"s",map:Ee=>Ee-ue.x-z.width,clamp:Math.max(0,ee-z.width-ae),style:{left:`${z.width}px`,right:`${ae}px`,width:""},seamLead:z.cols>0,seamTrail:z.trailingCols>0},...z.trailingCols>0?[{kind:"t",map:Ee=>Ee-I.current.colAxis.totalSize()+ae,clamp:ae,style:{left:"",right:"0px",width:`${ae}px`},seamLead:!0,seamTrail:!1}]:[]],Xe=z.rows<=0&&z.trailingRows<=0?[{kind:"m",map:Ee=>Ee-ue.y,clamp:re,style:Im,seamLead:!1,seamTrail:!1}]:[...z.rows>0?[{kind:"f",map:Ee=>Ee,clamp:z.height,style:{top:"0px",height:`${z.height}px`,bottom:""},seamLead:!1,seamTrail:!0}]:[],{kind:"s",map:Ee=>Ee-ue.y-z.height,clamp:Math.max(0,re-z.height-Oe),style:{top:`${z.height}px`,bottom:`${Oe}px`,height:""},seamLead:z.rows>0,seamTrail:z.trailingRows>0},...z.trailingRows>0?[{kind:"t",map:Ee=>Ee-I.current.rowAxis.totalSize()+Oe,clamp:Oe,style:{top:"",bottom:"0px",height:`${Oe}px`},seamLead:!0,seamTrail:!1}]:[]],ct=[];for(const Ee of Be){const ht=be?vi(Ee.kind,fe,z.width,z.trailingWidth):null,[Ve,We]=be?Oi(Ee.kind,de,z.cols,z.trailingCols):Ai;for(const tt of Xe){const $n=be?vi(tt.kind,Le,z.height,z.trailingHeight):null,[Zt,sr]=be?Oi(tt.kind,_e,z.rows,z.trailingRows):Ai;ct.push({nodes:A(`${Ee.kind}${tt.kind}`),xKind:Ee.kind,yKind:tt.kind,mapX:Ee.map,clampWidth:Ee.clamp,xStyle:Ee.style,xSeamLead:Ee.seamLead,xSeamTrail:Ee.seamTrail,xFirst:Ve,xLast:We,mapY:tt.map,clampHeight:tt.clamp,yStyle:tt.style,ySeamLead:tt.seamLead,ySeamTrail:tt.seamTrail,yFirst:Zt,yLast:sr,cells:{clampWidth:Si(Ee.clamp,ht),clampHeight:Si(tt.clamp,$n)},xCells:ht,yCells:$n})}}se={frozenCols:z.cols,frozenWidth:z.width,frozenRows:z.rows,frozenHeight:z.height,trailingCols:z.trailingCols,trailingWidth:z.trailingWidth,trailingVisibleWidth:z.trailingVisibleWidth,trailingRows:z.trailingRows,trailingHeight:z.trailingHeight,trailingVisibleHeight:z.trailingVisibleHeight,bodyWidth:ee,bodyHeight:re,framed:be,rowCount:_e,colCount:de,rowsTotal:Le,colsTotal:fe,ctxs:ct},ie.current=se}const ye=z.width>0,Re=z.trailingWidth>0,me=z.height>0,et=z.trailingHeight>0;for(const ae of se.ctxs){M(ae.nodes.container,ae.xStyle,ae.yStyle),B(ae.nodes,ae.clampWidth,ae.clampHeight),X(ae.nodes,0,ye),X(ae.nodes,1,Re),X(ae.nodes,2,me),X(ae.nodes,3,et);const Oe=Ei(ae.yCells),Be=Ei(ae.xCells);J(ae.nodes,0,Oe),J(ae.nodes,1,Oe),J(ae.nodes,2,Be),J(ae.nodes,3,Be),G(ae.nodes,ki(ae.xCells),ki(ae.yCells))}return se.ctxs},[n,A,M,B,X,J,G]),Ae=i.useCallback((S,F,K)=>{S.dividerSlots[F]=K,S.dividerShown[F]=!1,S.dividerEnd[F]="0px",zi(S)},[]),ze=i.useCallback((S,F)=>{S.frame=F===null?null:{node:F,last:{shown:!1,left:"",top:"",right:"",bottom:"",width:"",height:"",open:-1}},zi(S)},[]),Ne=i.useCallback((S,F)=>{for(const z of S.bandPool)Jr(z);S.bandPool.length=0,S.dragBand!==null&&(Jr(S.dragBand),S.dragBand=null),S.bandClampWidth=-1,S.bandClampHeight=-1,S.bandClip=F,S.bandClipWidth="",S.bandClipHeight="";const K=F===null?null:F.parentElement;F!==null&&K!==null&&K.firstChild!==F&&K.insertBefore(F,K.firstChild)},[]),Ie=i.useCallback(S=>{const F=()=>A(S);return{container:K=>{const z=F();z.container=K,K===null&&(z.fillPool.length=0,z.bandPool.length=0,z.dragBand=null,z.bandClampWidth=-1,z.bandClampHeight=-1)},dividerXLeading:K=>Ae(F(),0,K),dividerXTrailing:K=>Ae(F(),1,K),dividerYLeading:K=>Ae(F(),2,K),dividerYTrailing:K=>Ae(F(),3,K),frame:K=>ze(F(),K),bandClip:K=>Ne(F(),K),active:K=>{F().active=K},dragRect:K=>{F().dragRect=K},marquee:K=>{F().marquee=K},fillPreview:K=>{F().fillPreview=K},resizeGuide:K=>{F().resizeGuide=K}}},[A,Ae,ze,Ne]),ge=i.useMemo(()=>Object.fromEntries(Ni.map(S=>[S,Ie(S)])),[Ie]),Fe=Math.min(Math.max(0,U),t.count),lt=Ma(t,Fe),He=Math.min(Math.max(0,V),e.count),Ft=za(e,He),bt=O===void 0?0:Math.min(Math.max(0,O),t.count-Fe),it=Fa(t,bt),Qe=T===void 0?0:Math.min(Math.max(0,T),e.count-He),fn=Na(e,Qe),Qn=i.useRef(null),er=i.useRef("add"),En=i.useRef(s);En.current=s;const zr=i.useRef(!1),oe=st.useWheelBridge(n,{enableBridge:!s}),Ce=i.useCallback(S=>(r.current=S,oe(S)),[r,oe]),pe=i.useCallback((S,F)=>({top:F.mapY(e.offsetOf(S.startRow)),bottom:F.mapY(e.offsetOf(S.endRow)+e.sizeOf(S.endRow)),left:F.mapX(t.offsetOf(S.startCol)),right:F.mapX(t.offsetOf(S.endCol)+t.sizeOf(S.endCol))}),[e,t]),ft=i.useCallback((S,F)=>{if(F.clampHeight<=0||F.clampWidth<=0)return null;const{top:K,bottom:z,left:Q,right:ee}=pe(S,F),re=-F.clampHeight*Mt,ue=F.clampHeight*(1+Mt),be=-F.clampWidth*Mt,Te=F.clampWidth*(1+Mt);if(z<re||K>ue||ee<be||Q>Te)return null;const _e=Math.max(K,re),de=Math.max(Q,be);return{top:_e,left:de,width:Math.min(ee,Te)-de,height:Math.min(z,ue)-_e}},[pe]),xe=i.useCallback((S,F)=>{if(F.clampHeight<=0||F.clampWidth<=0)return null;const K=pe(S,F),z=-F.clampHeight*Mt,Q=F.clampHeight*(1+Mt),ee=-F.clampWidth*Mt,re=F.clampWidth*(1+Mt),ue=Math.min(Math.max(K.top,z),Q),be=Math.min(Math.max(K.left,ee),re);return{top:ue,left:be,width:Math.min(Math.max(K.right,ee),re)-be,height:Math.min(Math.max(K.bottom,z),Q)-ue}},[pe]),Kt=i.useCallback(()=>{if(g===void 0)return null;const S=g.current;return S.row||S.column||S.intersection?S:null},[g]),yt=i.useCallback((S,F,K)=>{if(F.bandClip!==null){for(const Q of ks(K))F.bandClip.appendChild(Q);return}const z=F.fillPool[0]?.node??Mi(F);for(const Q of ks(K))S.insertBefore(Q,z)},[]),Fr=i.useCallback(S=>{const F=S.nodes.frame;if(F===null)return;const K=a.current,z=K===void 0?null:$m(K,e.count,t.count),Q=z===null?null:xi(z.startCol,z.endCol,S.xFirst,S.xLast,S.mapX(t.offsetOf(z.startCol)),S.mapX(t.offsetOf(z.endCol)+t.sizeOf(z.endCol)),S.clampWidth),ee=z===null?null:xi(z.startRow,z.endRow,S.yFirst,S.yLast,S.mapY(e.offsetOf(z.startRow)),S.mapY(e.offsetOf(z.endRow)+e.sizeOf(z.endRow)),S.clampHeight),re=F.last,ue=F.node.style;if(Q===null||ee===null){re.shown&&(re.shown=!1,ue.display="none");return}re.shown||(re.shown=!0,ue.display="block");const be=Di(Q),Te=Di(ee);be.start!==re.left&&(re.left=be.start,ue.left=be.start),be.end!==re.right&&(re.right=be.end,ue.right=be.end),be.size!==re.width&&(re.width=be.size,ue.width=be.size),Te.start!==re.top&&(re.top=Te.start,ue.top=Te.start),Te.end!==re.bottom&&(re.bottom=Te.end,ue.bottom=Te.end),Te.size!==re.height&&(re.height=Te.size,ue.height=Te.size);const _e=Dm(Q,ee);_e!==re.open&&(re.open=_e,_e===0?F.node.removeAttribute("data-aqsp-frame-open"):F.node.setAttribute("data-aqsp-frame-open",Mm(_e)))},[e,t]),Nt=i.useCallback((S,F,K,z)=>{const Q=xe(F,K);if(Q===null){Li(S);return}Pm(S,Q,K,z,Lc(F,t.count)||Dc(F,e.count))},[xe,e,t]),Nr=i.useCallback((S,F,K,z)=>{const Q=S.nodes.bandPool;for(;Q.length>K.length;){const ee=Q.pop();ee!==void 0&&Jr(ee)}if(z===null){S.nodes.dragBand!==null&&(Jr(S.nodes.dragBand),S.nodes.dragBand=null);return}for(let ee=0;ee<K.length;ee+=1){let re=Q[ee];re===void 0&&(re=Ti(),Gr(re,S.clampWidth,S.clampHeight),yt(F,S.nodes,re),Q.push(re)),Nt(re,K[ee],S,z)}},[yt,Nt]),On=i.useCallback((S,F,K)=>{const z=S.nodes.container;if(z===null)return;if(F===null||K===null){S.nodes.dragBand!==null&&Li(S.nodes.dragBand);return}let Q=S.nodes.dragBand;Q===null&&(Q=Ti(),Gr(Q,S.clampWidth,S.clampHeight),yt(z,S.nodes,Q),S.nodes.dragBand=Q),Nt(Q,F,S,K)},[yt,Nt]),Ut=i.useCallback((S,F)=>{if(S!==null){if(F===null){S.style.display="none";return}S.style.display="block",S.style.transform=`translate(${F.left}px, ${F.top}px)`,S.style.width=`${F.width}px`,S.style.height=`${F.height}px`}},[]),pn=i.useCallback((S,F,K,z)=>{const Q=z==="point"?null:Kt();for(const ee of le(K,F))Ut(ee.nodes.dragRect,ft(S,ee)),On(ee,S,Q)},[ft,le,Ut,Kt,On]),An=i.useCallback((S,F,K)=>{for(const z of le(K,F))Ut(z.nodes.fillPreview,S===null?null:ft(S,z))},[ft,le,Ut]),tr=i.useCallback((S,F,K)=>{for(const z of le(K,F)){const Q=z.nodes.resizeGuide;if(Q===null)continue;if(S===null){Q.style.display="none";continue}const ee=S.anchor==="trailing";if(S.axis==="col"){if(ee&&z.xKind!=="t"){Q.style.display="none";continue}Q.style.display="block";const re=z.mapX(S.position);Q.style.transform=`translate(${ee?Math.max(0,re):re}px, 0px)`,Q.style.width="1px",Q.style.height="100%"}else{if(ee&&z.yKind!=="t"){Q.style.display="none";continue}Q.style.display="block";const re=z.mapY(S.position);Q.style.transform=`translate(0px, ${ee?Math.max(0,re):re}px)`,Q.style.width="100%",Q.style.height="1px"}}},[le]),nr=i.useCallback((S,F,K,z,Q,ee,re)=>{if(S===null)return;if(F===null||re<=0||ee<=0){S.style.clipPath=$i;return}const ue=Sn(e,F.row,z),be=vn(t,F.col,K),Te=t.sizeOf(F.col),_e=e.sizeOf(F.row),de=be>=ee||ue>=re,Le=F.col>=Q.cols&&be<Q.width,fe=F.row>=Q.rows&&ue<Q.height,se=Q.trailingWidth>0&&F.col<t.count-Q.trailingCols&&be+Te>ee-Q.trailingVisibleWidth,ye=Q.trailingHeight>0&&F.row<e.count-Q.trailingRows&&ue+_e>re-Q.trailingVisibleHeight;if(de||Le||fe||se||ye){S.style.clipPath=$i;return}S.style.clipPath="",S.style.transform=`translate(${be}px, ${ue}px)`;const Re=`${Te} ${_e}`;S.dataset.aqspAnchorSig!==Re&&(S.dataset.aqspAnchorSig=Re,S.style.width=`${Te}px`,S.style.height=`${_e}px`)},[e,t]),xn=i.useCallback((S,F,K)=>{if(v===void 0)return;const z=v.current,{width:Q,height:ee}=S.getViewportSize(),re=S.getFrozenSize(),ue={scroll:K,frozenCount:re.cols,trailingCount:re.trailingCols,extent:Q},be={scroll:F,frozenCount:re.rows,trailingCount:re.trailingRows,extent:ee};nr(k===void 0?null:k.current,z.interactive,ue,be,re,Q,ee),nr(b===void 0?null:b.current,z.tip,ue,be,re,Q,ee)},[v,k,b,nr]),Xt=i.useCallback(()=>{const S=R.current,F=n.current;if(S===null||F===null)return;const K=F.getScrollPosition(),z=Math.max(0,K.y),Q=Math.max(0,K.x),ee=o(),re=le(Q,z),ue=Kt(),be=ue===null?qm:ee.ranges.slice(-Nm(re.length));for(const fe of re){const se=fe.nodes.container;if(se===null)continue;const ye=fe.nodes.fillPool;for(let Re=0;Re<Math.max(ye.length,ee.ranges.length);Re+=1){let me=ye[Re];if(me===void 0){const Oe=document.createElement("div");Oe.className="aqsp-selection-fill",Oe.setAttribute("data-aqsp-fill",""),Oe.style.display="none",se.insertBefore(Oe,Mi(fe.nodes)),me={node:Oe,last:{shown:!1,width:-1,height:-1,transform:""}},ye.push(me)}const et=ee.ranges[Re],ae=et===void 0?null:ft(et,fe);if(ae===null)me.last.shown&&(me.last.shown=!1,me.node.style.display="none");else{me.last.shown||(me.last.shown=!0,me.node.style.display="block");const Oe=`translate(${ae.left}px, ${ae.top}px)`;Oe!==me.last.transform&&(me.last.transform=Oe,me.node.style.transform=Oe),ae.width!==me.last.width&&(me.last.width=ae.width,me.node.style.width=`${ae.width}px`),ae.height!==me.last.height&&(me.last.height=ae.height,me.node.style.height=`${ae.height}px`)}}for(;ye.length>ee.ranges.length;)ye.pop()?.node.remove();Ut(fe.nodes.active,ft(ke(ee.active,ee.active),fe)),Fr(fe),Nr(fe,se,be,ue)}const Te=h(),_e=Te===null||Te.foreign?null:Te;for(const fe of re){const se=fe.nodes.marquee;if(se===null)continue;const ye=_e===null?null:ft(_e.range,fe),Re=ye!==null&&(fe.xSeamTrail&&ye.left>=fe.clampWidth&&ye.left<fe.clampWidth+yr||fe.xSeamLead&&ye.left+ye.width<=0&&ye.left+ye.width>-yr||fe.ySeamTrail&&ye.top>=fe.clampHeight&&ye.top<fe.clampHeight+yr||fe.ySeamLead&&ye.top+ye.height<=0&&ye.top+ye.height>-yr)?null:ye;if(Re===null)se.style.display="none";else{se.style.display="block",se.style.transform=`translate(${Re.left}px, ${Re.top}px)`,se.style.width=`${Re.width}px`,se.style.height=`${Re.height}px`;const ae=Xr(Re.top),Oe=Xr(Re.left),Be=Xr(fe.cells.clampHeight-(Re.top+Re.height)),Xe=Xr(fe.cells.clampWidth-(Re.left+Re.width)),ct=`${ae} ${Xe} ${Be} ${Oe}`;ct!==se.dataset.aqspOutsetSig&&(se.dataset.aqspOutsetSig=ct,se.style.setProperty("--aqsp-clip-outset-top",ae),se.style.setProperty("--aqsp-clip-outset-right",Xe),se.style.setProperty("--aqsp-clip-outset-bottom",Be),se.style.setProperty("--aqsp-clip-outset-left",Oe))}const me=Re===null?null:_e?.kind??null,et=se.dataset.aqspClipKindLast??null;me!==et&&(me===null?(delete se.dataset.aqspClipKindLast,se.removeAttribute("data-aqsp-clip-kind")):(se.dataset.aqspClipKindLast=me,se.setAttribute("data-aqsp-clip-kind",me)))}Qn.current!==null&&pn(Qn.current,z,Q,er.current),d.current!==null&&tr(d.current,z,Q),E.current!==null&&An(E.current,z,Q);const de=D.current;if(de!==null&&!y()){const{width:fe,height:se}=F.getViewportSize(),ye=ee.ranges[ee.ranges.length-1];if(!(ee.ranges.length===1&&!En.current&&!m())||se<=0||fe<=0)de.style.display="none";else{const me=F.getFrozenSize(),et={scroll:Q,frozenCount:me.cols,trailingCount:me.trailingCols,extent:fe},ae={scroll:z,frozenCount:me.rows,trailingCount:me.trailingRows,extent:se},Oe=ye.endCol<me.cols,Be=ye.endRow<me.rows,Xe=ye.endCol>=t.count-me.trailingCols,ct=ye.endRow>=e.count-me.trailingRows,Ee=vn(t,ye.endCol,et)+t.sizeOf(ye.endCol),ht=Sn(e,ye.endRow,ae)+e.sizeOf(ye.endRow),Ve=Oe||Xe?0:me.width,We=Be||ct?0:me.height,tt=Xe?fe:fe-me.trailingVisibleWidth,$n=ct?se:se-me.trailingVisibleHeight;ht<=We||ht>$n||Ee<=Ve||Ee>tt?de.style.display="none":(de.style.display="block",de.style.transform=`translate(${Ee-Pi+1}px, ${ht-Pi+1}px)`)}}const Le=r.current;if(Le!==null){const fe=ee.active,{width:se,height:ye}=F.getViewportSize(),Re=F.getFrozenSize(),me={scroll:Q,frozenCount:Re.cols,trailingCount:Re.trailingCols,extent:se},et={scroll:z,frozenCount:Re.rows,trailingCount:Re.trailingRows,extent:ye},ae=Sn(e,fe.row,et),Oe=vn(t,fe.col,me),Be=ye>0?Math.min(Math.max(ae,0),Math.max(0,ye-1)):0,Xe=se>0?Math.min(Math.max(Oe,0),Math.max(0,se-1)):0;Le.style.top=`${Be}px`,Le.style.left=`${Xe}px`,En.current?(Le.style.width=`${t.sizeOf(fe.col)}px`,Le.style.height=`${e.sizeOf(fe.row)}px`,Le.style.paddingTop=`${_m(e.sizeOf(fe.row),x===void 0?Ht:x.current)}px`):(Le.style.width="1px",Le.style.height="1px",Le.style.paddingTop="0px");const ct=fe.col>=Re.cols&&Oe<Re.width,Ee=fe.row>=Re.rows&&ae<Re.height,ht=Re.trailingWidth>0&&fe.col<t.count-Re.trailingCols&&Oe+t.sizeOf(fe.col)>se-Re.trailingVisibleWidth,Ve=Re.trailingHeight>0&&fe.row<e.count-Re.trailingRows&&ae+e.sizeOf(fe.row)>ye-Re.trailingVisibleHeight,We=En.current&&ae===Be&&Oe===Xe&&!ct&&!Ee&&!ht&&!Ve;We!==zr.current&&(zr.current=We,We?Le.setAttribute("data-aqsp-editing",""):Le.removeAttribute("data-aqsp-editing"))}xn(F,z,Q)},[n,ft,le,Ut,pn,tr,An,h,o,m,y,D,r,e,t,Kt,Nr,Fr,x,xn]),rr=i.useCallback((S,F)=>{Qn.current=S,er.current=F;const K=S===null?"add":F;for(const ee of le(0,0)){const re=ee.nodes.dragRect;if(re===null)continue;const ue=re.dataset.aqspDragModeLast??"add";K!==ue&&(re.dataset.aqspDragModeLast=K,K==="add"?re.removeAttribute("data-aqsp-drag-mode"):re.setAttribute("data-aqsp-drag-mode",K))}const z=n.current;if(S===null||z===null){for(const ee of le(0,0))ee.nodes.dragRect!==null&&(ee.nodes.dragRect.style.display="none"),On(ee,null,null);return}const Q=z.getScrollPosition();pn(S,Math.max(0,Q.y),Math.max(0,Q.x),F)},[n,pn,le,On]),or=i.useCallback(S=>{E.current=S;const F=n.current;if(F===null){for(const z of le(0,0))z.nodes.fillPreview!==null&&(z.nodes.fillPreview.style.display="none");return}const K=F.getScrollPosition();An(S,Math.max(0,K.y),Math.max(0,K.x))},[n,An,le]),Gt=i.useCallback(S=>{d.current=S;const F=n.current;if(F===null){for(const z of le(0,0))z.nodes.resizeGuide!==null&&(z.nodes.resizeGuide.style.display="none");return}const K=F.getScrollPosition();tr(S,Math.max(0,K.y),Math.max(0,K.x))},[n,tr,le]);i.useLayoutEffect(()=>{const S=R.current;if(!(S===null||C===void 0))return S.style.setProperty("--aqsp-band-row",C.row),S.style.setProperty("--aqsp-band-column",C.column),S.style.setProperty("--aqsp-band-intersection",C.intersection),S.style.setProperty("--aqsp-band-opacity",String(C.opacity)),()=>{S.style.removeProperty("--aqsp-band-row"),S.style.removeProperty("--aqsp-band-column"),S.style.removeProperty("--aqsp-band-intersection"),S.style.removeProperty("--aqsp-band-opacity")}},[C]),i.useEffect(()=>(c.current=Xt,u.current=rr,N.current=or,W.current=Gt,()=>{c.current=null,u.current=null,N.current=null,W.current=null})),i.useEffect(()=>{Xt()},[Xt,s,Fe,He,bt,Qe]),i.useEffect(()=>{const S=r.current;if(S===null)return;const F=K=>_(K);return S.addEventListener("mousedown",F),()=>S.removeEventListener("mousedown",F)},[r,_]);const Ue=Fe>0||bt>0?[...Fe>0?[{k:"f",style:{left:0,width:lt}}]:[],{k:"s",style:{left:lt,right:it}},...bt>0?[{k:"t",style:{right:0,width:it}}]:[]]:[{k:"m",style:{left:0,right:0}}],Eo=He>0||Qe>0?[...He>0?[{k:"f",style:{top:0,height:Ft}}]:[],{k:"s",style:{top:Ft,bottom:fn}},...Qe>0?[{k:"t",style:{bottom:0,height:fn}}]:[]]:[{k:"m",style:{top:0,bottom:0}}],Tn=S=>S==="m"?0:S==="s"?1:S==="t"?2:3,pt=Ue.flatMap(S=>Eo.map(F=>({xk:S.k,yk:F.k,key:`${S.k}${F.k}`,style:{...S.style,...F.style}}))).sort((S,F)=>Tn(S.key[0])+Tn(S.key[1])-(Tn(F.key[0])+Tn(F.key[1]))),Pe=S=>S==="mm"?{"data-aqsp-overlay-main":""}:S==="fm"?{"data-aqsp-overlay-frozen":""}:S==="sm"?{"data-aqsp-overlay-scroll":""}:{};return Y.jsxs("div",{ref:R,className:"aqsp-overlay","data-aqsp-overlay":"",style:{right:De.SPREADSHEET_SCROLLBAR_SIZE_PX,bottom:De.SPREADSHEET_SCROLLBAR_SIZE_PX},children:[pt.map(({xk:S,yk:F,key:K,style:z})=>{const Q=ge[K];return Y.jsxs("div",{className:"aqsp-overlay-quad","data-aqsp-overlay-quad":K,...Pe(K),style:z,ref:Q.container,children:[f?Y.jsx("div",{className:"aqsp-band-clip","data-aqsp-band-clip":"",ref:Q.bandClip}):null,S==="s"&&Fe>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-leading",style:{left:0,top:0,bottom:0,display:"none"},ref:Q.dividerXLeading}):null,S==="s"&&bt>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-trailing",style:{right:0,top:0,bottom:0,display:"none"},ref:Q.dividerXTrailing}):null,F==="s"&&He>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-leading",style:{top:0,left:0,right:0,display:"none"},ref:Q.dividerYLeading}):null,F==="s"&&Qe>0?Y.jsx("div",{className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-trailing",style:{bottom:0,left:0,right:0,display:"none"},ref:Q.dividerYTrailing}):null,f?Y.jsx("div",{className:"aqsp-frame","data-aqsp-frame":"",style:{display:"none"},ref:Q.frame}):null,Y.jsx("div",{className:"aqsp-active-frame","data-aqsp-active":"",style:{display:"none"},ref:Q.active}),Y.jsx("div",{className:"aqsp-drag-rect","data-aqsp-drag-rect":"",style:{display:"none"},ref:Q.dragRect}),Y.jsx("div",{className:"aqsp-clip-marquee","data-aqsp-clip-marquee":"",style:{display:"none"},ref:Q.marquee}),Y.jsx("div",{className:"aqsp-autofill-preview","data-aqsp-autofill-preview":"",style:{display:"none"},ref:Q.fillPreview}),Y.jsx("div",{className:"aqsp-resize-guide","data-aqsp-resize-guide":"",style:{display:"none"},ref:Q.resizeGuide})]},K)}),Y.jsx("textarea",{ref:Ce,className:"aqsp-sink","aria-label":P,"aria-readonly":H?"true":void 0,"aria-keyshortcuts":$,tabIndex:-1,defaultValue:" ",inputMode:l?"text":"none",spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off","data-aqsp-sink":""}),j?Y.jsx("div",{ref:D,className:"aqsp-autofill-handle","data-aqsp-autofill-handle":"",style:{display:"none"}}):null]})},_a=({ctx:e,labels:t})=>{const[n,r]=i.useState(""),o=e.cellReadOnly===!0,s=i.useId(),l=i.useRef(!1),c=y=>{l.current=!0;try{y()}finally{l.current=!1}},u=()=>{o||n.trim()!==""&&c(()=>e.commit([...e.current,{text:n}]))},h=y=>{if(y.key==="Escape"){y.preventDefault(),c(e.close);return}y.key==="Enter"&&(y.ctrlKey||y.metaKey)&&!y.altKey&&!y.shiftKey&&(y.preventDefault(),u())},m=y=>{l.current||y.relatedTarget instanceof Node&&y.currentTarget.contains(y.relatedTarget)||e.rejected||c(e.close)};return Y.jsxs("div",{className:"aqsp-popover-comment","data-aqsp-popover":"comment","data-aqsp-popover-rejected":e.rejected?"":void 0,role:"dialog","aria-labelledby":s,onBlur:m,children:[Y.jsxs("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:s,children:[qe(t,"commentTitle"),Y.jsx("span",{className:"aqsp-popover-count","data-aqsp-comment-count":"",children:qe(t,"commentCount",e.current.length)})]}),Y.jsx("ul",{className:"aqsp-popover-thread","data-aqsp-comment-thread":"",children:e.current.map(y=>Y.jsxs("li",{className:"aqsp-popover-comment-item","data-aqsp-comment-id":y.id,children:[Y.jsx("span",{className:"aqsp-popover-comment-author",children:y.author}),Y.jsx("time",{className:"aqsp-popover-comment-time",dateTime:y.createdAt,children:y.createdAt}),Y.jsx("p",{className:"aqsp-popover-comment-text",children:y.text})]},y.id))}),Y.jsx("textarea",{className:"aqsp-popover-textarea","data-aqsp-comment-input":"","data-aqsp-popover-autofocus":"",value:n,"aria-label":qe(t,"commentReply"),"aria-invalid":e.rejected?!0:void 0,onChange:y=>r(y.currentTarget.value),onKeyDown:h}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-post":"",disabled:o,"aria-disabled":o?"true":void 0,onClick:u,children:qe(t,"commentPost")}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":qe(t,"popoverClose"),onClick:()=>c(e.close),children:"×"})]})]})},qa=({ctx:e,labels:t})=>{const[n,r]=i.useState(e.current.text),[o,s]=i.useState(e.current.url===void 0?"":e.current.url),l=e.cellReadOnly===!0,c=i.useId(),u=i.useRef(!1),h=o.trim()===""?null:un(o),m=o.trim()!==""&&h===null,y=j=>{u.current=!0;try{j()}finally{u.current=!1}},N=()=>{l||m||y(()=>e.commit({text:n===""&&h!==null?h:n,url:h}))},W=j=>{if(j.key==="Escape"){j.preventDefault(),y(e.close);return}j.key==="Enter"&&!j.altKey&&!j.shiftKey&&(j.preventDefault(),N())},D=j=>{u.current||j.relatedTarget instanceof Node&&j.currentTarget.contains(j.relatedTarget)||e.rejected||y(e.close)};return Y.jsxs("div",{className:"aqsp-popover-link","data-aqsp-popover":"link","data-aqsp-popover-rejected":e.rejected?"":void 0,"data-aqsp-link-invalid":m?"":void 0,role:"dialog","aria-labelledby":c,onBlur:D,children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:c,children:qe(t,"linkTitle")}),Y.jsxs("label",{className:"aqsp-popover-field",children:[Y.jsx("span",{className:"aqsp-popover-field-label",children:qe(t,"linkTextField")}),Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-link-text":"",type:"text",value:n,onChange:j=>r(j.currentTarget.value),onKeyDown:W})]}),Y.jsxs("label",{className:"aqsp-popover-field",children:[Y.jsx("span",{className:"aqsp-popover-field-label",children:qe(t,"linkUrlField")}),Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-link-url":"","data-aqsp-popover-autofocus":"",type:"url",value:o,"aria-invalid":m||e.rejected?!0:void 0,onChange:j=>s(j.currentTarget.value),onKeyDown:W})]}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-save":"",disabled:m||l,"aria-disabled":l?"true":void 0,onClick:N,children:qe(t,"linkSave")}),e.canOpen&&e.current.url!==void 0?Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-link-open":"",onClick:e.open,children:qe(t,"linkOpen")}):null,Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":qe(t,"popoverClose"),onClick:()=>y(e.close),children:"×"})]})]})},_i=500,ja=({ctx:e,labels:t})=>{const[n,r]=i.useState(e.typed),[o,s]=i.useState(0),l=i.useId(),c=i.useRef(!1),u=i.useMemo(()=>{const V=n.toLowerCase();return e.current.filter(O=>O.toLowerCase().startsWith(V))},[e.current,n]),h=i.useMemo(()=>u.length>_i?u.slice(0,_i):u,[u]),m=u.length-h.length,y=h.length===0?-1:Math.min(o,h.length-1),N=V=>{c.current=!0;try{V()}finally{c.current=!1}},W=()=>{y<0||N(()=>e.commit(h[y]))},D=V=>{if(V.key==="Escape"){V.preventDefault(),N(e.close);return}if(V.key==="Enter"){V.preventDefault(),W();return}if(V.key==="ArrowDown"){V.preventDefault(),s(y+1);return}V.key==="ArrowUp"&&(V.preventDefault(),s(Math.max(y-1,0)))},j=V=>{c.current||V.relatedTarget instanceof Node&&V.currentTarget.contains(V.relatedTarget)||N(e.close)},U=V=>`${l}-${V}`;return Y.jsxs("div",{className:"aqsp-popover-list","data-aqsp-popover":"list",onBlur:j,children:[Y.jsx("input",{className:"aqsp-popover-input","data-aqsp-list-input":"","data-aqsp-popover-autofocus":"",type:"text",role:"combobox","aria-label":qe(t,"listTitle"),"aria-expanded":"true","aria-autocomplete":"list","aria-controls":l,"aria-activedescendant":y<0?void 0:U(y),value:n,onChange:V=>{r(V.currentTarget.value),s(0)},onKeyDown:D}),Y.jsxs("div",{className:"aqsp-popover-options",id:l,role:"listbox","aria-label":qe(t,"listTitle"),children:[h.length===0?Y.jsx("div",{className:"aqsp-popover-empty","data-aqsp-list-empty":"",children:qe(t,"listEmpty")}):h.map((V,O)=>Y.jsx("div",{className:"aqsp-popover-option",id:U(O),role:"option",tabIndex:-1,"aria-selected":O===y,"data-aqsp-list-option":V,onPointerDown:T=>T.preventDefault(),onClick:()=>N(()=>e.commit(V)),children:V},U(O))),m>0?Y.jsx("div",{className:"aqsp-popover-empty","data-aqsp-list-more":"",children:qe(t,"listMore",m)}):null]})]})},Ia=({ctx:e,labels:t})=>Y.jsxs("div",{className:"aqsp-popover-message","data-aqsp-popover":"message","data-aqsp-popover-rejected":e.current.rejected?"":void 0,role:"status",children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",children:e.current.title}),Y.jsx("p",{className:"aqsp-popover-message-text","data-aqsp-popover-message-text":"",children:e.current.message}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":qe(t,"popoverClose"),onClick:e.close,children:"×"})]}),Ha=({ctx:e,labels:t})=>{const n=e.current===void 0?"":e.current,[r,o]=i.useState(n),s=e.cellReadOnly===!0,l=i.useId(),c=i.useId(),u=i.useRef(!1),h=D=>{u.current=!0;try{D()}finally{u.current=!1}},m=()=>{s||h(()=>e.commit(r===""?null:r))},y=()=>{r!==n&&!s?m():h(e.close)},N=D=>{if(D.key==="Escape"){D.preventDefault(),e.rejected?h(e.close):y();return}D.key==="Enter"&&(D.ctrlKey||D.metaKey)&&!D.altKey&&!D.shiftKey&&(D.preventDefault(),m())},W=D=>{u.current||D.relatedTarget instanceof Node&&D.currentTarget.contains(D.relatedTarget)||e.rejected||y()};return Y.jsxs("div",{className:"aqsp-popover-note","data-aqsp-popover":"note","data-aqsp-popover-rejected":e.rejected?"":void 0,role:"dialog","aria-labelledby":l,onBlur:W,children:[Y.jsx("div",{className:"aqsp-popover-title","data-aqsp-popover-title":"",id:l,children:qe(t,"noteTitle")}),Y.jsx("textarea",{className:"aqsp-popover-textarea","data-aqsp-note-input":"","data-aqsp-popover-autofocus":"",value:r,"aria-describedby":c,"aria-invalid":e.rejected?!0:void 0,onChange:D=>o(D.currentTarget.value),onKeyDown:N}),Y.jsx("p",{className:"aqsp-popover-hint",id:c,"data-aqsp-popover-hint":"",children:qe(t,s?"noteViewerHint":e.rejected?"noteRejectedHint":"noteEscapeHint")}),Y.jsxs("div",{className:"aqsp-popover-actions",children:[Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-save":"",disabled:s,"aria-disabled":s?"true":void 0,onClick:m,children:qe(t,"noteSave")}),Y.jsx("button",{type:"button",className:"aqsp-popover-button","data-aqsp-popover-close":"","aria-label":qe(t,"popoverClose"),onClick:()=>h(e.close),children:"×"})]})]})},Ba=({ctx:e})=>Y.jsx("div",{className:"aqsp-popover-note-tip","data-aqsp-popover":"note-tip",role:"tooltip",children:e.current}),jt=e=>Object.freeze({text:e.includes("text"),formula:e.includes("formula"),format:e.includes("format"),borders:e.includes("borders"),cf:e.includes("cf"),note:e.includes("note"),comments:e.includes("comments"),hyperlink:e.includes("hyperlink"),validation:e.includes("validation"),sizes:e.includes("sizes")}),qi=["text","formula","format","borders","cf","note","comments","hyperlink","validation","sizes"],Wa=Object.freeze({all:jt(qi),values:jt(["text"]),formats:jt(["format","borders","cf"]),formulas:jt(["text","formula"]),noBorders:jt(qi.filter(e=>e!=="borders")),columnWidths:jt(["sizes"]),validation:jt(["validation"]),conditionalFormats:jt(["cf"]),commentsAndNotes:jt(["note","comments"])}),ji=Object.freeze({mode:"all"}),Es=Object.freeze({t:""}),Ii=Object.freeze({row:1<<30,col:1<<30}),Bm=Object.freeze({add:"+",subtract:"-",multiply:"*",divide:"/"}),Wm=e=>e.t===""&&e.f===void 0,Vm=e=>e.length>1&&e.startsWith("="),Ym=(e,t,n)=>{switch(n){case"add":return e+t;case"subtract":return e-t;case"multiply":return e*t;case"divide":return e/t}},Hi=e=>Number.isFinite(e)?String(Number(e.toPrecision(15))):null,Km=(e,t,n,r)=>{const o=Vm(e),s=e===""?"0":wt(e);if(!o&&s===null)return null;const l=Bm[n];if(t.f!==void 0){const h=$r(t.f,r),m=h.startsWith("=")?h.slice(1):h;return`=(${o?e.slice(1):s})${l}(${m})`}if(t.t==="")return n==="multiply"||n==="divide"||o||e===""?null:Hi(Number(s));const c=wt(t.t);if(c===null)return null;const u=Number(c);return n==="divide"&&u===0?null:o?`=(${e.slice(1)})${l}(${c})`:Hi(Ym(Number(s),u,n))},Bi=e=>({row:e.col,col:e.row,absRow:!1,absCol:!1}),Um=e=>{switch(e.kind){case"cell":return e.absRow||e.absCol?e:{...e,row:e.col,col:e.row};case"range":return e.start.absRow||e.start.absCol||e.end.absRow||e.end.absCol?e:{...e,start:Bi(e.start),end:Bi(e.end)};case"column":return e.start.abs||e.end.abs?e:{...e,kind:"row",start:{row:e.start.col,abs:!1},end:{row:e.end.col,abs:!1}};case"row":return e.start.abs||e.end.abs?e:{...e,kind:"column",start:{col:e.start.row,abs:!1},end:{col:e.end.row,abs:!1}}}},Xm=e=>{const t=$r(e,Ii),n=Tr(t);let r="",o=0,s=!1;for(const l of n){const c=Um(l.token);c!==l.token&&(r+=`${t.slice(o,l.start)}${sn(c)}`,o=l.end,s=!0)}return s?Ro(`${r}${t.slice(o)}`,Ii):e},Gm=(e,t,n)=>{const r=e.cells[t];if(r===void 0)return Es;const o=r[n];return o===void 0?Es:o},Zm=e=>{const{rows:t,cols:n}=e,r=Vc(Xm);let o=t===1&&n===1&&e.colWidths===void 0&&e.rowHeights===void 0&&!e.wholeRows&&!e.wholeCols;const s=[];for(let c=0;c<n;c+=1){const u=[];for(let h=0;h<t;h+=1){const m=Gm(e,h,c);let y=m;if(m.f!==void 0){const N=r(m.f);y=N===m.f?m:{...m,f:N}}(y!==m||m===Es)&&(o=!1),u.push(y)}s.push(u)}if(o)return e;const l=e.conditionalFormats.length===0?e.conditionalFormats:e.conditionalFormats.map(c=>({...c,ranges:c.ranges.map(u=>({startRow:u.startCol,startCol:u.startRow,endRow:u.endCol,endCol:u.endRow}))}));return{v:1,rows:n,cols:t,clipId:e.clipId,formats:e.formats,validations:e.validations,cells:s,wholeRows:!1,wholeCols:!1,conditionalFormats:l}},Jm=(e,t)=>!t.formula&&e.f!==void 0||!t.format&&e.fmt!==void 0||!t.validation&&e.val!==void 0||!t.note&&e.note!==void 0||!t.comments&&e.comments!==void 0||!t.hyperlink&&e.link!==void 0,Qm=(e,t)=>{const n={t:e.t};return t.formula&&e.f!==void 0&&(n.f=e.f),t.format&&e.fmt!==void 0&&(n.fmt=e.fmt),t.validation&&e.val!==void 0&&(n.val=e.val),t.note&&e.note!==void 0&&(n.note=e.note),t.comments&&e.comments!==void 0&&(n.comments=e.comments),t.hyperlink&&e.link!==void 0&&(n.link=e.link),n},Wi=(e,t)=>{let n=!1;const r=[];for(const c of e.cells){let u=!1;const h=[];for(const m of c)Jm(m,t)?(h.push(Qm(m,t)),u=!0):h.push(m);u&&(n=!0),r.push(u?h:c)}const o=!t.format&&e.formats.length>0?[]:e.formats,s=!t.validation&&e.validations.length>0?[]:e.validations,l=!t.cf&&e.conditionalFormats.length>0?[]:e.conditionalFormats;return(o!==e.formats||s!==e.validations||l!==e.conditionalFormats)&&(n=!0),n?{...e,formats:o,validations:s,conditionalFormats:l,cells:r}:e},Vi=new WeakMap,Va=e=>{const t=Vi.get(e);if(t!==void 0)return t;const n=e.formats.map(s=>xt(s)),r=n.map(s=>s===void 0||s.borders===void 0?s:xt({...s,borders:void 0})),o={canonical:n,borderless:r};return Vi.set(e,o),o},go=(e,t)=>t===void 0?void 0:e[t],eg=(e,t,n,r)=>{const o=Va(e);if(n){const h=go(o.canonical,t.fmt);return h===void 0?null:h}const s=go(o.borderless,t.fmt),l=r.readFormat(),c=l===void 0?void 0:l.borders;if(c===void 0)return s===void 0?null:s;const u=xt(s===void 0?{borders:c}:{...s,borders:c});return u===void 0?null:u},tg=(e,t,n,r)=>{const o=t||e.f===void 0?e:{t:e.t};return r!==void 0?Km(n.readText(),o,r,n):o.f===void 0?o.t:$r(o.f,n)},Yi=(e,t,n,r,o)=>{const s=Wa[r.mode];if(r.skipBlanks===!0&&Wm(e))return null;const l={};let c=!1;if(s.text){const u=tg(e,s.formula&&o.formula,n,r.operation);u!==null&&(l.text=u,c=!0)}if(o.format){if(s.format)l.format=eg(t,e,s.borders,n),c=!0;else if(r.injectIntoEmpty===!0&&e.fmt!==void 0&&n.readText()===""){const u=go(Va(t).canonical,e.fmt);u!==void 0&&(l.format=u,c=!0)}}if(s.note&&o.note&&(l.note=e.note===void 0?null:e.note,c=!0),s.comments&&o.comments&&(l.comments=e.comments===void 0?null:e.comments,c=!0),s.hyperlink&&o.hyperlink&&(l.hyperlink=e.link===void 0?null:e.link,c=!0),s.validation&&o.validation){const u=go(t.validations,e.val);l.validation=u===void 0?null:u,c=!0}return c?l:null},Ki=(e,t)=>e.length===0?e:t.length===0?[]:e.map(n=>{const r=[];for(const o of t)for(const s of n.ranges)r.push({startRow:o.row+s.startRow,startCol:o.col+s.startCol,endRow:o.row+s.endRow,endCol:o.col+s.endCol});return{...n,ranges:r}}),ng=["text/html","text/plain"],rg=(e,t,n)=>{if(e===0||t===0)return 0;const r=Ct(n);return!(r.rows===1&&r.cols===1)&&r.rows%e===0&&r.cols%t===0?r.rows*r.cols:e*t},og=e=>e.mode==="all"&&e.operation===void 0&&e.transpose!==!0&&e.skipBlanks!==!0,sg=e=>e.text||e.formula||e.format||e.borders||e.note||e.comments||e.hyperlink||e.validation,lg=e=>{const t=Array.from(e.types),n=new Map;return{types:t,getData:r=>{const o=n.get(r);if(o!==void 0)return o;const s=e.getData(r);return n.set(r,s),s}}},Ui=e=>{const t=e.clipboardData;return t??null},ig=(e,t)=>{const n=Math.max(e.startRow,t.startRow),r=Math.min(e.endRow,t.endRow),o=Math.max(e.startCol,t.startCol),s=Math.min(e.endCol,t.endCol);return n>r||o>s?null:{startRow:n,startCol:o,endRow:r,endCol:s}},cg=(e,t)=>{const n=[];for(const r of e){const o=[];for(const l of r.ranges){const c=ig(l,t);c!==null&&o.push({startRow:c.startRow-t.startRow,startCol:c.startCol-t.startCol,endRow:c.endRow-t.startRow,endCol:c.endCol-t.startCol})}if(o.length===0)continue;const s={sourceRuleId:r.id,ranges:o,condition:r.condition,style:r.style};r.stopIfTrue!==void 0&&(s.stopIfTrue=r.stopIfTrue),n.push(s)}return n},ag=(e,t,n,r,o)=>{const s=Zn(e,r,o),l={t:s.isFormula?e.getCellText(r,o):s.text};if(s.isFormula&&(l.f=Ro(s.text,{row:r,col:o})),e.getCellFormat!==void 0){const c=e.getCellFormat(r,o);if(c!==void 0){const u=t.intern(c);u!==void 0&&(l.fmt=u)}}if(e.getCellNote!==void 0){const c=e.getCellNote(r,o);c!==void 0&&(l.note=c)}if(e.getCellComments!==void 0){const c=e.getCellComments(r,o);c!==void 0&&c.length>0&&(l.comments=c.map(({text:u,author:h,createdAt:m})=>({text:u,author:h,createdAt:m})))}if(e.getCellHyperlink!==void 0){const c=Jn(e.getCellHyperlink(r,o));c!==void 0&&(l.link=c)}if(e.getCellValidation!==void 0){const c=e.getCellValidation(r,o);c!==void 0&&(l.val=n.intern(c))}return l},Ya=(e,t)=>{const n=$c(),r=uf(),o=[];for(let s=t.startRow;s<=t.endRow;s+=1){const l=[];for(let c=t.startCol;c<=t.endCol;c+=1)l.push(ag(e,n,r,s,c));o.push(l)}return{formats:n.entries,validations:r.entries,cells:o,conditionalFormats:e.getConditionalFormats===void 0?[]:cg(e.getConditionalFormats(),t)}},Xi=e=>e.kind==="cut"?{...e.payload,...Ya(e.sourceAdapter,e.range)}:e.payload,ug=e=>({v:1,rows:e.length,cols:e[0].length,clipId:Ms(),formats:[],validations:[],cells:e.map(t=>t.map(n=>({t:n}))),wholeRows:!1,wholeCols:!1,conditionalFormats:[]}),dg=e=>{let t=!1;const n=[];for(const r of e.cells){let o=!1;const s=[];for(const l of r){if(l.link===void 0){s.push(l);continue}const c=un(l.link);if(c===l.link){s.push(l);continue}if(o=!0,c===null){const{link:u,...h}=l;s.push(h)}else s.push({...l,link:c})}o&&(t=!0),n.push(o?s:r)}return t?{...e,cells:n}:e},fg=(e,t,n)=>{const r={row:e,col:t,text:""};return n.format&&(r.format=null),n.note&&(r.note=null),n.comments&&(r.comments=null),n.hyperlink&&(r.hyperlink=null),n.validation&&(r.validation=null),r},pg=(e,t,n,r,o)=>{if(e.length===0)return null;let s=0,l=0;for(const c of e)s=Math.max(s,c.row+t-1),l=Math.max(l,c.col+n-1);return ke({row:e[0].row,col:e[0].col},{row:Math.min(s,r-1),col:Math.min(l,o-1)})},hg=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(null),r=i.useRef("none"),o=i.useCallback(()=>{n.current!==null&&(n.current=null,t.current.repaintOverlay(),t.current.onClipChange?.(null))},[]),s=i.useCallback(O=>{const T=n.current;if(T===null||O==="format"||O==="annotate")return;const P=r.current;P==="own"||P==="foreign"&&T.kind==="copy"||o()},[o]),l=i.useCallback(()=>{const O=n.current;if(O===null)return;if(O.kind==="copy"){o();return}const T=t.current;T.repaintOverlay(),T.onClipChange?.({kind:"cut",range:O.range,foreign:O.sourceAdapter!==T.adapter})},[o]),c=i.useCallback((O,T,P)=>{const H=t.current;n.current={kind:O,range:T,clipId:P.clipId,sourceAdapter:H.adapter,payload:P},H.repaintOverlay(),H.onClipChange?.({kind:O,range:T,foreign:!1})},[]),u=i.useCallback(O=>{const T=t.current,P=T.adapter,H=Ct(O),$={v:1,rows:H.rows,cols:H.cols,clipId:Ms(),...Ya(P,O),wholeRows:Lc(O,P.colCount),wholeCols:Dc(O,P.rowCount)};if(T.resize!==void 0){if($.wholeCols){const _=[];for(let x=O.startCol;x<=O.endCol;x+=1)_.push(Math.min(T.resize.colAxis.sizeOf(x),an));$.colWidths=_}if($.wholeRows){const _=[];for(let x=O.startRow;x<=O.endRow;x+=1)_.push(Math.min(T.resize.rowAxis.sizeOf(x),an));$.rowHeights=_}}return $},[]),h=i.useCallback((O,T)=>{const P=t.current,H=P.getSelection(),$=H.ranges[H.ranges.length-1],_=zt([$]);if(_>P.maxOperationCells)return O.preventDefault(),P.onOperationRejected?.(T,_,"limit"),null;if(T==="cut"&&br(P.adapter,$))return O.preventDefault(),P.rejectReadOnly({kind:"operation",op:"cut",cellCount:_}),null;H.ranges.length>1&&P.onCopyMultiRange?.();const x=u($),g=bc(x),p=Ui(O);return p!==null&&(p.setData("text/plain",Wt.serializeClipboardTsv(x.cells.map(C=>C.map(v=>v.t)))),p.setData("text/html",aa(x,g)),p.setData(po,g)),O.preventDefault(),{payload:x,range:$}},[u]),m=i.useCallback((O,T)=>t.current.commitPaste(O,T)!==null,[]),y=i.useCallback((O,T,P)=>{const H=t.current;if(!P.sizes||H.resize===void 0)return;const{rowAxis:$,colAxis:_,resizeTracks:x}=H.resize,g=(p,C,v)=>{const k=Ts(C,v,null,{maxOperationCells:H.maxOperationCells,rowHiddenLimit:As,axisKind:p});if(!k.ok){H.onOperationRejected?.("resize",k.count,k.reason);return}x(p,k.entries)};if(O.colWidths!==void 0){const p=[];for(let C=T.startCol;C<=T.endCol;C+=1)p.push({index:C,size:O.colWidths[(C-T.startCol)%O.cols]});g("col",_,p)}if(O.rowHeights!==void 0){const p=[];for(let C=T.startRow;C<=T.endRow;C+=1)p.push({index:C,size:O.rowHeights[(C-T.startRow)%O.rows]});g("row",$,p)}},[]),N=i.useCallback((O,T)=>{const P=t.current,H=P.adapter,$=O.payload,_={row:T.startRow,col:T.startCol},x=$.rows*$.cols+zt([O.range]);if(x>P.maxOperationCells)return P.onOperationRejected?.("paste",x,"limit"),"rejected";if(_.row+$.rows>H.rowCount||_.col+$.cols>H.colCount||O.range.endRow>=O.sourceAdapter.rowCount||O.range.endCol>=O.sourceAdapter.colCount)return P.onOperationRejected?.("paste",x,"bounds"),"rejected";const g=vs({rows:$.rows,cols:$.cols},ke(_,_),_,H.rowCount,H.colCount);if(g!==null&&br(H,g))return P.rejectReadOnly({kind:"operation",op:"paste",cellCount:$.rows*$.cols}),"rejected";if(br(O.sourceAdapter,O.range))return P.rejectReadOnly({kind:"operation",op:"cut",cellCount:zt([O.range])}),"rejected";const p=Xi(O),C=uo(H),v=Wi(p,C),k={row:0,col:0,readText:()=>Zn(H,k.row,k.col).text,readFormat:()=>H.getCellFormat===void 0?void 0:H.getCellFormat(k.row,k.col)},{edits:b,tiles:R}=fi(v.cells,ke(_,_),_,H.rowCount,H.colCount,(E,d,L)=>(k.row=O.range.startRow+(d-_.row),k.col=O.range.startCol+(L-_.col),Yi(E,v,k,ji,C))),a=uo(O.sourceAdapter),f=[];if(nn([O.range],E=>{f.push(fg(E.row,E.col,a))}),O.sourceAdapter===H){if(!m([...f,...b],{sameSheet:!0,conditionalFormats:[]}))return"rejected"}else{const E=P.commitPaste(b,{sameSheet:!1,conditionalFormats:Ki(v.conditionalFormats,R)});if(E===null)return"rejected";try{O.sourceAdapter.applyEdits(f,{transaction:E,source:"paste",sameSheet:!1,conditionalFormats:[]})}catch(d){P.onEditRejected?.(d,{source:"paste"})}}return P.setSelection({ranges:[ke(_,{row:_.row+p.rows-1,col:_.col+p.cols-1})],anchor:_,active:_}),"applied"},[m]),W=i.useCallback((O,T,P)=>{const H=t.current,$=H.adapter,_=X=>(H.onClipboardUnavailable?.(X),"rejected"),x=vc(O,T);if(x==="none")return T==="menu"?_("empty"):"empty";const g=H.getSelection(),p=g.ranges[g.ranges.length-1],C=P.transpose===!0,v=(X,G)=>{const J=rg(C?G:X,C?X:G,p);return J>H.maxOperationCells?(H.onOperationRejected?.("paste",J,"limit"),!0):!1};let k,b=null;if(x==="aqsp"){const X=Nd(O,T);if(X===null)return _("unreadable");const G=n.current;if(G!==null&&X.clipId===G.clipId&&(b=G),b!==null&&b.kind==="cut"&&og(P))return N(b,p);if(v(X.rows,X.cols))return"rejected";if(b!==null){if(b.kind==="cut"&&(b.range.endRow>=b.sourceAdapter.rowCount||b.range.endCol>=b.sourceAdapter.colCount))return H.onOperationRejected?.("paste",b.payload.rows*b.payload.cols,"bounds"),"rejected";k=Xi(b)}else{const J=Pd(O,T);if(J===null)return _("unreadable");if(v(J.rows,J.cols))return"rejected";k=dg(J)}}else if(x==="tsv"){const X=O.getData("text/plain"),G=Wt.measureTsv(X);if(v(G.rows,G.cols))return"rejected";k=ug(Wt.parseTsv(X))}else{const X=O.getData("text/html"),G=af(X);if(G.cols===0&&G.rows>H.maxOperationCells)return H.onOperationRejected?.("paste",G.rows,"limit"),"rejected";if(v(G.rows,G.cols))return"rejected";const J=pa(X,x,H.formats===void 0?{}:{currency:H.formats.currency,locale:H.formats.locale},H.maxOperationCells);if(J.outcome==="none")return _("unreadable");if(J.outcome==="limit")return H.onOperationRejected?.("paste",J.cells,"limit"),"rejected";if(v(J.payload.rows,J.payload.cols))return"rejected";k=J.payload}const R=uo($),a=Wi(C?Zm(k):k,R),f=Wa[P.mode];if(sg(f)){const X=vs({rows:a.rows,cols:a.cols},p,g.active,$.rowCount,$.colCount);if(X!==null&&br($,X))return H.rejectReadOnly({kind:"operation",op:"paste",cellCount:zt([X])}),"rejected"}const E={row:0,col:0,readText:()=>Zn($,E.row,E.col).text,readFormat:()=>$.getCellFormat===void 0?void 0:$.getCellFormat(E.row,E.col)},{edits:d,tiles:L}=fi(a.cells,p,g.active,$.rowCount,$.colCount,(X,G,J)=>(E.row=G,E.col=J,Yi(X,a,E,P,R))),A=pg(L,a.rows,a.cols,$.rowCount,$.colCount);if(A===null)return"empty";if(f.cf&&a.conditionalFormats.length>0){let X=0;for(const J of a.conditionalFormats)X+=J.ranges.length;const G=L.length*X;if(G>H.maxOperationCells)return H.onOperationRejected?.("paste",G,"limit"),"rejected"}const M=f.cf?Ki(a.conditionalFormats,L):[];if(d.length===0&&M.length===0)return y(a,A,f),"empty";r.current=b===null?"foreign":"own";let B=!1;try{B=m(d,{sameSheet:b!==null&&b.sourceAdapter===$,conditionalFormats:M})}finally{r.current="none"}if(!B)return"rejected";y(a,A,f);const I={row:A.startRow,col:A.startCol};return H.setSelection({ranges:[A],anchor:I,active:I}),"applied"},[N,m,y]),D=i.useCallback(async O=>{const T=C=>(t.current.onClipboardUnavailable?.(C),"rejected"),P=navigator;if(P.clipboard===void 0)return T("insecure-origin");let H;try{H=await P.clipboard.read({unsanitized:["text/html"]})}catch{return T("permission-denied")}if(H.length===0)return T("empty");const $=H[0],_=Array.from($.types),x=new Map;try{for(const C of ng)_.includes(C)&&x.set(C,await(await $.getType(C)).text())}catch{return T("unreadable")}const g={types:_,getData:C=>{const v=x.get(C);if(v===void 0)throw new RangeError(`[spreadsheet] clipboard flavour ${C} was not materialised for the menu path`);return v}},p=t.current;return!p.enabled||p.isDragging()||p.isEditing()?"rejected":W(g,"menu",O)},[W]),j=i.useCallback(async O=>{const T=await D(O);return t.current.onPasteResolved?.(T,"menu"),T},[D]),{enabled:U,sinkRef:V}=e;return i.useEffect(()=>{const O=V.current;if(!U||O===null)return;const T=_=>t.current.isDragging()?(_.preventDefault(),!0):!1,P=_=>{const x=t.current;if(T(_)||x.isEditing())return;const g=h(_,"copy");g!==null&&c("copy",g.range,g.payload)},H=_=>{const x=t.current;if(T(_)||x.isEditing())return;const g=h(_,"cut");g!==null&&c("cut",g.range,g.payload)},$=_=>{const x=t.current;if(T(_)||x.isEditing())return;_.preventDefault();let g=ji;const p=x.pendingPasteOptionsRef;p!==void 0&&p.current!==null&&(g=p.current,p.current=null);const C=Ui(_);if(C===null)return;const v=W(lg(C),"event",g);x.onPasteResolved?.(v,"event")};return O.addEventListener("copy",P),O.addEventListener("cut",H),O.addEventListener("paste",$),()=>{O.removeEventListener("copy",P),O.removeEventListener("cut",H),O.removeEventListener("paste",$)}},[U,V,h,c,W]),i.useMemo(()=>({getClip:()=>{const O=n.current;return O===null?null:{kind:O.kind,range:O.range,foreign:O.sourceAdapter!==t.current.adapter}},discardClip:o,discardClipOnCommit:s,onAdapterSwitch:l,paste:j}),[o,s,l,j])},Ka=e=>{if(e!==2&&e!==3&&e!==-2&&e!==-3)throw new RangeError(`[spreadsheet] self-calc exponent must be 2, 3, -2 or -3; got ${String(e)}`)},Ua=e=>{let t=e,n=!1;t.startsWith("-")?(n=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1));const r=t.search(/[eE]/);let o=null;r>=0&&(o=Number(t.slice(r+1)),t=t.slice(0,r));const s=t.indexOf("."),l=s<0?t:t.slice(0,s),c=s<0?"":t.slice(s+1);return{negative:n,digits:l+c,point:l.length,exponent:o}},Gi=(e,t,n)=>{let r,o;return n<=0?(r="0",o="0".repeat(-n)+t):n>=t.length?(r=t+"0".repeat(n-t.length),o=""):(r=t.slice(0,n),o=t.slice(n)),r=r.replace(/^0+(?=\d)/,""),o=o.replace(/0+$/,""),r==="0"&&o===""?"0":`${e?"-":""}${r}${o===""?"":`.${o}`}`},Xa=(e,t)=>{let n;if(e.exponent===null)n=Gi(e.negative,e.digits,e.point+t);else{const r=Gi(e.negative,e.digits,e.point);n=r==="0"?"0":`${r}e${e.exponent+t}`}return wt(n)===null?null:n},mg=(e,t)=>{Ka(t);const n=wt(e);return n===null?null:Xa(Ua(n),t)},gg=e=>{const t=wt(e);if(t!==null){const r=Ua(t);return Xa({...r,negative:!r.negative},0)}const n=e.trim().toUpperCase();return n==="TRUE"?"FALSE":n==="FALSE"?"TRUE":null},Ga=e=>{if(!e.startsWith("=")||e.length===1)throw new RangeError(`[spreadsheet] self-calc expects a formula ("=" followed by a body); got ${JSON.stringify(e)}`);return e.slice(1)},wg=e=>{let t=0,n=null;for(let r=0;r<e.length;r++){const o=e[r];if(n!==null){o===n&&(n=null);continue}if(o==='"'||o==="'")n=o;else if(o==="(")t++;else if(o===")"&&(t--,t<0))return!1}return n===null&&t===0},Za=(e,t,n)=>{if(e.length<=t.length+n.length||!e.startsWith(t)||!e.endsWith(n))return null;const r=e.slice(t.length,e.length-n.length);return wg(r)?r:null},Cg=(e,t)=>{Ka(t);const n=Ga(e),r=Math.abs(t)===2?"100":"1000",o=t>0?"*":"/",s=t>0?"/":"*",l=Za(n,"(",`)${s}${r}`);return l===null?`=(${n})${o}${r}`:`=${l}`},bg=e=>{const t=Ga(e),n=Za(t,"-(",")");return n===null?`=-(${t})`:`=${n}`},mr=(e,t,n,r)=>{const o=zt(t);return o>n?(r?.(e,o,"limit"),!1):!0},Qr={Yellow:"#FFFF99",Blue:"#CCFFFF",Green:"#CCFFCC",Red:"#FFCCCC"},eo={Yellow:"#FFFF00",Blue:"#0000FF",Green:"#00FF00",Red:"#FF0000"},Zi={bold:{kind:"toggle",key:"bold"},italic:{kind:"toggle",key:"italic"},underline:{kind:"toggle",key:"underline"},strikethrough:{kind:"toggle",key:"strikethrough"},clearFormatting:{kind:"clear"},alignLeft:{kind:"patch",patch:{align:"left"}},alignCenter:{kind:"patch",patch:{align:"center"}},alignRight:{kind:"patch",patch:{align:"right"}},formatNumber:{kind:"value",value:"number"},formatTime:{kind:"value",value:"time"},formatDate:{kind:"value",value:"date"},formatCurrency:{kind:"value",value:"currency"},formatPercent:{kind:"value",value:"percent"},formatScientific:{kind:"value",value:"scientific"},bordersOuter:{kind:"borders",preset:"outer"},bordersClear:{kind:"borders",preset:"clear"},borderTop:{kind:"borders",preset:"top"},borderRight:{kind:"borders",preset:"right"},borderBottom:{kind:"borders",preset:"bottom"},borderLeft:{kind:"borders",preset:"left"},insertLink:{kind:"popover",popover:"link"},insertNote:{kind:"popover",popover:"note"},insertComment:{kind:"popover",popover:"comment"},openHyperlink:{kind:"openHyperlink"},openValidationList:{kind:"popover",popover:"list"},pasteSpecial:{kind:"pasteSpecial"},fillDown:{kind:"fill",direction:"down"},fillRight:{kind:"fill",direction:"right"},fillSelection:{kind:"fill",direction:"selection"},insertDate:{kind:"insertNow",unit:"date"},insertTime:{kind:"insertNow",unit:"time"},hideRows:{kind:"hide",axis:"row",hide:!0},hideColumns:{kind:"hide",axis:"col",hide:!0},unhideRows:{kind:"hide",axis:"row",hide:!1},unhideColumns:{kind:"hide",axis:"col",hide:!1},formatGeneral:{kind:"patch",patch:{value:null}},bordersAll:{kind:"borders",preset:"all"},pasteFormats:{kind:"paste",options:{mode:"formats"}},pasteFormulas:{kind:"paste",options:{mode:"formulas"}},pasteAdd:{kind:"paste",options:{mode:"all",operation:"add"}},pasteSubtract:{kind:"paste",options:{mode:"all",operation:"subtract"}},pasteMultiply:{kind:"paste",options:{mode:"all",operation:"multiply"}},pasteDivide:{kind:"paste",options:{mode:"all",operation:"divide"}},multiplyBy100:{kind:"calc",exponent:2},multiplyBy1000:{kind:"calc",exponent:3},divideBy100:{kind:"calc",exponent:-2},divideBy1000:{kind:"calc",exponent:-3},signReversal:{kind:"sign"},fillColorYellow:{kind:"color",key:"background",preset:Qr.Yellow,custom:null},fillColorBlue:{kind:"color",key:"background",preset:Qr.Blue,custom:null},fillColorGreen:{kind:"color",key:"background",preset:Qr.Green,custom:null},fillColorRed:{kind:"color",key:"background",preset:Qr.Red,custom:null},fillColorCustom1:{kind:"color",key:"background",preset:null,custom:0},fillColorCustom2:{kind:"color",key:"background",preset:null,custom:1},fillColorCustom3:{kind:"color",key:"background",preset:null,custom:2},fillColorCustom4:{kind:"color",key:"background",preset:null,custom:3},fillColorCustom5:{kind:"color",key:"background",preset:null,custom:4},fontColorYellow:{kind:"color",key:"color",preset:eo.Yellow,custom:null},fontColorBlue:{kind:"color",key:"color",preset:eo.Blue,custom:null},fontColorGreen:{kind:"color",key:"color",preset:eo.Green,custom:null},fontColorRed:{kind:"color",key:"color",preset:eo.Red,custom:null},fontColorCustom1:{kind:"color",key:"color",preset:null,custom:0},fontColorCustom2:{kind:"color",key:"color",preset:null,custom:1},fontColorCustom3:{kind:"color",key:"color",preset:null,custom:2},fontColorCustom4:{kind:"color",key:"color",preset:null,custom:3},fontColorCustom5:{kind:"color",key:"color",preset:null,custom:4},increaseColumnWidth:{kind:"resize",axis:"col",step:1},decreaseColumnWidth:{kind:"resize",axis:"col",step:-1},increaseRowHeight:{kind:"resize",axis:"row",step:1},decreaseRowHeight:{kind:"resize",axis:"row",step:-1},autoFitColumnWidth:{kind:"resize",axis:"col",step:"fit"},toggleRowHighlight:{kind:"highlight",target:"row"},toggleColumnHighlight:{kind:"highlight",target:"column"},toggleBothHighlight:{kind:"highlight",target:"both"},toggleIntersectionHighlight:{kind:"highlight",target:"intersection"}},yg={value:null,align:null,verticalAlign:null,wrap:null,background:null,color:null,bold:null,italic:null,underline:null,strikethrough:null,fontFamily:null,fontSize:null,borders:null},kr=e=>e<10?`0${e}`:String(e),Rg=e=>{const t=new Date(e);return`${t.getFullYear()}-${kr(t.getMonth()+1)}-${kr(t.getDate())}`},vg=e=>{const t=new Date(e);return`${kr(t.getHours())}:${kr(t.getMinutes())}:${kr(t.getSeconds())}`},Sg=(e,t)=>(e.row===t.startRow?1:0)|(e.col===t.endCol?2:0)|(e.row===t.endRow?4:0)|(e.col===t.startCol?8:0),kg=(e,t)=>({...(e&1)!==0?{top:t}:{},...(e&2)!==0?{right:t}:{},...(e&4)!==0?{bottom:t}:{},...(e&8)!==0?{left:t}:{}}),Eg=e=>e===void 0||e.borders===void 0?{}:e.borders,Og={top:1,right:2,bottom:4,left:8},Ag={style:"thin",color:$s},xg=(e,t)=>{if(e===void 0)return!1;const n=ot(e);return n!==null&&n===ot(t)},Tg=(e,t)=>{const n=t===void 0||t.locale===void 0?{}:{locale:t.locale};switch(e){case"number":return{type:"number",decimals:2,grouping:!0,...n};case"time":return{type:"date",pattern:"HH:mm:ss"};case"date":return{type:"date"};case"currency":if(t===void 0)throw new RangeError("[spreadsheet] formatCurrency requires the formats prop (currency)");return{type:"currency",currency:t.currency,decimals:2,...n};case"percent":return{type:"percent",decimals:2,...n};default:return{type:"scientific",decimals:2,...n}}},$g=e=>{const t=i.useRef(e);t.current=e;const n=i.useCallback(()=>{const g=t.current;if(g.isEditing()){const p=g.getActive();return[ke(p,p)]}return g.getSelection().ranges},[]),r=i.useCallback(()=>{const g=t.current,p=g.getActive();return g.adapter.getCellFormat===void 0?void 0:g.adapter.getCellFormat(p.row,p.col)},[]),o=i.useCallback(g=>{const p=t.current,C=n();if(!mr("format",C,p.maxOperationCells,p.onOperationRejected))return!1;if(Bn(p.adapter,C))return p.rejectReadOnly({kind:"operation",op:"format",cellCount:zt(C)}),!1;const v=new Map,k=[],b=p.adapter.getCellFormat;for(const R of C)nn([R],a=>{const f=b===void 0?void 0:b(a.row,a.col),{bucket:E,patch:d}=g(a,R,f);let L=v.get(E);L===void 0&&(L=new Map,v.set(E,L));let A;L.has(f)?A=L.get(f):(A=Ds(f,d),L.set(f,A)),A!==f&&k.push({row:a.row,col:a.col,format:A===void 0?null:A})});return k.length===0?!0:p.commitEdits(k,{source:"format"})===null?!1:(p.isEditing()&&p.refreshEditPaint(),!0)},[n]),s=i.useCallback(g=>o(()=>({bucket:0,patch:g})),[o]),l=i.useCallback((g,p)=>{const C=t.current;C.formatCommandAnnouncement!==void 0&&C.announce(C.formatCommandAnnouncement({command:g,state:p}))},[]),c=i.useCallback((g,p=Ag)=>{if(g==="clear")return s({borders:null});if(g==="all")return s({borders:{top:p,right:p,bottom:p,left:p}});const C=g==="outer"?15:Og[g];return o((v,k,b)=>{const R=Sg(v,k)&C;return{bucket:R,patch:{borders:{...Eg(b),...kg(R,p)}}}})},[s,o]),u=i.useCallback((g,p,C)=>{const v=Ca(t.current.adapter,g.row,g.col);for(const k of p)C.push(ba(v,g,k))},[]),h=i.useCallback(g=>{const p=t.current,C=p.getSelection();if(!mr("fill",C.ranges,p.maxOperationCells,p.onOperationRejected))return!1;const v=[];if(g==="selection"){const b=C.active,R=[];nn(C.ranges,a=>{(a.row!==b.row||a.col!==b.col)&&R.push(a)}),v.push({source:b,targets:R})}else for(const b of C.ranges)if(g==="down"){const R=b.startRow===b.endRow;if(R&&b.startRow===0)continue;const a=R?b.startRow-1:b.startRow;for(let f=b.startCol;f<=b.endCol;f+=1){const E=[];for(let d=R?b.startRow:b.startRow+1;d<=b.endRow;d+=1)E.push({row:d,col:f});v.push({source:{row:a,col:f},targets:E})}}else{const R=b.startCol===b.endCol;if(R&&b.startCol===0)continue;const a=R?b.startCol-1:b.startCol;for(let f=b.startRow;f<=b.endRow;f+=1){const E=[];for(let d=R?b.startCol:b.startCol+1;d<=b.endCol;d+=1)E.push({row:f,col:d});v.push({source:{row:f,col:a},targets:E})}}for(const b of v)for(const R of b.targets)if(Je(p.adapter,R.row,R.col)){let a=0;for(const f of v)a+=f.targets.length;return p.rejectReadOnly({kind:"operation",op:"fill",cellCount:a}),!1}const k=[];for(const b of v)u(b.source,b.targets,k);return k.length===0?!0:p.commitEdits(k,{source:"fill"})!==null},[u]),m=i.useCallback(()=>{const g=t.current,p=g.getSessionText();if(p===null)return!1;const C=g.getSelection();if(!mr("fill",C.ranges,g.maxOperationCells,g.onOperationRejected))return!1;if(Bn(g.adapter,C.ranges))return g.rejectReadOnly({kind:"operation",op:"fill",cellCount:zt(C.ranges)}),!1;const v=[];let k=!1;return nn(C.ranges,b=>{if(!k){if(!g.validateCommit(b,p).ok){k=!0;return}v.push({row:b.row,col:b.col,text:p})}}),k||g.commitEdits(v,{source:"fill"})===null?!1:(g.cancelEdit(),!0)},[]),y=i.useCallback(g=>{const p=t.current,C=p.getSelection();if(!mr("calc",C.ranges,p.maxOperationCells,p.onOperationRejected))return!1;if(Bn(p.adapter,C.ranges))return p.rejectReadOnly({kind:"operation",op:"calc",cellCount:zt(C.ranges)}),!1;const v=[],k=p.adapter;return nn(C.ranges,b=>{const R=k.getCellFormula===void 0?void 0:k.getCellFormula(b.row,b.col),a=R===void 0?g.text(k.getCellText(b.row,b.col)):g.formula(R);a!==null&&v.push({row:b.row,col:b.col,text:a})}),v.length===0?!0:p.commitEdits(v,{source:"calc"})!==null},[]),N=i.useCallback((g,p)=>{const C=t.current,v=g==="row"?C.rowAxis:C.colAxis,k=C.getSelection(),b=g==="row"?Math.floor(C.maxOperationCells/xs):C.maxOperationCells;let R=0;for(const L of k.ranges)R+=g==="row"?L.endRow-L.startRow+1:L.endCol-L.startCol+1;if(R>b)return C.onOperationRejected?.("resize",R,"limit"),!1;const a=new Set,f=[],E=p?0:g==="row"?C.defaultRowHeight:C.defaultColumnWidth;for(const L of k.ranges){const A=g==="row"?L.startRow:L.startCol,M=g==="row"?L.endRow:L.endCol;for(let B=A;B<=M;B+=1){if(a.has(B))continue;a.add(B),v.sizeOf(B)===0!==p&&f.push({index:B,size:E})}}const d=Ts(v,f,null,{maxOperationCells:C.maxOperationCells,rowHiddenLimit:As,axisKind:g});return d.ok?(d.entries.length>0&&C.resizeTracks(g,d.entries),!0):(C.onOperationRejected?.("resize",d.count,d.reason),!1)},[]),W=i.useCallback(()=>{const g=t.current;if(g.adapter.getCellHyperlink===void 0)return;const p=g.getActive();return Jn(g.adapter.getCellHyperlink(p.row,p.col))},[]),D=i.useCallback(g=>{const p=t.current,C=p.adapter,v=Zi[g],k=C.getCellFormat!==void 0,b=R=>p.popovers===void 0?!0:p.popovers[R]!==!1;switch(v.kind){case"resize":return p.trackResize!==void 0;case"toggle":case"patch":case"clear":case"borders":case"color":return k;case"value":return k&&(v.value!=="currency"||p.formats!==void 0);case"popover":switch(v.popover){case"link":return C.getCellHyperlink!==void 0&&b("link");case"note":return C.getCellNote!==void 0&&b("note");case"comment":return C.getCellComments!==void 0&&b("comment");default:return C.getCellValidation!==void 0&&b("list")}case"openHyperlink":return C.getCellHyperlink!==void 0&&(p.onHyperlinkOpen!==void 0?W()!==void 0:b("link"));case"paste":return v.options.mode==="formats"?k:v.options.mode==="formulas"?C.getCellFormula!==void 0:!0;default:return!0}},[W]),j=i.useCallback(g=>{const p=t.current,C=g.kind==="popover"?g.popover:g.kind==="openHyperlink"&&p.onHyperlinkOpen===void 0?"link":void 0;if(C===void 0)return!0;const v=p.getActive();if(!Je(p.adapter,v.row,v.col))return!0;if(C==="list")return p.rejectReadOnly({kind:"edit",cell:v,editSession:"none"}),!1;let k;if(C==="link")k=W()!==void 0;else if(C==="note"){const b=p.adapter.getCellNote===void 0?void 0:p.adapter.getCellNote(v.row,v.col);k=b!==void 0&&b!==""}else{const b=p.adapter.getCellComments===void 0?void 0:p.adapter.getCellComments(v.row,v.col);k=b!==void 0&&b.length>0}return k?!0:(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1)},[W]),U=i.useCallback((g,p,C)=>{const v=t.current,k=v.trackResize;if(k===void 0)return!1;const b=v.getActive(),R=p==="col"?b.col:b.row,a=C==="fit"?k.autofitColumn(R):k.stepTrack(p,R,C),f=(p==="col"?v.colAxis:v.rowAxis).sizeOf(R);return a&&f>0&&v.formatResizeAnnouncement!==void 0&&v.announce(v.formatResizeAnnouncement({command:g,axis:p==="col"?"column":"row",index:R,size:f})),a},[]),V=i.useCallback(g=>{const p=t.current;if(!D(g))return!1;const C=Zi[g];if(!j(C))return!1;const v=p.isEditing();if(v&&!Ws.has(g)&&!p.requestCommit())return!1;switch(C.kind){case"toggle":{const k=r(),b=k!==void 0&&k[C.key]===!0;return s({[C.key]:b?null:!0})?(l(g,!b),!0):!1}case"patch":return s(C.patch)?(l(g,null),!0):!1;case"clear":return s(yg)?(l(g,null),!0):!1;case"value":return s({value:Tg(C.value,p.formats)})?(l(g,null),!0):!1;case"borders":return c(C.preset)?(l(g,null),!0):!1;case"color":{const k=C.key==="background"?p.colors.fill:p.colors.font,b=C.preset!==null?C.preset:C.custom!==null&&C.custom<k.length?k[C.custom]:void 0;if(b===void 0)return!1;const R=r(),a=xg(R===void 0?void 0:R[C.key],b);return s({[C.key]:a?null:b})?(l(g,!a),!0):!1}case"calc":return y({text:k=>mg(k,C.exponent),formula:k=>Cg(k,C.exponent)});case"sign":return y({text:gg,formula:bg});case"fill":return v&&C.direction==="selection"?m():h(C.direction);case"popover":return p.openPopover(C.popover),!0;case"openHyperlink":{if(p.onHyperlinkOpen!==void 0){const k=W();return k===void 0?!1:(p.onHyperlinkOpen(k,p.getActive()),!0)}return p.openPopover("link"),!0}case"pasteSpecial":return p.onPasteSpecialRequest!==void 0?(p.onPasteSpecialRequest({kind:"keyboard",cellRect:p.keyboardCellRect()}),!0):(p.paste({mode:"formats"}),!0);case"paste":return p.paste(C.options),!0;case"insertNow":{const k=C.unit==="date"?Rg(p.now()):vg(p.now());if(v)return p.insertAtCaret(k),!0;const b=p.getActive();return Je(p.adapter,b.row,b.col)?(p.rejectReadOnly({kind:"edit",cell:b,editSession:"none"}),!1):p.validateCommit(b,k).ok?p.commitEdits([{row:b.row,col:b.col,text:k}],{source:"edit",editSession:"discarded"})!==null:!1}case"hide":return N(C.axis,C.hide);case"resize":return U(g,C.axis,C.step);default:{const k=p.getHighlight();switch(C.target){case"row":return p.setHighlight({...k,row:!k.row}),!0;case"column":return p.setHighlight({...k,column:!k.column}),!0;case"both":{const b=k.row&&k.column;return p.setHighlight({...k,row:!b,column:!b}),!0}default:return p.setHighlight({...k,intersection:!k.intersection}),!0}}}},[D,j,W,r,s,l,c,y,h,m,N,U]),O=i.useCallback(()=>{const g=t.current;return!(g.isEditing()&&!g.requestCommit())},[]),T=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellHyperlink===void 0)throw new RangeError("[spreadsheet] setHyperlink requires the getCellHyperlink capability");const C=g===null?null:un(g);if(g!==null&&C===null)throw new RangeError(`[spreadsheet] setHyperlink received an unnormalisable url ${JSON.stringify(g)}`);if(!O())return!1;const v=p.getActive();return Je(p.adapter,v.row,v.col)?(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1):p.commitEdits([{row:v.row,col:v.col,hyperlink:C}],{source:"annotate"})!==null},[O]),P=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellNote===void 0)throw new RangeError("[spreadsheet] setNote requires the getCellNote capability");if(!O())return!1;const C=p.getActive();return Je(p.adapter,C.row,C.col)?(p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1):p.commitEdits([{row:C.row,col:C.col,note:g}],{source:"annotate"})!==null},[O]),H=i.useCallback(g=>{const p=t.current,C=p.adapter.getCellComments;if(C===void 0)throw new RangeError("[spreadsheet] addComment requires the getCellComments capability");if(!O())return!1;const v=p.getActive();if(Je(p.adapter,v.row,v.col))return p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),!1;const k=C(v.row,v.col),b=k===void 0?[g]:[...k,g];return p.commitEdits([{row:v.row,col:v.col,comments:b}],{source:"annotate"})!==null},[O]),$=i.useCallback(g=>{const p=t.current;if(p.adapter.getCellValidation===void 0)throw new RangeError("[spreadsheet] setValidation requires the getCellValidation capability");if(!O())return!1;const C=p.getSelection().ranges;if(!mr("annotate",C,p.maxOperationCells,p.onOperationRejected))return!1;if(Bn(p.adapter,C))return p.rejectReadOnly({kind:"operation",op:"annotate",cellCount:zt(C)}),!1;const v=[];return nn(C,k=>{v.push({row:k.row,col:k.col,validation:g})}),p.commitEdits(v,{source:"annotate"})!==null},[O]),_=i.useCallback(g=>{if(t.current.adapter.getCellFormat===void 0)throw new RangeError("[spreadsheet] applyFormat requires the getCellFormat capability");return s(g)},[s]),x=i.useCallback((g,p)=>{if(t.current.adapter.getCellFormat===void 0)throw new RangeError("[spreadsheet] setBorders requires the getCellFormat capability");return c(g,p)},[c]);return i.useMemo(()=>({executeCommand:V,applyFormat:_,setBorders:x,setHyperlink:T,setNote:P,addComment:H,setValidation:$,isCommandAvailable:D}),[V,_,x,T,P,H,$,D])},to="data-aqsp-pointing",Lg=(e,t)=>{const n=Gc(e,t);return n!==null&&"insertAt"in n},Dg=(e,t)=>{Object.assign(e.style,Object.fromEntries(t.map(n=>[n,""])))},Mg=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(null),[r,o]=i.useState(!1),s=i.useRef(!1),l=i.useRef(!1),c=i.useRef(!1),u=i.useRef(null),h=i.useRef(Ht),m=i.useCallback(()=>{const R=t.current,a=R.sinkRef.current;if(R.adapter.getCellFormula===void 0||n.current===null||!c.current||a===null)return null;const f=Gc(a.value,a.selectionStart);return f===null?null:{sink:a,target:f}},[]),y=i.useCallback(()=>{const R=t.current.sinkRef.current;if(R===null)return;const a=m()!==null;a!==R.hasAttribute(to)&&(a?R.setAttribute(to,""):R.removeAttribute(to))},[m]),N=i.useCallback((R,a)=>{const f=t.current;if(f.resolveEditPaint===void 0)return;const E=f.resolveEditPaint(a),d=E===null?Ht:E;d!==Ht&&Object.assign(R.style,d.style),h.current=d,f.editPaintRef!==void 0&&(f.editPaintRef.current=d)},[]),W=i.useCallback(R=>{Dg(R,Object.keys(h.current.style)),h.current=Ht;const a=t.current.editPaintRef;a!==void 0&&(a.current=Ht)},[]),D=i.useCallback(R=>{const a=t.current,f=n.current;if(f===null)return!0;const E=()=>{n.current=null,u.current=null;const d=a.sinkRef.current;d!==null&&(d.style.removeProperty("text-align"),W(d),d.removeAttribute(to)),o(!1)};if(R.commit){const d=a.sinkRef.current,L=d===null?"":d.value,A=Zn(a.adapter,f.cell.row,f.cell.col).text.replace(/\r\n?/g,`
13
+ `),M=L===A;let B;if(M)B=!0;else if(Je(a.adapter,f.cell.row,f.cell.col))a.rejectReadOnly({kind:"edit",cell:f.cell,editSession:R.onReject==="keep"?"kept":"discarded"}),B=!1;else{const I={source:"edit",editSession:R.onReject==="keep"?"kept":"discarded"};B=(a.validateCommit===void 0||a.validateCommit(f.cell,L).ok)&&a.commitEdits([{row:f.cell.row,col:f.cell.col,text:L}],I)!==null}if(!B)return R.onReject==="discard"&&(E(),a.rearmSink()),!1}return E(),R.rearm&&a.rearmSink(),!0},[W]),j=i.useCallback((R,a)=>{const f=t.current;if(f.isDragging()||n.current!==null)return;const E=f.sinkRef.current;if(E===null)return;const d=f.getActive();if(Je(f.adapter,d.row,d.col)){f.rejectReadOnly({kind:"edit",cell:d,editSession:"none"});return}if(f.discardClip(),f.ensureCellVisible(d),R==="edit"){const{text:A,isFormula:M}=Zn(f.adapter,d.row,d.col);E.value=A;const B=a===void 0||M?A.length:Math.min(a,A.length);E.setSelectionRange(B,B)}else E.value="";const L=f.resolveEditAlign(d);L!==null&&(E.style.textAlign=L),N(E,d),c.current=!1,u.current=null,n.current={cell:d,mode:R},o(!0)},[N]),U=i.useCallback(()=>{D({rearm:!0,commit:!1})},[D]),V=i.useCallback(()=>{const R=t.current;if(n.current===null)return!0;const a=R.sinkRef.current;if(s.current&&a!==null){l.current=!0;try{a.blur()}finally{l.current=!1}return D({rearm:!1,commit:!0,onReject:"keep"})?(R.focusSink(),R.rearmSink(),!0):(R.focusSink(),!1)}return D({rearm:!0,commit:!0,onReject:"keep"})},[D]),O=i.useCallback(()=>m()!==null,[m]),T=i.useCallback(()=>t.current.adapter.getCellFormula===void 0||n.current===null?!1:(c.current=!c.current,y(),!0),[y]),P=i.useCallback(()=>{const R=m(),a=n.current;if(R===null||a===null)return null;if("insertAt"in R.target)return u.current=a.cell,{origin:a.cell,cursor:a.cell,axis:"cells"};const f=Xc(R.sink.value,R.sink.selectionStart);if(f===null)return null;const E=f.token,d=u.current;switch(E.kind){case"cell":{const L={row:E.row,col:E.col};return u.current=L,{origin:L,cursor:L,axis:"cells"}}case"range":{const L=d!==null&&(d.row===E.start.row||d.row===E.end.row)&&(d.col===E.start.col||d.col===E.end.col)?{row:d.row,col:d.col}:{row:E.start.row,col:E.start.col};return u.current=L,{origin:L,cursor:{row:L.row===E.start.row?E.end.row:E.start.row,col:L.col===E.start.col?E.end.col:E.start.col},axis:"cells"}}case"column":{const L=d!==null&&(d.col===E.start.col||d.col===E.end.col)?d.col:E.start.col,A={row:a.cell.row,col:L};return u.current=A,{origin:A,cursor:{row:a.cell.row,col:L===E.start.col?E.end.col:E.start.col},axis:"columns"}}case"row":{const L=d!==null&&(d.row===E.start.row||d.row===E.end.row)?d.row:E.start.row,A={row:L,col:a.cell.col};return u.current=A,{origin:A,cursor:{row:L===E.start.row?E.end.row:E.start.row,col:a.cell.col},axis:"rows"}}}},[m]),H=i.useCallback((R,a)=>{const f=m();if(f===null)return;const E=Bf(R,a),{sink:d}=f,[L,A]="replace"in f.target?f.target.replace:[f.target.insertAt,f.target.insertAt],M=d.value;d.value=`${M.slice(0,L)}${E}${M.slice(A)}`;const B=L+E.length;d.setSelectionRange(B,B),"row"in R&&(u.current={row:R.row,col:R.col}),y()},[m,y]),$=i.useCallback(()=>{const R=t.current.sinkRef.current;return R===null?null:{value:R.value,selectionStart:R.selectionStart,selectionEnd:R.selectionEnd}},[]),_=i.useCallback(R=>{const a=t.current.sinkRef.current;a!==null&&(a.value=R.value,a.setSelectionRange(R.selectionStart,R.selectionEnd),u.current=null,y())},[y]),x=i.useCallback(()=>{const R=t.current,a=R.sinkRef.current;if(R.adapter.getCellFormula===void 0||n.current===null||a===null)return!1;const f=Qf(a.value,a.selectionStart);return f===null?!1:(a.value=f.text,a.setSelectionRange(f.caret,f.caret),y(),!0)},[y]),g=i.useCallback(R=>{const a=t.current.sinkRef.current;if(n.current===null||a===null)return;const f=a.selectionStart,E=a.selectionEnd;a.value=`${a.value.slice(0,f)}${R}${a.value.slice(E)}`;const d=f+R.length;a.setSelectionRange(d,d),u.current=null,y()},[y]),p=i.useCallback(()=>{const R=t.current.sinkRef.current;return n.current===null||R===null?null:R.value},[]),C=i.useCallback(()=>n.current===null?null:n.current.cell,[]),v=i.useCallback(()=>{const R=t.current,a=n.current,f=R.sinkRef.current;a===null||f===null||(W(f),N(f,a.cell),R.repaintOverlay?.())},[W,N]),{enabled:k,sinkRef:b}=e;return i.useEffect(()=>{const R=b.current;if(!k||R===null)return;const a=()=>{s.current=!0},f=()=>{s.current=!1},E=A=>{const M=t.current;if(l.current||n.current===null)return;const B=M.rootRef.current,I=A.relatedTarget;B!==null&&I instanceof Node&&B.contains(I)||D({rearm:!1,commit:!0,onReject:"discard"})},d=()=>{const A=t.current;u.current=null,A.adapter.getCellFormula!==void 0&&n.current!==null&&!c.current&&Lg(R.value,R.selectionStart)&&(c.current=!0),y()},L=()=>{n.current!==null&&y()};return R.addEventListener("compositionstart",a),R.addEventListener("compositionend",f),R.addEventListener("focusout",E),R.addEventListener("input",d),document.addEventListener("selectionchange",L),()=>{R.removeEventListener("compositionstart",a),R.removeEventListener("compositionend",f),R.removeEventListener("focusout",E),R.removeEventListener("input",d),document.removeEventListener("selectionchange",L)}},[k,b,D,y]),i.useMemo(()=>({isEditing:()=>n.current!==null,getEditingMode:()=>n.current?.mode??null,isFocusoutSuppressed:()=>l.current,requestCommit:V,cancelEdit:U,startEdit:j,getPointing:O,togglePointingArm:T,getReferenceCursor:P,insertReference:H,captureSink:$,restoreSink:_,cycleAnchorAtCaret:x,insertAtCaret:g,getSessionText:p,getSessionCell:C,refreshPaint:v,editing:r}),[V,U,j,O,T,P,H,$,_,x,g,p,C,v,r])},zg=(e,t,n)=>{const r=new st.FenwickMapTree(e,t);let o=0;if(n)for(let s=0;s<e;s+=1){const l=Math.round(n(s));l!==t&&r.update(s,l),l===0&&(o+=1)}return{tree:r,initialHidden:o}},Fg=(e,t,n)=>{const{tree:r,initialHidden:o}=zg(e,t,n);let s=o;const u={count:e,sizeOf:h=>r.get(h),offsetOf:h=>{const{cumulative:m,currentValue:y}=r.prefixSum(h);return m-y},indexAt:h=>{if(e===0||r.getTotal()===0)throw new RangeError("[spreadsheet] indexAt requires a non-empty axis with positive total size");const m=Math.floor(h),y=Math.min(Math.max(m,0),r.getTotal()-1);return r.findIndexAtOrAfter(y+.5).index},totalSize:()=>r.getTotal(),resize:(h,m)=>{if(!(Number.isFinite(m)&&m>=0))throw new RangeError(`[spreadsheet] resize requires a finite size >= 0, received ${m}`);const y=Math.round(m);r.get(h)===0!=(y===0)&&(s+=y===0?1:-1),r.update(h,y)},hiddenCount:()=>s};return{key:`${e}:${t}`,model:u}},ln=(e,t,n)=>{if(n>0){const o=e.offsetOf(t)+e.sizeOf(t);return o>=e.totalSize()?null:e.indexAt(o)}const r=e.offsetOf(t)-1;return r<0?null:e.indexAt(r)},Kn=(e,t,n)=>{if(t>n||e.count===0||e.totalSize()===0)return[];const r=[];let o=e.sizeOf(t)>0?t:ln(e,t,1);for(;o!==null&&o<=n;)r.push(o),o=ln(e,o,1);return r},Ji=(e,t,n)=>{if(!(Number.isInteger(t)&&t>0))throw new TypeError(`[spreadsheet] useAxisModel requires a positive integer defaultSize, received ${t}`);const r=i.useRef(n).current,o=i.useRef(null),s=`${e}:${t}`;return(o.current===null||o.current.key!==s)&&(o.current=Fg(e,t,r)),o.current.model},Un=256,os=256,Ng=2**32,Pg=4096,Ja=Object.freeze([]),Qa=["background","color","bold","italic","underline","strikethrough"],eu=(e,t)=>{if(!Array.isArray(e))throw new RangeError(`[spreadsheet] ${t} requires an array of conditional-format rules, received ${typeof e}`)},cn=(e,t,n)=>(e.size>=Pg&&e.clear(),e.set(t,n),n),tu=e=>(eu(e,"buildCfIndex"),{rules:e,buckets:new Map,columns:new Map}),nu=(e,t,n,r,o)=>{for(const s of e)if(s.startRow<=n&&s.endRow>=t&&s.startCol<=o&&s.endCol>=r)return!0;return!1},_g=(e,t,n)=>{const r=Math.floor(t/Un),o=Math.floor(n/os),s=r*65536+o,l=e.buckets.get(s);if(l!==void 0)return l;const c=r*Un,u=o*os,h=[];for(const m of e.rules)nu(m.ranges,c,c+Un-1,u,u+os-1)&&h.push(m);return cn(e.buckets,s,h.length===0?Ja:h)},qg=(e,t,n)=>{const r=Math.floor(t/Un),o=r*Ng+n,s=e.columns.get(o);if(s!==void 0)return s;const l=_g(e,t,n),c=r*Un,u=[];for(const h of l)nu(h.ranges,c,c+Un-1,n,n)&&u.push(h);return cn(e.columns,o,u.length===0?Ja:u)},jg=(e,t)=>{for(const n of e)if(kn(n,t))return!0;return!1},Ys=()=>({extrema:new Map,formulas:new Map,numbers:new Map}),no=(e,t)=>e<t?-1:e>t?1:0,Qi=(e,t,n)=>{switch(e){case"eq":return t===0;case"neq":return t!==0;case"gt":return t>0;case"gte":return t>=0;case"lt":return t<0;case"lte":return t<=0;case"between":return n!==null&&t>=0&&n<=0;case"notBetween":return n!==null&&(t<0||n>0);default:return!1}},ec=new WeakMap,Os=e=>e===null?null:Number(e),Ig=e=>{const t=ec.get(e);if(t!==void 0)return t;const n=e.b,r={a:Os(wt(e.a)),b:n===void 0?null:Os(wt(n))};return ec.set(e,r),r},ru=(e,t,n)=>{const r=`${t.row}\0${t.col}`,o=e.numbers.get(r);return o!==void 0?o:cn(e.numbers,r,Os(wt(n())))},Hg=(e,t,n,r)=>{const o=e.op==="between"||e.op==="notBetween",s=Ig(e),l=ru(r,t,n),c=o?s.b:null;if(l!==null&&s.a!==null&&(!o||c!==null))return Qi(e.op,no(l,s.a),c===null?null:no(l,c));const u=n(),h=e.b;return Qi(e.op,no(u,e.a),h===void 0?null:no(u,h))},Bg=(e,t)=>{switch(e.op){case"contains":return t.includes(e.value);case"notContains":return!t.includes(e.value);case"startsWith":return t.startsWith(e.value);case"endsWith":return t.endsWith(e.value);default:return!1}},ss=e=>{const t=ot(e);if(t===null)return null;const n=r=>Number.parseInt(t.slice(r,r+2),16);return[n(1),n(3),n(5),t.length===9?n(7):255]},ro=e=>e.toString(16).padStart(2,"0"),ls=(e,t,n)=>{const r=l=>Math.round(e[l]+(t[l]-e[l])*n),o=`#${ro(r(0))}${ro(r(1))}${ro(r(2))}`,s=r(3);return s===255?o:`${o}${ro(s)}`},is=(e,t,n)=>t===n?e<=t?0:1:Math.min(1,Math.max(0,(e-t)/(n-t))),Wg=(e,t,n,r,o)=>{let s=t.value===void 0?o.min:t.value,l=r.value===void 0?o.max:r.value,c=ss(t.color),u=ss(r.color);const h=n===void 0?void 0:ss(n.color);if(!(Number.isFinite(e)&&Number.isFinite(s)&&Number.isFinite(l))||c===null||u===null||h===null)return null;if(s>l){const y=s;s=l,l=y;const N=c;c=u,u=N}if(n!==void 0&&h!==void 0){const y=n.value===void 0?(s+l)/2:n.value;if(s<y&&y<l)return e<=y?ls(c,h,is(e,s,y)):ls(h,u,is(e,y,l))}return ls(c,u,is(e,s,l))},Vg=(e,t,n,r)=>{const o=r.extrema.get(e.id);if(o!==void 0)return o;const{min:s,max:l}=t;if(s.value!==void 0&&l.value!==void 0)return cn(r.extrema,e.id,{min:s.value,max:l.value});if(n.getRangeExtrema===void 0)return null;let c=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(const h of e.ranges){const m=n.getRangeExtrema(h);if(m===null)return cn(r.extrema,e.id,null);c=Math.min(c,m.min),u=Math.max(u,m.max)}return cn(r.extrema,e.id,{min:c,max:u})},Yg=(e,t,n,r,o,s)=>{const l=ru(s,n,r);if(l===null)return null;const c=Vg(e,t,o,s);return c===null?null:Wg(l,t.min,t.mid,t.max,c)},Kg=(e,t,n,r,o)=>{if(r.evaluateFormula===void 0)return!1;const s=`${e.id}\0${n.row}\0${n.col}`,l=o.formulas.get(s),c=l!==void 0?l:cn(o.formulas,s,r.evaluateFormula(t.formula,n));return c===!0||typeof c=="number"&&Number.isFinite(c)&&c!==0},Ug=(e,t,n,r,o)=>{const s=e.condition;switch(s.type){case"cellValue":return Hg(s,t,n,o)?e.style:null;case"text":return Bg(s,n())?e.style:null;case"empty":return n()===""?e.style:null;case"notEmpty":return n()!==""?e.style:null;case"colorScale":{const l=Yg(e,s,t,n,r,o);return l===null?null:{...e.style,background:l}}case"customFormula":return Kg(e,s,t,r,o)?e.style:null;default:return null}},tc=(e,t)=>Ds(e,t),Xg=(e,t,n)=>{e[t]=n},Gg=(e,t)=>{let n=e;for(const r of Qa)e[r]===void 0&&t[r]!==void 0&&(n===e&&(n={...e}),Xg(n,r,t[r]));return n},Zg=e=>{let t="";for(const n of Qa){const r=e[n];t+=r===void 0?"":typeof r=="boolean"?r?"t":"f":`s${r.length}:${r}`,t+="\0"}return t},nc=new WeakMap,Jg=Object.freeze({}),Qg=e=>{const t=e===void 0?Jg:e,n=nc.get(t);if(n!==void 0)return n;const r={byStyle:new WeakMap,byKey:new Map};return nc.set(t,r),r},ew=(e,t,n)=>{const r=Qg(e);if(n){const c=r.byStyle.get(t);if(c!==void 0)return c;const u=tc(e,t);return u!==void 0&&r.byStyle.set(t,u),u}const o=Zg(t),s=r.byKey.get(o);if(s!==void 0)return s;const l=tc(e,t);return l!==void 0&&cn(r.byKey,o,l),l},Ks=(e,t,n,r,o,s)=>{if(e.getCellFormat===void 0)return;const l=e.getCellFormat(r,o);if(t===null)return l;const c=qg(t,r,o);if(c.length===0)return l;const u={row:r,col:o};let h=null,m=!0;for(const y of c){if(!jg(y.ranges,u))continue;const N=Ug(y,u,s,e,n);if(N!==null){if(N!==y.style&&(m=!1),h===null)h=N;else{const W=Gg(h,N);W!==h&&(m=!1,h=W)}if(y.stopIfTrue===!0)break}}return h===null?l:ew(l,h,m)},rc=new WeakMap,tw=e=>{eu(e,"widthRelevantRules");const t=rc.get(e);if(t!==void 0)return t;const n=e.filter(o=>o.style.bold!==void 0||o.style.italic!==void 0||o.stopIfTrue===!0),r=n.length===e.length?e:n;return rc.set(e,r),r},nw=({row:e,col:t,text:n,display:r,renderCell:o,__onCellRender:s})=>{const l=i.useRef(!1);if(i.useEffect(()=>{const c=l.current?"update":"mount";l.current=!0,s?.(`cell-${e}-${t}`,c,0,0,0,0)}),o!==void 0){const c=o({row:e,col:t,text:n,displayText:r});return c===void 0?r:c}return r},rw=i.memo(nw),ow=Object.freeze({left:Object.freeze({justifyContent:Rr("left")}),center:Object.freeze({justifyContent:Rr("center")}),right:Object.freeze({justifyContent:Rr("right")})}),sw=Object.freeze({role:"rowgroup"}),lw=4096,oc=new WeakMap,oo=new Map,iw=(e,t)=>{if(e===null)return ow[t];let n=oc.get(e);n===void 0&&(n={},oc.set(e,n));const r=n[t];if(r!==void 0)return r;const o={...e.style,justifyContent:Rr(t)},s=JSON.stringify(o);let l=oo.get(s);return l===void 0&&(oo.size>=lw&&oo.clear(),l=Object.freeze(o),oo.set(s,l)),n[t]=l,l},cw=Ys(),aw=(e,t,n)=>{if(e.row!==t||e.col!==n)throw new RangeError(`[spreadsheet] cell renderer (${t}, ${n}) ran without its getCellProps (latched ${e.row}, ${e.col})`);return e.value},uw=(e,t,n,r,o,s)=>{if(e.getCellFormat===void 0&&e.getCellNote===void 0&&e.getCellComments===void 0&&e.getCellHyperlink===void 0&&e.getCellValidation===void 0)return null;const l=ao(e,o,s),c={};let u=null,h;if(e.getCellFormat!==void 0){const m=Ks(e,r===null?null:r.indexRef.current,r===null?cw:r.memoRef.current,o,s,l);h=m===void 0?void 0:m.value;const y=ha(m,l),N=ln(n,s,1),W=ln(t,o,1),D=yf(m,N===null?void 0:e.getCellFormat(o,N),W===null?void 0:e.getCellFormat(W,s),n.offsetOf(s)===0,t.offsetOf(o)===0);D!==null&&Object.assign(c,D.attrs),c["data-aqsp-align"]=y,u=iw(D,y)}if(e.getCellNote!==void 0&&e.getCellNote(o,s)!==void 0&&(c["data-aqsp-note"]=""),e.getCellComments!==void 0){const m=e.getCellComments(o,s);m!==void 0&&m.length>0&&(c["data-aqsp-comment"]="")}if(e.getCellHyperlink!==void 0&&Jn(e.getCellHyperlink(o,s))!==void 0&&(c["data-aqsp-link"]=""),e.getCellValidation!==void 0){const m=e.getCellValidation(o,s);m!==void 0&&xm(m,l())&&(c["data-aqsp-invalid"]="")}return{attrs:c,style:u,value:h}},dw=({adapter:e,rowAxis:t,colAxis:n,viewStore:r,handleRef:o,bodyRef:s,dataVersion:l,defaultColumnWidth:c,frozenColumns:u,frozenRows:h,frozenTrailingColumns:m,frozenTrailingRows:y,headerRows:N,labelledBy:W,gridLabel:D,readOnly:j,renderCell:U,onScroll:V,onRangeChange:O,focusSink:T,isEditing:P,requestCommit:H,testId:$,__onCellRender:_,__maxRenderedCells:x,cfIndexRef:g,cfMemoRef:p,isPointing:C,tapScrollCircleOptions:v,overscanRows:k,overscanCols:b,background:R,onRenderTruncated:a,locale:f,scrollLabels:E})=>{const d=i.useRef(null),L=s??d;if(g===void 0!=(p===void 0))throw new RangeError("[spreadsheet] cfIndexRef and cfMemoRef must be passed together");const A=i.useMemo(()=>g===void 0||p===void 0?null:{indexRef:g,memoRef:p},[g,p]),M=i.useCallback(()=>r.get().editVersion,[r]),B=i.useCallback(ge=>r.subscribeCoalesced(ge),[r]),X=i.useSyncExternalStore(B,M,M)+(l??0),G=i.useCallback(ge=>t.sizeOf(ge),[t]),J=i.useCallback(ge=>n.sizeOf(ge),[n]),ne=i.useCallback((ge,Fe)=>e.getCellText(ge,Fe),[e]),ie=i.useMemo(()=>({enableKeyboardNavigation:!1,pointerDragInputs:["pen","touch"],resetOnGetItemHeightChange:!0,resetOnGetColWidthChange:!0,defaultColWidth:c}),[c]),le=i.useMemo(()=>({width:De.SPREADSHEET_SCROLLBAR_SIZE_PX,tapScrollCircleOptions:v,enableArrowButtonTabStops:!1}),[v]),Ae=i.useRef({row:-1,col:-1,value:void 0}),ze=i.useCallback((ge,Fe)=>{const lt=ge<N,He={role:lt?"columnheader":"gridcell","aria-rowindex":ge+1,"aria-colindex":Fe+1,"data-aqsp-cell":"","data-row":ge,"data-col":Fe,className:"aqsp-cell",...Je(e,ge,Fe)?{"aria-readonly":"true","data-aqsp-readonly":""}:{},...lt?{"data-aqsp-header-row":""}:{}},Ft=Ah(e,ge,Fe),bt=Ft===null?He:{...He,...Ft},it=uw(e,t,n,A,ge,Fe),Qe=Ae.current;return Qe.row=ge,Qe.col=Fe,Qe.value=it===null?void 0:it.value,it===null?bt:it.style===null?{...bt,...it.attrs}:{...bt,...it.attrs,style:it.style}},[e,t,n,A,N]),Ne=i.useCallback(ge=>({role:"row","aria-rowindex":ge+1,"data-aqsp-row":ge,"data-aqsp-cells":"",className:"aqsp-row"}),[]),Ie=i.useCallback((ge,Fe,lt)=>{let He=ge;return e.getCellFormat!==void 0&&(He=Xn(ge,aw(Ae.current,Fe,lt))),Y.jsx(rw,{row:Fe,col:lt,text:ge,display:He,renderCell:U,__onCellRender:_})},[X,U,_,e]);return Y.jsx("div",{ref:L,className:"aqsp-body","data-aqsp-body":"","data-testid":$?`${$}-body`:void 0,role:"grid","aria-rowcount":e.rowCount,"aria-colcount":e.colCount,"aria-label":D,"aria-labelledby":W,"aria-readonly":j?"true":void 0,onPointerDownCapture:ge=>{if(!(ge.target instanceof Element&&ge.target.closest("[data-aqsp-cells]")!==null)&&ge.pointerType==="mouse"){if(ge.button!==0){ge.preventDefault();return}if(ge.preventDefault(),C?.()===!0){ge.stopPropagation(),T();return}if(P()&&!H()){ge.stopPropagation(),T();return}T()}},children:Y.jsx(st.VirtualGrid,{ref:o,rowCount:e.rowCount,colCount:e.colCount,frozenLeadingCols:u,frozenLeadingRows:h,frozenTrailingCols:m,frozenTrailingRows:y,getRowHeight:G,getColWidth:J,getCell:ne,getCellProps:ze,getRowProps:Ne,contentProps:sw,behaviorOptions:ie,scrollBarOptions:le,overscanRows:k,overscanCols:b,background:R,onRenderTruncated:a,__maxRenderedCells:x,locale:f,labels:E,callbackThrottleMs:0,onScroll:V,onRangeChange:O,testId:$,children:Ie})})},fw=i.memo(dw),Wn=6,gt=3,wo=(e,t)=>{const n=[],r=[];if(t.length===0)return n;const o=t[0];o>0&&e.sizeOf(o-1)===0&&r.push({kind:"unhide",index:o-1,start:e.offsetOf(o),length:gt});for(const s of t){const l=e.sizeOf(s),c=e.offsetOf(s)+l,u=ln(e,s,1);s<e.count-1&&(u===null||u>s+1)?(n.push({kind:"resize",index:s,start:c-Wn,length:gt}),r.push({kind:"unhide",index:s+1,start:c-gt,length:gt})):l>=2*Wn?n.push({kind:"resize",index:s,start:c-Wn,length:Wn}):n.push({kind:"resize",index:s,start:c-gt,length:gt})}return[...n,...r]},ou=(e,t)=>{const n=[],r=[];if(t.length===0)return n;const o=e.offsetOf(t[0]),s=e.totalSize()-o;for(const c of t){const u=e.sizeOf(c),h=e.offsetOf(c)-o;c>0&&e.sizeOf(c-1)===0?(r.push({kind:"unhide",index:c-1,start:h,length:gt}),n.push({kind:"resize",index:c,start:h+gt,length:gt})):u>=2*Wn?n.push({kind:"resize",index:c,start:h,length:Wn}):n.push({kind:"resize",index:c,start:h,length:gt})}const l=t[t.length-1];return l<e.count-1&&e.sizeOf(l+1)===0&&r.push({kind:"unhide",index:l+1,start:s-gt,length:gt}),[...n.reverse(),...r]},pw=({viewStore:e,colAxis:t,frozenCols:n,frozenTrailingCols:r,handleRef:o,bandRef:s,colTrackRef:l,windowOriginXRef:c,repaintColHeaders:u,selectionRanges:h,enableResizeUI:m,dividerLeadingRef:y,dividerTrailingRef:N})=>{const W=st.useWheelBridge(o),D=i.useCallback(d=>(s.current=d,W(d)),[s,W]),j=i.useCallback(()=>{const{colStart:d,colEnd:L,colVersion:A}=e.get();return`${d}:${L}:${A}`},[e]),U=i.useCallback(d=>e.subscribeCoalesced(d),[e]);i.useSyncExternalStore(U,j,j);const{colStart:V,colEnd:O}=e.get(),T=t.count===0?0:t.offsetOf(Math.min(V,t.count-1));i.useLayoutEffect(()=>{c.current=T,u()},[T,c,u]);const P=d=>h.some(L=>d>=L.startCol&&d<=L.endCol),H=Math.min(Math.max(0,n),t.count),$=Ma(t,H),_=H>0?Kn(t,0,H-1):[],x=Math.min(Math.max(0,r),t.count-H),g=Fa(t,x),p=t.totalSize()-g,C=x>0?Kn(t,t.count-x,t.count-1):[],v=Kn(t,Math.max(V,H),Math.min(O,Math.max(0,t.count-1)-x)),k=[];for(const d of v)k.push(Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-in-selection":P(d)?"":void 0,style:{left:t.offsetOf(d)-T,width:t.sizeOf(d)},children:De.columnIndexToName(d)},d));const b=m?wo(t,v):null,R=b===null?null:b.filter(d=>!(d.kind==="unhide"&&d.index<H&&$>0||d.kind==="unhide"&&d.index>=t.count-x&&g>0)),a=m&&H>0?wo(t,_):null,f=m&&x>0?ou(t,C):null,E=Y.jsxs("div",{ref:l,className:"aqsp-col-header-track",children:[k,R?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,style:{left:d.start-T,width:d.length}},`r${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{left:d.start-T,width:d.length}},`u${d.index}`))]});return Y.jsx("div",{ref:D,className:"aqsp-col-header","aria-hidden":"true","data-aqsp-col-header":"",children:H===0&&x===0?E:Y.jsxs(Y.Fragment,{children:[_.map(d=>Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-frozen-header":"","data-aqsp-in-selection":P(d)?"":void 0,style:{left:t.offsetOf(d),width:t.sizeOf(d)},children:De.columnIndexToName(d)},d)),a?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,style:{left:d.start,width:d.length}},`fr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{left:d.start,width:d.length}},`fu${d.index}`)),Y.jsxs("div",{className:"aqsp-col-header-scroll","data-aqsp-col-header-scroll":"",style:{left:$,right:x>0?`calc(${De.SPREADSHEET_SCROLLBAR_SIZE_PX}px + min(${g}px, max(0px, 100% - ${De.SPREADSHEET_SCROLLBAR_SIZE_PX+$}px)))`:void 0},children:[E,H>0?Y.jsx("div",{ref:y,className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-leading",style:{left:0,top:0,bottom:0}}):null,x>0?Y.jsx("div",{ref:N,className:"aqsp-freeze-divider aqsp-freeze-divider-v","data-aqsp-freeze-divider":"x-trailing",style:{right:0,top:0,bottom:0}}):null]}),x>0?Y.jsx("div",{className:"aqsp-col-header-scroll","data-aqsp-col-header-trailing":"",style:{left:`max(${$}px, calc(100% - ${g+De.SPREADSHEET_SCROLLBAR_SIZE_PX}px))`,right:De.SPREADSHEET_SCROLLBAR_SIZE_PX},children:Y.jsxs("div",{style:{position:"absolute",top:0,height:"100%",right:0,width:g},children:[C.map(d=>Y.jsx("div",{className:"aqsp-col-header-cell","data-col":d,"data-aqsp-trailing-header":"","data-aqsp-in-selection":P(d)?"":void 0,style:{left:t.offsetOf(d)-p,width:t.sizeOf(d)},children:De.columnIndexToName(d)},d)),f?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-col-resize-strip","data-aqsp-col-resize":d.index,"data-aqsp-resize-anchor":"trailing",style:{left:d.start,width:d.length}},`tr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,"data-aqsp-resize-anchor":"trailing",style:{left:d.start,width:d.length}},`tu${d.index}`))]})}):null]})})},hw=({viewStore:e,rowAxis:t,handleRef:n,bandRef:r,selectionRanges:o,rowTrackRef:s,windowOriginYRef:l,repaintHeaders:c,enableResizeUI:u,frozenRows:h,frozenTrailingRows:m,dividerLeadingRef:y,dividerTrailingRef:N})=>{const W=st.useWheelBridge(n),D=i.useCallback(d=>(r.current=d,W(d)),[r,W]),j=d=>o.some(L=>d>=L.startRow&&d<=L.endRow),U=i.useCallback(()=>{const{rowStart:d,rowEnd:L,rowGeomVersion:A}=e.get();return`${d}:${L}:${A}`},[e]),V=i.useCallback(d=>e.subscribeCoalesced(d),[e]);i.useSyncExternalStore(V,U,U);const{rowStart:O,rowEnd:T}=e.get(),P=t.count===0?0:t.offsetOf(Math.min(O,t.count-1));i.useLayoutEffect(()=>{l.current=P,c()},[P,l,c]);const H=Math.min(Math.max(0,h),t.count),$=za(t,H),_=H>0?Kn(t,0,H-1):[],x=Math.min(Math.max(0,m),t.count-H),g=Na(t,x),p=t.totalSize()-g,C=x>0?Kn(t,t.count-x,t.count-1):[],v=Kn(t,Math.max(O,H),Math.min(T,Math.max(0,t.count-1)-x)),k=[];for(const d of v)k.push(Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-in-selection":j(d)?"":void 0,style:{top:t.offsetOf(d)-P,height:t.sizeOf(d)},children:d+1},d));const b=u?wo(t,v):null,R=b===null?null:b.filter(d=>!(d.kind==="unhide"&&d.index<H&&$>0||d.kind==="unhide"&&d.index>=t.count-x&&g>0)),a=u&&H>0?wo(t,_):null,f=u&&x>0?ou(t,C):null,E=Y.jsxs("div",{ref:s,className:"aqsp-row-header-track",children:[k,R?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,style:{top:d.start-P,height:d.length}},`r${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{top:d.start-P,height:d.length}},`u${d.index}`))]});return Y.jsx("div",{ref:D,className:"aqsp-row-header","aria-hidden":"true","data-aqsp-row-header":"",style:{marginBottom:De.SPREADSHEET_SCROLLBAR_SIZE_PX},children:H===0&&x===0?E:Y.jsxs(Y.Fragment,{children:[_.map(d=>Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-frozen-row-header":"","data-aqsp-in-selection":j(d)?"":void 0,style:{top:t.offsetOf(d),height:t.sizeOf(d)},children:d+1},d)),a?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,style:{top:d.start,height:d.length}},`fr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,style:{top:d.start,height:d.length}},`fu${d.index}`)),Y.jsxs("div",{className:"aqsp-row-header-scroll","data-aqsp-row-header-scroll":"",style:{top:$,bottom:x>0?`calc(min(${g}px, max(0px, 100% - ${$}px)))`:void 0},children:[E,H>0?Y.jsx("div",{ref:y,className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-leading",style:{top:0,left:0,right:0}}):null,x>0?Y.jsx("div",{ref:N,className:"aqsp-freeze-divider aqsp-freeze-divider-h","data-aqsp-freeze-divider":"y-trailing",style:{bottom:0,left:0,right:0}}):null]}),x>0?Y.jsx("div",{className:"aqsp-row-header-scroll","data-aqsp-row-header-trailing":"",style:{top:`max(${$}px, calc(100% - ${g}px))`},children:Y.jsxs("div",{style:{position:"absolute",left:0,right:0,bottom:0,height:g},children:[C.map(d=>Y.jsx("div",{className:"aqsp-row-header-cell","data-row":d,"data-aqsp-trailing-row-header":"","data-aqsp-in-selection":j(d)?"":void 0,style:{top:t.offsetOf(d)-p,height:t.sizeOf(d)},children:d+1},d)),f?.map(d=>d.kind==="resize"?Y.jsx("div",{className:"aqsp-row-resize-strip","data-aqsp-row-resize":d.index,"data-aqsp-resize-anchor":"trailing",style:{top:d.start,height:d.length}},`tr${d.index}`):Y.jsx("div",{className:"aqsp-unhide-marker","data-aqsp-unhide":d.index,"data-aqsp-resize-anchor":"trailing",style:{top:d.start,height:d.length}},`tu${d.index}`))]})}):null]})})},mw=9,gw=4,sc=(e,t,n)=>{const r=t.get(e);if(r!==void 0)return r;const o=e.italic===!0?"italic":n.fontStyle,s=e.bold===!0?"bold":n.fontWeight,l=typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&e.fontSize>0?`${e.fontSize*4/3}px`:n.fontSize,c=typeof e.fontFamily=="string"&&e.fontFamily!==""?e.fontFamily:n.fontFamily,u=`${o} ${s} ${l} ${c}`;return t.set(e,u),u},lc=(e,t,n)=>e.anchor==="trailing"?t.offsetOf(e.index)+e.initialSize-n:t.offsetOf(e.index)+n,ww=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(0),s=i.useRef(null),l=i.useRef(0),c=i.useRef(null),u=i.useRef(null),h=i.useRef(""),m=i.useRef(null),y=i.useCallback(g=>s.current!==null?g.pointerId===s.current:g.pointerType==="mouse",[]),N=i.useCallback(()=>{const g=t.current;n.current=!1,r.current=null,u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),g.writeResizeGuide(null);const p=m.current;p!==null&&(window.removeEventListener("pointermove",p.move),window.removeEventListener("pointerup",p.up),m.current=null);const C=c.current;C!==null&&s.current!==null&&C.hasPointerCapture?.(s.current)&&C.releasePointerCapture(s.current),c.current=null,s.current=null,g.repaintOverlay()},[]),W=i.useCallback((g,p)=>{const C=t.current;return g==="col"?p.startRow===0&&p.endRow===C.rowAxis.count-1:p.startCol===0&&p.endCol===C.colAxis.count-1},[]),D=i.useCallback((g,p)=>{const C=t.current,v=C.getSelection().ranges.filter(f=>W(g,f));if(!v.some(f=>g==="col"?p>=f.startCol&&p<=f.endCol:p>=f.startRow&&p<=f.endRow))return[p];const b=v.reduce((f,E)=>f+(g==="col"?E.endCol-E.startCol+1:E.endRow-E.startRow+1),0),R=g==="row"?Math.floor(C.maxOperationCells/xs):C.maxOperationCells;if(b>R)return C.onOperationRejected?.("resize",b,"limit"),null;const a=new Set;for(const f of v){const E=g==="col"?f.startCol:f.startRow,d=g==="col"?f.endCol:f.endRow;for(let L=E;L<=d;L+=1)a.add(L)}return[...a]},[W]),j=i.useCallback((g,p,C)=>{const v=t.current,k=g==="col"?v.colAxis:v.rowAxis,b=Ts(k,p,C,{maxOperationCells:v.maxOperationCells,rowHiddenLimit:As,axisKind:g});return b.ok?(v.resizeTracks(g,b.entries),!0):(v.onOperationRejected?.("resize",b.count,b.reason),!1)},[]),U=i.useCallback((g,p)=>{if(p===g.initialSize)return;const C=g.kind==="unhide"?[g.index]:D(g.axis,g.index);C!==null&&j(g.axis,C.map(v=>({index:v,size:p})),g.index)},[D,j]),V=i.useCallback((g,p,C,v)=>{const k=t.current,b=k.fontSourceRef.current;if(b===null)return!1;if(p.length===0)return!0;const R=g.length*p.length;if(R>C)return k.onOperationRejected?.("resize",R,"limit"),!1;const a=document.createElement("canvas").getContext("2d");if(a===null)return!0;const f=getComputedStyle(b),E=`${f.fontStyle} ${f.fontWeight} ${f.fontSize} ${f.fontFamily}`,d=f.getPropertyValue("--_aqsp-header-row-font-weight").trim(),L={fontStyle:f.fontStyle,fontWeight:d===""?f.fontWeight:d,fontSize:f.fontSize,fontFamily:f.fontFamily},A=`${L.fontStyle} ${L.fontWeight} ${L.fontSize} ${L.fontFamily}`,M=k.adapter.getConditionalFormats===void 0?null:tw(k.adapter.getConditionalFormats()),B=Ys(),I=new WeakMap,X=new WeakMap,G=new Map;for(const le of g){const Ae=M===null?null:tu(M.filter(ze=>ze.ranges.some(Ne=>le>=Ne.startCol&&le<=Ne.endCol)));for(const ze of p){const Ne=k.adapter.getCellText(ze,le),Ie=k.adapter.getCellFormat===void 0?void 0:Ks(k.adapter,Ae,B,ze,le,()=>Ne),ge=ze<k.headerRows,Fe=Ie===void 0?ge?A:E:ge?sc(Ie,X,L):sc(Ie,I,f),lt=Xn(Ne,Ie===void 0?void 0:Ie.value),He=G.get(Fe);He===void 0?G.set(Fe,[{col:le,text:lt}]):He.push({col:le,text:lt})}}const J=b.ownerDocument.createElement("span");J.setAttribute("aria-hidden","true"),J.style.position="absolute",J.style.visibility="hidden",b.append(J);const ne=new Map;for(const[le,Ae]of G){a.font=le,J.style.font=le;const ze=getComputedStyle(J);a.letterSpacing=ze.letterSpacing==="normal"?"0px":ze.letterSpacing,a.wordSpacing=ze.wordSpacing==="normal"?"0px":ze.wordSpacing;for(const Ne of Ae){const Ie=a.measureText(Ne.text).width,ge=ne.get(Ne.col);(ge===void 0||Ie>ge)&&ne.set(Ne.col,Ie)}}J.remove();const ie=[];for(const le of g){const Ae=ne.get(le);Ae!==void 0&&Ae>0&&ie.push({index:le,size:Math.ceil(Ae)+mw})}return ie.length===0?!0:j("col",ie,v)},[j]),O=i.useCallback(g=>{const p=t.current,C=D("col",g);if(C===null)return!1;const v=p.handleRef.current,k=v===null?null:v.getFrozenSize(),b=k===null?0:k.rows,R=k===null?0:k.trailingRows,{rowStart:a,rowEnd:f}=p.viewStore.get(),E=Math.min(f,p.rowAxis.count-1),d=[],L=new Set,A=M=>{!L.has(M)&&p.rowAxis.sizeOf(M)>0&&(L.add(M),d.push(M))};for(let M=0;M<b;M+=1)A(M);for(let M=a;M<=E;M+=1)A(M);for(let M=p.rowAxis.count-R;M<p.rowAxis.count;M+=1)A(M);return V(C,d,Math.floor(p.maxOperationCells/gw),g)},[D,V]),T=i.useCallback((g,p,C)=>{const v=g==="col"?t.current.colAxis:t.current.rowAxis,k=Vu(v.sizeOf(p),C);if(k===v.sizeOf(p))return!0;const b=D(g,p);return b===null?!1:j(g,b.map(R=>({index:R,size:k})),p)},[D,j]),P=i.useCallback(g=>{const p=t.current;return p.autofitEnabled?p.colAxis.sizeOf(g)===0?!0:O(g):!1},[O]),H=i.useCallback(g=>{const p=t.current;if(!p.autofitEnabled)return!1;const C=[...new Set(g)].filter(k=>p.colAxis.sizeOf(k)>0);if(C.length===0)return!0;const v=[];for(let k=0;k<p.rowAxis.count;k+=1)p.rowAxis.sizeOf(k)>0&&v.push(k);return V(C,v,p.maxOperationCells,null)},[V]),{enabled:$,colBandRef:_,rowBandRef:x}=e;return i.useEffect(()=>{const g=_.current,p=x.current;if(!$||g===null||p===null)return;const C=I=>I==="col"?"[data-aqsp-col-resize], [data-aqsp-unhide]":"[data-aqsp-row-resize], [data-aqsp-unhide]",v=(I,X)=>{if(!(X instanceof Element))return null;const G=X.closest(C(I));if(G===null)return null;const J=G.hasAttribute("data-aqsp-unhide"),ne=Number(G.getAttribute(J?"data-aqsp-unhide":I==="col"?"data-aqsp-col-resize":"data-aqsp-row-resize")),ie=G.hasAttribute("data-aqsp-resize-anchor")?"trailing":"leading";return{kind:J?"unhide":"resize",index:ne,anchor:ie}},k=I=>{if(!(n.current&&y(I)))return;const X=r.current;if(X===null)return;const G=(X.axis==="col"?I.clientX-X.startClientX:I.clientY-X.startClientY)/t.current.zoomRef.current;o.current=Math.max(0,Math.round(X.anchor==="trailing"?X.initialSize-G:X.initialSize+G)),u.current===null&&(u.current=requestAnimationFrame(()=>{u.current=null;const J=r.current;if(!n.current||J===null)return;const ne=t.current,ie=J.axis==="col"?ne.colAxis:ne.rowAxis;ne.writeResizeGuide({axis:J.axis,position:lc(J,ie,o.current),anchor:J.anchor})}))},b=()=>{const I=r.current,X=o.current;N(),I!==null&&U(I,X)},R=I=>{k(I),n.current&&y(I)&&(l.current&1)!==0&&(I.buttons&1)===0&&b()},a=I=>{I.button!==0||!(n.current&&y(I))||b()},f=(I,X)=>G=>{const J=t.current;if(h.current=G.pointerType,G.pointerType!=="mouse")return;if(G.button!==0){G.preventDefault();return}const ne=v(I,G.target);if(ne===null)return;if(G.stopPropagation(),G.preventDefault(),J.isPointing()){J.focusSink();return}if(J.isEditing()&&!J.requestCommit()){J.focusSink();return}J.focusSink();const ie=I==="col"?J.colAxis:J.rowAxis,le={axis:I,kind:ne.kind,index:ne.index,anchor:ne.anchor,initialSize:ie.sizeOf(ne.index),startClientX:G.clientX,startClientY:G.clientY};r.current=le,o.current=le.initialSize,l.current=G.buttons,n.current=!0,J.repaintOverlay(),s.current=G.pointerId,c.current=X;try{X.setPointerCapture(G.pointerId)}catch{s.current=null}const Ae=R,ze=a;m.current={move:Ae,up:ze},window.addEventListener("pointermove",Ae),window.addEventListener("pointerup",ze),J.writeResizeGuide({axis:I,position:lc(le,ie,o.current),anchor:le.anchor})},E=(I,X)=>G=>{const J=t.current;if(h.current!=="mouse")return;const ne=X.getRootNode(),ie=ne instanceof ShadowRoot?ne:X.ownerDocument,le=G.target instanceof Element&&G.target.closest(C(I))!==null?G.target:typeof ie.elementFromPoint=="function"?ie.elementFromPoint(G.clientX,G.clientY):null,Ae=v(I,le);if(Ae!==null){if(G.stopPropagation(),J.isEditing()){J.focusSink();return}if(Ae.kind==="unhide"){j(I,[{index:Ae.index,size:I==="col"?J.defaultColumnWidth:J.defaultRowHeight}],null);return}if(J.autofitEnabled){if(I==="row"){const ze=D("row",Ae.index);ze!==null&&j("row",ze.map(Ne=>({index:Ne,size:J.defaultRowHeight})),Ae.index);return}O(Ae.index)}}},d=I=>{!n.current||s.current===null||I.pointerId!==s.current||N()},L=f("col",g),A=f("row",p),M=E("col",g),B=E("row",p);return g.addEventListener("pointerdown",L,{capture:!0}),p.addEventListener("pointerdown",A,{capture:!0}),g.addEventListener("dblclick",M),p.addEventListener("dblclick",B),g.addEventListener("lostpointercapture",d),p.addEventListener("lostpointercapture",d),()=>{g.removeEventListener("pointerdown",L,{capture:!0}),p.removeEventListener("pointerdown",A,{capture:!0}),g.removeEventListener("dblclick",M),p.removeEventListener("dblclick",B),g.removeEventListener("lostpointercapture",d),p.removeEventListener("lostpointercapture",d),N()}},[$,_,x,y,N,U,j,D,O]),i.useMemo(()=>({stepTrack:T,autofitColumn:P,autofitColumnsInAllRows:H,isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:()=>{n.current&&N()},cancelDrag:N}),[N,T,P,H])},Us=(e,t)=>e.startRow===t.startRow&&e.startCol===t.startCol&&e.endRow===t.endRow&&e.endCol===t.endCol,Cw=(e,t)=>e.ranges.length===t.ranges.length&&e.ranges.every((n,r)=>Us(n,t.ranges[r]))&&Vt(e.anchor,t.anchor)&&Vt(e.active,t.active),bw=(e,t,n)=>{const r=l=>l.row<t&&l.col<n,o=l=>l.endRow<t&&l.endCol<n;if(r(e.anchor)&&r(e.active)&&e.ranges.every(o))return e;const s=l=>dn(l,t,n);return{ranges:e.ranges.map(l=>o(l)?l:ke(s({row:l.startRow,col:l.startCol}),s({row:l.endRow,col:l.endCol}))),anchor:r(e.anchor)?e.anchor:s(e.anchor),active:r(e.active)?e.active:s(e.active)}},yw=(e,t)=>{const n=e.ranges[e.ranges.length-1];return Us(n,t)?e:{...e,ranges:[...e.ranges.slice(0,-1),t]}},Ar=(e,t,n)=>n.extend?yn(e,t):n.append?{ranges:[...e.ranges,ke(t,t)],anchor:t,active:t}:e.ranges.length===1&&Vt(e.anchor,t)&&Vt(e.active,t)&&Us(e.ranges[0],ke(t,t))?e:{ranges:[ke(t,t)],anchor:t,active:t},Rw=(e,t)=>({row:Math.min(Math.max(e.row,t.startRow),t.endRow),col:Math.min(Math.max(e.col,t.startCol),t.endCol)}),yn=(e,t)=>{const n=yw(e,ke(e.anchor,t));return n.ranges.some(r=>kn(r,n.active))?n:{...n,active:Rw(n.active,n.ranges[n.ranges.length-1])}},su=(e,t,n)=>{let r=!1;const o=[];for(const c of e.ranges){if(t.startRow>c.endRow||t.endRow<c.startRow||t.startCol>c.endCol||t.endCol<c.startCol){o.push(c);continue}r=!0,t.startRow>c.startRow&&o.push(ke({row:c.startRow,col:c.startCol},{row:t.startRow-1,col:c.endCol})),t.endRow<c.endRow&&o.push(ke({row:t.endRow+1,col:c.startCol},{row:c.endRow,col:c.endCol}));const u=Math.max(c.startRow,t.startRow),h=Math.min(c.endRow,t.endRow);t.startCol>c.startCol&&o.push(ke({row:u,col:c.startCol},{row:h,col:t.startCol-1})),t.endCol<c.endCol&&o.push(ke({row:u,col:t.endCol+1},{row:h,col:c.endCol}))}if(!r)return e;if(o.length===0)return{ranges:[ke(n,n)],anchor:n,active:n};const s=o.findIndex(c=>kn(c,e.active));if(s>=0){const[c]=o.splice(s,1);return o.push(c),{ranges:o,anchor:e.active,active:e.active}}const l={row:o[o.length-1].startRow,col:o[o.length-1].startCol};return{ranges:o,anchor:l,active:l}},vw=(e,t,n,r)=>{const o=e[t];if(r==="right"){if(n.col<o.endCol)return{rangeIndex:t,cell:{row:n.row,col:n.col+1}};if(n.row<o.endRow)return{rangeIndex:t,cell:{row:n.row+1,col:o.startCol}}}else if(r==="left"){if(n.col>o.startCol)return{rangeIndex:t,cell:{row:n.row,col:n.col-1}};if(n.row>o.startRow)return{rangeIndex:t,cell:{row:n.row-1,col:o.endCol}}}else if(r==="down"){if(n.row<o.endRow)return{rangeIndex:t,cell:{row:n.row+1,col:n.col}};if(n.col<o.endCol)return{rangeIndex:t,cell:{row:o.startRow,col:n.col+1}}}else{if(n.row>o.startRow)return{rangeIndex:t,cell:{row:n.row-1,col:n.col}};if(n.col>o.startCol)return{rangeIndex:t,cell:{row:o.endRow,col:n.col-1}}}if(r==="right"||r==="down"){const c=(t+1)%e.length,u=e[c];return{rangeIndex:c,cell:{row:u.startRow,col:u.startCol}}}const s=(t-1+e.length)%e.length,l=e[s];return{rangeIndex:s,cell:{row:l.endRow,col:l.endCol}}},lu=(e,t)=>{const n=e.ranges.findIndex(o=>kn(o,e.active));if(n===-1)throw new RangeError("[spreadsheet] reduceActiveCycle requires active inside some range (invariant violation)");let r={rangeIndex:n,cell:e.active};do if(r=vw(e.ranges,r.rangeIndex,r.cell,t),!Vt(r.cell,e.active))return{...e,active:r.cell};while(r.rangeIndex!==n);return e},It=24,ic=32,Co=4,_n=({handleRef:e,rowAxis:t,colAxis:n,bodyRef:r,onDragFrame:o,axis:s="both",zoomRef:l})=>{const c=i.useRef(null),u=i.useRef(null),h=i.useRef(null),m=i.useRef(null),y=i.useCallback(()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),u.current=null,m.current=null,h.current=null},[]),N=i.useCallback(()=>{const D=u.current,j=e.current,U=m.current;if(D===null||j===null||U===null){c.current=null;return}const{clientX:V,clientY:O}=D.getPointerPosition(),T=l.current,P=(V-U.left)/T,H=(O-U.top)/T,$=j.getViewportSize(),_=$.width,x=$.height;if(_<=0||x<=0){c.current=requestAnimationFrame(N);return}const g=R=>Math.min(ic,Math.ceil(R/It*ic));let p=0,C=0;if(s!=="x"){const R=j.getFrozenSize(),a=R.trailingVisibleHeight;H>x-a-It?D.anchorRow!==void 0&&R.trailingRows>0&&D.anchorRow>=t.count-R.trailingRows&&a>0&&H>=x-a||(p=g(H-(x-a-It))):H<R.height+It&&(D.anchorRow!==void 0&&D.anchorRow<R.rows&&R.height>0&&H<R.height||(p=-g(R.height+It-H)))}if(s!=="y"){const R=j.getFrozenSize(),a=R.trailingVisibleWidth;P>_-a-It?D.anchorCol!==void 0&&R.trailingCols>0&&D.anchorCol>=n.count-R.trailingCols&&a>0&&P>=_-a||(C=g(P-(_-a-It))):P<R.width+It&&(D.anchorCol!==void 0&&D.anchorCol<R.cols&&R.width>0&&P<R.width||(C=-g(R.width+It-P)))}const v=C!==0||p!==0?j.scrollBy({x:C!==0?C:void 0,y:p!==0?p:void 0}):j.getScrollPosition(),k=v.y,b=v.x;if(k>=0&&b>=0&&t.totalSize()>0&&n.totalSize()>0){const R=j.getFrozenSize(),a=dn({row:Mr(t,H,{scroll:k,frozenSize:R.height,trailingSize:R.trailingHeight,extent:$.height}),col:Dr(n,P,{scroll:b,frozenSize:R.width,trailingSize:R.trailingWidth,extent:$.width})},t.count,n.count),f=h.current;(p!==0||C!==0||f===null||f.row!==a.row||f.col!==a.col)&&(h.current=a,o(D.buildRange(a)))}c.current=requestAnimationFrame(N)},[e,t,n,s,o]),W=i.useCallback(D=>{y(),u.current=D,m.current=r.current?.getBoundingClientRect()??null,c.current=requestAnimationFrame(N)},[y,N,r]);return i.useEffect(()=>{const D=()=>{document.visibilityState==="hidden"&&y()};return document.addEventListener("visibilitychange",D),()=>{document.removeEventListener("visibilitychange",D),y()}},[y]),i.useMemo(()=>({start:W,stop:y}),[W,y])},cc=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(0),s=i.useRef(null),l=i.useRef({clientX:0,clientY:0}),c=i.useRef(null),u=i.useRef(null),h=i.useRef(0),m=i.useRef(null),y=i.useRef(!1),N=i.useRef(0),W=i.useCallback(($,_)=>{const{axis:x,mainAxis:g,handleRef:p,zoomRef:C}=t.current,v=s.current;if(v===null||g.totalSize()===0)return null;const k=C.current,b=p.current;if(b===null)return null;if(x==="col"){const E=b.getScrollPosition().x;if(E<0)return null;const d=b.getFrozenSize(),L=b.getViewportSize();return Math.min(Math.max(Dr(g,($-v.left)/k,{scroll:E,frozenSize:d.width,trailingSize:d.trailingWidth,extent:L.width}),0),g.count-1)}const R=b.getScrollPosition().y;if(R<0)return null;const a=b.getFrozenSize(),f=b.getViewportSize();return Math.min(Math.max(Mr(g,(_-v.top)/k,{scroll:R,frozenSize:a.height,trailingSize:a.trailingHeight,extent:f.height}),0),g.count-1)},[]),D=i.useCallback(($,_)=>{const{axis:x,crossCount:g}=t.current;return x==="col"?{press:{row:0,col:$},extend:{row:g-1,col:_}}:{press:{row:$,col:0},extend:{row:_,col:g-1}}},[]),j=i.useCallback(($,_)=>{const{axis:x,crossCount:g}=t.current;return $.ranges.some(p=>x==="col"?p.startRow===0&&p.endRow===g-1&&_>=p.startCol&&_<=p.endCol:p.startCol===0&&p.endCol===g-1&&_>=p.startRow&&_<=p.endRow)},[]),U=i.useRef(!1),V=i.useRef({clientX:0,clientY:0}),O=i.useCallback(()=>{U.current=!1;const{autoScroller:$,headerRef:_,onDragFrame:x}=t.current;n.current=!1,r.current=null,m.current=null,y.current=!1,N.current=0,c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),$.stop();const g=_.current;g!==null&&u.current!==null&&g.hasPointerCapture?.(u.current)&&g.releasePointerCapture(u.current),u.current=null,x(null),t.current.repaintOverlay()},[]),T=i.useCallback(()=>{if(!n.current)return;const $=r.current;$!==null&&t.current.setSelection($),O()},[O]),{enabled:P,headerRef:H}=e;return i.useEffect(()=>{const $=H.current;if(!P||$===null)return;const _=b=>{const R=t.current;if(b.pointerType!=="mouse")return;if(b.button!==0){b.preventDefault();return}if(y.current=!1,R.pointing?.getPointing()){s.current=$.getBoundingClientRect();const d=W(b.clientX,b.clientY);if(d===null)return;b.preventDefault(),R.focusSink(),R.pointing.insertReference(R.axis==="col"?{row:0,col:d}:{row:d,col:0},R.axis==="col"?"columns":"rows");return}if(R.isEditing()&&!R.requestCommit()){b.preventDefault(),R.focusSink();return}s.current=$.getBoundingClientRect();const a=W(b.clientX,b.clientY);if(a===null)return;b.preventDefault(),R.focusSink();const f=R.getSelection();r.current=f;const E=b.ctrlKey||b.metaKey;if(b.shiftKey){const d=R.axis==="col"?{row:0,col:f.anchor.col}:{row:f.anchor.row,col:0},{extend:L}=D(a,a),A={...f,anchor:d};R.setSelection(yn(A,L)),o.current=R.axis==="col"?d.col:d.row}else if(E&&j(f,a))y.current=!0,N.current=a,o.current=a;else{const{press:d,extend:L}=D(a,a),A=Ar(f,d,{extend:!1,append:E});R.setSelection(yn(A,L)),o.current=a}n.current=!0,R.repaintOverlay(),l.current={clientX:b.clientX,clientY:b.clientY},u.current=b.pointerId,h.current=b.buttons;try{$.setPointerCapture(b.pointerId)}catch{u.current=null}m.current=d=>{const L=t.current.axis==="col"?d.col:d.row,{press:A}=D(o.current,o.current),{extend:M}=D(o.current,L);return ke(A,M)},R.autoScroller.stop(),U.current=!1,V.current={clientX:b.clientX,clientY:b.clientY}},x=b=>u.current!==null?b.pointerId===u.current:b.pointerType==="mouse",g=b=>{if(n.current&&x(b)){if(y.current){const R=b.clientX!==l.current.clientX||b.clientY!==l.current.clientY;if(l.current={clientX:b.clientX,clientY:b.clientY},!R)return;const a=W(b.clientX,b.clientY);if(a===null||a===N.current)return;y.current=!1;const f=t.current,{press:E,extend:d}=D(N.current,N.current),L=Ar(f.getSelection(),E,{extend:!1,append:!0});f.setSelection(yn(L,d));const A=m.current,M=Math.abs(b.clientX-V.current.clientX),B=Math.abs(b.clientY-V.current.clientY);A!==null&&Math.max(M,B)>=Co&&(U.current=!0,f.autoScroller.start({getPointerPosition:()=>l.current,buildRange:A,anchorCol:f.axis==="col"?o.current:void 0,anchorRow:f.axis==="row"?o.current:void 0}))}else if(l.current={clientX:b.clientX,clientY:b.clientY},!U.current&&m.current!==null){const R=Math.abs(b.clientX-V.current.clientX),a=Math.abs(b.clientY-V.current.clientY);Math.max(R,a)>=Co&&(U.current=!0,t.current.autoScroller.start({getPointerPosition:()=>l.current,buildRange:m.current,anchorCol:t.current.axis==="col"?o.current:void 0,anchorRow:t.current.axis==="row"?o.current:void 0}))}c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null;const R=m.current;if(!n.current||R===null)return;const a=W(l.current.clientX,l.current.clientY);a!==null&&t.current.onDragFrame(R(t.current.axis==="col"?{row:0,col:a}:{row:a,col:0}))}))}},p=b=>{g(b),n.current&&x(b)&&(h.current&1)!==0&&(b.buttons&1)===0&&v(b)},C=b=>{b.button!==0||!(n.current&&x(b))||v(b)},v=b=>{const R=t.current;if(y.current){const{press:f,extend:E}=D(N.current,N.current);R.setSelection(su(R.getSelection(),ke(f,E),f)),O();return}const a=W(b.clientX,b.clientY);if(a!==null){const{extend:f}=D(o.current,a);R.setSelection(yn(R.getSelection(),f))}O()},k=b=>{!n.current||u.current===null||b.pointerId!==u.current||T()};return $.addEventListener("pointerdown",_),$.addEventListener("pointermove",p),$.addEventListener("pointerup",C),$.addEventListener("lostpointercapture",k),()=>{$.removeEventListener("pointerdown",_),$.removeEventListener("pointermove",p),$.removeEventListener("pointerup",C),$.removeEventListener("lostpointercapture",k),O()}},[P,H,W,D,O,T]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:T,cancelDrag:O}),[T,O])},Sw=({handleRef:e,rowAxis:t,colAxis:n})=>r=>{const o=e.current;if(o===null)return;const{x:s,y:l}=o.getScrollPosition(),{width:c,height:u}=o.getViewportSize();if(l<0||s<0)return;const h=o.getFrozenSize();if(u>0&&r.row>=h.rows&&r.row<t.count-h.trailingRows){const m=t.offsetOf(r.row),y=m+t.sizeOf(r.row);m<h.height+l?o.scrollBy({y:m-(h.height+l)}):y>l+u-h.trailingVisibleHeight&&o.scrollBy({y:y-(l+u-h.trailingVisibleHeight)})}if(c>0){if(r.col<h.cols||r.col>=n.count-h.trailingCols)return;const m=n.offsetOf(r.col),y=m+n.sizeOf(r.col);m<h.width+s?o.scrollBy({x:m-(h.width+s)}):y>s+c-h.trailingVisibleWidth&&o.scrollBy({x:y-(s+c-h.trailingVisibleWidth)})}},kw=50,Ew=100,iu=(e,t)=>e.isComposing||e.keyCode===229?!0:(e.key==="Enter"||e.key==="Escape")&&t!==null?e.timeStamp-t<kw:!1,gr={selectAll:rn("Ctrl+A"),undo:rn("Ctrl+Z"),redo:rn("Ctrl+Y"),redoShiftZ:rn("Ctrl+Shift+Z"),pasteValues:rn("Ctrl+Shift+V")},Ow=new Set(["Shift","Control","Alt","Meta","AltGraph"]),Aw={ArrowRight:"right",ArrowLeft:"left",ArrowDown:"down",ArrowUp:"up"},xw=e=>!e.shiftKey||e.altKey||!(e.ctrlKey||e.metaKey)?!1:e.key==="PageUp"||e.key==="PageDown",Tw=e=>{const t=i.useRef(null),n=i.useRef(null),r=i.useRef(!1),o=i.useRef(!1),s=i.useRef(e);s.current=e;const{enabled:l,sinkRef:c,rootRef:u,handleRef:h}=e;i.useEffect(()=>{const m=c.current,y=u.current;if(!l||m===null||y===null)return;const N=()=>{o.current&&(o.current=!1,s.current.onPointFrame?.(null))},W=(a,f,E)=>ln(a,f,E)??f,D=(a,f)=>{const E=s.current;return f==="left"||f==="right"?{row:a.row,col:W(E.colAxis,a.col,f==="right"?1:-1)}:{row:W(E.rowAxis,a.row,f==="down"?1:-1),col:a.col}},j=a=>a.indexAt(0),U=a=>a.indexAt(a.totalSize()-1),V=(a,f,E,d)=>{if(a.sizeOf(f)>0)return f;const L=ln(a,f,E);if(L!==null)return L;const A=ln(a,f,E===1?-1:1);return A!==null?A:d},O=()=>{const a=s.current.getSelection(),f=a.ranges[a.ranges.length-1];return{row:a.anchor.row===f.startRow?f.endRow:f.startRow,col:a.anchor.col===f.startCol?f.endCol:f.startCol}},T=a=>D(O(),a),P=(a,f)=>{const E=s.current,d=f==="left"||f==="right",L=f==="right"||f==="down"?1:-1;let A;return E.findDataEdge!==void 0?(A=E.findDataEdge({row:a.row,col:a.col},f),H(A,a,f)):A={row:f==="down"?E.rowAxis.count-1:f==="up"?0:a.row,col:f==="right"?E.colAxis.count-1:f==="left"?0:a.col},d?{row:A.row,col:V(E.colAxis,A.col,L,a.col)}:{row:V(E.rowAxis,A.row,L,a.row),col:A.col}},H=(a,f,E)=>{const d=s.current;if(!(Number.isInteger(a.row)&&Number.isInteger(a.col)&&a.row>=0&&a.row<d.rowAxis.count&&a.col>=0&&a.col<d.colAxis.count))throw new RangeError(`[spreadsheet] findDataEdge returned an out-of-grid coordinate {row: ${a.row}, col: ${a.col}} for a ${d.rowAxis.count} x ${d.colAxis.count} grid`);const L=E==="left"||E==="right";if(L?a.row!==f.row:a.col!==f.col)throw new RangeError(`[spreadsheet] findDataEdge must stay on the origin ${L?"row":"column"} (received {row: ${a.row}, col: ${a.col}} from {row: ${f.row}, col: ${f.col}})`)},$=(a,f,E)=>{if(!(Number.isInteger(a)&&a>=0&&a<f))throw new RangeError(`[spreadsheet] findDataEdge returned an out-of-axis ${E} component ${a} (count ${f})`)},_=a=>{const f=s.current,E=f.getSelection();if(lu(E,a)===E){f.moveActive({mode:"reset",cell:D(E.active,a)});return}f.moveActive({mode:"cycle",direction:a})},x=()=>{const a=c.current;if(a===null)return;const f=a.selectionStart??a.value.length,E=a.selectionEnd??f;a.value=`${a.value.slice(0,f)}
14
+ ${a.value.slice(E)}`,a.setSelectionRange(f+1,f+1)},g=(a,f)=>{const E=s.current,d=E.pageExtent();if(d<=0)return W(E.rowAxis,a,f==="down"?1:-1);const L=E.rowAxis.indexAt(E.rowAxis.offsetOf(a)+(f==="down"?d:-d));return L===a?W(E.rowAxis,a,f==="down"?1:-1):L},p=a=>{const f=s.current;if(r.current=!1,iu(a,t.current))return;const E=a.ctrlKey||a.metaKey,d=a.altKey,L=Aw[a.key];if(o.current&&!Ow.has(a.key)&&!f.isDragging()&&N(),f.isEditing()){const M=f.getEditingMode();if(f.isDragging()){a.preventDefault(),a.key==="Escape"&&!E&&!a.shiftKey&&!d&&f.abortDrag();return}const B=f.pointing;if(B!==void 0){if(L!==void 0&&!d){const X=B.getReferenceCursor();if(X!==null){a.preventDefault();const G=dn(X.cursor,f.rowAxis.count,f.colAxis.count),J=dn(X.origin,f.rowAxis.count,f.colAxis.count),ne=E?P(G,L):D(G,L);if(f.ensureCellVisible(ne),B.insertReference(a.shiftKey?ke(J,ne):ne,X.axis),f.onPointFrame!==void 0){const ie=a.shiftKey?ke(J,ne):ke(ne,ne);f.onPointFrame(X.axis==="columns"?ke({row:0,col:ie.startCol},{row:f.rowAxis.count-1,col:ie.endCol}):X.axis==="rows"?ke({row:ie.startRow,col:0},{row:ie.endRow,col:f.colAxis.count-1}):ie),o.current=!0}return}}if(a.key==="F2"&&!E&&!a.shiftKey&&!d&&B.togglePointingArm()){a.preventDefault();return}if(a.key==="F4"&&!E&&!a.shiftKey&&!d&&B.cycleAnchorAtCaret()){a.preventDefault();return}}const I=f.commands;if(I!==void 0){const X=hi(I.table,a);if(X!==null&&Ws.has(X)&&I.isAvailable(X)){a.preventDefault(),I.execute(X);return}}if(L!==void 0&&!d){if(E&&a.shiftKey){a.preventDefault();return}if(E)return;if(M==="replace"){if(a.preventDefault(),!f.requestCommit())return;a.shiftKey?f.moveActive({mode:"extend",cell:T(L)}):f.moveActive({mode:"reset",cell:D(f.getSelection().active,L)});return}return}if(a.key==="Enter"&&d&&!E&&!a.shiftKey){a.preventDefault(),x();return}if((a.key==="Enter"||a.key==="Tab")&&!E&&!d){if(a.preventDefault(),!f.requestCommit())return;const X=!a.shiftKey;_(a.key==="Tab"?X?"right":"left":X?"down":"up");return}if((a.key==="PageUp"||a.key==="PageDown")&&!a.shiftKey&&!E&&!d){if(a.preventDefault(),!f.requestCommit())return;const X=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:g(X.row,a.key==="PageDown"?"down":"up"),col:X.col}});return}if(a.key==="Escape"&&!E&&!a.shiftKey&&!d){a.preventDefault(),f.cancelEdit();return}return}if(a.defaultPrevented)return;if(f.isDragging()&&a.key!=="Escape"){a.preventDefault();return}const A=f.commands;if(A!==void 0){const M=hi(A.table,a);if(M!==null&&A.isAvailable(M)){a.preventDefault(),A.execute(M);return}}if(L!==void 0&&!d){const M=L==="left"||L==="right",B=L==="right"||L==="down"?1:-1;if(E&&a.shiftKey){a.preventDefault();const I=f.getSelection(),X=O();let G;if(f.findDataEdge!==void 0){const J=M?{row:I.active.row,col:X.col}:{row:X.row,col:I.active.col},ne=f.findDataEdge(J,L);G=M?ne.col:ne.row,$(G,M?f.colAxis.count:f.rowAxis.count,M?"col":"row"),G=V(M?f.colAxis:f.rowAxis,G,B,M?X.col:X.row)}else{const J=M?f.colAxis:f.rowAxis;G=B===1?U(J):j(J)}f.moveActive({mode:"extend",cell:M?{row:X.row,col:G}:{row:G,col:X.col}});return}if(E){a.preventDefault(),f.moveActive({mode:"reset",cell:P(f.getSelection().active,L)});return}if(a.shiftKey){a.preventDefault(),f.moveActive({mode:"extend",cell:T(L)});return}a.preventDefault(),f.moveActive({mode:"reset",cell:D(f.getSelection().active,L)});return}if(xw(a)){a.preventDefault();return}if((a.key==="Tab"||a.key==="Enter")&&!E&&!d){a.preventDefault();const M=!a.shiftKey;_(a.key==="Tab"?M?"right":"left":M?"down":"up");return}if(a.key==="Home"&&!d){if(a.preventDefault(),a.shiftKey){const B=O();f.moveActive({mode:"extend",cell:{row:E?j(f.rowAxis):B.row,col:j(f.colAxis)}});return}const M=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:E?j(f.rowAxis):M.row,col:j(f.colAxis)}});return}if(a.key==="End"&&!d){if(a.preventDefault(),a.shiftKey){const B=O();f.moveActive({mode:"extend",cell:{row:E?U(f.rowAxis):B.row,col:U(f.colAxis)}});return}const M=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:E?U(f.rowAxis):M.row,col:U(f.colAxis)}});return}if((a.key==="PageUp"||a.key==="PageDown")&&!E&&!d){a.preventDefault();const M=a.key==="PageDown"?"down":"up";if(a.shiftKey){const I=O();f.moveActive({mode:"extend",cell:{row:g(I.row,M),col:I.col}});return}const B=f.getSelection().active;f.moveActive({mode:"reset",cell:{row:g(B.row,M),col:B.col}});return}if(a.key==="F2"&&!E&&!a.shiftKey&&!d){a.preventDefault(),f.startEdit("edit");return}if((a.key==="Delete"||a.key==="Backspace")&&!E&&!a.shiftKey&&!d){a.preventDefault();const M=f.getSelection(),B=zt(M.ranges);if(B>f.maxOperationCells){f.onOperationRejected?.("delete",B,"limit");return}if(f.adapter!==void 0&&Bn(f.adapter,M.ranges)){f.rejectReadOnly({kind:"operation",op:"delete",cellCount:B});return}const I=[],X=f.adapter!==void 0&&uo(f.adapter).hyperlink;nn(M.ranges,G=>{I.push(X?{row:G.row,col:G.col,text:"",hyperlink:null}:{row:G.row,col:G.col,text:""})}),f.commitEdits(I,{source:"delete"});return}if(a.key==="Escape"){if(f.isDragging()){a.preventDefault(),f.abortDrag();return}if(E||a.shiftKey||d||(a.preventDefault(),f.hideNoteTip?.())||f.closeRejectedMessage?.())return;if(f.getClip()!==null){f.discardClip();return}f.handOffFocusToRoot();return}if(pr(gr.selectAll,a)){a.preventDefault();const M=f.getSelection(),B=ke({row:0,col:0},{row:f.rowAxis.count-1,col:f.colAxis.count-1});f.setSelection({ranges:[B],anchor:M.anchor,active:M.active});return}if(pr(gr.undo,a)){a.preventDefault(),f.onUndoRequest?.();return}if(pr(gr.redo,a)||pr(gr.redoShiftZ,a)){a.preventDefault(),f.onRedoRequest?.();return}if(a.key==="F10"&&a.shiftKey&&!E&&!d||a.key==="ContextMenu"&&!E&&!a.shiftKey&&!d){a.preventDefault();const M=f.getSelection().active;f.ensureCellVisible(M);const B=h.current,I=B===null?{x:0,y:0}:B.getScrollPosition(),X=Math.max(0,I.y),G=Math.max(0,I.x),J=B===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:B.getFrozenSize(),ne=B===null?{width:0,height:0}:B.getViewportSize(),ie=f.zoomRef.current;f.onCellContextMenu?.(M,{kind:"keyboard",cellRect:{top:Sn(f.rowAxis,M.row,{scroll:X,frozenCount:J.rows,trailingCount:J.trailingRows,extent:ne.height})*ie,left:vn(f.colAxis,M.col,{scroll:G,frozenCount:J.cols,trailingCount:J.trailingCols,extent:ne.width})*ie,width:f.colAxis.sizeOf(M.col)*ie,height:f.rowAxis.sizeOf(M.row)*ie}});return}if(a.key===" "&&!d&&E!==a.shiftKey){a.preventDefault();const M=f.getSelection(),B=M.ranges.map(I=>E?ke({row:0,col:I.startCol},{row:f.rowAxis.count-1,col:I.endCol}):ke({row:I.startRow,col:0},{row:I.endRow,col:f.colAxis.count-1}));f.setSelection({ranges:B,anchor:M.anchor,active:M.active});return}if(f.pendingPasteOptionsRef!==void 0&&pr(gr.pasteValues,a)){f.pendingPasteOptionsRef.current={mode:"values"};return}if(a.key.length===1&&!a.metaKey&&a.ctrlKey===a.altKey){if(a.ctrlKey&&a.altKey){r.current=!0;return}f.startEdit("replace");return}},C=()=>{const a=s.current;a.isEditing()||a.startEdit("replace")},v=a=>{t.current=a.timeStamp,n.current!==null&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current=null,n.current=null},Ew)},k=()=>{const a=s.current;if(N(),!a.isEditing()){if(r.current){r.current=!1;const f=m.value;if(f!==""&&(a.startEdit("replace"),a.isEditing())){m.value=f,m.setSelectionRange(f.length,f.length);return}}a.rearmSink()}},b=()=>{r.current=!1;const a=s.current.pendingPasteOptionsRef;a!==void 0&&(a.current=null)},R=()=>{r.current=!1;const a=s.current.pendingPasteOptionsRef;a!==void 0&&(a.current=null),N()};return m.addEventListener("keydown",p),m.addEventListener("keyup",b),m.addEventListener("blur",R),m.addEventListener("compositionstart",C),m.addEventListener("compositionend",v),m.addEventListener("input",k),()=>{m.removeEventListener("keydown",p),m.removeEventListener("keyup",b),m.removeEventListener("blur",R),m.removeEventListener("compositionstart",C),m.removeEventListener("compositionend",v),m.removeEventListener("input",k),n.current!==null&&window.clearTimeout(n.current),N()}},[l,c,u,h])},$w=()=>{let e={vy:0,rowStart:0,rowEnd:0,colStart:0,colEnd:0,colVersion:0,rowGeomVersion:0,editVersion:0};const t=new Set;let n=null;const r=()=>{n=null;for(const l of[...t])l()},o=()=>{t.size!==0&&n===null&&(n=requestAnimationFrame(r))},s=l=>{e={...e,...l},o()};return{get:()=>e,setVy:l=>{l!==e.vy&&s({vy:l})},setRowRange:(l,c)=>{(l!==e.rowStart||c!==e.rowEnd)&&s({rowStart:l,rowEnd:c})},setColRange:(l,c)=>{(l!==e.colStart||c!==e.colEnd)&&s({colStart:l,colEnd:c})},bumpColVersion:()=>s({colVersion:e.colVersion+1}),bumpRowGeometry:()=>s({rowGeomVersion:e.rowGeomVersion+1}),bumpEdit:()=>s({editVersion:e.editVersion+1}),subscribeCoalesced:l=>(t.add(l),()=>{t.delete(l),t.size===0&&n!==null&&(cancelAnimationFrame(n),n=null)})}},Lw=4,Dw=Object.freeze({cols:0,width:0,rows:0,height:0,trailingCols:0,trailingRows:0,trailingWidth:0,trailingHeight:0,trailingVisibleWidth:0,trailingVisibleHeight:0}),Mw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef(null),l=i.useRef({clientX:0,clientY:0}),c=i.useRef({clientX:0,clientY:0}),u=i.useRef(!1),h=i.useRef({dx:0,dy:0}),m=i.useRef(null),y=i.useRef(0),N=i.useRef(null),W=i.useRef(null),D=i.useRef(!1),j=i.useCallback($=>m.current!==null?$.pointerId===m.current:$.pointerType==="mouse",[]),U=i.useCallback(($,_)=>{const{handleRef:x,rowAxis:g,colAxis:p}=t.current,C=x.current,v=s.current;if(C===null||v===null)return null;const{x:k,y:b}=C.getScrollPosition();if(b<0||k<0||g.totalSize()===0||p.totalSize()===0)return null;const R=t.current.zoomRef.current,a=C.getFrozenSize(),f=C.getViewportSize();return dn({row:Mr(g,(_-v.top)/R,{scroll:b,frozenSize:a.height,trailingSize:a.trailingHeight,extent:f.height}),col:Dr(p,($-v.left)/R,{scroll:k,frozenSize:a.width,trailingSize:a.trailingWidth,extent:f.width})},g.count,p.count)},[]),V=i.useCallback($=>{const _=r.current;if(_===null)return ke($,$);const x=ke({row:Math.min(_.startRow,$.row),col:Math.min(_.startCol,$.col)},{row:Math.max(_.endRow,$.row),col:Math.max(_.endCol,$.col)}),g=x.startRow!==_.startRow||x.endRow!==_.endRow||x.startCol!==_.startCol||x.endCol!==_.endCol;return o.current=g?x:null,g?x:_},[]),O=i.useCallback(()=>{const $=t.current;n.current=!1,r.current=null,o.current=null,s.current=null,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),$.xAutoScroller.stop(),$.yAutoScroller.stop(),D.current=!1,u.current=!1,h.current={dx:0,dy:0},$.writeFillPreview(null);const _=W.current;_!==null&&(window.removeEventListener("pointermove",_.move),window.removeEventListener("pointerup",_.up),W.current=null);const x=t.current.handleNodeRef.current;x!==null&&m.current!==null&&x.hasPointerCapture?.(m.current)&&x.releasePointerCapture(m.current),m.current=null,$.repaintOverlay()},[]),T=i.useCallback(()=>{const $=t.current,_=r.current,x=o.current;if(O(),_===null||x===null)return;const g=$h(_,x);if(g>$.maxOperationCells){$.onOperationRejected?.("fill",g,"limit");return}if(Bn($.adapter,Lh(_,x))){const v=(x.endRow-x.startRow+1)*(x.endCol-x.startCol+1),k=(_.endRow-_.startRow+1)*(_.endCol-_.startCol+1);$.rejectReadOnly({kind:"operation",op:"fill",cellCount:v-k});return}const p=Dh((v,k)=>Ca($.adapter,v,k),_,x,ba);if($.commitEdits(p,{source:"fill"})===null)return;const C=$.getSelection();$.setSelection({ranges:[x],anchor:C.anchor,active:C.active})},[O]),{enabled:P,handleNodeRef:H}=e;return i.useEffect(()=>{const $=H.current;if(!P||$===null)return;const _=v=>{x(v),n.current&&j(v)&&(y.current&1)!==0&&(v.buttons&1)===0&&T()},x=v=>{if(!(n.current&&j(v)))return;l.current={clientX:v.clientX,clientY:v.clientY};const k=Math.abs(v.clientX-c.current.clientX),b=Math.abs(v.clientY-c.current.clientY);if(!u.current&&Math.max(k,b)>=Lw&&(u.current=!0),!!u.current){if(!D.current){const R=t.current,a={getPointerPosition:()=>({clientX:l.current.clientX-h.current.dx,clientY:l.current.clientY-h.current.dy}),buildRange:V,anchorCol:r.current?.endCol,anchorRow:r.current?.endRow};R.xAutoScroller.start(a),R.yAutoScroller.start(a),D.current=!0}N.current===null&&(N.current=requestAnimationFrame(()=>{if(N.current=null,!(n.current&&u.current))return;const R=U(l.current.clientX-h.current.dx,l.current.clientY-h.current.dy);R!==null&&t.current.writeFillPreview(V(R))}))}},g=v=>{v.button!==0||!(n.current&&j(v))||T()},p=v=>{const k=t.current;if(v.pointerType!=="mouse")return;if(v.button!==0){v.preventDefault();return}v.preventDefault(),v.stopPropagation(),k.focusSink();const b=k.getSelection(),R=b.ranges[b.ranges.length-1];r.current=R,o.current=null,u.current=!1,k.xAutoScroller.stop(),k.yAutoScroller.stop(),D.current=!1,c.current={clientX:v.clientX,clientY:v.clientY},l.current=c.current,y.current=v.buttons,n.current=!0,k.repaintOverlay(),s.current=k.bodyRef.current?.getBoundingClientRect()??null;const a=s.current,f=k.handleRef.current?.getScrollPosition()??{x:-1,y:-1},E=f.y;if(a!==null&&E>=0&&f.x>=0){const A=f.x,M=k.zoomRef.current,B=k.handleRef.current?.getFrozenSize()??Dw,I=k.handleRef.current?.getViewportSize()??{width:0,height:0},X={scroll:A,frozenCount:B.cols,trailingCount:B.trailingCols,extent:I.width},G={scroll:E,frozenCount:B.rows,trailingCount:B.trailingRows,extent:I.height},J=vn(k.colAxis,R.endCol,X)+k.colAxis.sizeOf(R.endCol),ne=Sn(k.rowAxis,R.endRow,G)+k.rowAxis.sizeOf(R.endRow),ie=J-1,le=R.endCol>=B.cols&&B.width>0?Math.max(ie,B.width):ie,ze=!(R.endCol>=k.colAxis.count-B.trailingCols)&&B.trailingWidth>0?Math.min(le,I.width-B.trailingVisibleWidth-1):le,Ne=ne-1,Ie=R.endRow>=B.rows&&B.height>0?Math.max(Ne,B.height):Ne,Fe=!(R.endRow>=k.rowAxis.count-B.trailingRows)&&B.trailingHeight>0?Math.min(Ie,I.height-B.trailingVisibleHeight-1):Ie;h.current={dx:v.clientX-(a.left+ze*M),dy:v.clientY-(a.top+Fe*M)}}else h.current={dx:0,dy:0};m.current=v.pointerId;try{$.setPointerCapture(v.pointerId)}catch{m.current=null}const d=_,L=g;W.current={move:d,up:L},window.addEventListener("pointermove",d),window.addEventListener("pointerup",L),k.writeFillPreview(r.current)},C=v=>{!n.current||m.current===null||v.pointerId!==m.current||O()};return $.addEventListener("pointerdown",p),$.addEventListener("lostpointercapture",C),()=>{$.removeEventListener("pointerdown",p),$.removeEventListener("lostpointercapture",C),O()}},[P,H,j,U,V,O,T]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"add",abortDrag:()=>{n.current&&O()},cancelDrag:O}),[O])},zw=320,fo=8,Fw=64,Nw=150,cu=e=>Math.max(0,Math.min(zw,e.width-De.SPREADSHEET_SCROLLBAR_SIZE_PX-fo)),Pw=(e,t,n)=>{const r=n.width-De.SPREADSHEET_SCROLLBAR_SIZE_PX,o=n.height-De.SPREADSHEET_SCROLLBAR_SIZE_PX,s=cu(n),l=Math.max(0,Math.min(t,o-fo)),c=e.left+e.width,u=e.top+e.height,h=j=>j>=0&&j+s<=r,m=[e.left,c-s],y=[{left:e.left,top:u},{left:c-s,top:u},{left:e.left,top:e.top-l},{left:c-s,top:e.top-l}];for(const j of y)if(h(j.left)&&j.top>=0&&j.top+l<=o)return{left:j.left,top:j.top,width:s,height:l};const N=o-u,W=e.top,D=Math.min(l,Math.max(N,W));if(D>=Fw){const j=N>=W?u:e.top-D;for(const U of m)if(h(U))return{left:U,top:j,width:s,height:D}}return{left:fo,top:fo,width:s,height:l}},_w=(e,t,n,r)=>t===null||e!==null&&Vt(e,t)||n?!1:r(t),qw=(e,t)=>{switch(e.kind){case"note":return Y.jsx(Ha,{ctx:e,labels:t});case"note-tip":return Y.jsx(Ba,{ctx:e,labels:t});case"comment":return Y.jsx(_a,{ctx:e,labels:t});case"link":return Y.jsx(qa,{ctx:e,labels:t});case"list":return Y.jsx(ja,{ctx:e,labels:t});default:return Y.jsx(Ia,{ctx:e,labels:t})}},cs=e=>e===null?null:`${e.kind}:${e.cell.row}:${e.cell.col}`,jw=({controller:e,renderPopover:t,labels:n,interactiveAnchorRef:r,tipAnchorRef:o})=>{const{context:s,tipContext:l}=e,c=i.useRef(null),u=i.useRef(null),h=i.useRef(l);h.current=l;const m=i.useRef(e);m.current=e;const y=cs(s),N=cs(l),W=i.useRef(null),D=(T,P)=>{const H=m.current.getLayerSize();T.style.width=`${cu(H)}px`,T.style.maxHeight="";const $=Pw(P,T.offsetHeight,H);T.style.left=`${$.left-P.left}px`,T.style.top=`${$.top-P.top}px`,T.style.maxHeight=`${$.height}px`};i.useLayoutEffect(()=>{const T=c.current;if(T===null||s===null){W.current=null;return}if(D(T,s.anchorRect),s.kind==="message")return;const P=cs(s);if(W.current===P)return;W.current=P;const H=T.querySelector("[data-aqsp-popover-autofocus]");H!==null?H.focus({preventScroll:!0}):T.focus({preventScroll:!0})},[s]),i.useLayoutEffect(()=>{const T=u.current,P=h.current;T===null||P===null||D(T,P.anchorRect)},[N]);const j=T=>t===void 0?qw(T,n):t(T),U=T=>{e.isCompositionKey(T.nativeEvent)&&T.stopPropagation()},V=T=>{T.key==="Escape"&&!T.defaultPrevented&&(T.preventDefault(),e.close())},O=T=>{e.registerCompositionEnd(T.timeStamp)};return Y.jsxs("div",{className:"aqsp-popover-layer","data-aqsp-popover-layer":"",onKeyDownCapture:U,onKeyDown:V,onCompositionEnd:O,children:[Y.jsx("div",{ref:r,className:"aqsp-popover-anchor","data-aqsp-popover-anchor":"interactive","data-aqsp-popover-open":s===null?void 0:"",inert:s===null,children:s===null?null:Y.jsx("div",{ref:c,className:"aqsp-popover","data-aqsp-popover-frame":s.kind,tabIndex:-1,children:j(s)},y)}),Y.jsx("div",{ref:o,className:"aqsp-popover-anchor","data-aqsp-popover-anchor":"tip","data-aqsp-popover-open":l===null?void 0:"",inert:l===null,onPointerEnter:e.onTipPointerEnter,onPointerLeave:e.onTipPointerLeave,children:l===null?null:Y.jsx("div",{ref:u,id:e.tipId,className:"aqsp-popover","data-aqsp-popover-frame":"note-tip",children:j(l)})})]})},Iw=["note","note-tip","comment","link","list","message"],Hw=(e,t)=>{switch(t){case"note":case"note-tip":return e.getCellNote!==void 0;case"comment":return e.getCellComments!==void 0;case"link":return e.getCellHyperlink!==void 0;default:return e.getCellValidation!==void 0}},wr=(e,t,n)=>(t===void 0?!0:t[n]!==!1)&&Hw(e,n),Bw=e=>{const t=i.useRef(e);t.current=e;const[n,r]=i.useState(null),[o,s]=i.useState(null),l=i.useRef(null),c=i.useRef(null),u=i.useRef(null),h=i.useRef(!1),m=i.useRef(null),y=i.useRef(null),N=i.useRef(null),W=i.useRef(null),D=i.useId(),j=i.useCallback(A=>{const M=t.current,B=M.handleRef.current,I=B===null?{x:0,y:0}:B.getScrollPosition(),X=B===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:B.getFrozenSize(),G=B===null?{width:0,height:0}:B.getViewportSize();return{top:Sn(M.rowAxis,A.row,{scroll:Math.max(0,I.y),frozenCount:X.rows,trailingCount:X.trailingRows,extent:G.height}),left:vn(M.colAxis,A.col,{scroll:Math.max(0,I.x),frozenCount:X.cols,trailingCount:X.trailingCols,extent:G.width}),width:M.colAxis.sizeOf(A.col),height:M.rowAxis.sizeOf(A.row)}},[]),U=i.useCallback(A=>{const M=t.current;M.anchors.current={...M.anchors.current,...A},M.repaintOverlay()},[]),V=i.useCallback(()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)},[]),O=i.useCallback(()=>{const A=t.current.sinkRef.current;if(A===null)return;const M=c.current;M!==null&&Vt(M,t.current.getActive())?A.setAttribute("aria-describedby",D):A.getAttribute("aria-describedby")===D&&A.removeAttribute("aria-describedby")},[D]),T=i.useCallback(()=>(V(),h.current=!1,c.current===null?!1:(c.current=null,s(null),U({tip:null}),O(),!0)),[V,U,O]),P=i.useCallback(()=>{V(),m.current=window.setTimeout(()=>{m.current=null,T()},Nw)},[V,T]),H=i.useCallback(A=>{const M=t.current;V();const B=M.adapter.getCellNote===void 0?void 0:M.adapter.getCellNote(A.row,A.col);B===void 0||B===""||(c.current=A,s({kind:"note-tip",cell:A,anchorRect:j(A),current:B,close:T}),U({tip:A}),O())},[j,V,T,U,O]),$=i.useCallback(A=>{const M=t.current;if(A===null&&h.current)return;const B=u.current;u.current=A;const I=c.current;if(I!==null&&A!==null&&Vt(I,A)){V();return}const X=G=>{const J=M.adapter.getCellNote===void 0?void 0:M.adapter.getCellNote(G.row,G.col);return J!==void 0&&J!==""};if(_w(B,A,M.isDraggingAny(),X)){A!==null&&H(A);return}I!==null&&P()},[H,V,P]),_=i.useCallback((A,M)=>{const B=t.current,I=B.bodyRef.current,X=B.handleRef.current;if(I===null||X===null)return null;const G=I.getBoundingClientRect(),J=B.zoomRef.current,ne=X.getScrollPosition(),ie=X.getFrozenSize(),le=X.getViewportSize();return dn({row:Mr(B.rowAxis,(M-G.top)/J,{scroll:Math.max(0,ne.y),frozenSize:ie.height,trailingSize:ie.trailingHeight,extent:le.height}),col:Dr(B.colAxis,(A-G.left)/J,{scroll:Math.max(0,ne.x),frozenSize:ie.width,trailingSize:ie.trailingWidth,extent:le.width})},B.rowAxis.count,B.colAxis.count)},[]),x=i.useCallback(A=>{N.current=A,y.current===null&&(y.current=requestAnimationFrame(()=>{y.current=null;const M=N.current;$(M===null?null:"cell"in M?M.cell:_(M.clientX,M.clientY))}))},[$,_]),g=i.useCallback(A=>x({cell:A}),[x]),p=i.useCallback(()=>T(),[T]),C=i.useCallback(A=>{if(l.current===null)return;const M=t.current;l.current=null,r(null),U({interactive:null}),(A===void 0||A.restoreFocus)&&M.focusSink({preventScroll:!0}),M.isEditing()||M.rearmSink()},[U]),v=i.useCallback(A=>{l.current=A.kind,r(A),U({interactive:A.cell})},[U]),k=i.useCallback(A=>{const M=t.current;return ma(M.adapter)?{cellReadOnly:Je(M.adapter,A.row,A.col)}:{}},[]),b=i.useCallback((A,M)=>{const B=t.current;if(Je(B.adapter,A.cell.row,A.cell.col)){B.rejectReadOnly({kind:"operation",op:"annotate",cellCount:1}),v({...A,...k(A.cell)});return}if(B.commitEdits(M,{source:"annotate"})===null){v({...A,rejected:!0});return}C()},[v,C,k]),R=i.useCallback((A,M)=>{const B=t.current;if(!wr(B.adapter,B.popovers,A))throw new RangeError(`[spreadsheet] openPopover("${A}") is unavailable: the kind is disabled by the popovers prop or its adapter capability is undeclared`);const I=B.getActive();if(A==="list"&&Je(B.adapter,I.row,I.col)){B.rejectReadOnly({kind:"edit",cell:I,editSession:"none"});return}if(A==="note-tip"){H(I);return}if(A==="message"){if(l.current!==null&&l.current!=="message")return;const ne=M!==void 0&&M.message!==void 0?M.message:void 0,ie=B.adapter.getCellValidation===void 0?void 0:B.adapter.getCellValidation(I.row,I.col),le=ne!==void 0?ne:ie===void 0?void 0:ie.inputMessage;if(le===void 0)return;const Ae=M!==void 0&&M.rejected===!0;v({kind:"message",cell:I,anchorRect:j(I),current:{title:qe(B.labels,"messageTitle"),message:le,rejected:Ae},close:C});return}if(B.isEditing()&&!B.requestCommit())return;if(A==="list"){const ne=B.adapter.getCellValidation===void 0?void 0:B.adapter.getCellValidation(I.row,I.col);if(ne===void 0||ne.type!=="list")return;const ie=M!==void 0&&M.typed!==void 0?M.typed:"";T(),B.focusSink({preventScroll:!0}),v({kind:"list",cell:I,anchorRect:j(I),current:ne.values,typed:ie,commit:le=>{if(Je(t.current.adapter,I.row,I.col)){t.current.rejectReadOnly({kind:"edit",cell:I,editSession:"none"}),C();return}t.current.commitEdits([{row:I.row,col:I.col,text:le}],{source:"edit",editSession:"discarded"}),C()},close:C});return}if(T(),B.focusSink({preventScroll:!0}),A==="note"){const ne=B.adapter.getCellNote===void 0?void 0:B.adapter.getCellNote(I.row,I.col),ie={kind:"note",cell:I,anchorRect:j(I),current:ne,commit:le=>{b(ie,[{row:I.row,col:I.col,note:le}])},close:C,rejected:!1,...k(I)};v(ie);return}if(A==="comment"){const ne=B.adapter.getCellComments===void 0?void 0:B.adapter.getCellComments(I.row,I.col),ie={kind:"comment",cell:I,anchorRect:j(I),current:ne===void 0?[]:ne,commit:le=>{b(ie,[{row:I.row,col:I.col,comments:le}])},close:C,rejected:!1,...k(I)};v(ie);return}const X=B.adapter.getCellHyperlink===void 0?void 0:Jn(B.adapter.getCellHyperlink(I.row,I.col)),G=B.adapter.getCellText(I.row,I.col),J={kind:"link",cell:I,anchorRect:j(I),current:{text:G,url:X},commit:ne=>{const ie=ne.url===null?null:un(ne.url);if(ie===null&&ne.url!==null)throw new RangeError(`[spreadsheet] link commit received an unnormalisable url ${JSON.stringify(ne.url)}`);const le=ne.text===G?{row:I.row,col:I.col,hyperlink:ie}:{row:I.row,col:I.col,text:ne.text,hyperlink:ie};b(J,[le])},close:C,canOpen:B.onHyperlinkOpen!==void 0,open:()=>{const ne=t.current.onHyperlinkOpen;ne!==void 0&&X!==void 0&&ne(X,I)},rejected:!1,...k(I)};v(J)},[j,C,b,T,v,H,k]),{enabled:a,bodyRef:f}=e;i.useEffect(()=>{const A=f.current;if(!a||A===null)return;const M=I=>{const X=t.current;wr(X.adapter,X.popovers,"note-tip")&&x({clientX:I.clientX,clientY:I.clientY})},B=()=>{wr(t.current.adapter,t.current.popovers,"note-tip")&&x({cell:null})};return A.addEventListener("pointermove",M),A.addEventListener("pointerleave",B),()=>{A.removeEventListener("pointermove",M),A.removeEventListener("pointerleave",B)}},[a,f,x]),i.useEffect(()=>()=>{y.current!==null&&cancelAnimationFrame(y.current),m.current!==null&&window.clearTimeout(m.current)},[]);const{adapter:E,popovers:d}=e,L=i.useMemo(()=>Iw.some(A=>wr(E,d,A)),[E,d]);return i.useMemo(()=>({layerEnabled:L,isKindEnabled:A=>wr(t.current.adapter,t.current.popovers,A),open:R,close:C,isOpen:()=>l.current,onCellHover:g,hideTip:p,onTipPointerEnter:()=>{h.current=!0,V()},onTipPointerLeave:()=>{h.current=!1,c.current!==null&&P()},syncTipAriaDescribedBy:O,context:n,tipContext:o,registerCompositionEnd:A=>{W.current=A},isCompositionKey:A=>iu(A,W.current),getLayerSize:()=>{const A=t.current.handleRef.current;return A===null?{width:0,height:0}:A.getViewportSize()},tipId:D}),[L,R,C,g,p,V,P,O,n,o,D])},Ww=(e,t,n)=>{let r=null,o=0;if(typeof document.caretPositionFromPoint=="function"){const l=document.caretPositionFromPoint(e,t);if(l===null)return;r=l.offsetNode,o=l.offset}else if(typeof document.caretRangeFromPoint=="function"){const l=document.caretRangeFromPoint(e,t);if(l===null)return;r=l.startContainer,o=l.startOffset}else return;if(r===null||r.nodeType!==Node.TEXT_NODE)return;const s=r.parentElement?.closest("[data-aqsp-cell]")??null;if(!(s===null||Number(s.getAttribute("data-row"))!==n.row||Number(s.getAttribute("data-col"))!==n.col))return o},au=(e,t,n,r,o,s,l)=>{if(e===null||t===null)return null;const{x:c,y:u}=e.getScrollPosition();if(u<0||c<0||n.totalSize()===0||r.totalSize()===0)return null;const h=e.getFrozenSize(),m=e.getViewportSize();return dn({row:Mr(n,(l-t.top)/o,{scroll:u,frozenSize:h.height,trailingSize:h.trailingHeight,extent:m.height}),col:Dr(r,(s-t.left)/o,{scroll:c,frozenSize:h.width,trailingSize:h.trailingWidth,extent:m.width})},n.count,r.count)},Vw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef({clientX:0,clientY:0}),l=i.useRef(null),c=i.useRef(null),u=i.useRef(0),h=i.useRef(null),m=i.useRef(!1),y=i.useRef(null),N=i.useRef(""),W=i.useRef(!1),D=i.useRef(!1),j=i.useCallback((x,g)=>{const{handleRef:p,rowAxis:C,colAxis:v,zoomRef:k}=t.current;return au(p.current,o.current,C,v,k.current,x,g)},[]),U=i.useRef(!1),V=i.useRef(null),O=i.useRef(null),T=i.useRef({clientX:0,clientY:0}),P=i.useCallback(()=>{const{autoScroller:x,bodyRef:g,onDragFrame:p}=t.current;n.current=!1,r.current=null,h.current=null,U.current=!1,V.current=null,O.current=null,m.current=!1,y.current=null,l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),x.stop();const C=g.current;C!==null&&c.current!==null&&C.hasPointerCapture?.(c.current)&&C.releasePointerCapture(c.current),c.current=null,p(null),t.current.repaintOverlay()},[]),H=i.useCallback(()=>{if(!n.current)return;const x=r.current;x!==null&&t.current.setSelection(x),P()},[P]),{enabled:$,bodyRef:_}=e;return i.useEffect(()=>{const x=_.current;if(!$||x===null)return;const g=d=>d instanceof Element&&d.closest("[data-aqsp-cells]")!==null,p=d=>{const L=t.current;if(d.pointerType==="mouse"&&d.button===0&&(m.current=!1,y.current=null,D.current=!1),W.current=g(d.target),!W.current){if(d.pointerType==="mouse"){if(d.preventDefault(),d.button!==0)return;if(L.getPointing?.()){L.focusSink();return}if(L.isEditing()&&!L.requestCommit()){d.stopPropagation(),L.focusSink();return}L.focusSink()}return}if(N.current=d.pointerType,d.pointerType!=="mouse")return;if(d.button!==0){d.preventDefault();return}if((L.pointDragRef===void 0?null:L.pointDragRef.current)?.onPointerDown(d))return;if(L.isEditing()&&!L.requestCommit()){d.preventDefault(),L.focusSink();return}o.current=x.getBoundingClientRect();const M=j(d.clientX,d.clientY);if(M===null)return;if(d.preventDefault(),L.focusSink(),(d.ctrlKey||d.metaKey)&&!d.shiftKey&&L.openHyperlinkAt?.(M)===!0){D.current=!0;return}const B=L.getSelection();r.current=B;const I=d.shiftKey,X=d.ctrlKey||d.metaKey,G=X&&!I&&B.ranges.some(ne=>kn(ne,M));m.current=G,y.current=G?M:null,G||L.setSelection(Ar(B,M,{extend:I,append:X})),n.current=!0,L.repaintOverlay(),s.current={clientX:d.clientX,clientY:d.clientY},c.current=d.pointerId,u.current=d.buttons;try{x.setPointerCapture(d.pointerId)}catch{c.current=null}const J=G?M:L.getSelection().anchor;h.current=ne=>ke(J,ne),V.current=J.col,O.current=J.row,L.autoScroller.stop(),U.current=!1,T.current={clientX:d.clientX,clientY:d.clientY}},C=d=>c.current!==null?d.pointerId===c.current:d.pointerType==="mouse",v=d=>{if(n.current&&C(d)){if(s.current={clientX:d.clientX,clientY:d.clientY},!U.current&&h.current!==null){const L=Math.abs(d.clientX-T.current.clientX),A=Math.abs(d.clientY-T.current.clientY);Math.max(L,A)>=Co&&(U.current=!0,t.current.autoScroller.start({getPointerPosition:()=>s.current,buildRange:h.current,anchorCol:V.current??void 0,anchorRow:O.current??void 0}))}l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const L=h.current;if(!n.current||L===null)return;const A=t.current,M=j(s.current.clientX,s.current.clientY);M!==null&&A.onDragFrame(L(M))}))}},k=d=>{v(d),n.current&&C(d)&&(u.current&1)!==0&&(d.buttons&1)===0&&R(d)},b=d=>{d.button!==0||!(n.current&&C(d))||R(d)},R=d=>{const L=t.current,A=j(d.clientX,d.clientY);if(A!==null){const M=y.current;m.current&&M!==null?L.setSelection(su(L.getSelection(),ke(M,A),M)):L.setSelection(yn(L.getSelection(),A))}P()},a=d=>{!n.current||c.current===null||d.pointerId!==c.current||H()},f=d=>{const L=t.current;if(!g(d.target)||N.current!=="mouse"||L.isAnyDragging())return;if(L.isEditing()&&!L.requestCommit()){L.focusSink();return}L.focusSink(),o.current=x.getBoundingClientRect();const A=j(d.clientX,d.clientY);if(A===null)return;const M=L.getSelection();M.ranges.some(I=>kn(I,A))||L.setSelection(Ar(M,A,{extend:!1,append:!1})),L.onContextMenuSelect(A,d)},E=d=>{const L=t.current;if(!W.current||N.current!=="mouse"||L.getPointing?.()||D.current)return;o.current=x.getBoundingClientRect();const A=j(d.clientX,d.clientY);A!==null&&Vt(L.getSelection().active,A)&&L.onRequestEdit(A,L.caretFromPointEnabled(A)?Ww(d.clientX,d.clientY,A):void 0)};return x.addEventListener("pointerdown",p),x.addEventListener("pointermove",k),x.addEventListener("pointerup",b),x.addEventListener("lostpointercapture",a),x.addEventListener("contextmenu",f),x.addEventListener("dblclick",E),()=>{x.removeEventListener("pointerdown",p),x.removeEventListener("pointermove",k),x.removeEventListener("pointerup",b),x.removeEventListener("lostpointercapture",a),x.removeEventListener("contextmenu",f),x.removeEventListener("dblclick",E),P()}},[$,_,j,P,H]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>m.current?"subtract":"add",abortDrag:H,cancelDrag:P}),[H,P])},Yw=e=>{const t=i.useRef(e);t.current=e;const n=i.useRef(!1),r=i.useRef(null),o=i.useRef(null),s=i.useRef({clientX:0,clientY:0}),l=i.useRef({clientX:0,clientY:0}),c=i.useRef(null),u=i.useRef(null),h=i.useRef(0),m=i.useRef(null),y=i.useRef(null),N=i.useRef(!1),W=i.useCallback((T,P)=>{const{handleRef:H,rowAxis:$,colAxis:_,zoomRef:x}=t.current;return au(H.current,o.current,$,_,x.current,T,P)},[]),D=i.useCallback(()=>{const{autoScroller:T,bodyRef:P,onDragFrame:H}=t.current;n.current=!1,r.current=null,m.current=null,y.current=null,N.current=!1,o.current=null,c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),T.stop();const $=P.current;$!==null&&u.current!==null&&$.hasPointerCapture?.(u.current)&&$.releasePointerCapture(u.current),u.current=null,H(null)},[]),j=i.useCallback(()=>{if(!n.current)return;const T=r.current;T!==null&&t.current.restoreSink(T),D()},[D]),U=i.useCallback(T=>{const P=t.current,H=P.bodyRef.current;if(!P.enabled||H===null||!P.getPointing())return!1;o.current=H.getBoundingClientRect();const $=W(T.clientX,T.clientY);if($===null)return o.current=null,!1;const _=P.captureSink();if(_===null)return o.current=null,!1;T.preventDefault(),P.focusSink(),r.current=_,y.current=$,P.insertReference($,"cells"),n.current=!0,s.current={clientX:T.clientX,clientY:T.clientY},l.current={clientX:T.clientX,clientY:T.clientY},u.current=T.pointerId,h.current=T.buttons;try{H.setPointerCapture(T.pointerId)}catch{u.current=null}return m.current=x=>{const g=ke($,x);return t.current.insertReference(g,"cells"),g},P.autoScroller.stop(),N.current=!1,P.onDragFrame(ke($,$)),!0},[W]),{enabled:V,bodyRef:O}=e;return i.useEffect(()=>{const T=O.current;if(!V||T===null)return;const P=x=>u.current!==null?x.pointerId===u.current:x.pointerType==="mouse",H=x=>{if(!(n.current&&P(x)))return;s.current={clientX:x.clientX,clientY:x.clientY};const g=m.current,p=y.current;if(!N.current&&g!==null&&p!==null){const C=Math.abs(x.clientX-l.current.clientX),v=Math.abs(x.clientY-l.current.clientY);Math.max(C,v)>=Co&&(N.current=!0,t.current.autoScroller.start({getPointerPosition:()=>s.current,buildRange:g,anchorCol:p.col,anchorRow:p.row}))}c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null;const C=m.current;if(!n.current||C===null)return;const v=W(s.current.clientX,s.current.clientY);v!==null&&t.current.onDragFrame(C(v))})),(h.current&1)!==0&&(x.buttons&1)===0&&D()},$=x=>{x.button!==0||!(n.current&&P(x))||D()},_=x=>{!n.current||u.current===null||x.pointerId!==u.current||D()};return T.addEventListener("pointermove",H),T.addEventListener("pointerup",$),T.addEventListener("lostpointercapture",_),()=>{T.removeEventListener("pointermove",H),T.removeEventListener("pointerup",$),T.removeEventListener("lostpointercapture",_),D()}},[V,O,W,D]),i.useMemo(()=>({isDragging:()=>n.current,getDragMode:()=>"point",abortDrag:j,cancelDrag:D,onPointerDown:U}),[j,D,U])},Kw=Object.freeze({width:0,height:0}),as=33,Uw=e=>e.nodeType===Node.DOCUMENT_NODE||e.nodeType===Node.DOCUMENT_FRAGMENT_NODE,Xw=(e,t,n)=>{const r=(n-t)/(as-1);let o=-1,s=-1;for(let c=0;c<as;c++)e(t+r*c)&&(o===-1&&(o=c),s=c);if(o===-1)return null;const l=(c,u)=>{let h=c,m=u;for(;Math.abs(m-h)>1;){const y=(h+m)/2;e(y)?m=y:h=y}return m};return{top:o===0?t:l(t+r*(o-1),t+r*o),bottom:s===as-1?n:l(t+r*(s+1),t+r*s)}},Gw=(e,t)=>{if(!Number.isInteger(e)||e<0||e>0&&e>t)throw new RangeError(`[spreadsheet] headerRows must be a whole number from 0 to frozenRows = ${t} (got ${e})`)},Zw=e=>{if(e!==void 0&&(typeof e!="string"||e===""||/\s/u.test(e)))throw new RangeError(`[spreadsheet] labelledBy must be one non-empty id without whitespace (got ${JSON.stringify(e)})`)},Jw=e=>{if(e===void 0)return;if(![e.startRow,e.startCol,e.endRow,e.endCol].every(n=>Number.isInteger(n)&&n>=0)||e.startRow>e.endRow||e.startCol>e.endCol)throw new RangeError(`[spreadsheet] frame must hold non-negative integer bounds with each start at most its end (got startRow ${String(e.startRow)}, startCol ${String(e.startCol)}, endRow ${String(e.endRow)}, endCol ${String(e.endCol)})`)},ac=(e,t)=>{if(t!==void 0&&!(Number.isInteger(t)&&t>=0))throw new RangeError(`[spreadsheet] ${e} must be a non-negative integer (got ${typeof t=="string"?JSON.stringify(t):String(t)})`);return t},Qw=24,e0=200,uu=Object.freeze(["#FF0000","#00FF00","#0000FF","#FFFF00","#FF00FF"]),uc=5,t0=/^#[0-9A-Fa-f]{6}$/,n0=Object.freeze({row:!1,column:!1,intersection:!1}),dc=Object.freeze({ok:!0}),fc=(e,t)=>{if(t===void 0)return uu;if(t.length!==uc)throw new RangeError(`[spreadsheet] colors.${e} must contain exactly ${uc} colours (got ${t.length})`);for(const n of t)if(typeof n!="string"||!t0.test(n))throw new RangeError(`[spreadsheet] colors.${e} entries must be #rrggbb strings (got ${JSON.stringify(n)})`);return t},r0=e=>{for(const t of["row","column","intersection"])if(ot(e[t])===null)throw new RangeError(`[spreadsheet] highlightColors.${t} is not a colour (got ${JSON.stringify(e[t])})`);if(!(Number.isFinite(e.opacity)&&e.opacity>=0&&e.opacity<=1))throw new RangeError(`[spreadsheet] highlightColors.opacity must be a number in [0, 1] (got ${e.opacity})`);return e},o0=(e,t)=>{if(e!==void 0)return e;if(t.row||t.column||t.intersection)return Pa},s0=e=>{if(e===void 0)throw new RangeError("[spreadsheet] commitEdits: a paste commit requires its sheet context (sameSheet / conditionalFormats)");return e},l0=e=>{const t=i.useRef(null),n=t.current;return n!==null&&st.VIRTUAL_SCROLL_LABEL_KEYS.every(r=>n[r]===e[r])?n:(t.current=e,e)},qn={ranges:[ke({row:0,col:0},{row:0,col:0})],anchor:{row:0,col:0},active:{row:0,col:0}},i0=i.forwardRef(function({adapter:t,headerRows:n=0,readOnly:r=!1,labelledBy:o,defaultRowHeight:s=Qw,defaultColumnWidth:l=De.SPREADSHEET_DEFAULT_COLUMN_WIDTH_PX,frozenColumns:c=0,frozenRows:u=0,frozenTrailingColumns:h=0,frozenTrailingRows:m=0,tapScrollCircleOptions:y,overscanRows:N,overscanCols:W,background:D,onRenderTruncated:j,renderCell:U,onSelectionChange:V,onCellContextMenu:O,onUndoRequest:T,onRedoRequest:P,onCopyMultiRange:H,onOperationRejected:$,onEditRejected:_,onReadOnlyRejected:x,formatReadOnlyAnnouncement:g,dataVersion:p,maxOperationCells:C=De.SPREADSHEET_MAX_OPERATION_CELLS,enableFillHandle:v=!0,enableResizeUI:k=!0,headings:b=!0,onContentSizeChange:R,frame:a,formatCellAnnouncement:f,formatSelectionAnnouncement:E,formatCommandAnnouncement:d,formatResizeAnnouncement:L,locale:A,labels:M,shortcuts:B,colors:I,formats:X,highlight:G,defaultHighlight:J,onHighlightChange:ne,highlightColors:ie,popovers:le,renderPopover:Ae,onClipChange:ze,onHyperlinkOpen:Ne,onValidationRejected:Ie,onPasteSpecialRequest:ge,onClipboardUnavailable:Fe,onPasteResolved:lt,now:He=Date.now,zoom:Ft,defaultZoom:bt,onZoomChange:it,testId:Qe,className:fn,__onCellRender:Qn,__onVirtualKeyboardRaise:er,__maxRenderedCells:En},zr){const oe=i.useMemo(()=>r?kh(t):t,[t,r]),Ce=Ji(oe.rowCount,s),pe=Ji(oe.colCount,l),ft=i.useRef(null);ft.current===null&&(ft.current=$w());const xe=ft.current,Kt=st.resolveVirtualScrollLocale(A),yt=i.useMemo(()=>Ea(A,M),[A,M]),Fr=l0(Gh(yt)),Nt=i.useMemo(()=>Yh(B),[B]),Nr=i.useMemo(()=>{if(!k)return;const q=[...Nt].filter(([,Z])=>es.includes(Z)).sort(([,Z],[,te])=>es.indexOf(Z)-es.indexOf(te)).map(([Z])=>jh(Z)).filter(Z=>Z!==null);return q.length===0?void 0:q.join(" ")},[Nt,k]),On=i.useMemo(()=>({fill:fc("fill",I===void 0?void 0:I.fill),font:fc("font",I===void 0?void 0:I.font)}),[I]),Ut=i.useMemo(()=>ie===void 0?void 0:r0(ie),[ie]);if(oe.getConditionalFormats!==void 0&&oe.getCellFormat===void 0)throw new RangeError("[spreadsheet] getConditionalFormats requires getCellFormat");Gw(n,u),Zw(o),Jw(a);const pn=i.useCallback(()=>xe.get().editVersion,[xe]),An=i.useCallback(w=>xe.subscribeCoalesced(w),[xe]),nr=i.useSyncExternalStore(An,pn,pn)+(p===void 0?0:p),xn=oe.getConditionalFormats===void 0?null:oe.getConditionalFormats(),Xt=i.useMemo(()=>({index:xn===null?null:tu(xn),memo:Ys()}),[oe,xn,nr]),rr=i.useRef(Xt.index);rr.current=Xt.index;const or=i.useRef(Xt.memo);or.current=Xt.memo;const Gt=i.useCallback((w,q,Z)=>Ks(oe,rr.current,or.current,w,q,Z),[oe]),Ue=i.useRef(null),[Eo,Tn]=i.useState(()=>De.clampSpreadsheetZoom(bt??1)),pt=De.clampSpreadsheetZoom(Ft??Eo),Pe=i.useRef(pt);Pe.current=pt;const S=i.useRef(pt);S.current=pt;const F=i.useRef(null),K=i.useRef(it);K.current=it;const z=i.useRef(Ft!==void 0);z.current=Ft!==void 0;const Q=i.useCallback(w=>{const q=De.clampSpreadsheetZoom(w);q!==S.current&&(S.current=q,z.current||Tn(q),K.current?.(q))},[]),ee=oe.rowCount===0||oe.colCount===0,re=!ee;i.useEffect(()=>{const w=Ue.current;if(!re||w===null)return;const q=te=>{te.defaultPrevented||!te.altKey||te.ctrlKey||te.metaKey||te.shiftKey||te.deltaY!==0&&(te.preventDefault(),te.stopPropagation(),!F.current?.()&&Q(De.stepSpreadsheetZoom(S.current,te.deltaY<0?1:-1)))},Z=te=>{if(te.defaultPrevented||!(te.ctrlKey&&te.altKey)||te.metaKey||te.getModifierState("AltGraph"))return;const he=te.key==="="||te.key==="+"?De.stepSpreadsheetZoom(S.current,1):te.key==="-"?De.stepSpreadsheetZoom(S.current,-1):te.key==="0"?1:null;he!==null&&(te.preventDefault(),te.stopPropagation(),!F.current?.()&&Q(he))};return w.addEventListener("wheel",q,{passive:!1,capture:!0}),w.addEventListener("keydown",Z,!0),()=>{w.removeEventListener("wheel",q,{capture:!0}),w.removeEventListener("keydown",Z,!0)}},[Q,re]);const ue=i.useRef(null),be=i.useRef(null),Te=i.useRef(null),_e=i.useRef(null),de=i.useRef(null),Le=i.useRef(null),fe=i.useRef(null),se=i.useRef(0),ye=i.useRef(null),Re=i.useRef(0),me=i.useRef(null),et=i.useRef(null),ae=i.useRef(null),Oe=i.useRef(null),Be=i.useRef(null),Xe=i.useRef(null),ct=i.useRef(null),[Ee,ht]=i.useState(qn),Ve=i.useRef(Ee),We=i.useCallback(()=>Ve.current,[]),[tt,$n]=i.useState(()=>J===void 0?n0:J),Zt=G!==void 0?G:tt,sr=i.useRef(Zt);sr.current=Zt;const du=o0(Ut,Zt),Xs=i.useRef(G!==void 0);Xs.current=G!==void 0;const Gs=i.useRef(ne);Gs.current=ne;const fu=i.useCallback(w=>{Xs.current||$n(w),Gs.current?.(w)},[]),Zs=i.useRef(null),Oo=i.useRef(null),Pt=i.useRef(null),Ao=i.useRef(()=>!1),Js=i.useRef(()=>{}),Qs=i.useRef(()=>null),el=i.useRef(()=>{}),hn=i.useCallback(()=>Ao.current(),[]),xo=i.useMemo(()=>({getPointing:()=>Ao.current(),insertReference:(w,q)=>Js.current(w,q)}),[]),tl=i.useRef(Ht),nl=i.useRef(null),To=i.useRef({interactive:null,tip:null}),rl=i.useRef(null),ol=i.useRef(null),Pr=i.useRef(()=>{}),sl=i.useRef(()=>!1),Jt=i.useRef(null),lr=i.useCallback(()=>{const w=Jt.current;if(w===null||w.isOpen()!=="message")return!1;const q=w.context;return q===null||q.kind!=="message"||!q.current.rejected?!1:(w.close(),!0)},[]),$o=i.useRef(()=>!1),ll=i.useRef(()=>!1),il=i.useRef(null),Lo=i.useRef(()=>Promise.resolve("rejected")),$e=i.useCallback(()=>{Zs.current?.()},[]),_t=i.useCallback(w=>{Le.current?.focus(w)},[]),Ye=i.useCallback(()=>{_t({preventScroll:!0})},[_t]),Do=i.useRef(!1),pu=i.useCallback(()=>{const w=Ue.current;if(w!==null){Do.current=!0;try{w.focus()}finally{Do.current=!1}}},[]),at=i.useCallback(()=>{const w=Le.current;w!==null&&(w.value=" ",w.setSelectionRange(0,1))},[]),Ln=i.useCallback((w,q)=>{if(w===null)return;const Z=q?"":"none";w.style.display!==Z&&(w.style.display=Z)},[]),Rt=i.useCallback(()=>{const w=fe.current;if(w!==null){const Z=Math.max(0,de.current?.getScrollPosition().y??0),te=de.current?.getFrozenSize().height??0;w.style.transform=`translateY(${se.current-Z-te}px)`}const q=de.current;if(q!==null&&(Be.current!==null||Xe.current!==null)){const Z=q.getFrozenSize();Ln(Be.current,Z.height>0),Ln(Xe.current,Z.trailingHeight>0)}},[Ln]),vt=i.useCallback(()=>{const w=ye.current;if(w!==null){const Z=Math.max(0,de.current?.getScrollPosition().x??0),te=de.current?.getFrozenSize().width??0;w.style.transform=`translateX(${Re.current-Z-te}px)`}const q=de.current;if(q!==null&&(ae.current!==null||Oe.current!==null)){const Z=q.getFrozenSize();Ln(ae.current,Z.width>0),Ln(Oe.current,Z.trailingWidth>0)}},[Ln]),ir=i.useRef(null),Dn=i.useCallback(()=>{ae.current===null&&Oe.current===null&&Be.current===null&&Xe.current===null||ir.current===null&&(ir.current=requestAnimationFrame(()=>{ir.current=null,Rt(),vt(),$e()}))},[Rt,vt,$e]);i.useEffect(()=>()=>{ir.current!==null&&cancelAnimationFrame(ir.current)},[]);const Mo=i.useRef(null),zo=i.useRef(null);(Mo.current===null||zo.current?.rowAxis!==Ce||zo.current?.colAxis!==pe)&&(zo.current={rowAxis:Ce,colAxis:pe},Mo.current=Sw({handleRef:de,rowAxis:Ce,colAxis:pe}));const _r=i.useCallback(w=>{const q=de.current,Z=q===null?{x:0,y:0}:q.getScrollPosition(),te=q===null?{rows:0,cols:0,trailingRows:0,trailingCols:0}:q.getFrozenSize(),he=q===null?{width:0,height:0}:q.getViewportSize(),ve=Pe.current;return{top:Sn(Ce,w.row,{scroll:Math.max(0,Z.y),frozenCount:te.rows,trailingCount:te.trailingRows,extent:he.height})*ve,left:vn(pe,w.col,{scroll:Math.max(0,Z.x),frozenCount:te.cols,trailingCount:te.trailingCols,extent:he.width})*ve,width:pe.sizeOf(w.col)*ve,height:Ce.sizeOf(w.row)*ve}},[Ce,pe]),cl=i.useCallback(w=>{const q=_e.current,Z=Ue.current,te=be.current;if(q===null||Z===null||te===null||de.current===null)return;const he=Pe.current,ve=_r(w),Ze=te.offsetTop*he+ve.top,dt=te.offsetLeft*he+ve.left,Ke=Math.max(0,Ze),Dt=Math.max(0,dt),tn=Math.min(Z.clientHeight,Ze+ve.height),Hr=Math.min(Z.clientWidth,dt+ve.width);if(tn<=Ke||Hr<=Dt)return;q.style.top=`${Ke}px`,q.style.left=`${Dt}px`,q.style.width=`${Hr-Dt}px`,q.style.height=`${tn-Ke}px`;const Nn=q.getBoundingClientRect();Nn.width===0&&Nn.height===0||q.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"})},[_r]),Qt=i.useCallback(w=>{Mo.current?.(w),cl(w)},[cl]),hu=i.useCallback(()=>{const w=de.current,q=w===null?-1:w.getViewportSize().height,Z=ue.current,te=Ue.current;if(q<=0||Z===null||te===null)return q;const he=Z.getBoundingClientRect(),ve=te.getRootNode();if(he.height<=0||Z.offsetHeight<=0||!Uw(ve))return q;const Ze=te.ownerDocument.documentElement,dt=Math.max(he.left,0),Ke=Math.min(he.right,Ze.clientWidth),Dt=Math.max(he.top,0)+.5,tn=Math.min(he.bottom,Ze.clientHeight)-.5,Hr=(dt+Ke)/2,Nn=Ke>dt&&tn>=Dt?Xw(Wu=>{const _l=ve.elementFromPoint(Hr,Wu);return _l!==null&&te.contains(_l)},Dt,tn):null,Bu=Nn===null?Ze.clientHeight:Nn.bottom-Nn.top+1;return Math.min(q,Bu*(Z.offsetHeight/he.height))},[]),al=i.useRef(R);al.current=R;const Fo=i.useRef(null),qt=i.useCallback(()=>{const w=al.current;if(w===void 0)return;const q=be.current;let Z;if(q===null)Z=Kw;else{if(q.getClientRects().length===0)return;{const he=Te.current,ve=Pe.current;Z={width:((he===null?0:he.offsetWidth)+pe.totalSize()+De.SPREADSHEET_SCROLLBAR_SIZE_PX)*ve,height:((he===null?0:he.offsetHeight)+Ce.totalSize()+De.SPREADSHEET_SCROLLBAR_SIZE_PX)*ve}}}const te=Fo.current;te!==null&&te.width===Z.width&&te.height===Z.height||(Fo.current=Z,w(Z))},[Ce,pe]);i.useLayoutEffect(()=>{if(R===void 0){Fo.current=null;return}qt()});const ul=R!==void 0;i.useEffect(()=>{const w=be.current;if(!ul||w===null)return;const q=new ResizeObserver(()=>qt());return q.observe(w),()=>q.disconnect()},[ul,qt,ee]);const Mn=i.useRef(null),mn=i.useRef(null),zn=i.useCallback(w=>{Mn.current!==null&&window.clearTimeout(Mn.current),mn.current!==null&&(cancelAnimationFrame(mn.current),mn.current=null),Mn.current=window.setTimeout(()=>{Mn.current=null;const q=ct.current;q!==null&&(q.textContent="",mn.current=requestAnimationFrame(()=>{mn.current=null,q.textContent=w}))},e0)},[]);i.useEffect(()=>()=>{Mn.current!==null&&window.clearTimeout(Mn.current),mn.current!==null&&cancelAnimationFrame(mn.current)},[]);const Fn=i.useCallback(w=>{x?.(w),g!==void 0&&zn(g(w))},[x,g,zn]),dl=i.useCallback((w,q)=>{if(f===void 0&&E===void 0)return;const Z=q.ranges[q.ranges.length-1],te=Ct(Z),he=q.ranges.length===1&&te.rows===1&&te.cols===1,ve=w.ranges[w.ranges.length-1],Ze=w.ranges.length!==q.ranges.length||ve.startRow!==Z.startRow||ve.startCol!==Z.startCol||ve.endRow!==Z.endRow||ve.endCol!==Z.endCol,dt=()=>{if(f!==void 0){const Ke=q.active,Dt=oe.getCellText(Ke.row,Ke.col),tn=oe.getCellFormat===void 0?void 0:Gt(Ke.row,Ke.col,()=>Dt);zn(f({row:Ke.row,col:Ke.col,text:Dt,displayText:Xn(Dt,tn===void 0?void 0:tn.value),columnName:De.columnIndexToName(Ke.col),...ma(oe)?{readOnly:Je(oe,Ke.row,Ke.col)}:{}}))}};if(he){dt();return}if(Ze){E!==void 0&&zn(E({range:Z,anchor:q.anchor,active:q.active,rangeRowCount:te.rows,rangeColCount:te.cols,rangeCount:q.ranges.length}));return}dt()},[oe,f,E,zn,Gt]),Ge=i.useCallback(w=>{const q=Ve.current;Object.is(w,q)||Cw(w,q)||(Ve.current=w,ht(w),V?.(w),dl(q,w),(Pt.current?.()??!1)||at())},[V,dl,at]),mu=i.useCallback(w=>{const q=Ve.current;if(w.mode==="cycle"){const te=lu(q,w.direction);Ge(te),Qt(te.active);return}const Z=dn(w.cell,Ce.count,pe.count);if(w.mode==="extend"){Ge(yn(q,Z)),Qt(Z);return}Ge(Ar(q,Z,{extend:!1,append:!1})),Qt(Z)},[Ge,Qt,Ce,pe]),nt=i.useCallback(()=>Pt.current?.()??!1,[]),fl=i.useRef(null),St=i.useCallback(()=>fl.current?.()??!0,[]),pl=i.useRef(null),cr=i.useCallback((w,q)=>{const Z=Pt.current?.()??!1;pl.current?.(w,q),!Z&&(Pt.current?.()??!1)&&lr()},[lr]),[gu,No]=i.useState(!1),hl=i.useCallback(()=>{er?.(),No(!0)},[er]),wu=i.useCallback((w,q)=>{Je(oe,w.row,w.col)||hl(),cr("edit",q)},[oe,hl,cr]),ml=i.useRef(null),qr=i.useCallback(()=>ml.current?.()??null,[]),gl=i.useRef(null),Tt=i.useCallback(()=>{gl.current?.()},[]),wl=i.useRef(null),Cl=i.useCallback(w=>{wl.current?.(w)},[]),bl=i.useRef(()=>{}),jr=i.useRef(0),gn=i.useCallback((w,q,Z)=>{let te;if(q.source==="paste"){const he=s0(Z);if(w.length===0&&he.conditionalFormats.length===0)return null;jr.current+=1,te={transaction:jr.current,source:"paste",sameSheet:he.sameSheet,conditionalFormats:he.conditionalFormats}}else{if(w.length===0)return null;jr.current+=1,te={transaction:jr.current,source:q.source}}try{oe.applyEdits(w,te)}catch(he){return _?.(he,q),null}return xe.bumpEdit(),Cl(q.source),te.transaction},[oe,xe,_,Cl]),Cu=i.useCallback((w,q)=>gn(w,{source:"paste"},q),[gn]),bu=i.useCallback(w=>{xe.setVy(w.y),Rt(),vt(),$e()},[xe,Rt,vt,$e]),yl=i.useRef({rowStart:-1,rowEnd:-1,colStart:-1,colEnd:-1}),yu=i.useCallback(w=>{xe.setRowRange(w.renderingRowStart,w.renderingRowEnd),xe.setColRange(w.renderingColStart,w.renderingColEnd);const q=yl.current;(q.rowStart!==w.renderingRowStart||q.rowEnd!==w.renderingRowEnd||q.colStart!==w.renderingColStart||q.colEnd!==w.renderingColEnd)&&(yl.current={rowStart:w.renderingRowStart,rowEnd:w.renderingRowEnd,colStart:w.renderingColStart,colEnd:w.renderingColEnd},$e())},[xe,$e]),Rl=i.useRef(()=>"add"),en=i.useCallback(w=>{Oo.current?.(w,Rl.current())},[]),Ru=i.useCallback(w=>{Oo.current?.(w,"point")},[]),vl=i.useRef(null),Po=i.useCallback(w=>{vl.current?.(w)},[]),Sl=i.useRef(null),vu=i.useCallback(w=>{Sl.current?.(w)},[]),kl=i.useRef(null),_o=i.useCallback((w,q)=>{if(q.length===0)return;const Z=de.current;if(w==="col"){for(const te of q){const he=Math.round(te.size);pe.resize(te.index,he),Z?.updateColSize(te.index,he)}xe.bumpColVersion(),vt(),$e(),Dn(),qt();return}for(const te of q){const he=Math.round(te.size);Ce.resize(te.index,he),Z?.updateRowSize(te.index,he)}xe.bumpRowGeometry(),Rt(),$e(),Dn(),qt()},[Ce,pe,xe,vt,Rt,$e,Dn,qt]),Su=i.useCallback((w,q)=>{O?.(w,{kind:"pointer",event:q})},[O]),ku=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:en,axis:"both",zoomRef:Pe}),Eu=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:en,axis:"x",zoomRef:Pe}),Ou=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:en,axis:"y",zoomRef:Pe}),Au=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:Po,axis:"x",zoomRef:Pe}),xu=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:Po,axis:"y",zoomRef:Pe}),Tu=_n({handleRef:de,rowAxis:Ce,colAxis:pe,bodyRef:ue,onDragFrame:en,axis:"both",zoomRef:Pe}),El=i.useRef(null),Ol=i.useRef(()=>!1),qo=i.useCallback(()=>Ol.current(),[]),kt=Vw({zoomRef:Pe,enabled:!ee,rowAxis:Ce,colAxis:pe,handleRef:de,bodyRef:ue,isEditing:nt,requestCommit:St,getSelection:We,setSelection:Ge,focusSink:Ye,onDragFrame:en,onContextMenuSelect:Su,onRequestEdit:wu,caretFromPointEnabled:w=>{if(U!==void 0||oe.getCellFormula!==void 0&&oe.getCellFormula(w.row,w.col)!==void 0)return!1;if(oe.getCellFormat===void 0)return!0;const q=oe.getCellText(w.row,w.col);return Xn(q,oe.getCellFormat(w.row,w.col)?.value)===q},isAnyDragging:qo,autoScroller:ku,repaintOverlay:$e,pointDragRef:El,getPointing:hn,openHyperlinkAt:Ne===void 0||oe.getCellHyperlink===void 0?void 0:w=>{const q=oe.getCellHyperlink===void 0?void 0:Jn(oe.getCellHyperlink(w.row,w.col));return q===void 0?!1:(Ne(q,w),!0)}}),$t=cc({zoomRef:Pe,enabled:!ee&&b,axis:"col",headerRef:me,mainAxis:pe,crossCount:oe.rowCount,handleRef:de,isEditing:nt,requestCommit:St,getSelection:We,setSelection:Ge,focusSink:Ye,onDragFrame:en,autoScroller:Eu,repaintOverlay:$e,pointing:xo}),Lt=cc({zoomRef:Pe,enabled:!ee&&b,axis:"row",headerRef:et,mainAxis:Ce,crossCount:oe.colCount,handleRef:de,isEditing:nt,requestCommit:St,getSelection:We,setSelection:Ge,focusSink:Ye,onDragFrame:en,autoScroller:Ou,repaintOverlay:$e,pointing:xo}),ut=ww({zoomRef:Pe,enabled:!ee&&k&&b,colBandRef:me,rowBandRef:et,fontSourceRef:ue,colAxis:pe,rowAxis:Ce,viewStore:xe,handleRef:de,isEditing:nt,requestCommit:St,focusSink:Ye,getSelection:We,adapter:oe,autofitEnabled:U===void 0,headerRows:n,defaultRowHeight:s,defaultColumnWidth:l,maxOperationCells:C,onOperationRejected:$,resizeTracks:_o,writeResizeGuide:vu,repaintOverlay:$e,isPointing:hn}),Et=Mw({zoomRef:Pe,enabled:!ee&&v,handleNodeRef:kl,bodyRef:ue,rowAxis:Ce,colAxis:pe,handleRef:de,getSelection:We,setSelection:Ge,focusSink:Ye,adapter:oe,commitEdits:gn,maxOperationCells:C,onOperationRejected:$,rejectReadOnly:Fn,writeFillPreview:Po,repaintOverlay:$e,xAutoScroller:Au,yAutoScroller:xu}),mt=Yw({zoomRef:Pe,enabled:!ee,bodyRef:ue,handleRef:de,rowAxis:Ce,colAxis:pe,getPointing:hn,insertReference:xo.insertReference,captureSink:()=>Qs.current(),restoreSink:w=>el.current(w),focusSink:Ye,autoScroller:Tu,onDragFrame:en});El.current=mt;const ar=i.useCallback(()=>kt.isDragging()||$t.isDragging()||Lt.isDragging()||ut.isDragging()||Et.isDragging()||mt.isDragging(),[kt,$t,Lt,ut,Et,mt]);F.current=ar,Ol.current=ar,Rl.current=()=>mt.isDragging()?"point":kt.getDragMode();const $u=i.useCallback(()=>{kt.abortDrag(),$t.abortDrag(),Lt.abortDrag(),ut.abortDrag(),Et.abortDrag(),mt.abortDrag()},[kt,$t,Lt,ut,Et,mt]),jo=i.useCallback(()=>Ve.current.active,[]),Al=i.useCallback((w,q)=>{const Z=oe.getCellValidation===void 0?void 0:oe.getCellValidation(w.row,w.col);if(Z===void 0)return dc;const te=oe.evaluateFormula,he=xa(Z,q,Kt,te===void 0?void 0:ve=>te(ve,w));return he.ok||Z.strict!==!0?dc:(Ie?.({cell:w,rule:Z,text:q,message:he.message}),Jt.current?.isKindEnabled("message")&&Pr.current("message",{message:he.message,rejected:!0}),he)},[oe,Ie,Kt]),je=Mg({enabled:!ee,sinkRef:Le,rootRef:Ue,adapter:oe,commitEdits:gn,getActive:jo,ensureCellVisible:Qt,focusSink:_t,rearmSink:at,discardClip:Tt,isDragging:qo,rejectReadOnly:Fn,resolveEditAlign:w=>{if(oe.getCellFormat===void 0)return null;const q=ao(oe,w.row,w.col);return ha(Gt(w.row,w.col,q),q)},resolveEditPaint:w=>oe.getCellFormat===void 0?null:Rf(Gt(w.row,w.col,ao(oe,w.row,w.col))),editPaintRef:tl,repaintOverlay:$e,validateCommit:Al});Pt.current=je.isEditing,fl.current=je.requestCommit,pl.current=je.startEdit,Ao.current=je.getPointing,Js.current=je.insertReference,Qs.current=je.captureSink,el.current=je.restoreSink;const xl=i.useCallback(()=>{je.cancelEdit(),lr()},[je.cancelEdit,lr]),ur=hg({enabled:!ee,sinkRef:Le,adapter:oe,isEditing:nt,getSelection:We,setSelection:Ge,commitPaste:Cu,maxOperationCells:C,onOperationRejected:$,onCopyMultiRange:H,repaintOverlay:$e,isDragging:qo,resize:{rowAxis:Ce,colAxis:pe,resizeTracks:_o},pendingPasteOptionsRef:nl,formats:X,onClipChange:ze,onClipboardUnavailable:Fe,onEditRejected:_,rejectReadOnly:Fn,onPasteResolved:lt});ml.current=ur.getClip,gl.current=ur.discardClip,wl.current=ur.discardClipOnCommit,bl.current=ur.onAdapterSwitch,Lo.current=ur.paste;const dr=Bw({enabled:!ee,adapter:oe,popovers:le,sinkRef:Le,bodyRef:ue,handleRef:de,rowAxis:Ce,colAxis:pe,zoomRef:Pe,getActive:jo,isEditing:nt,requestCommit:St,focusSink:_t,rearmSink:at,isDraggingAny:ar,commitEdits:gn,labels:yt,onHyperlinkOpen:Ne,anchors:To,repaintOverlay:$e,rejectReadOnly:Fn});Jt.current=dr,Pr.current=dr.open,sl.current=dr.hideTip;const Lu=i.useCallback(()=>{const w=Ve.current.active;return Qt(w),_r(w)},[Qt,_r]),Io=$g({adapter:oe,trackResize:k&&!ee?ut:void 0,getSelection:We,commitEdits:gn,getActive:jo,isEditing:nt,requestCommit:St,cancelEdit:xl,getSessionText:je.getSessionText,validateCommit:Al,insertAtCaret:je.insertAtCaret,refreshEditPaint:je.refreshPaint,maxOperationCells:C,onOperationRejected:$,colors:On,formats:X,getHighlight:()=>sr.current,setHighlight:fu,popovers:le,openPopover:w=>Pr.current(w),onHyperlinkOpen:Ne,onPasteSpecialRequest:ge,paste:w=>Lo.current(w),rowAxis:Ce,colAxis:pe,resizeTracks:_o,defaultRowHeight:s,defaultColumnWidth:l,now:He,announce:zn,formatCommandAnnouncement:d,formatResizeAnnouncement:L,keyboardCellRect:Lu,rejectReadOnly:Fn});il.current=Io,$o.current=Io.executeCommand,ll.current=Io.isCommandAvailable;const Du=i.useMemo(()=>({table:Nt,execute:w=>$o.current(w),isAvailable:w=>ll.current(w)}),[Nt]),Mu=i.useCallback(()=>{Tt(),T?.()},[Tt,T]),zu=i.useCallback(()=>{Tt(),P?.()},[Tt,P]);Tw({zoomRef:Pe,enabled:!ee,sinkRef:Le,rootRef:Ue,handOffFocusToRoot:pu,getSelection:We,setSelection:Ge,moveActive:mu,ensureCellVisible:Qt,pageExtent:hu,isEditing:nt,requestCommit:St,startEdit:cr,commitEdits:gn,maxOperationCells:C,onOperationRejected:$,rejectReadOnly:Fn,getClip:qr,discardClip:Tt,isDragging:ar,abortDrag:$u,findDataEdge:oe.findDataEdge,getEditingMode:je.getEditingMode,cancelEdit:xl,onUndoRequest:Mu,onRedoRequest:zu,onCellContextMenu:O,rowAxis:Ce,colAxis:pe,handleRef:de,rearmSink:at,commands:Du,pointing:je,adapter:oe,hideNoteTip:()=>sl.current(),closeRejectedMessage:lr,pendingPasteOptionsRef:nl,onPointFrame:Ru});const Fu=Ee.active.row,Nu=Ee.active.col;i.useLayoutEffect(()=>{const w=Jt.current;w!==null&&(w.syncTipAriaDescribedBy(),w.isKindEnabled("message")&&(w.isOpen()==="message"&&w.close(),w.open("message")))},[Fu,Nu]),i.useLayoutEffect(()=>{$e()},[$e,Zt.row,Zt.column,Zt.intersection]),i.useLayoutEffect(()=>{$e()},[$e,a?.startRow,a?.startCol,a?.endRow,a?.endCol]);const Pu=i.useCallback(w=>{(Pt.current?.()??!1)||(w.preventDefault(),Ye(),at())},[Ye,at]),_u=i.useCallback(w=>{const q=Ue.current,Z=w.relatedTarget,te=q!==null&&!q.matches(":focus-visible");if(q!==null&&Z instanceof Node&&q.contains(Z)){w.target===q&&Z===Le.current&&!Do.current&&_t({preventScroll:te});return}(Pt.current?.()??!1)||(_t({preventScroll:te}),at())},[_t,at]),qu=i.useCallback(w=>{const q=Ue.current,Z=w.relatedTarget;q!==null&&Z instanceof Node&&q.contains(Z)||je.isFocusoutSuppressed()||No(!1)},[je]),Ir=i.useRef(null),fr=i.useCallback(()=>{const w=Ir.current;w!==null&&(Ir.current=null,window.removeEventListener("pointerup",w.up,!0),window.removeEventListener("pointercancel",w.cancel,!0))},[]),Ho=i.useCallback(()=>{if(Ir.current!==null)return;const w=Z=>{Z.pointerType==="mouse"&&(fr(),Z.button===1&&Z.preventDefault())},q=Z=>{Z.pointerType==="mouse"&&fr()};Ir.current={up:w,cancel:q},window.addEventListener("pointerup",w,!0),window.addEventListener("pointercancel",q,!0)},[fr]);i.useEffect(()=>fr,[fr]),i.useEffect(()=>{const w=Ue.current;if(ee||w===null)return;let q=0;const Z=ve=>{if(ve.pointerType!=="mouse"){(Pt.current?.()??!1)||No(!1);return}q=ve.buttons,ve.button===1&&(ve.target===Le.current&&(Pt.current?.()??!1)||Ho())},te=ve=>{ve.pointerType==="mouse"&&(q=ve.buttons)},he=ve=>{if(ve.pointerType!=="mouse"||ve.buttons===q)return;const Ze=ve.buttons&~q;q=ve.buttons,ve.preventDefault(),(Ze&4)!==0&&Ho()};return w.addEventListener("pointerdown",Z,!0),w.addEventListener("pointerup",te,!0),w.addEventListener("pointermove",he,!0),()=>{w.removeEventListener("pointerdown",Z,!0),w.removeEventListener("pointerup",te,!0),w.removeEventListener("pointermove",he,!0)}},[ee,Ho]);const ju=i.useCallback(w=>{if(!(w.target!==w.currentTarget||w.pointerType!=="mouse")&&(w.preventDefault(),w.button===0)){if(hn()){Ye();return}if(nt()&&!St()){Ye();return}Ye()}},[Ye,nt,St,hn]),Bo=i.useRef(!1);i.useLayoutEffect(()=>{if(ee){Bo.current=!1;return}if(Bo.current)return;Bo.current=!0,at();const w=(Ue.current?.clientHeight??0)/Pe.current;w>0&&Ce.totalSize()>0&&xe.setRowRange(0,Ce.indexAt(Math.min(w-1,Ce.totalSize()-1)));const q=(Ue.current?.clientWidth??0)/Pe.current;q>0&&pe.totalSize()>0&&xe.setColRange(0,pe.indexAt(Math.min(q-1,pe.totalSize()-1)))},[ee,at,xe,Ce,pe]);const Tl=i.useRef(t);i.useLayoutEffect(()=>{Tl.current!==t&&(Tl.current=t,kt.cancelDrag(),$t.cancelDrag(),Lt.cancelDrag(),ut.cancelDrag(),Et.cancelDrag(),mt.cancelDrag(),je.cancelEdit(),Jt.current?.hideTip(),Jt.current?.close(),ee?(Ve.current=qn,ht(qn)):Ge(qn),bl.current())},[t,ee,Ge,kt,$t,Lt,ut,Et,mt,xe,je.cancelEdit]);const $l=i.useRef({adapter:oe,rows:Ce.count,cols:pe.count}),{getSessionCell:Ll,cancelEdit:Dl}=je;i.useLayoutEffect(()=>{const w=$l.current,q=Ce.count,Z=pe.count;if($l.current={adapter:oe,rows:q,cols:Z},w.adapter!==oe||q>=w.rows&&Z>=w.cols)return;ee?(Ve.current=qn,ht(qn)):Ge(bw(Ve.current,q,Z)),kt.cancelDrag(),$t.cancelDrag(),Lt.cancelDrag(),ut.cancelDrag(),Et.cancelDrag(),mt.cancelDrag();const te=dt=>ee||dt.row>=q||dt.col>=Z,he=Ll();he!==null&&te(he)&&Dl();const ve=To.current;if(ve.tip!==null&&te(ve.tip)&&Jt.current?.hideTip(),ve.interactive!==null&&te(ve.interactive)){const dt=Ue.current?.contains(document.activeElement)===!0;Jt.current?.close({restoreFocus:dt})}const Ze=qr();Ze!==null&&!Ze.foreign&&te({row:Ze.range.endRow,col:Ze.range.endCol})&&Tt()},[oe,Ce.count,pe.count,ee,Ge,kt,$t,Lt,ut,Et,mt,Ll,Dl,qr,Tt]);const Ml=i.useRef(c),zl=i.useRef(u),Fl=i.useRef(h),Nl=i.useRef(m);i.useLayoutEffect(()=>{(Ml.current!==c||zl.current!==u||Fl.current!==h||Nl.current!==m)&&(Ml.current=c,zl.current=u,Fl.current=h,Nl.current=m,kt.cancelDrag(),$t.cancelDrag(),Lt.cancelDrag(),ut.cancelDrag(),Et.cancelDrag(),mt.cancelDrag())},[c,u,h,m,kt,$t,Lt,ut,Et,mt]),i.useLayoutEffect(()=>{Rt(),vt(),$e()},[c,u,h,m,Rt,vt,$e]);const Pl=i.useRef(p);i.useLayoutEffect(()=>{Pl.current!==p&&(Pl.current=p,Tt())},[p,Tt]),i.useLayoutEffect(()=>{$e()},[$e,Ee]);const wn=i.useCallback(()=>{const w=il.current;if(w===null)throw new RangeError("[spreadsheet] the command runner is not mounted");return w},[]);if(i.useImperativeHandle(zr,()=>({resizeRow:(w,q)=>{const Z=Math.round(q);Ce.resize(w,Z),de.current?.updateRowSize(w,Z),xe.bumpRowGeometry(),Rt(),$e(),Dn(),qt()},resizeColumn:(w,q)=>{const Z=Math.round(q);pe.resize(w,Z),de.current?.updateColSize(w,Z),xe.bumpColVersion(),vt(),$e(),Dn(),qt()},autoFitColumns:w=>{for(const q of w)if(!Number.isInteger(q)||q<0||q>=pe.count)throw new RangeError(`[spreadsheet] autoFitColumns: each column must be a whole number from 0 to ${pe.count-1} (got ${String(q)})`);return ut.autofitColumnsInAllRows(w)},scrollToCell:(w,q)=>{de.current?.scrollToCell(w.row,w.col,q)},focus:w=>{_t(w),nt()||at()},executeCommand:w=>$o.current(w),applyFormat:w=>wn().applyFormat(w),setBorders:(w,q)=>wn().setBorders(w,q),setHyperlink:w=>wn().setHyperlink(w),setNote:w=>wn().setNote(w),addComment:w=>wn().addComment(w),setValidation:w=>wn().setValidation(w),paste:w=>Lo.current(w),getSelection:()=>Ve.current,getBaseFormat:w=>oe.getCellFormat===void 0?void 0:oe.getCellFormat(w.row,w.col),getPaintedFormat:w=>oe.getCellFormat===void 0?void 0:Gt(w.row,w.col,ao(oe,w.row,w.col)),startEdit:w=>{cr(w)},openPopover:w=>{Pr.current(w)}}),[Ce,pe,xe,vt,Rt,$e,Dn,qt,ut,_t,nt,at,oe,Gt,cr,wn]),ee)return Y.jsx("div",{className:fn?`aqsp-root ${fn}`:"aqsp-root","data-aqsp-empty":"","data-testid":Qe});const Iu=f!==void 0||E!==void 0||d!==void 0||g!==void 0||L!==void 0,Hu=o===void 0?{"aria-label":yt.rootAriaLabel}:{"aria-labelledby":o};return Y.jsxs("div",{ref:Ue,className:fn?`aqsp-root ${fn}`:"aqsp-root",role:"group",...Hu,tabIndex:0,onFocus:_u,onBlur:qu,"data-aqsp-root":"","data-aqsp-headings-hidden":b?void 0:"","data-aqsp-framed":a===void 0?void 0:"","data-testid":Qe,children:[Y.jsxs("div",{className:"aqsp-zoom","data-aqsp-zoom":pt,onPointerDown:ju,style:pt===1?void 0:{width:`${100/pt}%`,height:`${100/pt}%`,transform:`scale(${pt})`,"--_aqsp-zoom":String(pt)},children:[b?Y.jsxs(Y.Fragment,{children:[Y.jsx("div",{ref:Te,className:"aqsp-corner","aria-hidden":"true","data-aqsp-corner":"",onPointerDown:w=>{if(w.pointerType==="mouse"&&(w.preventDefault(),w.button===0)){if(hn()){Ye();return}if(nt()&&!St()){Ye();return}Ye(),Ge({ranges:[ke({row:0,col:0},{row:oe.rowCount-1,col:oe.colCount-1})],anchor:{row:0,col:0},active:{row:0,col:0}})}}}),Y.jsx(pw,{viewStore:xe,colAxis:pe,frozenCols:c,frozenTrailingCols:h,handleRef:de,bandRef:me,colTrackRef:ye,windowOriginXRef:Re,repaintColHeaders:vt,selectionRanges:Ee.ranges,enableResizeUI:k,dividerLeadingRef:ae,dividerTrailingRef:Oe}),Y.jsx(hw,{viewStore:xe,rowAxis:Ce,handleRef:de,bandRef:et,selectionRanges:Ee.ranges,rowTrackRef:fe,windowOriginYRef:se,repaintHeaders:Rt,enableResizeUI:k,frozenRows:u,frozenTrailingRows:m,dividerLeadingRef:Be,dividerTrailingRef:Xe})]}):null,Y.jsxs("div",{ref:be,className:"aqsp-body-stack","data-aqsp-body-stack":"",children:[Y.jsx(fw,{adapter:oe,rowAxis:Ce,colAxis:pe,viewStore:xe,handleRef:de,bodyRef:ue,dataVersion:p,defaultColumnWidth:l,frozenColumns:c,frozenRows:u,frozenTrailingColumns:h,frozenTrailingRows:m,headerRows:n,labelledBy:o,gridLabel:o===void 0?yt.rootAriaLabel:void 0,readOnly:r,tapScrollCircleOptions:y,overscanRows:ac("overscanRows",N),overscanCols:ac("overscanCols",W),background:D,onRenderTruncated:j,renderCell:U,onScroll:bu,onRangeChange:yu,focusSink:Ye,isEditing:nt,requestCommit:St,testId:Qe?`${Qe}-vs`:void 0,__onCellRender:Qn,__maxRenderedCells:En,cfIndexRef:rr,cfMemoRef:or,isPointing:hn,locale:Kt,scrollLabels:Fr}),Y.jsx(Hm,{rowAxis:Ce,colAxis:pe,handleRef:de,sinkRef:Le,getSelection:We,editing:je.editing,virtualKeyboard:gu,repaintRef:Zs,dragFrameRef:Oo,getClip:qr,getIsDraggingAny:ar,getIsFillDragging:Et.isDragging,fillFrameRef:vl,resizeGuideFrameRef:Sl,fillHandleNodeRef:kl,enableFillHandle:v,frozenCols:c,frozenRows:u,trailingCols:h,trailingRows:m,sinkAriaLabel:yt.sinkAriaLabel,sinkReadOnly:r,sinkKeyShortcuts:Nr,onSinkMouseDown:Pu,editPaintRef:tl,highlightRef:sr,frameRange:a,highlightColors:du,popoverAnchors:To,interactiveAnchorRef:rl,tipAnchorRef:ol}),dr.layerEnabled?Y.jsx(jw,{controller:dr,labels:yt,renderPopover:Ae,interactiveAnchorRef:rl,tipAnchorRef:ol}):null]}),Iu?Y.jsx("div",{ref:ct,className:"aqsp-live-region","aria-live":"polite","data-aqsp-live-region":""}):null]}),Y.jsx("div",{ref:_e,className:"aqsp-reveal","aria-hidden":"true","data-aqsp-reveal":""})]})});exports.iterateTsvPrefixRows=Wt.iterateTsvPrefixRows;exports.iterateTsvRows=Wt.iterateTsvRows;exports.measureTsv=Wt.measureTsv;exports.parseTsv=Wt.parseTsv;exports.serializeClipboardTsv=Wt.serializeClipboardTsv;exports.serializeTsv=Wt.serializeTsv;exports.columnIndexToName=De.columnIndexToName;exports.columnNameToIndex=De.columnNameToIndex;exports.BORDER_DEFAULT_COLOR=$s;exports.CommentPopover=_a;exports.DEFAULT_CUSTOM_COLORS=uu;exports.DEFAULT_HIGHLIGHT_COLORS=Pa;exports.DEFAULT_SHORTCUTS=Sa;exports.LinkPopover=qa;exports.ListPopover=ja;exports.MessagePopover=Ia;exports.NotePopover=Ha;exports.NoteTip=Ba;exports.SPREADSHEET_LABEL_CATALOGS=ka;exports.SPREADSHEET_RESERVED_SHORTCUTS=Ih;exports.Spreadsheet=i0;exports.canonicalizeFormat=xt;exports.detectClipSource=vc;exports.enumerateRangeCells=nn;exports.estimatePasteCellCount=xh;exports.expandPaste=Th;exports.formatCellValue=Xn;exports.formatEquals=td;exports.fromR1C1=$r;exports.makeRange=ke;exports.mergeFormat=Ds;exports.normalizeHyperlink=un;exports.parseChord=rn;exports.parseClipPayload=fs;exports.parseHtmlTable=pa;exports.rangeContains=kn;exports.rangeSize=Ct;exports.resolveLabel=qe;exports.resolveLabels=Ea;exports.serializeClipPayload=bc;exports.serializeHtmlTable=aa;exports.shiftFormula=Yc;exports.toR1C1=Ro;exports.validateCellText=xa;