@betteroffice/xlsx-react 0.2.1 → 0.5.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/README.md +117 -97
- package/dist/chunk-2S2QUCJE.js +1 -0
- package/dist/chunk-OADYDRKQ.js +3 -0
- package/dist/index.d.ts +1165 -51
- package/dist/index.js +1 -1
- package/package.json +9 -6
package/README.md
CHANGED
|
@@ -1,118 +1,138 @@
|
|
|
1
1
|
# @betteroffice/xlsx-react
|
|
2
2
|
|
|
3
|
-
React
|
|
4
|
-
|
|
5
|
-
drop-in `<XlsxEditor>` component with the toolbar, selection, keyboard, and
|
|
6
|
-
clipboard wired up. Formula calculation and rendering run in the core's
|
|
7
|
-
Rust/WebAssembly engine; the grid is painted onto canvas.
|
|
3
|
+
React XLSX editor with a canvas grid, toolbar, selection, keyboard input, and clipboard support.
|
|
4
|
+
The engine runs in a Web Worker by default, with promise-returning host operations and exports.
|
|
8
5
|
|
|
9
|
-
|
|
6
|
+
## Install
|
|
10
7
|
|
|
11
8
|
```bash
|
|
12
|
-
bun add @betteroffice/xlsx-react
|
|
9
|
+
bun add @betteroffice/xlsx-react react react-dom
|
|
13
10
|
```
|
|
14
11
|
|
|
15
|
-
`react` and `react-dom`
|
|
12
|
+
`react` and `react-dom` 18 or 19 are peer dependencies; the XLSX core is included as a dependency.
|
|
16
13
|
|
|
17
|
-
##
|
|
14
|
+
## Usage
|
|
18
15
|
|
|
19
16
|
```tsx
|
|
20
|
-
import { XlsxEditor } from
|
|
21
|
-
|
|
22
|
-
<XlsxEditor file={bytes} fileName="report.xlsx" />;
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
`file` is a `Uint8Array` of `.xlsx` bytes; omit it to render an empty frame.
|
|
26
|
-
|
|
27
|
-
## Open and save
|
|
28
|
-
|
|
29
|
-
```tsx
|
|
30
|
-
import { useState } from "react";
|
|
31
|
-
import { XlsxEditor } from "@betteroffice/xlsx-react";
|
|
32
|
-
|
|
33
|
-
export function App() {
|
|
34
|
-
const [file, setFile] = useState<Uint8Array>();
|
|
17
|
+
import { XlsxEditor } from '@betteroffice/xlsx-react';
|
|
35
18
|
|
|
19
|
+
export function Spreadsheet({ bytes }: { bytes: Uint8Array }) {
|
|
36
20
|
return (
|
|
37
|
-
|
|
38
|
-
<
|
|
39
|
-
|
|
40
|
-
accept=".xlsx"
|
|
41
|
-
onChange={async (e) => {
|
|
42
|
-
const f = e.target.files?.[0];
|
|
43
|
-
if (f) setFile(new Uint8Array(await f.arrayBuffer()));
|
|
44
|
-
}}
|
|
45
|
-
/>
|
|
46
|
-
<XlsxEditor
|
|
47
|
-
file={file}
|
|
48
|
-
fileName="workbook.xlsx"
|
|
49
|
-
onSave={(bytes) => console.log(`saved ${bytes.length} bytes`)}
|
|
50
|
-
/>
|
|
51
|
-
</>
|
|
21
|
+
<div style={{ height: 600 }}>
|
|
22
|
+
<XlsxEditor file={bytes} fileName="report.xlsx" />
|
|
23
|
+
</div>
|
|
52
24
|
);
|
|
53
25
|
}
|
|
54
26
|
```
|
|
55
27
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
`
|
|
76
|
-
`
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
28
|
+
`file` contains XLSX bytes. Give the editor's container a height; omitting `file` shows an empty
|
|
29
|
+
editor that asks for an XLSX file. See [hosting](https://docs.betteroffice.dev/docs/migrating-to-0-5#hosting) for worker, chunk and CSP needs.
|
|
30
|
+
|
|
31
|
+
## Key options
|
|
32
|
+
|
|
33
|
+
The default props are described by `XlsxAsyncEditorProps`:
|
|
34
|
+
|
|
35
|
+
| prop | type | description |
|
|
36
|
+
| --- | --- | --- |
|
|
37
|
+
| `file` | `Uint8Array \| ArrayBuffer` | XLSX bytes to open. |
|
|
38
|
+
| `fileName` | `string` | Download name; defaults to `workbook.xlsx`. |
|
|
39
|
+
| `onReady` | `(api: XlsxAsyncEditorApi) => void \| (() => void)` | Receive the editor API; optionally return cleanup. |
|
|
40
|
+
| `onSave` | `(bytes: Uint8Array) => void` | Receive saved workbook bytes. |
|
|
41
|
+
| `onSaveRequest` | `() => boolean \| void \| Promise<boolean \| void>` | Intercept saves; return `true` to continue. |
|
|
42
|
+
| `downloadOnSave` | `boolean` | Save also downloads; defaults to `!onSave`. |
|
|
43
|
+
| `onDocumentChange` | `(change: XlsxDocumentChange) => void` | Receives `{ version }` after a committed edit. |
|
|
44
|
+
| `initialZoom` | `number` | Initial scale, clamped to 0.1 through 5; defaults to 1. |
|
|
45
|
+
| `loadingIndicator` | `React.ReactNode` | Shown while a supplied file opens. |
|
|
46
|
+
| `style` | `React.CSSProperties` | Overrides root inline styles. |
|
|
47
|
+
| `onChange` | `() => void` | Called after a user edit changes the workbook. |
|
|
48
|
+
| `onError` | `(error: Error) => void` | Receive engine errors. |
|
|
49
|
+
| `readOnly` | `boolean` | Block user edits while keeping navigation and selection. |
|
|
50
|
+
| `toolbar` | `React.ReactNode` | Replace the default toolbar; `null` removes it. |
|
|
51
|
+
| `showToolbar` | `boolean` | `false` hides the toolbar region, including custom content. |
|
|
52
|
+
| `collaboration` | `XlsxEditorCollaborationOptions` | Configure the editor-owned replica and presence provider. |
|
|
53
|
+
| `i18n` | `Translations` | Override UI strings using `@betteroffice/xlsx-i18n`. |
|
|
54
|
+
| `plugins` | `readonly XlsxPlugin[]` | Install host plugins. |
|
|
55
|
+
| `pluginGrants` | `Readonly<Record<string, XlsxPluginGrant>>` | Grant capabilities by plugin ID. |
|
|
56
|
+
| `onPluginError` | `(error: XlsxPluginError) => void` | Receive plugin failures. |
|
|
57
|
+
| `className` | `string` | CSS class for the editor root. |
|
|
58
|
+
|
|
59
|
+
All listed props are optional. The default toolbar is hidden when `readOnly`; a supplied `toolbar`
|
|
60
|
+
remains visible unless `showToolbar` is `false`.
|
|
61
|
+
|
|
62
|
+
Deprecated: `legacySyncApi` keeps the synchronous API on the in-thread engine and is removed in 0.6.0; omit it
|
|
63
|
+
for the default asynchronous editor API.
|
|
64
|
+
|
|
65
|
+
## Editor API
|
|
66
|
+
|
|
67
|
+
`onReady` receives `XlsxAsyncEditorApi`. Its exports wait for pending editor input before reading the
|
|
68
|
+
workbook, and its command store is shared with the toolbar and host controls.
|
|
69
|
+
|
|
70
|
+
| member | purpose |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `hydrated` | Whether the worker editor is ready. |
|
|
73
|
+
| `whenHydrated()` | Await editor readiness. |
|
|
74
|
+
| `failure` | Current engine failure, or `null`. |
|
|
75
|
+
| `commands` | Inspect command availability and execute actions asynchronously. |
|
|
76
|
+
| `version()`, `readCells`, `findText` | Read after pending input commits. |
|
|
77
|
+
| `validateEdits`, `applyEdits` | Validate or apply version-checked batches; refuse while read-only. |
|
|
78
|
+
| `save()` | Commit input, return bytes and call `onSave` without downloading or consulting `onSaveRequest`. |
|
|
79
|
+
| `focus()` | Focus the editor. |
|
|
80
|
+
| `renderPng`, `renderRangePng`, `printDisplayList` | Render asynchronously. |
|
|
81
|
+
| `exportStructured`, `exportMarkdown` | Export content asynchronously. |
|
|
82
|
+
| `proposeChanges` | Optional method for staging tracked cell edits on worker editors. |
|
|
83
|
+
| `collaboration` | Asynchronous collaboration replica, or `null`. |
|
|
84
|
+
| `recoverySave()` | Recover bytes after a non-collaborative worker session fails. |
|
|
85
|
+
|
|
86
|
+
Treat the API as belonging to the open document. Return cleanup from `onReady` to release host
|
|
87
|
+
subscriptions when that document is replaced or the editor unmounts.
|
|
88
|
+
|
|
89
|
+
## Saving
|
|
90
|
+
|
|
91
|
+
Use `await api.commands.execute('save', null)` to save from host UI. The command waits for accepted
|
|
92
|
+
input and calls `onSave` when supplied. It also downloads when `downloadOnSave ?? !onSave` is true.
|
|
93
|
+
Use `await api.save()` to receive bytes directly without downloading or consulting `onSaveRequest`.
|
|
94
|
+
|
|
95
|
+
`onSaveRequest` intercepts toolbar saves, the save command, and Ctrl/Cmd+S before serialization.
|
|
96
|
+
Return `true` to continue built-in saving; `false` or `void` handles or cancels the request. Promises
|
|
97
|
+
are awaited, concurrent requests are coalesced, and requests for replaced documents are discarded.
|
|
98
|
+
|
|
99
|
+
Commands return a success or a typed failure. A refused cell draft must be corrected or discarded
|
|
100
|
+
before saving can complete. `recoverySave()` requires a failed non-collaborative worker session and
|
|
101
|
+
returns `{ bytes, recovery: true }`.
|
|
102
|
+
|
|
103
|
+
## Toolbar
|
|
104
|
+
|
|
105
|
+
The toolbar composition API is experimental. Use `toolbar` to supply controls connected to the
|
|
106
|
+
editor's command store. See
|
|
107
|
+
[Compose the XLSX toolbar](https://docs.betteroffice.dev/docs/javascript#compose-the-xlsx-toolbar)
|
|
108
|
+
for built-in parts, custom controls, and command results.
|
|
109
|
+
|
|
110
|
+
## Plugins and edit batches
|
|
111
|
+
|
|
112
|
+
The plugin API is experimental and may change in minor releases. Plugins contribute panels,
|
|
113
|
+
overlays, and commands through restricted clients; their read and edit
|
|
114
|
+
clients support version-checked operations. See
|
|
115
|
+
[Host XLSX editor plugins](https://docs.betteroffice.dev/docs/javascript#host-xlsx-editor-plugins)
|
|
116
|
+
and [Edit XLSX in version-checked batches](https://docs.betteroffice.dev/docs/javascript#edit-xlsx-in-version-checked-batches).
|
|
117
|
+
|
|
118
|
+
## Structured export
|
|
119
|
+
|
|
120
|
+
Await `api.exportStructured()` or `api.exportMarkdown()` for content with positional anchors and
|
|
121
|
+
omission diagnostics. See
|
|
122
|
+
[Export XLSX content with anchors](https://docs.betteroffice.dev/docs/javascript#export-xlsx-content-with-anchors)
|
|
123
|
+
for scopes, hidden content, and export limits.
|
|
95
124
|
|
|
96
125
|
## Collaboration
|
|
97
126
|
|
|
98
|
-
Pass `collaboration`
|
|
99
|
-
|
|
127
|
+
Pass `collaboration` and connect a provider when `collaboration.onReplica` publishes the replica.
|
|
128
|
+
The editor retains its default worker runtime; see the
|
|
129
|
+
[collaboration guide](https://docs.betteroffice.dev/docs/collaboration) for transport setup and cleanup.
|
|
100
130
|
|
|
101
|
-
|
|
102
|
-
import { CollaborationProvider } from "@betteroffice/xlsx/collaboration";
|
|
103
|
-
|
|
104
|
-
<XlsxEditor
|
|
105
|
-
file={file}
|
|
106
|
-
collaboration={{ clientId }}
|
|
107
|
-
onReady={({ handle }) => {
|
|
108
|
-
const provider = new CollaborationProvider(handle, transport, {
|
|
109
|
-
user: { name: "Ada" }, // shown on this peer's selection flag
|
|
110
|
-
});
|
|
111
|
-
provider.connect();
|
|
112
|
-
return () => provider.destroy();
|
|
113
|
-
}}
|
|
114
|
-
/>;
|
|
115
|
-
```
|
|
131
|
+
## Documentation
|
|
116
132
|
|
|
117
|
-
[JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
|
|
118
|
-
[
|
|
133
|
+
- [JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
|
|
134
|
+
- [Collaboration guide](https://docs.betteroffice.dev/docs/collaboration)
|
|
135
|
+
- [Package guide](https://docs.betteroffice.dev/docs/packages)
|
|
136
|
+
- [XLSX core on npm](https://www.npmjs.com/package/@betteroffice/xlsx)
|
|
137
|
+
- [Localization package on npm](https://www.npmjs.com/package/@betteroffice/xlsx-i18n)
|
|
138
|
+
- [Repository](https://github.com/openooxml/betteroffice)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {Z,Y,q,ua,H,ma,ga,ta,A,x,u,n,z,w,m,i,Na,Fa,Q,P,I,S,T,xa,Ba,ya,r,h,qa,pa,sa,l,Ga,a,Ra,Qa,Sa,Va,p,Ea,Ha,va,wa,N,O,g,f,oa,F,B,D,y,Wa,Ka,La,Ia,E,d,t,s,o,v,Ja}from'./chunk-OADYDRKQ.js';import {normalizeRange,rangeRect,cellRect,buildA11yGrid,isProposalsAvailable,selectionAt,paintDisplayList,hyperlinkAtCell,chartRegionAtPoint,cellAtPoint,extendTo,safeExternalHyperlink,parseHyperlinkLocation,selectionKeyReducer,workbookSessionRecovery,WorkbookRecoveryReplayError,toTsv}from'@betteroffice/xlsx';import {memo,useSyncExternalStore,useState,useEffect,useLayoutEffect,useMemo,useCallback,useRef}from'react';import {flushSync}from'react-dom';import {jsxs,jsx,Fragment}from'react/jsx-runtime';function Ge(){let t,e,r=null,o=new Set,i=new Promise((l,h)=>{t=l,e=h;});return i.catch(()=>{}),{promise:i,resolve:t,reject(l){r={error:l},e(l);for(let h of o)h(l);o.clear();},wait(l){return r?(Promise.resolve(l).catch(()=>{}),Promise.reject(r.error)):new Promise((h,f)=>{let a=d=>{o.delete(a),f(d);};o.add(a),Promise.resolve(l).then(d=>{o.delete(a),h(d);},a);})}}}function et(t,e){return t.generation===e.generation&&t.source===e.source&&t.sheet===e.sheet&&t.row===e.row&&t.col===e.col}function Zn(t,e){return et(t,e)&&t.value===e.value&&(!("revision"in t&&"revision"in e)||t.revision===e.revision)}function ri(t){return typeof t?.then=="function"}function Yn(t){return "target"in t.payload?structuredClone(t.payload.target??null):"toolbar"in t.payload?structuredClone(t.payload.toolbar.target??null):"selection"in t.payload?structuredClone(t.payload.selection??null):null}function Qn(t,e){return e&&t.kind!=="setReadOnly"&&t.kind!=="applyUpdate"&&t.kind!=="collabPipe"?{...t,payload:{...t.payload,selection:e}}:t}function eo(t){let e=(c,x)=>Number.isSafeInteger(c)&&c>0?Math.min(c,128):x,r=e(t.maxOutstanding,64),o=e(t.maxQueued,128),i=new Set,l=new Set,h=null,f="",a=t.generation(),d=Ge(),g=[],y=[],I=new Map,C=new Map,p=null,m=[],T=null,k=false,q=false,E=1,X=0,L=0,B,re,D,se=new Map,J=new WeakMap,Be=new WeakMap,de=1,we=t.readOnly?.()??false,Ie=()=>{},ue=()=>{},ke=false,ye=null,j=null,ve=null,Ee,Ce=c=>{let x=false,O=()=>{if(!x){x=true;for(let M of i)try{M(c);}catch{}}};try{t.onEvent?.(c,O);}catch{}O();},We=(c,x)=>{c.ticket.outcome||c.ticket.failure||(c.ticket.failure={error:x},re===c.ticket&&(re=void 0),D===c.ticket&&(D=void 0),c.result.reject(x),Ce({type:"cancelled",seq:c.ticket.seq,target:c.target,draft:c.draft}));},vt=c=>{Ie(),ue(),d.reject(c);for(let x of [...g,...I.values()])"ticket"in x?We(x,c):x.reject(c);g=[],I=new Map,C.clear(),y=[],ye=null,d=Ge(),re=void 0,B=void 0,D=void 0,p=null,m=[],se=new Map,Be=new WeakMap,J=new WeakMap,l.clear();},ge=()=>{if(k)return;let c=t.session(),x=c?`${c.commandIdentity.session}:${c.commandIdentity.incarnation}:${c.confirmedBasis.epoch}`:"";if(c===h&&x===f&&a===t.generation())return;vt(new w("document-replaced")),h=c,f=x,a=t.generation(),q=false,T=null,we=t.readOnly?.()??false,X=h?.throughSeq??0,L=X,E=X+1;let O=d;Ie=h?.onAck(M=>{if(ge(),O!==d||k||T||M.frame&&(M.frame.session!==h?.commandIdentity.session||M.frame.incarnation!==h?.commandIdentity.incarnation))return;let A=M.statuses.filter(ne=>ne.committed&&ne.status==="applied"),Z=A.length?C.get(A[0].seq)?.acknowledge:void 0;for(let ne of M.statuses)Ot(ne);if(M.throughSeq>=X){X=M.throughSeq;let ne=()=>Ce({type:"coverage",throughSeq:X,coversThroughSeq:M.frame?.coversThroughSeq,ack:M});Z&&A.every(oe=>C.get(oe.seq)?.acknowledge===Z)?Z(ne):ne();for(let oe of C.keys())oe<=X&&C.delete(oe);}Me();})??(()=>{}),ue=h?.onFailure?.(M=>{ge(),O===d&&at(M);})??(()=>{}),h?.failure&&at(h.failure);},at=c=>{if(T||k)return;y=(ye&&!("ticket"in ye)?[ye,...g]:g).flatMap(O=>{if("ticket"in O&&(O.ticket.failure||ct(O)))return [];let M="ticket"in O?O.input:O.recoveryInput?.();return M?[structuredClone(M)]:[]}),T={error:c},we=true,d.reject(c);for(let O of [...g,...I.values()])"ticket"in O?We(O,c):O.reject(c);g=[],I.clear(),C.clear(),l.clear();try{t.onError?.(c);}catch{}},ct=c=>{let x=c.after;return typeof x=="object"&&x.failure},Ot=c=>{let x=I.get(c.seq);if(x)if(I.delete(c.seq),x.ticket.outcome=c,c.status==="applied"||c.status==="noop")x.draft&&(m=m.filter(O=>!et(O,x.draft))),x.result.resolve(c),Ce({type:"accepted",seq:c.seq,target:x.target,draft:x.draft,status:c});else {let O=new Oe(c,x.target,x.draft);x.ticket.failure={error:O},re===x.ticket&&(re=void 0),D===x.ticket&&(D=void 0),c.status==="refused"&&x.draft&&(m=[...m.filter(M=>!et(M,x.draft)),x.draft].slice(-o),p||(p=x.draft)),x.result.reject(O),Ce({type:c.status,seq:c.seq,target:x.target,draft:x.draft,status:c});for(let M of g)"ticket"in M&&ct(M)&&We(M,O);}},Ve=()=>{if(ge(),k)throw new w("document-replaced");if(q)throw new w("document-replaced");if(T)throw T.error;if(!t.isReady()||!h?.commandIdentity.session||!h.commandIdentity.incarnation)throw new w("editor-unavailable")},bt=c=>{if(g.length>=o)throw new z("Worker input queue is full");j===null?g.push(c):g.splice(j++,0,c);},Me=()=>{if(ge(),!(ke||ye||T||k||q)){ke=true;try{for(;g.length&&!T&&!k;){let c=g[0];if("ticket"in c){if(c.ticket.failure){g.shift();continue}let x=ct(c);if(x){g.shift(),We(c,x.error);continue}if(c.prepare){let Z=d;ye=c,Z.wait(c.prepare).then(ne=>{if(!(Z!==d||ye!==c)){try{c.input=structuredClone(Qn(ne,c.selection)),c.target=Yn(c.input),c.prepare=void 0;}catch(oe){We(c,oe);}ye=null,Me();}},ne=>{Z!==d||ye!==c||(We(c,ne),ye=null,Me());});break}if(I.size>=r)break;let O=typeof c.after=="object"?c.after:void 0;if(O?.lease&&O.lease!==d){g.shift(),We(c,new w("document-replaced"));continue}let M=O?.outcome?void 0:typeof c.after=="number"?c.after:c.after?.seq??void 0;if(typeof c.after=="number"&&(!Number.isSafeInteger(c.after)||c.after<=0||c.after>=E)){g.shift(),We(c,new z("Invalid command dependency"));continue}if(c.after&&!O?.outcome&&M===void 0)break;g.shift();let A=()=>{let Z=E++;(c.frame||!(c.input?.kind==="applyOps"&&"toolbar"in c.input.payload&&c.input.payload.toolbar.id==="refreshProposals"))&&(L=Z),Object.defineProperty(c.ticket,"seq",{value:Z,configurable:!0});let ne={...structuredClone(c.input),...h.commandIdentity,seq:Z,basis:{...h.confirmedBasis},...M?{afterSeq:M}:{},...c.frame?{frame:c.frame}:{}};I.set(Z,c),c.ticket.acknowledge&&C.set(Z,c.ticket);let oe=d;if(Ce({type:"dispatched",seq:Z,target:c.target,draft:c.draft,command:ne,selectionRevision:c.selectionRevision}),!(oe!==d||T||k))try{h.submit(ne).then(ce=>{ge(),!(oe!==d||T||k)&&(Ot(ce),Me());},ce=>{ge(),oe===d&&at(ce);});}catch(ce){at(ce);}};try{c.dispatch?c.dispatch(A):A();}catch(Z){We(c,Z);}if(T||k)break}else {g.shift(),j=0;try{let x=c.run();if(ri(x)){ye=c;let O=d;O.wait(x).then(()=>{O!==d||ye!==c||(ye=null,Me());},M=>{c.reject(M),!(O!==d||ye!==c)&&(ye=null,Me());});break}}catch(x){c.reject(x);}finally{j=null;}}}}finally{ke=false;}}},wt=(c,x,O={},M=false,A)=>{let Z=Ge(),ne={seq:null,result:Z.promise,lease:d,acknowledge:O.acknowledge},oe=null;try{if(oe=c?Yn(c):null,Ve(),ne.lease=d,(ve??we)&&(A||c&&c.kind!=="select"&&c.kind!=="setActiveSheet"&&c.kind!=="setReadOnly"&&c.kind!=="applyUpdate"&&c.kind!=="collabPipe"&&!(c.kind==="applyOps"&&"toolbar"in c.payload&&c.payload.toolbar.id==="refreshProposals")))throw new w("input-failed");let ce={input:c?structuredClone(Qn(c,O.selection)):null,draft:x?Object.freeze({...x}):null,target:oe,after:O.after===null?void 0:O.after??(Ee!==void 0?(M?Ee.last:Ee.boundary)??void 0:M?D:re),ticket:ne,result:Z,fence:M,prepare:A,dispatch:O.dispatch,frame:structuredClone("frame"in O?O.frame:t.frame?.()),selection:structuredClone(O.selection),selectionRevision:"selectionRevision"in O?O.selectionRevision:t.selectionRevision?.()},ie=g[g.length-1];if(!M&&x&&ie&&"ticket"in ie&&!ie.fence&&!ie.ticket.failure&&!ie.prepare&&ie.draft&&et(ie.draft,x)&&ie.after===ce.after&&JSON.stringify(ie.target)===JSON.stringify(ce.target))return ie.input=ce.input,ie.draft=ce.draft,ie.frame=ce.frame,ie.selectionRevision=ce.selectionRevision,J.set(x,ie.ticket),ie.ticket;bt(ce),D=ne,M&&(re=ne),Me();}catch(ce){ne.failure={error:ce},Z.reject(ce);let ie=x?Object.freeze({...x}):null;ie&&(m=[...m.filter(Te=>!et(Te,ie)),ie].slice(-o),p||(p=ie)),Ce({type:"refused",seq:null,target:oe,draft:ie});}return ne},Pt=(c,x={})=>{ge();let O=x.compositionId?se.get(x.compositionId):J.get(c);if(O&&(x.compositionId||!O.failure))return O;let M;if("modified"in c&&c.modified===false||x.compositionId&&c.value===""){let A={seq:0,status:"noop",committed:false};M={seq:null,result:Promise.resolve(A),outcome:A,lease:d};}else if(c.generation!==a){let A=Ge(),Z=new w("document-replaced");A.reject(Z),M={seq:null,result:A.promise,failure:{error:Z}};}else try{let A=x.target??t.draftTarget?.(c)??t.target(c.sheet,c.row,c.col);M=wt({kind:"editCell",payload:{args:[c.sheet,c.row,c.col,c.value],target:A}},c,{...x,after:x.after===void 0?t.dependency?.(c)??null:x.after},!!(x.compositionId||x.selection));}catch(A){let Z=Ge();Z.reject(A),M={seq:null,result:Z.promise,failure:{error:A}};let ne=Object.freeze({...c});m=[...m.filter(oe=>!et(oe,ne)),ne].slice(-o),p||(p=ne),Ce({type:"refused",seq:null,target:null,draft:ne});}return J.set(c,M),!M.failure&&p&&et(p,c)&&p.value===c.value&&(p=null),x.compositionId&&(se.set(x.compositionId,M),se.size>o&&se.delete(se.keys().next().value)),M},ae=(c,x=false,O)=>{let M=Ge();try{if(Ve(),l.size>=o)throw new z("Worker input queue is full");l.add(M),M.promise.then(()=>l.delete(M),()=>l.delete(M));let A=d,Z=we,ne={last:D??null,boundary:re??null},oe=O?{pendingInput:O}:t.seal();if(oe.refused)throw new w(oe.refused);let ce=B,ie=oe.pendingInput?.ready??oe.composition,Te=oe.pendingInput?.draft??oe.compositionDraft,fe=oe.pendingInput?.ticket,pe=!fe&&ie!==ce?.composition?ie:void 0;ie||t.sync();let _e=ce?.compositionDraft?.()??ce?.pendingTarget,Xt=_e&&p&&!Zn(_e,p),Se=!pe&&ce?.composition&&!Xt?ce:fe?{ticket:ce?.ticket??fe}:{},rt=pe?Ge():void 0,Kt=ee=>{Se.ticket=ee;let me=()=>{B===Se&&(B=void 0);};ee?ee.result.then(me,me):me();},Je=pe&&!oe.pendingInput&&p?{...p}:null,Ht=ee=>Je?{...ee,generation:Je.generation,sheet:Je.sheet,row:Je.row,col:Je.col,source:Je.source}:ee,b=pe&&!oe.pendingInput?t.compositionId?.()??Be.get(pe)??`local-composition:${de++}`:void 0;pe&&b&&Be.set(pe,b);let qe,Ut=!1;if(rt){let ee={seq:null,result:rt.promise,lease:d};Object.defineProperty(ee,"seq",{get:()=>qe?.seq??null}),rt.promise.then(me=>{ee.outcome=me,Me();},me=>{ee.failure={error:me},re===ee&&(re=void 0),D===ee&&(D=void 0),Me();}),M.promise.catch(rt.reject),Se.composition=pe,Se.compositionDraft=Te,Se.pendingTarget=oe.pendingInput?.target,B=Se,Kt(ee),oe.pendingInput&&(oe.pendingInput.ticket=ee,D=re=ee);}else Se.composition||(ie&&!fe&&t.sync(),p&&(!fe||!Zn(p,oe.pendingInput.target))&&(B=Se,qe=Pt(p,{after:ce?.ticket??fe}),Kt(qe)));let G=[...I.values(),...g.slice(0,j??g.length).filter(ee=>"ticket"in ee)].map(ee=>ee.ticket.result);Se.ticket&&G.push(Se.ticket.result);let ut=()=>{if(A!==d)throw new w("document-replaced");Ve();let ee=ve,me=Ee;ve=Z;let Ne=qe??Se.ticket??ce?.ticket;Ee=Ne?{last:Ne,boundary:Ne}:ne;try{let Ae=c();return A.wait(Ae).then(Re=>{oe.restoreFocus?.(),M.resolve(Re);},M.reject),x===!0||x==="settled"||x==="read"?Promise.resolve(Ae).then(()=>{}):void 0}finally{ve=ee,Ee=me;}},Ze=async()=>{let ee=[...G,...[...I.values()].map(Re=>Re.ticket.result)];if(x==="settled"||x==="read")await A.wait(Promise.allSettled(ee));else if(await A.wait(Promise.all(ee)),m.length)throw new w("input-failed");let me=ke,Ne=j;ke=!0,j=0;let Ae;try{Ae=ut();}finally{j=Ne,ke=me;}await Ae;};bt({preservesMerges:x==="read"||!!O,reject:M.reject,recoveryInput:()=>{if(!pe||Ut||Z||Se.ticket?.failure||ce?.ticket?.failure)return null;let ee=Te?.();if(!ee||ee.generation!==a||ee.value===""&&!oe.pendingInput||"modified"in ee&&ee.modified===!1)return null;let me=Ht(ee),Ne=t.draftTarget?.(me)??t.target(me.sheet,me.row,me.col);return {kind:"editCell",payload:{args:[me.sheet,me.row,me.col,me.value],target:Ne}}},run:()=>pe||x?(async()=>{if(pe){let ee=await A.wait(pe);if(A!==d)throw new w("document-replaced");ke=!0,j=0;try{if(ee){let me=Te?.();Te||(t.sync(),me=p);let Ne=ve;ve=Z;try{me&&(Ut=!0,qe=Pt(Ht(me),{...oe.pendingInput?.options,compositionId:b,after:ce?.ticket}));}finally{ve=Ne;}}qe??(qe=ce?.ticket),rt.resolve(qe?.result??{seq:0,status:"noop",committed:!1}),Se.composition=void 0,x?bt({preservesMerges:x==="read"||!!O,run:Ze,reject:M.reject}):ut();}finally{j=null,ke=!1,ye=null,Me();}return}await Ze();})():ut()}),Me();}catch(A){M.reject(A);}return M.promise};return ge(),{get draft(){return ge(),p},get committed(){return ge(),[...I.values(),...g.filter(c=>"ticket"in c)].flatMap(c=>c.draft&&!c.ticket.failure?[c.draft]:[])},get rejected(){return ge(),m},get pending(){return ge(),g.length>0||I.size>0||ye!==null},get pendingSelectionGeometryStable(){return ge(),[...g,...I.values(),...ye?[ye]:[]].every(c=>"ticket"in c?c.input!==null&&(["select","setActiveSheet","editCell","editCells"].includes(c.input.kind)||c.input.kind==="applyOps"&&"toolbar"in c.input.payload&&["refreshProposals","paintFormat"].includes(c.input.payload.toolbar.id)):c.preservesMerges===true)},get error(){return ge(),T?.error??null},get readOnly(){return ge(),we||T!==null||k||q},get throughSeq(){return ge(),X},get submittedThroughSeq(){return ge(),E-1},get recoveryCommands(){return structuredClone(y)},setDraft(c){ge(),!B?.pendingTarget&&(!c||!p&&!B?.composition)&&(B=void 0),p=c?Object.freeze({...c}):null;},discardRejected(c){ge(),m=m.filter(x=>!et(x,c)),p&&et(p,c)&&(p=null);},submit(c,x){return ge(),Pt(c,{...x,after:B?.pendingTarget?B.ticket??x?.after:x?.after})},reserveInput(c){if(ge(),c.ticket)return c.ticket;let x=ae(()=>{},false,c);return x.catch(()=>{}),B?.composition===c.ready&&B.ticket?B.ticket:{seq:null,result:x.then(()=>({seq:0,status:"noop",committed:false}))}},command:(c,x)=>wt(c,null,x,c.kind==="setReadOnly"),clipboard(c,x,O){try{if(Ve(),g.length>=o)throw new z("Worker input queue is full");let M={...O,target:structuredClone(O?.target),selection:structuredClone(O?.selection),frame:structuredClone(O?.frame??t.frame?.()),selectionRevision:O?.selectionRevision??t.selectionRevision?.()},A=d,Z=c(),ne=M.target,oe=A.wait(Z).then(fe=>{if(Ve(),A!==d)throw new w("document-replaced");let pe=x(fe);return ne?{...pe,payload:{...pe.payload,target:ne}}:pe});oe.catch(()=>{});let ce=Ge(),ie={seq:null,result:ce.promise,lease:d};return ae(()=>{let fe=wt(null,null,M,!0,oe);return Object.defineProperty(ie,"seq",{get:()=>fe.seq}),fe.result}).then(fe=>{ie.outcome=fe,ce.resolve(fe);},fe=>{ie.failure={error:fe},ce.reject(fe);}),ie}catch(M){let A=Ge();return A.reject(M),{seq:null,result:A.promise}}},setReadOnly(c){ge();let x=Ge(),O={seq:null,result:x.promise,lease:d};return ae(()=>{let A=wt({kind:"setReadOnly",payload:{readOnly:c}},null,{after:null},!0);return Object.defineProperty(O,"seq",{get:()=>A.seq}),A.result}).then(A=>{O.outcome=A,x.resolve(A);},A=>{!c&&O.lease===d&&(we=true),O.failure={error:A},x.reject(A);}),we=c,O},runAfterPendingInput:ae,flush:()=>ae(()=>{},true),whenApplied(c=E-1){try{if(Ve(),!Number.isSafeInteger(c)||c<0||c>=E)throw new z("Invalid command sequence");let x=d;return x.wait(Promise.all([...I.entries()].filter(([O])=>O<=c).map(([,O])=>O.ticket.result.catch(M=>{if(!(M instanceof Oe))throw M})))).then(()=>{if(x!==d)throw new w("document-replaced");Ve();})}catch(x){return Promise.reject(x)}},save:()=>ae(()=>h.save(),true),whenPresented:c=>ae(()=>h.whenPresented(c??L),true),subscribe(c){return i.add(c),()=>{i.delete(c);}},fail:at,reset(){ge(),vt(new w("document-replaced")),q=true;},retire(){k=true,vt(new w("document-replaced")),i.clear();}}}var Oe=class extends z{constructor(r,o,i){super(r.reason??"Worker command refused");a(this,"status",r);a(this,"target",o);a(this,"draft",i);this.name="XlsxWorkerCommandRefusal";}};var ni=new Set(["zoom","searchMenus","proposalsPanel"]);function oi(t){if(t.range.kind==="rowCol")return {top:t.range.start.row,left:t.range.start.col,bottom:t.range.end.row,right:t.range.end.col};let e=/^\$?([A-Za-z]+)\$?([1-9]\d*)(?::\$?([A-Za-z]+)\$?([1-9]\d*))?$/.exec(t.range.a1);if(!e)return null;let r=o=>[...o.toUpperCase()].reduce((i,l)=>i*26+l.charCodeAt(0)-64,0)-1;return {top:Number(e[2])-1,left:r(e[1]),bottom:Number(e[4]??e[2])-1,right:r(e[3]??e[1])}}function oo(t){let e=(r,o)=>{let i="";for(let l=o+1;l>0;l=Math.floor((l-1)/26))i=String.fromCharCode(65+(l-1)%26)+i;return `${i}${r+1}`};return `${e(t.top,t.left)}:${e(t.bottom,t.right)}`}function ii(t$1){let e=new Set,r$1=null,o$1=null,i="",l="",h=0,f=()=>{},a=()=>{},d=null,g=()=>{let k=t$1(),q=k.session();if(k.selection)return structuredClone(k.selection()??void 0);if(q?.selection)return structuredClone(q.selection);let E=k.view(),X=q?.editState.sheets?.find(B=>B.index===E.sheet)?.id;if(!X||!E.selection)return;let L=normalizeRange(E.selection);return {sheetId:X,activeCell:{...E.selection.anchor},range:{kind:"rowCol",start:{row:L.top,col:L.left},end:{row:L.bottom,col:L.right}}}},y=()=>{let k=t$1().session();return `${t$1().generation()}:${k?.commandIdentity.session}:${k?.commandIdentity.incarnation}:${k?.confirmedBasis.epoch}`},I=()=>{let k=t$1().session(),q=k?.editState;return JSON.stringify({formatting:q?.formatting,formattingAvailable:q?.formattingAvailable,selectionEditable:q?.selectionEditable,mergedRanges:q?.mergedRanges,canUndo:q?.canUndo,canRedo:q?.canRedo,readOnly:q?.readOnly,activeSheet:q?.activeSheet,sheets:q?.sheets,selection:k?.selection})},C=()=>{let k=t$1().session(),q=t$1().coordinator,E=y();if(k===r$1&&q===o$1&&i===E)return;f(),a(),r$1=k,o$1=q,i=E,h=0,l=I();let X=q.pending;a=q.subscribe(()=>{if(t$1().coordinator!==q||t$1().session()!==k||i!==E||y()!==E)return;let L=q.pending;if(L!==X){X=L;for(let B of e)B();}}),f=k?.onAck(L=>{if(t$1().session()!==k||i!==E||y()!==E||!L.selection&&(!L.editState||Object.keys(L.editState).every(re=>re==="calculation")))return;let B=I();if(B!==l){l=B;for(let re of e)re();}})??(()=>{});},p=k=>{if(C(),k&&d)return d.env;let q=t$1(),E=q.view(),X=q.session(),L=X?.editState??{},B=q.selection?q.selection():X?.selection,re=B?oi(B):q.selection?null:E.selection?normalizeRange(E.selection):null,D=B?L.sheets?.find(se=>se.id===B.sheetId)?.index??E.sheet:E.sheet;return {status:q.status(),readOnly:q.readOnly()||q.coordinator.readOnly||L.readOnly===true,collaborative:q.collaborative(),selection:E.chartSelected?"chart":re?{sheet:D,...re,merged:L.mergedRanges??[],formatting:L.formattingAvailable===false?null:L.formatting??null}:null,canUndo:q.coordinator.pending||(L.canUndo??false),canRedo:q.coordinator.pending||(L.canRedo??false),pendingInput:q.coordinator.draft!==null||q.coordinator.committed.length>0,zoom:E.zoom,paintFormat:q.formatToken()!==null,borderStyle:E.borderStyle??L.formatting?.borderStyle??null,borderColor:E.borderColor??L.formatting?.borderColor??null,pngExport:X?.pngExport===true,proposals:E.proposalsAvailable?E.proposals.map(se=>({id:se.id,label:se.agentId})):null,proposalsPanelOpen:E.proposalsPanelOpen,fontFamilies:s,fontSizes:t,translate:q.translate,hostDisabled:L.selectionEditable===false?new Set(Object.keys(o).filter(v)):void 0}},m=(k,q=p(false))=>{if(!v(k))return "document";let E=q.selection;return E==="chart"?"chart":E?`${E.sheet}:${E.top}:${E.left}:${E.bottom}:${E.right}`:"none"};return {requestSave:k=>t$1().requestSave?.(k)??k(),environment:p,ordered:k=>!ni.has(k),perform:async(k,q,E)=>{let X=t$1(),L=X.generation(),B=X.session(),re=d,D=re?re.selection:g(),se=(j=true)=>({ok:true,status:j?"executed":"noop"}),J=j=>({ok:false,failure:r(j,E)});if(k==="zoom"){let j=q.scale;return j===E.zoom?se(false):(X.setZoom(j),se())}if(k==="proposalsPanel"){let j=q===null?!E.proposalsPanelOpen:q.open;return j===E.proposalsPanelOpen?se(false):(X.setProposalsPanelOpen(j),se())}if(!B)return J("editor-unavailable");if(k==="paintFormat"){let j=X.formatToken()!==null;if(X.setFormatToken(null),j)return se()}let Be=X.formatRevision(),de=typeof E.selection=="object"?E.selection:null,we=de?B.editState.sheets?.find(j=>j.index===de.sheet)?.id:void 0,Ie=de&&we?{sheetId:we,range:{kind:"rowCol",start:{row:de.top,col:de.left},end:{row:de.bottom,col:de.right}}}:void 0,ue=q,ke=j=>{if(!de||!Ie)throw new w("editor-unavailable");return {kind:"patchRangeStyle",payload:{args:[de.sheet,oo(de),j],target:Ie,selection:D}}},ye=async j=>{try{return await j()}catch(ve){throw t$1().generation()===L&&t$1().session()===B&&!(ve instanceof Oe)&&!(ve instanceof w)&&!X.coordinator.error&&X.coordinator.fail(ve),ve}};try{if(k==="save"){let Ce=await ye(()=>X.coordinator.save());return t$1().generation()!==L||t$1().session()!==B?J("document-replaced"):(X.deliver(Ce),se())}if(k==="print")return await ye(()=>X.coordinator.whenPresented()),t$1().generation()!==L||t$1().session()!==B?J("document-replaced"):(window.print(),se());if(k==="exportPng"){let Ce=re?re.frame:X.frame();if(!B.pngExport||!B.call)return J("png-unavailable");if(!Ce||!X.deliverPng)return J("editor-unavailable");let We=await B.call.renderPng(Ce.viewport,{sheet:Ce.sheet});return t$1().generation()!==L||t$1().session()!==B?J("document-replaced"):(X.deliverPng(We),se())}let j;switch(k){case "bold":case "italic":case "strikethrough":case "fontSizeStep":case "merge":case "paintFormat":if(!Ie)return J("cell-selection-required");j={kind:"applyOps",payload:{toolbar:{id:k,args:q,target:Ie},selection:D}};break;case "fontFamily":j=ke({fontFamily:ue.family});break;case "fontSize":j=ke({fontSize:ue.points});break;case "textColor":j=ke({textColor:ue.color});break;case "fillColor":j=ke({fillColor:ue.color});break;case "horizontalAlignment":j=ke({horizontalAlignment:ue.value});break;case "verticalAlignment":j=ke({verticalAlignment:ue.value});break;case "textWrapping":j=ke({textWrapping:ue.value});break;case "borderPreset":j=ke({border:{preset:ue.value,style:E.borderStyle??"solid",color:E.borderColor??"#000000"}});break;case "borderStyle":X.setBorderStyle(ue.value),j=ke({border:{style:ue.value}});break;case "borderColor":X.setBorderColor(ue.color),j=ke({border:{color:ue.color}});break;case "numberFormat":case "decimalPlaces":if(!de||!Ie)return J("cell-selection-required");k==="numberFormat"&&ue.value==="custom"?j={kind:"applyOps",payload:{toolbar:{id:k,args:q,target:Ie},selection:D}}:j={kind:"setNumberFormat",payload:{args:[de.sheet,oo(de),k==="decimalPlaces"?ue.direction==="increase"?"increaseDecimal":"decreaseDecimal":ue.value],target:Ie,selection:D}};break;case "undo":case "redo":j={kind:k,payload:{args:[]}};break;case "proposalAccept":j={kind:"acceptProposal",payload:{args:[ue.proposalId,{force:ue.force}]}};break;case "proposalReject":j={kind:"rejectProposal",payload:{args:[ue.proposalId]}};break;default:return J("unsupported-command")}let ve=X.coordinator.command(j,{frame:re?.frame,selectionRevision:re?.selectionRevision}),Ee=await ye(()=>ve.result);if(t$1().generation()!==L||t$1().session()!==B)return J("document-replaced");if(k==="paintFormat"&&ve.seq!==null&&ve.seq>=h&&t$1().formatRevision()===Be){let Ce=Ee.result;if(typeof Ce?.formatToken!="string"){let We=new Error("Worker format capture omitted its token");throw X.coordinator.fail(We),We}X.setFormatToken(Ce.formatToken),h=ve.seq;}return (k==="proposalAccept"||k==="proposalReject")&&(X.markStale(ue.proposalId,null),X.refreshProposals()),k==="proposalReject"&&Ee.result===!1?J("proposal-not-found"):se(Ee.status!=="noop")}catch(j){if(t$1().generation()!==L||t$1().session()!==B)return J("document-replaced");if(j instanceof Oe){if(k==="proposalAccept"&&j.status.reason==="stale-proposal"){let ve=j.status.result;return X.markStale(ue.proposalId,ve?.cells??[]),X.refreshProposals(),J("proposal-stale")}return j.status.reason==="read-only"?J("read-only"):k==="proposalReject"&&j.status.reason==="missing-target"?J("proposal-not-found"):J("input-failed")}return j instanceof w?J(j.code):j instanceof Error&&j.name==="WorkbookPngUnavailableError"?J("png-unavailable"):J("command-failed")}},admit(k,q){let E=p(false),X={env:E,selection:g(),frame:structuredClone(t$1().frame()),selectionRevision:t$1().selectionRevision()};return t$1().coordinator.runAfterPendingInput(()=>{let L=d;d=X;try{return k(E.readOnly)}finally{d=L;}},q==="exportPng")},capture(k){return t$1().status()==="empty"?null:{generation:t$1().generation(),target:m(k)}},resume(k,q){return t$1().generation()!==k.generation?"document-replaced":m(q,d?.env)===k.target?null:"target-changed"},refuse:k=>t$1().refuse?.(k),chrome:()=>({i18n:t$1().i18n()}),focusEditor:()=>t$1().focusGrid(),subscribe(k){return e.add(k),C(),()=>{e.delete(k);}},refreshSubscription:C,dispose(){f(),a(),e.clear(),r$1=null,o$1=null,i="";}}}function io(t,e){let r=useRef(e);r.current=e;let o=useRef(null);useLayoutEffect(()=>{let i=ii(()=>r.current);o.current=i,t.attach(i);let l=i.subscribe(()=>t.refresh());return ()=>{l(),i.dispose(),t.detach(i),o.current=null;}},[t]),useLayoutEffect(()=>{o.current?.refreshSubscription(),t.refresh();});}function so(t,e,r){return t.call.cellInputs(e,r).then(o=>o.cells[0]?.[0]?.input??"")}function lo(t,e,r,o,i,l){let h;return t.runAfterPendingInput(async()=>{if(!i())try{let f=e().then(a=>{i()||r(a);});await Promise.race([f.then(()=>o),o]);}catch(f){throw h={error:f},f}},"read").catch(f=>{if(h)throw h.error;l(f);})}function ao(t,e,r,o){if(!("identity"in e))throw new Error("Async plugin clients require document access");let i=()=>{let p=t.refusal();return p?Ka(p):null},l=async(p,m=true)=>{let T=i();if(T)return T;let k=e.identity();if(!k)return Ka("plugin-unavailable");let q=false,E=await La([t.signal,t.lifetimeSignal],e.admit(k,()=>{let X=i();return X?{refused:X}:(q=true,{value:p(k)})},m),()=>q);if(!E)return i()??Ka("aborted");if(!E.ok)return i()??Ka(E.code);if("refused"in E.value)return E.value.refused;try{let X=await E.value.value;return e.identity()===k?X:Ka("document-replaced")}catch{return i()??Ka("input-failed")}},h={version:()=>l(p=>e.readVersion(p)),readCells(p){let m=structuredClone(p);return l(T=>e.readCells(T,m))},findText(p){let m=structuredClone(p);return l(T=>e.findText(T,m))},validateEdits(p){let m=structuredClone(p);return l(T=>e.validateEdits(T,m))}},f=p=>i()??(Ha(r(),p)?null:Ka("permission-denied")),a=p=>t.commit(p),d=Ha(r(),"separate")?{async applyEdits(p){let m=f(p?.history);if(m)return m;if(!e.admitEdits)return l(E=>e.applyEdits(E,p,()=>f(p.history),a));let T=e.identity();if(!T)return Ka("plugin-unavailable");let k=structuredClone(p),q=await e.admitEdits(T,k,E=>E?Ha(r(),k.history)?null:Ka("permission-denied"):f(k.history),a,[t.signal,t.lifetimeSignal]);return q.ok?q.value:Ka(q.code)}}:null,g={getDescriptor:p=>o.getDescriptor(p),getState:(p,m)=>o.getState(p,m),subscribe:p=>o.subscribe(p),execute:async(p,m)=>i()??o.execute(p,m)},y=()=>t.refusal()===null,I=async(p,m)=>{let T=await l(k=>e.version(k)===p?.expectVersion?m(k):"stale-version");return T===null?{ok:true}:typeof T=="object"?T:{ok:false,failure:{code:T,message:Ia[T]}}};return {read:h,commands:g,edits:d,navigation:{selectCells(p,m){let T=structuredClone(p),k=structuredClone(m);return I(k,q=>e.navigator.selectCells(q,T,k.focus===true,y,k.expectVersion))},scrollToCell(p,m){let T=structuredClone(p),k=structuredClone(m);return I(k,q=>{let E=k.align??"nearest";return Ja.has(E)?e.navigator.scrollToCell(q,T,E,y,k.expectVersion):"unsupported"})}}}}var si=new Set(["stale-version","missing-target","content-mismatch","overlapping-steps","locked-target","read-only","unsupported","invalid-step","limit-exceeded"]);function co(t){let e=a=>{let d=t.owner();if(d!==a||!d?.current||d.retiring)throw new w("document-replaced");if(d.failure)throw d.failure;return d},r=()=>{let a=t.coordinator();if(!a)throw new w("editor-unavailable");return a},o=a=>({ok:false,code:a instanceof w&&a.code==="document-replaced"?"document-replaced":"input-failed",error:a}),i=a=>typeof a=="object"&&a!==null&&"ok"in a&&a.ok===false&&"failure"in a,l=new WeakMap,h=(a,d)=>{let g=e(a),y=(l.get(g)??Promise.resolve()).then(()=>(e(a),d()));return l.set(g,y.then(()=>{},()=>{})),y},f={identity:()=>{let a=t.owner();return a?.ready&&a.current&&!a.retiring&&!a.failure?a:null},version:a=>f.identity()===a?e(a).session.confirmedBasis.version:null,currentVersion:a=>t.coordinator()?.pending?null:f.version(a),subscribe(a,d){let y=e(a).subscribe(()=>{f.identity()!==a&&d();}),I=r().subscribe(C=>{C.type==="coverage"&&f.identity()===a&&d();});return ()=>{I(),y();}},selection:a=>t.selection(e(a)),readOnly:a=>e(a).session.editState.readOnly===true,async admit(a,d,g=false){try{return e(a),await r().runAfterPendingInput(()=>{e(a);let y=d();return e(a),{ok:!0,value:y}},g)}catch(y){return o(y)}},readVersion:async a=>({ok:true,version:await e(a).session.call.version()}),readCells:(a,d)=>e(a).session.call.readCells(d),findText:(a,d)=>e(a).session.call.findText(d),validateEdits:(a,d)=>f.readOnlyRefusal(a)??e(a).session.call.validateEdits(d),readOnlyRefusal:a=>t.readOnly()||e(a).session.editState.readOnly?{ok:false,version:e(a).session.confirmedBasis.version,failure:{code:"read-only",message:"The editor is read-only"}}:null,applyEdits:()=>{throw Ka("unsupported-policy")},async admitEdits(a,d,g,y,I=[]){let C=false,p=null;try{p=e(a);let m=r(),T=m.runAfterPendingInput(()=>{e(a);let q=g(!1);if(q)return q;let E=f.readOnlyRefusal(a);return E||m.command({kind:"applyEdits",payload:{args:[d]}},{acknowledge:y,dispatch(X){e(a);let L=g(!1)??f.readOnlyRefusal(a);if(L)throw L;return C=!0,y(X)}}).result.then(X=>{if(!X.result)throw Ka("input-failed");return X.result})}),k=await La(I,T,()=>C);if(k===null){let q=g(!1);if(q)return {ok:!0,value:q};throw Ka("aborted")}return C||e(a),{ok:!0,value:k}}catch(m){if(i(m))return {ok:true,value:m};if(m instanceof Oe){if(m.status.result)return {ok:true,value:m.status.result};let T=m.status.reason;if(T&&si.has(T)&&p)return {ok:true,value:{ok:false,version:p.session.confirmedBasis.version,failure:{code:T,message:m.message}}}}return o(m)}},commands:t.commands,navigator:{selectCells:(a,...d)=>h(a,()=>t.navigator.selectCells(a,...d)),scrollToCell:(a,...d)=>h(a,()=>t.navigator.scrollToCell(a,...d))}};return f}function uo(t,e,r,o,i){return Ea(t,e,r,o,()=>{let l=i();return l.version===t.version&&l.painted===e})}function fo(t,e,r$1){let o=()=>{if(!t.current||t.retiring)throw new w("document-replaced")},i=p=>{try{if(o(),t.failure)throw t.failure;if(!t.ready)throw new w("editor-unavailable");let m=p(),T=r$1().exportCoordinator?.();if(!T)throw new w("editor-unavailable");return T.runAfterPendingInput(async()=>{o();let k=await m();return o(),k},!0)}catch(m){return Promise.reject(m)}},l=t.session.replica?.async,h=()=>{if(o(),t.failure||!t.ready)throw new w("editor-unavailable")},f=p=>({ok:false,failure:r(p,null)}),a=async p=>{if(o(),t.failure)throw t.failure;let m;try{m=await p();}catch(T){throw o(),t.failure?t.failure:T}if(o(),t.failure)throw t.failure;return m},d=()=>{if(o(),t.failure)throw t.failure;if(!t.ready)throw new w("editor-unavailable");let p=r$1().editorDocument?.();if(!p)throw new w("editor-unavailable");if(p.identity()!==t)throw new w("document-replaced");return p},g=p=>{if(p.ok)return p.value;throw p.error instanceof w?p.error:new w(p.code)},y$1=p=>a(async()=>{let m=d();return await g(await m.admit(t,()=>p(m),!0))}),I=l?{clientId:l.clientId,encodeStateVector:()=>a(()=>t.session.call.collaborationStateVector()),encodeStateAsUpdate:p=>{let m=p?.slice();return a(()=>t.session.call.collaborationStateAsUpdate(m))},applyUpdate:p=>{let m=p.slice();return a(()=>l.applyUpdate(m))},...l.applyUpdateChunks&&{applyUpdateChunks:p=>{let m=p.map(T=>T.slice());return a(()=>l.applyUpdateChunks(m))}},onUpdate(p){return o(),l.onUpdate((m,T)=>{t.current&&!t.retiring&&!t.failure&&p(m,T);})}}:null,C={get hydrated(){return t.ready},get failure(){return t.failure},whenHydrated:()=>t.whenReady(),recoverySave:()=>t.recoverySave(),version:()=>y$1(async p=>{let m=await p.readVersion(t);if(!m.ok)throw new w("input-failed");return m.version}),readCells(p){let m=structuredClone(p);return y$1(async T=>{let k=await T.readCells(t,m);if(!k.ok&&!("version"in k))throw new w("input-failed");return k})},findText(p){let m=structuredClone(p);return y$1(async T=>{let k=await T.findText(t,m);if(!k.ok&&!("version"in k))throw new w("input-failed");return k})},validateEdits(p){let m=structuredClone(p);return y$1(async T=>{let k=await T.validateEdits(t,m);if(!k.ok&&!("version"in k))throw new w("input-failed");return k})},applyEdits(p){let m=structuredClone(p);return a(async()=>{let T=d();if(!T.admitEdits)throw new w("editor-unavailable");return g(await T.admitEdits(t,m,()=>null,k=>k()))})},save:()=>a(async()=>{if(!t.ready)throw new w("editor-unavailable");let p=r$1().exportCoordinator?.();if(!p)throw new w("editor-unavailable");let m=await p.save();if(o(),t.failure)throw t.failure;return r$1().saved?.(m),m}),commands:y(e).guarded(o),collaboration:I,async proposeChanges(p){try{h();let m=structuredClone(p),T=r$1().exportCoordinator?.();if(!T)throw new w("editor-unavailable");return await T.runAfterPendingInput(async()=>{if(h(),T.readOnly)return f("read-only");let q=await T.command({kind:"propose",payload:{args:[m.agentId,m.note??null,m.edits]}}).result;return h(),{ok:!0,proposal:q.result}},"posted")}catch(m){return !t.current||t.retiring?f("document-replaced"):t.failure||!t.ready?f("editor-unavailable"):m instanceof Oe?m.status.reason==="read-only"?f("read-only"):m.status.reason==="unsupported"?f("unsupported-command"):m.status.reason==="invalid-command"||m.status.reason==="invalid-step"?f("invalid-arguments"):f("input-failed"):m instanceof w?f(m.code):f("command-failed")}},renderPng:p=>i(()=>{let m=structuredClone(p),T=r$1().exportSheet?.()??t.session.state.activeSheet;return ()=>t.session.call.renderPng(m,{sheet:T})}),renderRangePng:p=>i(()=>{let m=structuredClone(p),T=r$1().exportSheet?.()??t.session.state.activeSheet;return ()=>t.session.call.renderRangePng(m,{sheet:T})}),exportStructured:p=>i(()=>{let m=structuredClone(p);return ()=>t.session.call.exportStructured(m)}),exportMarkdown:(p,m)=>i(()=>{let T=structuredClone([p,m]);return ()=>t.session.call.exportMarkdown(...T)}),printDisplayList:(...p)=>i(()=>{let m=structuredClone(p);return ()=>t.session.call.printDisplayList(...m)}),focus(){o(),t.failure||r$1().focus();}};return Wa(C)}var Nt=class{constructor(e,r,o){a(this,"workerSession",e);a(this,"generation",r);a(this,"options",o);a(this,"alive",true);a(this,"retiring",false);a(this,"failure",null);a(this,"beforeRetire",null);a(this,"session");a(this,"painted",false);a(this,"cleanup");a(this,"listeners",new Set);a(this,"pending",new Set);a(this,"readiness");a(this,"resolveReady");a(this,"rejectReady");a(this,"offFailure",()=>{});a(this,"offAck",()=>{});a(this,"offDraft",()=>{});a(this,"offInput",()=>{});a(this,"recoveryInput",null);a(this,"recoveryDrafts",null);a(this,"checkpointTimer");a(this,"checkpointScheduler");a(this,"checkpointRevision",0);a(this,"checkpointBusy",false);a(this,"disposal",Promise.resolve());a(this,"disposeSession",()=>this.dispose());this.checkpointScheduler=o.checkpointScheduler??{now:()=>performance.now(),schedule(a,d){let g=setTimeout(a,d);return ()=>clearTimeout(g)}},this.readiness=new Promise((a,d)=>{this.resolveReady=a,this.rejectReady=d;}),this.readiness.catch(()=>{});let i=a=>{let d=new WeakMap;return g=>{let y=Reflect.get(a,g,a);if(typeof y!="function")return y;let I=d.get(y);return I||(I=(...C)=>this.track(()=>Reflect.apply(y,a,C),g==="submit"||g==="command"||g==="applyEdits"),d.set(y,I)),I}},l=i(e.call),h=i(e),f=new Proxy(e.call,{get:(a,d)=>l(d)});this.session=new Proxy(e,{get:(a,d)=>d==="call"?f:d==="dispose"?this.disposeSession:d==="submit"||d==="save"||d==="whenPresented"?h(d):Reflect.get(a,d,a)}),this.offFailure=e.onFailure(a=>this.fail(a)),this.offAck=e.onAck(()=>{this.notify(),this.scheduleCheckpoint(true);}),e.failure&&this.fail(e.failure);}get current(){return this.alive&&this.options.isCurrent()}get commandsAccepted(){let e=this.workerSession.commandIdentity;return this.current&&!this.retiring&&!this.failure&&this.workerSession.state.stage==="ready"&&!!(e.session&&e.incarnation)}get ready(){return this.commandsAccepted&&this.painted}get readOnly(){return !this.ready||this.workerSession.editState.readOnly===true}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}whenReady(){return !this.current||this.retiring?Promise.reject(new w("document-replaced")):this.failure?Promise.reject(this.failure):this.readiness}connectRecoveryInput(e,r){this.offDraft(),this.offInput(),this.recoveryInput=e,this.failure&&e.fail?.(this.failure),this.recoveryDrafts=r,this.offDraft=r.subscribe(()=>this.scheduleCheckpoint()),this.offInput=e.subscribe?.(()=>this.scheduleCheckpoint())??(()=>{}),this.scheduleCheckpoint();}recoverySave(){let e=()=>{if(!this.current||this.retiring)throw new w("document-replaced")};return this.track(async()=>{if(e(),this.workerSession.replica)throw new Error("Recovery is unavailable for collaborative workbooks");if(!this.failure)throw new Error("Recovery requires a failed workbook edit peer");try{let r=workbookSessionRecovery.get(this.workerSession);if(!r)throw new Error("Workbook recovery state is unavailable");let o=await r.save(e,this.recoveryInput?.recoveryCommands);return e(),{bytes:o,recovery:!0}}catch(r){if(e(),r instanceof w)throw r;this.failure=r instanceof Sa?r:new Sa(r),this.changed();try{this.options.onError(this.failure);}catch{}throw this.failure}},false,true)}firstPaint(){if(!(!this.commandsAccepted||this.painted)){this.painted=true;try{let e=this.options.onReady();!this.current&&typeof e=="function"?e():this.cleanup=e;}catch(e){this.fail(e);}this.ready&&this.resolveReady(),this.changed(),this.scheduleCheckpoint();}}fail(e){if(!(!this.current||this.failure)){this.failure=e instanceof Sa?e:new Sa(e),this.checkpointTimer?.(),this.checkpointTimer=void 0,this.checkpointRevision+=1,this.recoveryInput?.fail?.(this.failure),this.rejectReady(this.failure),this.rejectPending(this.failure),this.changed();try{this.options.onError(this.failure);}catch{}}}dispose(){if(!this.alive||this.retiring)return this.disposal;this.retiring=true;try{this.beforeRetire?.();}catch(r){try{this.options.onError(Ra(r));}catch{}}this.alive=false;let e=new w("document-replaced");this.rejectReady(e),this.rejectPending(e),this.offFailure(),this.offAck(),this.offDraft(),this.offInput(),this.checkpointTimer?.(),this.checkpointTimer=void 0,this.checkpointRevision+=1,this.recoveryInput=null,this.recoveryDrafts=null,this.changed(),this.listeners.clear();try{typeof this.cleanup=="function"&&this.cleanup();}catch(r){try{this.options.onError(Ra(r));}catch{}}finally{this.disposal=this.workerSession.dispose(),this.disposal.catch(()=>{});}return this.disposal}changed(){this.options.changed(),this.notify();}notify(){for(let e of this.listeners)try{e();}catch{}}rejectPending(e){for(let r of this.pending)r.reject(e);this.pending.clear();}scheduleCheckpoint(e=false){let r=++this.checkpointRevision;this.checkpointTimer?.(),this.checkpointTimer=void 0;let o=workbookSessionRecovery.get(this.workerSession),i=(o?.retainedCommands??0)>=192,l=()=>this.ready&&!!this.recoveryInput&&!this.recoveryInput?.draft&&!this.recoveryDrafts?.compositionId&&(i||r===this.checkpointRevision&&!this.recoveryInput?.pending);if(!o||o.retainedCommands<64||this.checkpointBusy||!l())return;let h=()=>{if(this.checkpointTimer=void 0,!l())return;this.checkpointBusy=true;let g=o.throughSeq;o.capture(l).then(y=>{this.checkpointBusy=false,(y&&o.throughSeq>g||r!==this.checkpointRevision)&&this.scheduleCheckpoint();},y=>{this.checkpointBusy=false,this.current&&!this.retiring&&this.fail(y);});};if(i){(e||!this.recoveryInput?.pending)&&h();return}let f=this.checkpointScheduler.now(),a=o.checkpointIdleMs??150,d=()=>{if(this.checkpointTimer=void 0,!l())return;let g=a-(this.checkpointScheduler.now()-f);g>0?this.checkpointTimer=this.checkpointScheduler.schedule(d,g):h();};this.checkpointTimer=this.checkpointScheduler.schedule(d,a);}track(e,r=false,o=false){return !this.current||this.retiring?Promise.reject(new w("document-replaced")):this.failure&&!o?Promise.reject(this.failure):r&&!this.ready?Promise.reject(new w("editor-unavailable")):new Promise((i,l)=>{let h={reject:l};this.pending.add(h);try{e().then(i,f=>{f instanceof WorkbookRecoveryReplayError&&this.fail(f),l(o?f:this.failure??f);}).finally(()=>this.pending.delete(h));}catch(f){this.pending.delete(h),f instanceof WorkbookRecoveryReplayError&&this.fail(f),l(this.failure??f);}})}};function yo(t,e,r,o){let i=useRef({props:t,bridge:r,options:o});i.current={props:t,bridge:r,options:o};let l=useRef(0),[h,f]=useState(null),[,a]=useState(0),[d,g]=useState(null),[y,I]=useState(false),C=t.collaboration,p=C!==void 0,m=C?.clientId,T=C?.initialUpdate,k=useCallback(X=>{let L=Ra(X);g(L);try{i.current.props.onError?.(L);}catch{}},[]);useEffect(()=>{let X=++l.current,L=new AbortController,B=false,re,D=()=>!B&&X===l.current&&i.current.props.file===t.file,se=()=>{D()&&a(J=>J+1);};return f(null),g(null),I(!!t.file),t.file&&(async()=>{try{let J=await Qa.open(t.file,{signal:L.signal,includeEditState:!0,...C?{collaborative:!0,clientId:m,initialUpdate:T?.slice()}:{},...i.current.options.initialViewport?{initialViewport:i.current.options.initialViewport()}:{}});if(!D()){J.dispose().catch(()=>{});return}let Be={changed:se,isCurrent:D,onError:Ie=>{if(D())k(Ie);else try{i.current.props.onError?.(Ie);}catch{}}},de=new Nt(J,X,{...Be,onReady:()=>D()?i.current.props.onReady?.(we):void 0}),we=fo(de,e,()=>i.current.bridge);re=de,f(re),I(!1);}catch(J){if(!D())return;re?re.fail(J):k(new Sa(J));}finally{D()&&I(false);}})(),()=>{B=true,l.current+=1,L.abort(),re?.dispose();}},[t.file,p,m,T,e,k]),useLayoutEffect(()=>()=>{h?.dispose();},[h,t.file,p,m,T]);let q=C?.onReplica,E=h instanceof Nt&&h.ready;return useEffect(()=>{if(!E||!(h instanceof Nt)||!q)return;let X=h.session.replica;if(X)for(let L of ["encodeStateVector","encodeStateAsUpdate"])X[L]=()=>{throw new Va(`replica.${L}()`,`await api.collaboration.${L}()`)};return q(X??null),()=>q(null)},[h,E,q]),{run:h?.current?h:null,error:d,loading:y,reportError:k}}var ci={request:t=>requestAnimationFrame(t),cancel:t=>cancelAnimationFrame(t)};function pr(t){return {...t,viewport:{...t.viewport}}}function Lr(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function jt(t,e,r=true){return t!==null&&t.generation===e.generation&&t.sheet===e.sheet&&(!r||t.navigation===e.navigation)&&t.width===e.width&&t.height===e.height&&t.zoom===e.zoom&&t.dpr===e.dpr&&Lr(t.viewport,e.viewport)}var mr=class{constructor(e){a(this,"options",e);a(this,"scheduler");a(this,"disposed",false);a(this,"failed",false);a(this,"raf",null);a(this,"pipeRaf",null);a(this,"pipeFrame",null);a(this,"revision",0);a(this,"paintedRevision",-1);a(this,"pending",null);a(this,"running",false);a(this,"lastPaint",null);a(this,"lastFrameSequence",0);a(this,"commandCoverage",0);a(this,"installation",0);a(this,"transactions",new Set);this.scheduler=e.scheduler??ci;}get painted(){return this.lastPaint}get coversThroughSeq(){return this.commandCoverage}registerPaintTransaction(e){return this.disposed?()=>{}:(this.transactions.add(e),()=>{this.transactions.delete(e);})}captureCommandFrame(){let e=this.failed?null:this.capture();return e?{...e,requestGeneration:this.revision,coversThroughSeq:this.options.sentSequence()}:null}installInitial(e){let r=this.capture();if(!e||!r||this.failed||this.lastPaint||this.running||this.pending||this.pipeFrame||this.raf!==null||this.revision!==0||e.coversThroughSeq!==0||e.sequence!==0||!Number.isSafeInteger(e.requestGeneration)||e.requestGeneration<0||e.viewport.width!==r.width/e.zoom||e.viewport.height!==r.height/e.zoom||r.requestGeneration!==void 0&&e.requestGeneration!==r.requestGeneration)return false;let o={...r,sheet:e.sheet,viewport:{...e.viewport},zoom:e.zoom,dpr:e.dpr,requestGeneration:e.requestGeneration};return this.revision=e.requestGeneration,this.install(e,o)?true:(this.revision=0,false)}install(e,r){if(!e||!this.accepts(e,r))return false;try{return this.publish("worker",pr(r),{displayList:e.displayList,mergedRanges:e.mergedRanges??[],version:e.version},e.sequence,e.coversThroughSeq),this.installation+=1,!0}catch(o){return this.fail(o),false}}queuePipeFrame(e,r){return this.accepts(e,r)?((!this.pipeFrame||e.coversThroughSeq>this.pipeFrame.frame.coversThroughSeq||e.coversThroughSeq===this.pipeFrame.frame.coversThroughSeq&&e.sequence>=this.pipeFrame.frame.sequence)&&(this.pipeFrame={frame:e,request:pr(r)}),this.pipeRaf===null&&(this.pipeRaf=this.scheduler.request(()=>{this.pipeRaf=null;let o=this.pipeFrame;this.pipeFrame=null,o&&!this.install(o.frame,o.request)&&this.schedule();})),true):false}advanceCoverage(e,r){if(!this.current||this.failed||this.pipeFrame||!this.lastPaint||this.paintedRevision!==this.revision||this.lastPaint.version!==e||!jt(this.capture(),this.lastPaint.request,false)||!Number.isSafeInteger(r)||r<this.commandCoverage)return false;if(r>this.commandCoverage){let o=this.commandCoverage;this.commandCoverage=r;try{this.options.onCovered?.(r);}catch(i){return this.commandCoverage=o,this.fail(i),false}}return true}schedule(){!this.current||this.failed||(this.cancelPipeFrame(),this.revision+=1,this.raf===null&&(this.raf=this.scheduler.request(()=>{if(this.raf=null,!this.current||this.failed)return;let e=this.capture();e&&(this.pending={request:e,revision:this.revision,sequence:this.options.sentSequence(),installation:this.installation},this.drain().catch(r=>this.fail(r)));})));}fail(e){if(!(!this.current||this.failed)){this.failed=true,this.cancelFrame();try{this.options.onError(e);}catch{}}}dispose(){this.disposed||(this.disposed=true,this.cancelFrame(),this.transactions.clear());}get current(){return !this.disposed&&(this.options.isCurrent?.()??true)}capture(){if(!this.current)return null;let e=this.options.capture();return e?.generation===this.options.generation?pr(e):null}matches(e){return e.revision===this.revision&&e.installation===this.installation&&jt(this.capture(),e.request)}accepts(e,r){let o=this.options.commandIdentity;return !!o&&this.current&&!this.failed&&e.session===o.session&&e.incarnation===o.incarnation&&e.requestGeneration===(r.requestGeneration??r.generation)&&(r.requestGeneration===void 0||r.requestGeneration===this.revision)&&e.zoom===r.zoom&&e.dpr===r.dpr&&e.sheet===r.sheet&&Lr(e.viewport,r.viewport)&&jt(this.capture(),r)&&Number.isSafeInteger(e.coversThroughSeq)&&Number.isSafeInteger(e.sequence)&&e.sequence>=0&&e.coversThroughSeq>=Math.max(this.commandCoverage,r.coversThroughSeq??0)}cancelPipeFrame(){this.pipeRaf!==null&&this.scheduler.cancel(this.pipeRaf),this.pipeRaf=null,this.pipeFrame=null;}cancelFrame(){this.raf!==null&&this.scheduler.cancel(this.raf),this.raf=null,this.pending=null,this.cancelPipeFrame();}retry(e){let r=this.capture();!r||jt(r,e.request)&&this.options.sentSequence()===e.sequence||!this.pending&&this.raf===null&&this.schedule();}publish(e,r,o,i,l){let h={...o,source:e,request:r,sequence:i,geometry:o.displayList.grid,...l===void 0?{}:{coversThroughSeq:l}},f=this.lastPaint,a=this.lastFrameSequence,d=this.commandCoverage;this.lastPaint=h,this.lastFrameSequence=Math.max(this.lastFrameSequence,i),l!==void 0&&(this.commandCoverage=l);try{let g=()=>{this.options.publish(h);};for(let y of [...this.transactions].reverse()){let I=g;g=()=>{y(h,I);};}g();}catch(g){throw this.lastPaint===h&&(this.lastPaint=f,this.lastFrameSequence=a,this.commandCoverage=d),g}return this.paintedRevision=this.revision,this.pipeFrame&&l!==void 0&&l>=this.pipeFrame.frame.coversThroughSeq&&this.cancelPipeFrame(),this.options.onInstalled?.(h),h}async drain(){if(!(this.running||!this.current||this.failed)){this.running=true;try{for(;this.current&&!this.failed&&this.pending;){let e=this.pending;if(this.pending=null,!this.matches(e)){this.retry(e);continue}let{request:r}=e,o;try{o=await this.options.requestFrame(pr(r));}catch(l){if(!this.current||this.failed)break;e.installation!==this.installation||!jt(this.capture(),r)||l instanceof Error&&l.name==="SessionSuperseded"?this.retry(e):this.fail(l);continue}if(!this.current||this.failed)break;let i="coversThroughSeq"in o&&typeof o.coversThroughSeq=="number"?o.coversThroughSeq:void 0;if(!this.matches(e)||o.sheet!==r.sheet||!Lr(o.viewport,r.viewport)||(r.coversThroughSeq===void 0?!(o.sequence>=this.options.sentSequence())||o.sequence<this.lastFrameSequence:i===void 0||i<Math.max(r.coversThroughSeq,this.commandCoverage))){this.retry(e);continue}try{this.publish("worker",r,{displayList:o.displayList,mergedRanges:o.mergedRanges??[],version:o.version},o.sequence,i);}catch(l){this.fail(l);}}}finally{this.running=false;}}}};function Br(t){return `${t.sheet}:${t.row}:${t.col}`}function Nr(t,e){let r=Math.max(t.x,e.x),o=Math.max(t.y,e.y),i=Math.min(t.x+t.w,e.x+e.w)-r,l=Math.min(t.y+t.h,e.y+e.h)-o;return i>0&&l>0?{x:r,y:o,w:i,h:l}:null}function pi(t,e){return !t.chart&&t.x>=e.x&&t.x<e.x+e.w&&t.y>=e.y&&t.y<e.y+e.h}function mi(t,e){let r=Nr(t,e);return r?[{x:t.x,y:t.y,w:t.w,h:r.y-t.y},{x:t.x,y:r.y+r.h,w:t.w,h:t.y+t.h-r.y-r.h},{x:t.x,y:r.y,w:r.x-t.x,h:r.h},{x:r.x+r.w,y:r.y,w:t.x+t.w-r.x-r.w,h:r.h}].filter(i=>i.w>0&&i.h>0):[t]}var hr=class{constructor(e){a(this,"options",e);a(this,"frame");a(this,"patches",new Map);a(this,"appearance",new Map);a(this,"maxPatches");a(this,"maxTextLength");a(this,"unregister");a(this,"disposed",false);if(this.maxPatches=Math.max(0,Math.floor(e.maxPatches??256)),this.maxTextLength=Math.max(0,Math.floor(e.maxTextLength??4096)),!Number.isSafeInteger(this.maxPatches)||!Number.isSafeInteger(this.maxTextLength))throw new RangeError("Invalid cell echo limit");this.frame=e.source.painted,this.unregister=e.source.registerPaintTransaction((r,o)=>{let i=this.frame,l=this.patches,h=this.appearance;try{this.frame=r,this.patches=new Map,this.appearance=new Map;for(let[f,a]of l)if(!(r.coversThroughSeq!==void 0&&f<=r.coversThroughSeq))for(let d of a.values())this.cellAppearance(d)&&this.store(f,d);o(),this.repaint(this.appearanceBounds());}catch(f){throw this.frame=i,this.patches=l,this.appearance=h,f}});}get size(){let e=0;for(let r of this.patches.values())e+=r.size;return e}patch(e,r){if(this.disposed||!this.frame||this.maxPatches===0||!Number.isSafeInteger(e)||e<=this.options.source.coversThroughSeq)return;let o=this.options.source.captureCommandFrame(),i=this.frame.request;if(!o||o.sheet!==i.sheet||o.zoom!==i.zoom||o.dpr!==i.dpr||o.width!==i.width||o.height!==i.height||o.viewport.x!==i.viewport.x||o.viewport.y!==i.viewport.y||o.viewport.width!==i.viewport.width||o.viewport.height!==i.viewport.height)return;let l=[],h=r[Symbol.iterator]();for(let f=0;f<this.maxPatches;f++){let a=h.next();if(a.done)break;let d=a.value;if(!Number.isSafeInteger(d.row)||!Number.isSafeInteger(d.col)||d.row<0||d.col<0||d.text.length>this.maxTextLength)continue;let g=this.cellAppearance(d);if(g)for(l.push(g.bounds),this.store(e,{...d});this.size>this.maxPatches;){let y=Math.min(...this.patches.keys()),I=this.patches.get(y),C=I.keys().next().value,p=this.appearance.get(C)?.bounds;p&&l.push(p),I.delete(C),I.size===0&&this.patches.delete(y);}}h.return?.(),this.pruneAppearance(),this.paint(l);}paste(e,r,o){let i=this.frame?.geometry;if(!i||!this.frame||r!==this.frame.request.sheet||o.length===0)return;let l=(f,a)=>{let d=0,g=o.length;for(;d<g;){let y=Math.floor((d+g)/2),I=o[y];I.row<f||I.row===f&&I.col<a?d=y+1:g=y;}return d},h=this.maxPatches;this.patch(e,(function*(){let f=0;for(let a=0;a<i.rowOffsets.length-1;a++){let d=i.rowIndices?.[a]??i.startRow+a,g=l(d,0),y=l(d+1,0);if(g!==y)for(let I=0;I<i.colOffsets.length-1;I++){let C=i.colIndices?.[I]??i.startCol+I;if(C<o[g].col||C>o[y-1].col)continue;if(f++>=h)return;let p=l(d,C),m=o[p];m?.row===d&&m.col===C&&(yield {sheet:r,row:d,col:C,text:m.input});}}})());}clear(e,r){let o=this.frame?.geometry;if(!o||!this.frame||r.sheet!==this.frame.request.sheet)return;let{rowOffsets:i,colOffsets:l,rowIndices:h,colIndices:f,startRow:a,startCol:d}=o;function*g(){for(let y=0;y<i.length-1;y++){let I=h?.[y]??a+y;if(!(I<r.top||I>r.bottom))for(let C=0;C<l.length-1;C++){let p=f?.[C]??d+C;p>=r.left&&p<=r.right&&(yield {sheet:r.sheet,row:I,col:p,text:""});}}}this.patch(e,g());}acknowledge(e){let r=new Set;for(let o of e.statuses)if(!(o.status!=="refused"&&o.status!=="cancelled")){r.add(o.seq);for(let i of o.affectedSeqs??[])r.add(i);}this.drop(r);}refuse(e){this.drop(new Set([e]));}dispose(){if(this.disposed)return;let e=this.appearanceBounds();this.patches.clear(),this.appearance.clear(),this.paint(e),this.disposed=true,this.unregister(),this.frame=null;}store(e,r){let o=this.patches.get(e);o||this.patches.set(e,o=new Map),o.set(Br(r),r);}drop(e){if(this.disposed)return;let r=[];for(let o of e){for(let i of this.patches.get(o)?.values()??[]){let l=this.appearance.get(Br(i));l&&r.push(l.bounds);}this.patches.delete(o);}this.pruneAppearance(),this.paint(r);}pruneAppearance(){let e=new Set;for(let r of this.patches.values())for(let o of r.keys())e.add(o);for(let r of this.appearance.keys())e.has(r)||this.appearance.delete(r);}appearanceBounds(){return [...this.appearance.values()].map(e=>e.bounds)}cellAppearance(e){if(!this.frame||e.sheet!==this.frame.request.sheet)return null;let r=Br(e),o=this.appearance.get(r);if(o)return o;let i=cellRect(this.frame.geometry,e.row,e.col);if(!i)return null;let l=this.frame.mergedRanges.find(I=>e.row>=I.start.row&&e.row<=I.end.row&&e.col>=I.start.col&&e.col<=I.end.col),h=l?rangeRect(this.frame.geometry,{top:l.start.row,left:l.start.col,bottom:l.end.row,right:l.end.col}):i;if(!h)return null;let f=this.frame.displayList,a=this.frame.request,d=Nr(h,{x:0,y:0,w:Math.min(f.width,a.viewport.width,a.width/a.zoom),h:Math.min(f.height,a.viewport.height,a.height/a.zoom)});if(!d||f.charts?.some(I=>Nr(I.clip,d)))return null;let g=f.commands.find(I=>I.op==="text"&&!I.ghost&&pi(I,h)),y={bounds:d,text:g?{...g,clip:d}:{op:"text",text:"",x:d.x+4,y:d.y+Math.min(18,d.h-2),fontSize:11,color:"#000000",clip:d}};return this.appearance.set(r,y),y}paint(e){try{this.repaint(e);}catch(r){this.options.source.fail(r);}}repaint(e){if(!this.frame||e.length===0)return;let r=this.options.context();if(!r)throw new Error("Cell echo canvas context is unavailable");let o=new Map;for(let g of [...this.patches.keys()].sort((y,I)=>y-I))for(let[y,I]of this.patches.get(g))o.delete(y),o.set(y,I);let i=[];for(let[g,y]of o){let I=this.appearance.get(g);I&&i.push({...I.text,text:y.text,numberFormat:void 0});}let l=this.frame.displayList,h={x:0,y:0,w:l.width,h:l.height},f=[];for(let g of l.commands){if(g.op!=="text"||g.chart||i.length===0){f.push(g);continue}let y=[g.clip??h];for(let I of i)y=y.flatMap(C=>mi(C,I.clip));for(let I of y)f.push({...g,clip:I});}let a={...l,commands:[...f,...i]},d=this.frame.request.dpr*this.frame.request.zoom;r.save();try{r.setTransform(d,0,0,d,0,0),r.beginPath();for(let g of e)r.rect(g.x,g.y,g.w,g.h);r.clip(),paintDisplayList(r,a,d);}finally{r.restore();}}};function gr(t,e){if("inputType"in t){if(t.isComposing||t.inputType==="insertCompositionText")return null;if(["insertText","insertReplacementText","insertFromPaste","insertFromDrop"].includes(t.inputType))return {kind:"insert",text:t.data??t.dataTransfer?.getData("text/plain")??""};let h=/^delete(Content|Word|SoftLine|HardLine)(Backward|Forward)$/.exec(t.inputType);return h?{kind:"delete",direction:h[2]==="Backward"?"backward":"forward",unit:h[1]==="Content"?"character":h[1]==="Word"?"word":"line"}:null}let r=t.ctrlKey||t.metaKey,o=e?t.altKey&&!t.metaKey:t.ctrlKey&&!t.altKey,i=e&&t.metaKey&&!t.altKey;if(r&&!t.altKey&&t.key.toLowerCase()==="a")return {kind:"selectAll"};if(!r&&t.key.length===1)return {kind:"insert",text:t.key};if(!e&&t.altKey)return null;let l=t.key==="Home"||i&&t.key==="ArrowLeft"?"start":t.key==="End"||i&&t.key==="ArrowRight"?"end":t.key==="ArrowLeft"?"left":t.key==="ArrowRight"?"right":null;return l?{kind:"move",direction:l,extend:t.shiftKey,...o?{unit:"word"}:{}}:t.key==="Backspace"||t.key==="Delete"?{kind:"delete",direction:t.key==="Backspace"?"backward":"forward",unit:i?"line":o?"word":"character"}:null}function jr(t,e,r){if(!r)return Math.min(t.length,e+((t.codePointAt(e)??0)>65535?2:1));let o=t.charCodeAt(e-1),i=t.charCodeAt(e-2);return Math.max(0,e-(o>=56320&&o<=57343&&i>=55296&&i<=56319?2:1))}function ko(t,e,r){let o=()=>jr(t,e,r),i=()=>t.slice(Math.min(e,o()),Math.max(e,o()));for(;/\s/u.test(i());)e=o();let l=/[\p{L}\p{N}_]/u.test(i());for(;i()&&!/\s/u.test(i())&&/[\p{L}\p{N}_]/u.test(i())===l;)e=o();return e}function zt(t,e,r){let o=Math.max(0,Math.min(t.length,r?.anchor??t.length)),i=Math.max(0,Math.min(t.length,r?.focus??t.length));for(let l of e){let h=Math.min(o,i),f=Math.max(o,i);if(l.kind==="select"){o=Math.max(0,Math.min(t.length,l.anchor)),i=Math.max(0,Math.min(t.length,l.focus));continue}if(l.kind==="selectAll"){o=0,i=t.length;continue}if(l.kind==="move"){let d=l.direction==="left",g=l.direction==="start"?0:l.direction==="end"?t.length:h!==f&&!l.extend?d?h:f:l.unit==="word"?ko(t,i,d):jr(t,i,d);l.extend||(o=g),i=g;continue}if(l.kind==="delete"&&h===f){let d=l.direction==="backward",g=l.unit==="line"?d?0:t.length:l.unit==="word"?ko(t,i,d):jr(t,i,d);h=Math.min(i,g),f=Math.max(i,g);}let a=l.kind==="insert"?l.text:"";t=t.slice(0,h)+a+t.slice(f),o=i=h+a.length;}return {value:t,anchor:o,focus:i}}var yr=class{constructor(e){a(this,"options",e);a(this,"coordinator",null);a(this,"listeners",new Set);a(this,"snapshot",{cell:null,formula:null,refused:[]});a(this,"draft",null);a(this,"formulaTarget",null);a(this,"formulaThroughSeq",null);a(this,"restoredRefusal",null);a(this,"revision",0);a(this,"compositionRevision",0);a(this,"composing",null);a(this,"trailing",null);a(this,"conversionEnter",false);a(this,"disposed",false);a(this,"loading",null);a(this,"cellSelection",null);a(this,"cellInput",null);a(this,"formulaInput",null);a(this,"focusedCellInput",null);a(this,"getSnapshot",()=>this.snapshot);a(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e);}));a(this,"sync",()=>{if(this.loading)return;let e=this.draft,r=e?.source==="cell"?this.cellInput:this.formulaInput;if(!e||!r||r.value===e.value)return;let o={...e,value:r.value,modified:true,revision:++this.revision};this.setDraft(o),this.composing||this.publish(o.source==="cell"?{cell:o}:{formula:o.value});});a(this,"cancel",()=>{this.options.defer?.(this.cancel)||(this.cancelPrefill(),this.composing?.settle(false),this.composing=null,this.compositionRevision+=1,this.trailing=null,this.formulaTarget=null,this.formulaThroughSeq=null,this.restoredRefusal&&this.coordinator?.discardRejected(this.restoredRefusal),this.setDraft(null),this.publish({cell:null,formula:null}),this.options.focus());});a(this,"seal",()=>{if(this.loading&&(this.loading.operations.length||this.composing?.loading===this.loading))return this.sealPrefill(this.loading);if(!this.composing)return !this.draft&&this.snapshot.cell&&this.publish({cell:null}),{};let e=this.composing;e.sealed=true;let r=e.source==="cell"?this.cellInput:this.formulaInput;return r?.blur(),{composition:e.done,compositionDraft:()=>e.completed,restoreFocus:()=>{if(this.disposed||this.composing||this.draft||!this.options.editable())return;let o=document.activeElement;o&&o!==document.body&&o!==r||(e.source==="formula"?this.formulaInput?.focus({preventScroll:true}):this.options.focus());}}});}attach(e){this.coordinator=e;}get compositionId(){return this.composing?.id}get loadingCell(){return this.loading!==null}get prefillIdentity(){return `${this.revision}:${this.compositionRevision}`}get focusedCellIdentity(){let e=this.options.selection()?.anchor;return JSON.stringify([this.options.identity(),this.options.navigation(),this.options.sheet(),e?.row,e?.col,this.options.valueRevision?.()])}isComposing(e){return this.composing?.source===e}get ownsFocus(){return this.draft!==null||this.snapshot.cell!==null||this.composing!==null}publish(e){this.snapshot={...this.snapshot,...e};for(let r of this.listeners)r();}setDraft(e){this.draft=e,e||(this.cellSelection=null),e||(this.restoredRefusal=null),this.coordinator?.setDraft(e);}create(e,r,o,i=true){return {generation:this.options.generation(),sheet:this.options.sheet(),...r,source:e,value:o,revision:++this.revision,modified:i,after:this.options.dependency(),target:this.options.target(this.options.sheet(),r.row,r.col)}}open(e){if(this.options.defer?.(()=>this.open(e)))return;let r=this.options.selection();if(!this.coordinator||!this.options.editable()||!r||this.composing||this.snapshot.cell)return;this.commit("formula"),this.trailing=null;let o=this.focusedCellInput?.identity===this.focusedCellIdentity?this.focusedCellInput.value:void 0,i=this.coordinator.pending?void 0:o,l=this.create("cell",r.anchor,e??i??"",e!==void 0),h,f=new Promise(g=>{h=g;}),a=e===void 0?{draft:l,identity:this.options.identity(),navigation:this.options.navigation(),operations:[],cancelled:false,sealed:false,completed:null,settle:h,input:{ready:f,target:l,draft:()=>a.completed}}:null,d=a?lo(this.coordinator,()=>this.options.prefill(l.sheet,l),g=>{a.value=g,this.completePrefill(a);},a.input.ready,()=>a.cancelled,g=>this.refusePrefill(a,g)):null;this.loading=a,this.setDraft(l),this.publish({cell:l,formula:null}),!(!a||!d)&&d.catch(g=>{a.settle(false),!a.cancelled&&!this.disposed&&this.options.identity()===a.identity&&this.options.fail(g);});}completePrefill(e){if(e.cancelled||this.disposed||this.options.identity()!==e.identity||!e.sealed&&(this.loading!==e||this.options.navigation()!==e.navigation)){e.settle(false);return}if(e.completed||e.value===void 0||this.composing?.loading===e)return;this.loading===e&&this.captureCellSelection();let r=zt(e.value,e.operations),o=r.value!==e.value||e.operations.some(l=>l.kind==="insert"||l.kind==="delete"),i=Object.freeze({...e.draft,value:r.value,modified:o,reserved:e.sealed,revision:o?++this.revision:e.draft.revision});e.completed=i,e.sealed||(this.loading=null,this.setDraft(i),this.trailing?.prefill&&this.trailing.input===this.cellInput&&(this.trailing.replay=r),this.writeCellSelection(i,r),this.publish({cell:i})),e.settle(true);}refusePrefill(e,r){e.settle(false),!(e.cancelled||this.disposed||this.options.identity()!==e.identity)&&(this.loading===e&&(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null})),this.coordinator?.error||this.options.report(r));}cancelPrefill(){this.loading&&(this.loading.cancelled=true,this.loading.settle(false)),this.loading=null;}sealPrefill(e){let r=this.cellInput,o=e.sealed;return e.sealed=true,this.composing?.loading===e?!o&&r&&r.ownerDocument?.activeElement===r&&r.blur():this.loading===e&&(this.loading=null,this.setDraft(null),this.publish({cell:null})),{pendingInput:e.input,restoreFocus:()=>{if(!r||this.disposed||this.composing||this.draft||!this.options.editable())return;let i=this.options.selection()?.anchor,l=e.draft.target?this.options.resolveSheet(e.draft.target.sheetId):e.draft.sheet;if(this.options.sheet()!==l||i?.row!==e.draft.row||i?.col!==e.draft.col)return;let h=r.ownerDocument.activeElement;h&&h!==r.ownerDocument.body&&h!==r||this.options.focus();}}}reservePrefill(e){this.sealPrefill(e),this.coordinator&&!e.input.ticket&&(e.input.ticket=this.coordinator.reserveInput(e.input),this.options.committed(e.input.ticket,e.draft));}writeCellSelection(e,r){let o=this.cellInput;this.cellSelection=o&&o.ownerDocument.activeElement===o?null:{revision:e.revision,anchor:r.anchor,focus:r.focus},o&&(o.value=r.value,o.setSelectionRange(Math.min(r.anchor,r.focus),Math.max(r.anchor,r.focus),r.anchor>r.focus?"backward":"forward"));}restoreCellSelection(){let e=this.cellSelection,r=this.cellInput;!e||!r||(this.cellSelection=null,this.draft?.revision===e.revision&&r.setSelectionRange(Math.min(e.anchor,e.focus),Math.max(e.anchor,e.focus),e.anchor>e.focus?"backward":"forward"));}holdCellEdit(e){return this.loading?(this.loading.sealed||this.loading.operations.push(e),true):false}captureCellSelection(){let e=this.loading,r=this.cellInput;if(!e||!r||this.composing?.loading===e||!r.value.length)return;let o=r.selectionStart??r.value.length,i=r.selectionEnd??o,l=r.selectionDirection==="backward"?{anchor:i,focus:o}:{anchor:o,focus:i},h=e.nativeSelection;h?.anchor===l.anchor&&h.focus===l.focus||(e.nativeSelection=l,o===0&&i===r.value.length?this.holdCellEdit({kind:"selectAll"}):o===i&&i===r.value.length?h&&this.holdCellEdit({kind:"move",direction:"end"}):this.holdCellEdit({kind:"select",...l}));}holdCellBeforeInput(e){if(this.trailing?.prefill&&!this.composing&&["insertText","insertFromComposition","insertCompositionText"].includes(e.inputType)&&e.data===this.trailing.data)return this.trailing.data!=="";if(!this.loading||this.composing?.loading===this.loading)return false;this.captureCellSelection();let r=this.cellInput;if(e.inputType==="insertReplacementText"&&r?.value.length){let i=e.getTargetRanges?.()[0];i&&this.holdCellEdit(i.startOffset===0&&i.endOffset===r.value.length?{kind:"selectAll"}:{kind:"select",anchor:i.startOffset,focus:i.endOffset});}let o=gr(e,p());return o?this.holdCellEdit(o):false}holdCellKey(e){let r=this.loading;if(!r)return false;this.captureCellSelection();let o=gr(e,p());if(!o||o.kind==="insert")return false;this.holdCellEdit(o);let i=this.cellInput;if(i){let l=zt(i.value,[o],{anchor:i.selectionDirection==="backward"?i.selectionEnd??0:i.selectionStart??0,focus:i.selectionDirection==="backward"?i.selectionStart??0:i.selectionEnd??0});i.setSelectionRange(Math.min(l.anchor,l.focus),Math.max(l.anchor,l.focus),l.anchor>l.focus?"backward":"forward"),r.nativeSelection={anchor:l.anchor,focus:l.focus};}return true}cellKey(e){let r=gr(e,p()),o=this.snapshot.cell;if(!r||!o)return false;if(this.holdCellEdit(r))return true;let i=this.cellSelection?.revision===o.revision?this.cellSelection:void 0,l=zt(o.value,[r],i);return (r.kind==="insert"||r.kind==="delete")&&this.change("cell",l.value,null),this.writeCellSelection(this.draft??o,l),true}change(e,r,o){if(this.options.defer?.(()=>this.change(e,r,o))||!this.options.editable()||!this.coordinator)return;if(this.trailing?.source===e&&this.trailing.input===o&&this.trailing.value===r){this.trailing.replay&&this.draft?.value===this.trailing.replay.value&&this.writeCellSelection(this.draft,this.trailing.replay);return}if(e==="cell"&&this.composing?.loading){this.composing.value=r;return}e==="cell"&&this.loading&&this.cancelPrefill(),this.cellSelection=null,this.trailing=null;let i=this.options.selection();if(!i)return;this.draft&&this.draft.source!==e&&!this.composing&&this.commit(this.draft.source);let h={...this.draft??(e==="cell"?this.snapshot.cell:null)??this.create(e,i.anchor,r),value:r,modified:true,revision:++this.revision};this.setDraft(h),!this.composing&&this.publish(e==="cell"?{cell:h,formula:null}:{formula:r,cell:null});}commit(e,r,o=false){if(!o&&this.options.defer?.(()=>this.commit(e,r,true),true)){e==="formula"&&r&&this.options.focus();return}if(!this.composing&&!(e==="cell"?this.loading||this.snapshot.cell:this.formulaTarget)&&this.draft?.source!==e||!this.options.editable()||!this.coordinator)return;if(this.composing){let a=this.composing.loading;e==="cell"&&!r&&a&&!a.sealed&&this.reservePrefill(a);return}if(e==="cell"&&this.loading){let a=this.loading;if(a.operations.length){if(this.reservePrefill(a),r){let d=a.draft.target?this.options.resolveSheet(a.draft.target.sheetId):a.draft.sheet;d!==void 0&&this.options.select(d,a.draft,r),a.input.options={selection:this.options.selectionTarget(),selectionRevision:this.options.navigation()},a.operations.some(g=>g.kind==="insert"||g.kind==="delete")||this.options.navigate(),this.options.focus();}return}this.cancelPrefill();}if(this.trailing?.source===e&&this.conversionEnter&&(r==="up"||r==="down")){this.trailing=null,this.conversionEnter=false;return}r&&(this.trailing=null,this.conversionEnter=false),o||this.sync();let i=this.draft?.source===e?this.draft:null,l=e==="cell"?this.snapshot.cell:this.formulaTarget;if(!i&&!l||!i&&e==="formula"&&!r)return;let h=i??l;this.setDraft(null),e==="cell"?this.publish({cell:null}):i&&(this.formulaTarget={...i,modified:false},this.formulaThroughSeq=null,this.publish({formula:i.value}));let f=h.target?this.options.resolveSheet(h.target.sheetId):h.sheet;if(f!==void 0&&this.options.select(f,h,r),i?.modified){let a=this.coordinator.submit(i,{selection:this.options.selectionTarget(),after:i.after});this.options.committed(a,i);}else this.options.navigate();(r||e==="cell")&&this.options.focus();}start(e){if(this.options.defer?.(()=>this.start(e))||!this.options.editable()||this.composing)return;e==="cell"&&this.captureCellSelection();let r=this.options.selection();if(!r)return;this.draft&&this.draft.source!==e&&this.commit(this.draft.source);let o=e==="cell"?this.cellInput:this.formulaInput,i=this.draft??this.create(e,r.anchor,o?.value??"",false);this.setDraft(i),this.trailing=null,this.conversionEnter=false;let l,h=new Promise(a=>{l=a;}),f=e==="cell"?this.loading??void 0:void 0;this.composing={id:`${this.options.identity()}:composition:${++this.compositionRevision}`,source:e,target:i,done:h,settle:l,sealed:false,completed:null,loading:f,inputState:f?{value:o?.value??"",anchor:o?.selectionStart??0,focus:o?.selectionEnd??0}:void 0};}end(e,r,o=false){if(!o&&this.options.defer?.(()=>this.end(e,r,true)))return;let i=this.composing;i&&(e!==void 0&&(i.result=e),o&&r!==void 0&&(i.completedValue=r),queueMicrotask(()=>{this.composing===i&&this.completeComposition();}));}completeComposition(){let e=this.composing;if(!e||!this.coordinator)return;if(e.loading){let i=e.loading,l=this.cellInput,h=e.inputState,f=e.completedValue??l?.value??e.value??"",a=Math.min(h.anchor,h.focus),d=h.value.length-Math.max(h.anchor,h.focus),g=e.result??(f===h.value?"":f.slice(a,Math.max(a,f.length-d))),y=g===""?h:zt(h.value,[{kind:"insert",text:g}],h);g!==""&&i.operations.push({kind:"insert",text:g}),l&&(this.trailing={source:"cell",input:l,value:y.value,data:g,prefill:true}),this.composing=null,l&&(l.value=y.value,l.setSelectionRange(Math.min(y.anchor,y.focus),Math.max(y.anchor,y.focus))),i.sealed&&(this.loading=null,this.setDraft(null),this.publish({cell:null})),this.completePrefill(i),e.settle(g!=="");return}e.completedValue===void 0&&this.sync();let r=e.source==="cell"?this.cellInput:this.formulaInput,o={...e.target,value:e.completedValue??r?.value??this.draft?.value??"",modified:true,revision:++this.revision};if(e.completed=o.value!==""?Object.freeze({...o}):null,this.composing=null,this.setDraft(e.sealed&&o.value!==""?o:null),r&&(this.trailing={source:o.source,input:r,value:o.value}),o.value!==""){let i=o.target?this.options.resolveSheet(o.target.sheetId):o.sheet;if(!e.sealed&&i!==void 0&&i!==this.options.sheet()&&this.options.select(i,o),o.source==="formula"&&(this.formulaTarget={...o,modified:false},this.formulaThroughSeq=null,this.publish({formula:o.value})),!e.sealed){let l=this.coordinator.submit(o,{compositionId:e.id,selection:this.options.selectionTarget(),after:o.after});this.options.committed(l,o);}this.publish(o.source==="cell"?{cell:o}:{formula:o.value});}else this.publish({cell:null,formula:null});e.settle(o.value!=="");}key(e,r){return this.isComposing(e)||r.nativeEvent.isComposing||r.keyCode===229?(r.key==="Enter"&&(this.conversionEnter=true),true):r.key==="Enter"&&this.conversionEnter?(this.conversionEnter=false,this.trailing=null,true):(this.trailing?.prefill&&(this.trailing=null),false)}keyUp(){this.composing||(this.trailing=null,this.conversionEnter=false);}refused(e,r){let o={...r,modified:true,revision:++this.revision,after:null},i={seq:e,draft:o};this.publish({refused:[...this.snapshot.refused,i].slice(-64)});let l=this.options.selection()?.anchor,h=o.target?this.options.resolveSheet(o.target.sheetId):o.sheet,f=this.options.sheet()===h&&l?.row===o.row&&l?.col===o.col;!this.ownsFocus&&this.options.editable()&&(!r.reserved||f)?this.restore(i):this.coordinator?.setDraft(this.draft);}restore(e=this.snapshot.refused[0]){if(!e||this.options.defer?.(()=>this.restore(e))||this.ownsFocus||!this.options.editable())return;let r=e.draft.target?this.options.resolveSheet(e.draft.target.sheetId):e.draft.sheet;r!==void 0&&(this.options.restoreCell?this.options.restoreCell(r,e.draft,o=>this.restoreResolved(e,r,o,true)):this.restoreResolved(e,r,e.draft,false));}restoreResolved(e,r,o,i){if(this.ownsFocus||!this.options.editable())return;let l={...e.draft,row:o.row,col:o.col,sheet:r,reserved:false,target:this.options.target(r,o.row,o.col)};i||this.options.select(r,l),this.setDraft(l),this.restoredRefusal=e.draft,this.publish({cell:l.source==="cell"?l:null,formula:l.source==="formula"?l.value:null,refused:this.snapshot.refused.filter(h=>h!==e)}),e.draft.source==="formula"&&this.formulaInput?.focus({preventScroll:true});}finish(){if(this.loading){this.loading.operations.length||this.composing?.loading===this.loading?(this.reservePrefill(this.loading),this.composing&&this.end()):(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null,formula:null}));return}if(this.composing){this.sync(),this.end();return}this.sync();let e=this.draft;e?.modified&&this.coordinator&&this.options.committed(this.coordinator.submit(e,{after:e.after}),e),this.setDraft(null),this.publish({cell:null,formula:null});}selectionChanged(){this.loading&&this.options.navigation()!==this.loading.navigation&&(this.loading.operations.length||this.composing?.loading===this.loading?this.reservePrefill(this.loading):(this.cancelPrefill(),this.setDraft(null),this.publish({cell:null}))),this.formulaTarget=null,this.formulaThroughSeq=null,!this.draft&&!this.composing&&this.snapshot.formula!==null&&this.publish({formula:null});}submitted(e,r){if(this.composing)return;let o=e,i=this.draft?.source===e.source&&this.draft.sheet===e.sheet&&this.draft.row===e.row&&this.draft.col===e.col&&this.draft.value===e.value&&this.draft.revision===o.revision;i&&(this.draft=null),e.source==="cell"?i&&this.publish({cell:null}):(i||this.formulaTarget?.revision===o.revision)&&(this.formulaTarget={...o,modified:false},this.formulaThroughSeq=r);}presented(e){this.formulaThroughSeq===null||e<this.formulaThroughSeq||this.draft||this.composing||(this.formulaThroughSeq=null,this.snapshot.formula!==null&&this.publish({formula:null}));}dispose(){this.disposed=true,this.cancelPrefill(),this.composing?.settle(false),this.composing=null,this.listeners.clear();}};var wo=memo(function({controller:e,presentation:r,run:o,active:i,selectedChart:l,error:h,readOnly:f,navigation:a,onNavigate:d,children:g}){let{selection:y,view:I,painted:C}=useSyncExternalStore(r.subscribe,r.getSnapshot),[p,m]=useState(null),T=C?.coversThroughSeq??0,k=Kr(o,f);useEffect(()=>{if(!o?.current||o.failure||!y||l)return;let D=`${o.generation}:${o.session.confirmedBasis.epoch}`,se=a.current,J=e.focusedCellIdentity,Be=`${i}:${zr(y.anchor)}`,de=false;return o.session.call.cellInputs(i,zr(y.anchor)).then(we=>{if(!de&&o.current&&!o.failure&&D===`${o.generation}:${o.session.confirmedBasis.epoch}`&&a.current===se&&e.focusedCellIdentity===J){let Ie=we.cells[0]?.[0]?.input??"";e.focusedCellInput={identity:J,value:Ie},m({at:Be,value:Ie}),e.presented(T);}}).catch(we=>{!de&&o.current&&o.fail(we);}),()=>{de=true;}},[o,i,y,l,C,T,e,a]),useLayoutEffect(()=>{m(null);},[o]);let q=useSyncExternalStore(e.subscribe,e.getSnapshot),E=useMemo(()=>({native:true,onNavigate:d,inputRef:D=>{e.formulaInput=D;},isComposing:()=>e.isComposing("formula"),onChange:D=>e.change("formula",D,e.formulaInput),onCommit:D=>e.commit("formula",D),onCancel:e.cancel,onBlur:()=>e.commit("formula"),onCompositionStart:()=>e.start("formula"),onCompositionEnd:()=>e.end(void 0,e.formulaInput?.value),onKeyDown:D=>e.key("formula",D)?(D.stopPropagation(),true):false,onKeyUp:()=>e.keyUp()}),[e,d]),X=y?zr(y.anchor):"",L=q.formula??(p?.at===`${i}:${X}`?p.value:"");useLayoutEffect(()=>{let D=e.formulaInput;D&&!e.isComposing("formula")&&D.value!==L&&Z(D,L);},[e,q,L]);let B=!I||!y||h,re=useMemo(()=>({...E,a1:X,value:L,disabled:B,readOnly:k||l}),[E,X,L,B,k,l]);return jsxs(Y.Provider,{value:re,children:[g,q.refused.map(D=>jsx("button",{"data-testid":"xlsx-refused-draft","data-sheet":D.draft.sheet,"data-row":D.draft.row,"data-col":D.draft.col,onClick:()=>e.restore(D),children:D.draft.value},D.seq??D.draft.revision))]})}),Po=memo(function({controller:e,rect:r,disabled:o,zoom:i}){let l=useCallback(C=>{e.cellInput=C;},[e]),f=useSyncExternalStore(e.subscribe,e.getSnapshot).cell,a=useRef({target:"",rect:null}),d=f?`${f.generation}:${f.sheet}:${f.row}:${f.col}`:"";d!==a.current.target&&(a.current={target:d,rect:null});let g=f?r(f.row,f.col,f.sheet):null;g&&!e.isComposing("cell")&&(a.current.rect=g);let y=a.current.rect;if(useLayoutEffect(()=>{let C=e.cellInput;if(!C)return;let p=T=>{e.holdCellBeforeInput(T)&&T.preventDefault();},m=()=>e.captureCellSelection();return C.addEventListener("beforeinput",p),C.addEventListener("select",m),()=>{C.removeEventListener("beforeinput",p),C.removeEventListener("select",m);}},[e,f!==null,y!==null]),useLayoutEffect(()=>{let C=e.cellInput;if(!f||!C||e.isComposing("cell"))return;C.value!==f.value&&(C.value=f.value);let p=C.ownerDocument.activeElement;if(p!==C){let m=C.closest("[tabindex]");if(p&&p!==C.ownerDocument.body&&!m?.contains(p))return;C.focus({preventScroll:true}),C.setSelectionRange(C.value.length,C.value.length);}e.restoreCellSelection();},[e,f,y!==null]),!f||!y)return null;let I={position:"absolute",left:y.x*i,top:y.y*i,width:y.w*i,height:y.h*i,boxSizing:"border-box",border:"2px solid #217346",background:"#ffffff",padding:"0 3px",font:`${13*i}px system-ui, sans-serif`,pointerEvents:"auto",outline:"none"};return jsx("input",{ref:l,"data-testid":"xlsx-cell-editor",defaultValue:f.value,disabled:o,style:I,onChange:C=>e.change("cell",C.target.value,C.currentTarget),onCompositionStart:()=>e.start("cell"),onCompositionEnd:C=>e.end(C.nativeEvent.data,C.currentTarget.value),onKeyDown:C=>{if(q(C)||C.stopPropagation(),!e.key("cell",C)){if(e.holdCellKey(C)){C.preventDefault(),C.stopPropagation();return}C.key==="Enter"?(e.commit("cell",C.shiftKey?"up":"down"),C.preventDefault()):C.key==="Tab"?(e.commit("cell",C.shiftKey?"left":"right"),C.preventDefault()):C.key==="Escape"&&(e.cancel(),C.preventDefault());}},onKeyUp:()=>e.keyUp(),onBlur:()=>e.commit("cell")})});function zr(t){let e="";for(let r=t.col+1;r>0;r=Math.floor((r-1)/26))e=String.fromCharCode(65+(r-1)%26)+e;return `${e}${t.row+1}`}function Kr(t,e){let r=useCallback(i=>t?.subscribe(i)??(()=>{}),[t]),o=useCallback(()=>!t||!t.ready||t.readOnly,[t]);return useSyncExternalStore(r,o)||e}function wi(t,e){return t===e||!!(t&&e&&t.sheet===e.sheet&&t.contentWidth===e.contentWidth&&t.contentHeight===e.contentHeight&&t.frozenRows===e.frozenRows&&t.frozenCols===e.frozenCols&&t.frozenWidth===e.frozenWidth&&t.frozenHeight===e.frozenHeight&&t.initialScrollX===e.initialScrollX&&t.initialScrollY===e.initialScrollY)}var br=class{constructor(){a(this,"selectionRef",{current:null});a(this,"viewRef",{current:null});a(this,"snapshot",{selection:null,view:null,painted:null});a(this,"listeners",new Set);a(this,"coverageListeners",new Set);a(this,"coverage",0);a(this,"publication",null);a(this,"getSnapshot",()=>this.snapshot);a(this,"subscribeCoverage",e=>(this.coverageListeners.add(e),()=>{this.coverageListeners.delete(e);}));a(this,"advanceCoverage",e=>{if(!(e<=this.coverage)){this.coverage=e;for(let r of this.coverageListeners)r();}});a(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e);}));a(this,"publish",()=>{this.publication=null;for(let e of this.listeners)e();});a(this,"setSelection",e=>{this.selectionRef.current=e,this.snapshot.selection!==e&&(this.snapshot={...this.snapshot,selection:e},this.publish());});a(this,"setView",e=>{this.viewRef.current=e,!wi(this.snapshot.view,e)&&(this.snapshot={...this.snapshot,view:e},this.schedule());});a(this,"setPainted",e=>{this.snapshot.painted!==e&&(this.snapshot={...this.snapshot,painted:e},e?.coversThroughSeq!==void 0&&this.advanceCoverage(e.coversThroughSeq),this.schedule());});}get coversThroughSeq(){return this.coverage}schedule(){if(this.publication)return;let e={};this.publication=e,queueMicrotask(()=>{this.publication===e&&this.publish();});}reset(){this.selectionRef.current=null,this.viewRef.current=null,this.snapshot={selection:null,view:null,painted:null},this.coverage=0,this.publish();}cancel(){this.publication=null;}};function tt(t,e){let r=useMemo(()=>{let o;return ()=>{let i=t.getSnapshot();return (!o||o.state!==i)&&(o={state:i,value:e(i)}),o.value}},[t,e]);return useSyncExternalStore(t.subscribe,r)}function So(t,e,r,o,i){let[l,h]=useState({run:null,provider:null,peers:[]});return useLayoutEffect(()=>{if(h({run:t,provider:e,peers:[]}),!t?.current||t.failure||!e)return;let f=e.onAwareness(a=>{t.current&&!t.retiring&&!t.failure&&h({run:t,provider:e,peers:[...a]});});return ()=>{f(),e.setCursor(null);}},[t,t?.failure,e]),useEffect(()=>{if(!e)return;if(!t?.ready){e.setCursor(null);return}let f=i.find(d=>d.index===r)?.id,a=o?normalizeRange(o):null;e.setCursor(f&&o&&a?{sheet:f,anchor:o.range?{row:a.top,col:a.left}:{...o.anchor},head:o.range?{row:a.bottom,col:a.right}:{...o.focus}}:null);},[t,t?.ready,e,r,o,i]),t?.current&&!t.retiring&&!t.failure&&l.run===t&&l.provider===e?l.peers:[]}var Pr=t=>t.selection,Hr=t=>t.painted,Ai=t=>t.view,Wo={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},Ro=memo(function({store:e,zoom:r}){let o=tt(e,Ai);return jsx("div",{style:{position:"absolute",top:0,left:0,width:o?o.contentWidth*r:"100%",height:o?o.contentHeight*r:"100%"}})}),Io=memo(function({store:e,active:r,zoom:o,selectedChart:i,chartOffset:l,controller:h,disabled:f,run:a}){let d=Kr(a,f),g=tt(e,Hr),y=tt(e,Pr),I=g?.request.zoom??o,C=g?.request.sheet===r?y:null,p=g?.displayList.grid,m=C?ua(normalizeRange(C),g?.mergedRanges??[]):null,T=p&&m?rangeRect(p,m):null,k=C?ua({top:C.anchor.row,left:C.anchor.col,bottom:C.anchor.row,right:C.anchor.col},g?.mergedRanges??[]):null,q=p&&k?rangeRect(p,k):null,E=i?g?.displayList.charts?.find(B=>B.id===i.id)?.rect:null,X=useCallback((B,re,D)=>g?.geometry&&g.request.sheet===D?cellRect(g.geometry,B,re):null,[g]),L=(B,re,D)=>{let se=ta(B,I);return {position:"absolute",left:se.x,top:se.y,width:se.w,height:se.h,boxSizing:"border-box",border:re,background:D}};return jsxs("div",{"data-testid":"xlsx-overlay-host",style:{position:"absolute",top:0,left:0,width:0,height:0,pointerEvents:"none"},children:[T&&!i&&jsx("div",{"data-testid":"xlsx-selection",style:L(T,"1px solid #217346","rgba(33, 115, 70, 0.12)")}),q&&!i&&jsx("div",{style:L(q,"2px solid #217346")}),E&&jsx("div",{"data-testid":"xlsx-chart-selection","data-chart-id":i?.id,"aria-hidden":true,style:{...L(E,"2px solid #217346"),transform:`translate(${l?.x??0}px, ${l?.y??0}px)`}}),jsx(Po,{controller:h,zoom:I,disabled:d,rect:X})]})}),To=memo(function({store:e,active:r,sheets:o}){let{t:i}=H(),l=tt(e,Hr),h=tt(e,Pr),f=l?.displayList,a=l?.request.sheet===r?h:null,d=l?o[l.request.sheet]?.name??"":"",g=useMemo(()=>f?buildA11yGrid(f,a,d,{gridLabel:i("a11y.gridLabel"),rowHeaderLabel:i("a11y.rowHeaderLabel"),columnHeaderLabel:i("a11y.columnHeaderLabel"),cellLabel:i("a11y.cellLabel"),cellLabelSelected:i("a11y.cellLabelSelected"),emptyCellLabel:i("a11y.emptyCellLabel"),emptyCellLabelSelected:i("a11y.emptyCellLabelSelected")}):null,[f,a,d,i]);return g?jsx(Di,{grid:g}):null}),Di=memo(function({grid:e}){return jsxs(Fragment,{children:[jsxs("div",{style:Wo,role:"grid","aria-label":e.label,children:[jsxs("div",{role:"row",children:[jsx("span",{role:"columnheader"}),e.columnHeaders.map(r=>jsx("span",{role:"columnheader",children:r.label},r.col))]}),e.rows.map(r=>jsxs("div",{role:"row",children:[jsx("span",{role:"rowheader",children:r.header}),r.cells.map(o=>jsx("span",{role:"gridcell","aria-selected":o.selected,children:o.label},o.col))]},r.row))]}),e.charts.map((r,o)=>jsx("div",{style:Wo,role:"img","aria-label":r.label},`${o}:${r.label}`))]})});function qo({store:t,onChange:e}){let r=tt(t,Pr);return useEffect(e,[r,e]),null}function Eo({store:t,run:e,provider:r,active:o,sheets:i}){let l=tt(t,Hr),h=tt(t,Pr),f=So(e,r,o,h,i),a=i.map(d=>d.id);return jsxs(Fragment,{children:[jsx("div",{style:{position:"absolute",top:8,left:0,width:l?.request.width??0,display:"flex",justifyContent:"flex-end",pointerEvents:"none"},children:jsx(va,{peers:f,sheetIds:a,sheetNames:i.map(d=>d.name),activeSheet:o})}),l?.request.sheet===o&&jsx("div",{style:{pointerEvents:"none"},children:jsx(wa,{peers:f,sheetIds:a,activeSheet:o,grid:l.displayList.grid,zoom:l.request.zoom,mergedRanges:l.mergedRanges??[]})})]})}var zi="#217346",$i="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Ki={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};function _r(t){let e="";for(let r=t.col+1;r>0;r=Math.floor((r-1)/26))e=String.fromCharCode(65+(r-1)%26)+e;return `${e}${t.row+1}`}function Vr(t,e){let r,o;if(t.range.kind==="rowCol")({start:r,end:o}=t.range);else {let h=/^\$?([A-Z]+)\$?([1-9]\d*)(?::\$?([A-Z]+)\$?([1-9]\d*))?$/i.exec(t.range.a1);if(!h)return null;let f=(a,d)=>({row:Number(d)-1,col:[...a.toUpperCase()].reduce((g,y)=>g*26+y.charCodeAt(0)-64,0)-1});r=f(h[1],h[2]),o=f(h[3]??h[1],h[4]??h[2]);}let i=t.activeCell??r,l=e?normalizeRange(e):null;return e&&e.anchor.row===i.row&&e.anchor.col===i.col&&l?.top===r.row&&l.left===r.col&&l.bottom===o.row&&l.right===o.col?e:i.row!==r.row&&i.row!==o.row||i.col!==r.col&&i.col!==o.col?{...selectionAt(i),range:{top:r.row,left:r.col,bottom:o.row,right:o.col}}:{anchor:{...i},focus:{row:i.row===r.row?o.row:r.row,col:i.col===r.col?o.col:r.col}}}function Hi(t){return `${_r({row:t.top,col:t.left})}:${_r({row:t.bottom,col:t.right})}`}function Dt(t){return N(t.nativeEvent)!==null||O(t.target)}function kt(t){let[e,r]=useState(t),o=useRef(e),i=useCallback(l=>{o.current=typeof l=="function"?l(o.current):l,r(o.current);},[]);return [e,i,o]}function Xo(t,e){let r=t.request;return r.generation===e.generation&&r.sheet===e.sheet&&r.navigation===e.navigation&&r.zoom===e.zoom&&r.dpr===e.dpr&&r.width===e.width&&r.height===e.height&&JSON.stringify(r.viewport)===JSON.stringify(e.viewport)}function Fo(t,e,r,o,i,l){return r?null:l==="start"?t:l==="center"?Math.max(0,t-Math.max(0,i-e)/2):t>=o&&t+e<=o+i?null:t<o||e>=i?t:Math.max(0,t+e-i)}var Ui=memo(function(){return jsxs(ma,{mode:"commands",children:[jsx(ma.Toolbar,{}),jsxs("div",{style:{display:"flex",padding:"4px 8px"},children:[jsx(ma.FormulaBar,{}),isProposalsAvailable()&&jsx(ga,{id:"proposalsPanel"})]})]})});function Nl(t){let{t:e}=H(),[r$1]=useState(()=>new A),o=useRef(null),i$1=useRef(null),l$1=useRef(null),h$1=useRef(null);useLayoutEffect(()=>()=>h$1.current?.host.close("unmounted"),[]);let f$1=useRef(t);f$1.current=t;let[a]=useState(x),[d$1,g$1,y]=kt(0),I$1=useRef(void 0),[C]=useState(()=>new br),{setSelection:p,selectionRef:m$1,setView:T$1,viewRef:k,setPainted:q$1}=C,[E$1,X,L]=kt([]),[B$1,re,D$1]=kt(u(t.initialZoom)),[se,J]=useState(null),[Be,de,we]=kt(null),[Ie,ue]=useState(null),[ke,ye,j]=kt(null),ve=useRef(null),Ee=useRef(0),Ce=useRef(null),We=n=>{Ee.current++,Ce.current=null,ye(n),n||(ve.current=null);},vt=useRef(void 0),ge=useRef(void 0),[at,ct,Ot]=kt([]),[Ve,bt,Me]=kt(false),[wt,Pt]=useState({}),ae=useRef(0),[c]=useState(n),x$1=useRef(selectionAt({row:0,col:0})),O=useRef(null),M=useRef(0),A$1=useRef(null),Z=useRef(null),ne=useRef(false),[oe,ce]=useState(0),ie=useRef(null),Te=useRef(null),fe=useRef(null),pe=useRef(null),_e=useRef(null),Xt=useRef(()=>{}),Se=useCallback(()=>i$1.current?.focus({preventScroll:true}),[]),rt=useRef(()=>{}),Kt=useCallback(n=>rt.current(n),[]),Je=useRef(null),[Ht]=useState(()=>({coordinator:()=>null,readOnly:()=>f$1.current.readOnly??false,focus:Se,exportSheet:()=>y.current,exportCoordinator:()=>Je.current,editorDocument:()=>Zt,saved:n=>f$1.current.onSave?.(n),clearSelection:()=>{},refreshProposals:()=>{},recoverInput:async()=>{},selectCells:()=>false,selectCellsAsync:async()=>false,apply:()=>{}})),{run:b,error:qe,loading:Ut}=yo(t,a.store,Ht,{backend:"peerless",initialViewport:()=>{let n=i$1.current;if(!(!n?.clientWidth||!n.clientHeight))return {width:n.clientWidth,height:n.clientHeight,zoom:D$1.current,dpr:window.devicePixelRatio||1,requestGeneration:0}}}),G=useRef(b);G.current=b;let ut=useMemo(()=>new Map,[b]),Ze=useMemo(()=>new Map,[b]),ee=n=>(G.current?.session.editState.sheets??G.current?.session.state.sheets)?.find(s=>s.index===n)?.id,me=n=>{let s=ee(n);if(s&&s===I$1.current&&m$1.current)return m$1.current;let u=G.current?.session.selection;return (s?ut.get(s):void 0)??(u&&u.sheetId===s?Vr(u):null)??selectionAt({row:0,col:0})},Ne=n=>{let s=i$1.current;if(!s)return;let u=s.firstElementChild;u&&(u.style.width=`${n.contentWidth*D$1.current}px`,u.style.height=`${n.contentHeight*D$1.current}px`);let v=ee(n.sheet),w=v?Ze.get(v):void 0;s.scrollLeft=(w?.x??n.initialScrollX)*D$1.current,s.scrollTop=(w?.y??n.initialScrollY)*D$1.current;},Ae=()=>!!(G.current?.ready&&!G.current.retiring&&!G.current.failure&&!G.current.readOnly&&!f$1.current.readOnly&&!Lt.current?.readOnly),Re=useCallback(n=>{n instanceof Oe&&n.status.reason==="read-only"?J({code:"read-only"}):n instanceof z?J({code:n.code,detail:n.message}):n instanceof w?J({code:n.code}):J({code:"input-failed",detail:n instanceof Error?n.message:String(n)});},[]),Fe=(n,s)=>{let u=G.current?.session.editState.sheets?.find(w=>w.index===n)?.id??G.current?.session.state.sheets.find(w=>w.index===n)?.id;if(!u)throw new w("editor-unavailable");let v=normalizeRange(s);return {sheetId:u,range:{kind:"rowCol",start:{row:v.top,col:v.left},end:{row:v.bottom,col:v.right}},activeCell:{...s.anchor}}},Ft=()=>{let n=G.current,s=n?.session.editState.sheets??n?.session.state.sheets;return m$1.current&&s?.some(u=>u.index===y.current)?Fe(y.current,m$1.current):void 0},Gt=()=>f(A$1.current?.painted?.displayList.grid),Ke=()=>{let n=G.current;if(!n?.current||n.retiring||n.failure)return null;let s=n.session.confirmedBasis;return {owner:n,sheet:y.current,selection:m$1.current??x$1.current,navigation:ae.current,version:`${s.epoch}:${s.version}:${n.session.state.version}`}},Ct=(n=Ke())=>{let s=A$1.current?.painted,u=G.current?.session.confirmedBasis,v=s?.request.sheet===n?.sheet&&s?.version===u?.version?h(s?.mergedRanges):void 0;return n?c.merges(n,v):h(void 0)},St=()=>oa(A$1.current?.painted?.displayList??null,(i$1.current?.clientHeight??0)/D$1.current),Ye=(n,s)=>{let u=ee(n);if(n===y.current&&u===I$1.current&&m(m$1.current,s))return;let v=I$1.current,w=i$1.current;if((u!==v||n!==y.current)&&w){v&&Ze.set(v,{x:w.scrollLeft/D$1.current,y:w.scrollTop/D$1.current});let F=u?Ze.get(u):void 0;w.scrollLeft=(F?.x??0)*D$1.current,w.scrollTop=(F?.y??0)*D$1.current;}u!==v&&v&&m$1.current&&ut.set(v,structuredClone(m$1.current)),u&&ut.set(u,structuredClone(s)),ae.current+=1,I$1.current=u,g$1(n),p(structuredClone(s)),de(null),K.selectionChanged(),a.refresh();},Jr=(n,s,u=false)=>{let v=A$1.current?.painted,w=G.current?.session.confirmedBasis;return !u&&te.pending&&!te.pendingSelectionGeometryStable?false:c.known(n,s)?true:!v||v.request.sheet!==n.sheet||v.version!==w?.version?false:g(v.displayList.grid,s)},He=()=>({context:Ke,activeCell:n=>n.anchor,limits:St,hidden:Gt,merges:Ct,known:Jr,query:(n,s)=>G.current.session.call.selectionData(n.sheet,n.selection.focus.row,n.selection.focus.col,s),apply:(n,s=y.current)=>(Ye(s,n),ft(s,n.focus),it({kind:"select",payload:{selection:Fe(s,n)}}),true)}),dt=(n,s,u=false,v=false)=>{n===y.current&&m(m$1.current,s)||c.select(s,{...He(),known:(w,F)=>Jr(w,F,v),apply:w=>(Ye(n,w),true)},n,u);},ft=(n,s,u)=>{let v=G.current,w=A$1.current?.painted;if(!v?.current||v.failure)return;let F=i$1.current,P=w?.geometry&&w.request.sheet===n?cellRect(w.geometry,s.row,s.col):null,W=D$1.current,z=2/W;if(u===void 0&&P&&F&&w?.request.zoom===W&&w.request.viewport.x===F.scrollLeft/W&&w.request.viewport.y===F.scrollTop/W&&(P.x===0||P.x>=z)&&(P.y===0||P.y>=z)&&P.x+P.w+z<=F.clientWidth/W&&P.y+P.h+z<=F.clientHeight/W)return;let V=ae.current;if(_e.current?.generation===v.generation&&_e.current.navigation===V)return;let he={generation:v.generation,navigation:V};_e.current=he,v.session.call.cellGeometry(n,s.row,s.col).then(H=>{let $=i$1.current;if(!v.current||G.current!==v||ae.current!==V||!$||u!==void 0&&!qa($,H.rect,u))return;let le=k.current,S=ee(n);if(!le||le.sheet!==n){S&&Ze.set(S,H.scrollPosition),$.scrollLeft=H.scrollPosition.x*D$1.current,$.scrollTop=H.scrollPosition.y*D$1.current,A$1.current?.schedule();return}let Q=D$1.current,U=2/Q,_=pa($,le,{...H.rect,w:H.rect.w+U,h:H.rect.h+U},Q);Qt.current={sheet:n,contentWidth:_.contentWidth,contentHeight:_.contentHeight},T$1(_);let xe=sa(H.rect,s,le,{x:$.scrollLeft/Q,y:$.scrollTop/Q,width:$.clientWidth/Q,height:$.clientHeight/Q},U);S&&Ze.set(S,xe),$.scrollLeft=xe.x*Q,$.scrollTop=xe.y*Q,A$1.current?.schedule();}).catch(H=>{v.current&&G.current===v&&ae.current===V&&v.fail(H);}).finally(()=>{_e.current===he&&(_e.current=null);});},xr=useRef(B$1);useLayoutEffect(()=>{if(xr.current===B$1)return;let n=xr.current;xr.current=B$1;let s=m$1.current;s&&!we.current&&ft(y.current,s.anchor,n);},[B$1]);let Qe=useMemo(()=>new Map,[b]),pt=useMemo(()=>new Set,[b]),Zr=useMemo(()=>({current:0}),[b]),Mt=useMemo(()=>new Set,[b]),mt=useMemo(()=>new Map,[b]),Vt=useMemo(()=>new Map,[b]),Yr=useRef(()=>{}),Lt=useRef(null),K=useMemo(()=>new yr({defer:(n,s)=>s||K.ownsFocus?c.defer(Ke(),n,s&&!K.ownsFocus):c.beforeInput({...He(),apply:u=>(Ye(y.current,u),true)},n,()=>Re(new w("editor-unavailable"))),restoreCell:(n,s,u)=>{c.select(selectionAt(s),{...He(),apply:v=>(Ye(n,v),u(v.anchor),ft(n,v.anchor),true)},n);},generation:()=>b?.generation??0,identity:()=>`${b?.generation}:${b?.session.commandIdentity.session}:${b?.session.commandIdentity.incarnation}:${b?.session.confirmedBasis.epoch}`,valueRevision:()=>b?.session.confirmedBasis.version??"",navigation:()=>ae.current,sheet:()=>y.current,selection:()=>{let n=m$1.current,s=n&&i(n.anchor,Ct());return n&&s!==n.anchor?{...n,anchor:s}:n},target:(n,s,u)=>Fe(n,selectionAt({row:s,col:u})),resolveSheet:n=>(b?.session.editState.sheets??b?.session.state.sheets)?.find(s=>s.id===n)?.index,editable:Ae,prefill:(n,s)=>so(b.session,n,_r(s)),select:(n,s,u)=>{let v=selectionAt(s);if((n!==y.current||!m(m$1.current,v))&&dt(n,v),u){let w=true;c.enqueue({key:u==="down"||u==="up"?"Enter":"Tab",shiftKey:u==="up"||u==="left"},{...He(),apply:F=>(Ye(n,F),ft(n,F.focus),w||it({kind:"select",payload:{selection:Fe(n,F)}}),true)}),w=false;}},selectionTarget:Ft,dependency:()=>O.current,navigate:()=>{let n=Ft();n&&Lt.current?.command({kind:"select",payload:{selection:n}}).result.catch(Re);},committed:n=>{n.result.catch(Re),a.refresh();},fail:n=>b?.fail(n),report:Re,focus:Se}),[b]),_t=useCallback(()=>{let n=G.current,s=i$1.current;if(!n?.current||!s?.clientWidth||!s.clientHeight||!l$1.current||!k.current)return null;let u=D$1.current;return {generation:n.generation,sheet:y.current,navigation:ae.current,coversThroughSeq:Math.max(n.session.throughSeq,Lt.current?.submittedThroughSeq??0),width:s.clientWidth,height:s.clientHeight,zoom:u,dpr:window.devicePixelRatio||1,viewport:{x:s.scrollLeft/u,y:s.scrollTop/u,width:s.clientWidth/u,height:s.clientHeight/u}}},[]),te=useMemo(()=>eo({generation:()=>b?.generation??0,session:()=>b?.session??null,isReady:()=>b?.ready??false,readOnly:()=>f$1.current.readOnly??false,seal:()=>Te.current?{refused:"gesture-active"}:(Xt.current(),K.seal()),sync:K.sync,compositionId:()=>K.compositionId,dependency:n=>n.after,target:(n,s,u)=>Fe(n,selectionAt({row:s,col:u})),draftTarget:n=>n.target,frame:()=>A$1.current?.captureCommandFrame()??void 0,selectionRevision:()=>ae.current,onEvent:(n,s)=>Yr.current(n,s),onError:n=>b?.fail(n)}),[b,K]);Lt.current=te,Je.current=te,K.attach(te);let Wr=useRef(null),ht=useRef(null),Jt=useRef(null),[Zt]=useState(()=>co({owner:()=>G.current,coordinator:()=>Lt.current,readOnly:()=>f$1.current.readOnly??false,commands:()=>a,selection(n){let s=n.session.selection,u=n.session.editState.sheets??n.session.state.sheets,v=n.session.editState.activeSheet??n.session.state.activeSheet,w=u.find(V=>V.index===v),F=s&&u.find(V=>V.id===s.sheetId),P=w??F,W=Jt.current,z=W?.owner===n&&W.sheetId===P?.id&&W.target===JSON.stringify(s)?W.cells:s&&F?.id===P?.id?Vr(s):null;return P?{sheetId:P.id,sheetIndex:P.index,cells:we.current?null:z,chartId:we.current?.id??null}:null},navigator:{selectCells:(...n)=>Wr.current.selectCells(...n),scrollToCell:(...n)=>Wr.current.scrollToCell(...n)}})),Rr=Zt.identity(),Mo=Rr?Zt.selection(Rr):null,je=Na({...t,access:Zt,commands:a,createClients:ao,createGeometry:uo,readOnly:t.readOnly??false,handle:Rr,selection:Mo,canvasRef:l$1,t:e});h$1.current=je;let[Lo,Bo]=Fa(je.managed);useLayoutEffect(()=>{let n=async([s,...u])=>{let v=await te.command({kind:"applyUpdate",payload:{update:s,...u.length?{updates:u}:{}}},{after:null}).result;if(v.status!=="applied"&&v.status!=="noop")throw new Error(v.reason??"Remote update refused");let w=v.result?.refusedUpdate;if(w)throw new Error(w);return v};return b?.session.bindCollaboration?.(s=>n([s]),n,async s=>{let u=await te.command({kind:"collabPipe",payload:s},{after:null}).result;if(u.status!=="applied"&&u.status!=="noop")throw new Error(u.reason??"Collaboration pipe refused");return u})},[b,te]),useLayoutEffect(()=>{b?.connectRecoveryInput(te,K);},[b,te,K]);let nt=useRef(0),ot=useRef(0),xt=useRef(null),gt=useRef(null),No=useCallback((n=false)=>{let s=G.current;if(!s?.ready||s.failure||s.retiring||!isProposalsAvailable())return Promise.resolve();let u=n?te.submittedThroughSeq:ot.current;if(gt.current?.owner===s)return gt.current.requiredSequence=Math.max(gt.current.requiredSequence,u),gt.current.promise;if(n&&nt.current++,xt.current?.owner===s&&xt.current.revision===nt.current&&xt.current.sequence>=ot.current)return Promise.resolve();let v={owner:s,requiredSequence:u,promise:Promise.resolve()};return gt.current=v,v.promise=Promise.resolve().then(async()=>{for(;;){if(G.current!==s||!s.current||s.retiring)throw new w("document-replaced");if(s.failure)throw s.failure;let w$1=v.requiredSequence;if(await te.whenApplied(w$1),w$1!==v.requiredSequence)continue;let F=nt.current,P=te.command({kind:"applyOps",payload:{toolbar:{id:"refreshProposals",args:null}}},{after:null,frame:void 0}),W=await P.result;if(G.current!==s||!s.current||s.retiring)throw new w("document-replaced");if(s.failure)throw s.failure;let z=P.seq??0,V=Math.max(ot.current,v.requiredSequence);if(F!==nt.current||z<V){let H=xt.current;if(H?.owner===s&&H.revision===nt.current&&H.sequence>=V)return;continue}let he=W.result;he?.proposals&&JSON.stringify(he.proposals)!==JSON.stringify(Ot.current)&&(ct(he.proposals),a.refresh()),xt.current={owner:s,revision:F,sequence:z};return}}).finally(()=>{gt.current===v&&(gt.current=null);}),v.promise},[te,a]),Yt=(n=false)=>{let s=G.current;No(n).catch(u=>{s?.current&&!s.retiring&&!s.failure&&G.current===s&&Re(u);});},Ir=useRef(0),Qt=useRef(null),er=useCallback((n=false)=>{let s=G.current;if(!s?.ready||s.failure)return;let u=y.current,v=++Ir.current;s.session.call.sheetView(u).then(w=>{if(G.current!==s||!s.current||s.failure||v!==Ir.current||y.current!==w.sheet)return;let F=k.current?.sheet!==w.sheet,P=Qt.current;P?.sheet!==w.sheet&&(Qt.current=null);let W=P?.sheet===w.sheet?{...w,contentWidth:Math.max(w.contentWidth,P.contentWidth),contentHeight:Math.max(w.contentHeight,P.contentHeight)}:w;T$1(W),F&&Ne(W),(n||F)&&A$1.current?.schedule();}).catch(w=>{G.current===s&&s.current&&!s.failure&&s.fail(w);});},[T$1,k,Ze]),jo=()=>{let n=m$1.current;if(!n)return "";let s=normalizeRange(n);return `${y.current}:${s.top}:${s.left}:${s.bottom}:${s.right}`};Yr.current=(n,s)=>{if(!b?.current||b.failure)return;if(n.type==="dispatched"&&n.seq!==null&&n.command){let S=n.command;Vt.set(n.seq,S),S.kind==="collabPipe"&&pt.add(n.seq);let Q=S.kind==="editCells"&&JSON.stringify(S.payload.selection)===JSON.stringify(Ft())?ae.current:n.selectionRevision??ae.current;for(mt.set(n.seq,Q);mt.size>256;)mt.delete(mt.keys().next().value);for(S.frame&&(S.kind!=="collabPipe"&&(Zr.current=n.seq),Qe.set(n.seq,{...S.frame,navigation:Q,coversThroughSeq:n.seq}));Qe.size>256;)Qe.delete(Qe.keys().next().value);if((S.kind==="select"||S.kind==="setActiveSheet"||S.kind==="undo"||S.kind==="redo"||"selection"in S.payload)&&(Mt.add(n.seq),O.current=n.seq),S.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="paintFormat"){let U=S.payload.toolbar.target,_=b.session.editState.sheets?.find(xe=>xe.id===U?.sheetId)?.index;_!==void 0&&U?.range.kind==="rowCol"&&(ve.current=`${_}:${U.range.start.row}:${U.range.start.col}:${U.range.end.row}:${U.range.end.col}`);}if(n.draft)Z.current?.patch(n.seq,[{...n.draft,text:n.draft.value}]),K.submitted(n.draft,n.seq);else if(S.kind==="editCells"){let[U,_]=S.payload.args;Z.current?.paste(n.seq,U,_);}else if(S.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="clear"){let U=S.payload.toolbar.target,_=b.session.editState.sheets?.find(xe=>xe.id===U?.sheetId)?.index;_!==void 0&&U?.range.kind==="rowCol"&&Z.current?.clear(n.seq,{sheet:_,top:U.range.start.row,left:U.range.start.col,bottom:U.range.end.row,right:U.range.end.col});}return}if(n.type==="accepted"&&n.seq!==null){let S=Vt.get(n.seq);n.status?.committed&&r$1.changed(),Vt.delete(n.seq);let Q=S?.kind==="applyOps"&&"toolbar"in S.payload&&S.payload.toolbar.id==="refreshProposals";S&&!Q&&S.kind!=="select"&&S.kind!=="setActiveSheet"&&S.kind!=="setReadOnly"&&S.kind!=="applyUpdate"&&S.kind!=="collabPipe"&&(n.status?.committed||S.kind==="rejectProposal"||(S.kind==="propose"||S.kind==="acceptProposal"||S.kind==="undo"||S.kind==="redo")&&n.status?.status==="applied")&&(ot.current=Math.max(ot.current,n.seq),Yt());return}if(n.type==="refused"||n.type==="cancelled"){n.status?.reason==="stale-proposal"&&(nt.current++,Yt()),n.seq!==null&&Vt.delete(n.seq),n.seq!==null&&Z.current?.refuse(n.seq),n.type==="refused"&&n.draft&&(K.refused(n.seq,n.draft),Re(new Oe(n.status??{seq:n.seq??0,status:"refused"},n.target,n.draft)));return}if(n.type!=="coverage")return;Z.current?.acknowledge(n.ack);let u=n.ack,v=ht.current,w=v?.owner===b?u.statuses.find(S=>S.seq===v.ticket?.seq):void 0;v?.clear&&w&&(w.status==="applied"||w.status==="noop")?Jt.current={owner:b,sheetId:v.sheetId,target:JSON.stringify(b.session.selection),cells:null}:u.statuses.some(S=>Mt.has(S.seq)&&(S.status==="applied"||S.status==="noop"))&&(Jt.current=null);let F=false;for(let S of u.statuses){let Q=S.result;Q?.remoteUpdate&&(F=true,r$1.changed(),ot.current=Math.max(ot.current,S.seq),Q.proposals&&(ct(Q.proposals),xt.current={owner:b,revision:nt.current,sequence:S.seq}),a.refresh());}u.editState?.sheets&&JSON.stringify(u.editState.sheets)!==JSON.stringify(L.current)&&X(u.editState.sheets);let P=Math.max(0,...Mt),W=!c.isPending(Ke())&&P>0&&u.throughSeq>=P&&mt.get(P)===ae.current&&!K.ownsFocus;if(u.selection&&W){let S=u.selection,Q=b.session.editState.sheets?.find(_=>_.id===S.sheetId)?.index,U=Vr(S,m$1.current);Q!==void 0&&U&&dt(Q,U);}else !u.selection&&u.editState?.activeSheet!==void 0&&W&&u.editState.activeSheet!==y.current&&dt(u.editState.activeSheet,me(u.editState.activeSheet));s?.();let z=A$1.current,V=u.frame,he=V&&Qe.get(V.coversThroughSeq),H=false;if(V&&he&&z){let S=W?{...he,navigation:ae.current}:he,Q=Zr.current>z.coversThroughSeq;H=pt.has(V.coversThroughSeq)&&!Q?z.queuePipeFrame(V,S):z.install(V,S);}let $=false;for(let S of pt)if(S>(z?.coversThroughSeq??0)&&S<=u.throughSeq){$=true;break}let le=$&&!u.frame&&z?.advanceCoverage(u.version,u.throughSeq);!H&&!le&&(u.frame||F||$&&u.throughSeq>=te.submittedThroughSeq)&&z?.schedule();for(let S of pt)S<=(z?.coversThroughSeq??0)&&pt.delete(S);for(let S of Qe.keys())S<=(A$1.current?.coversThroughSeq??0)&&Qe.delete(S);for(let S of Mt)S<=u.throughSeq&&Mt.delete(S);for(let S of mt.keys())S<=u.throughSeq&&mt.delete(S);O.current!==null&&O.current<=u.throughSeq&&(O.current=null),u.statuses.some(S=>S.committed&&S.status==="applied")&&(M.current+=1,er(),f$1.current.onDocumentChange?.({version:u.version}),f$1.current.onChange?.());};let zo=async(n,s,u,v,w,F)=>{let P=ae.current,W=A$1.current?.painted,z=k.current?.sheet===s&&k.current.version===F?k.current:null,V=W?.version===F&&W.request.sheet===s&&W.geometry?cellRect(W.geometry,u.row,u.col):null,[he,H]=await Promise.all([V&&W?{version:F,rect:V}:n.session.call.cellGeometry(s,u.row,u.col),z??n.session.call.sheetView(s)]);if(G.current!==n||!n.current||n.failure||!w()||ae.current!==P||y.current!==s)return "unsupported";if(he.version!==F||H.version!==F||n.session.confirmedBasis.version!==F)return "stale-version";let $=i$1.current;if(!$)return "layout-unavailable";k.current!==H&&(Ir.current+=1,T$1(H));let le=D$1.current,S=$.scrollLeft/le,Q=$.scrollTop/le,U=Fo(he.rect.x+(V&&W&&u.col>=H.frozenCols?W.request.viewport.x:0),he.rect.w,u.col<H.frozenCols,S,$.clientWidth/le-H.frozenWidth,v),_=Fo(he.rect.y+(V&&W&&u.row>=H.frozenRows?W.request.viewport.y:0),he.rect.h,u.row<H.frozenRows,Q,$.clientHeight/le-H.frozenHeight,v),xe=U!==null&&U!==S,be=_!==null&&_!==Q;return xe&&($.scrollLeft=U*le),be&&($.scrollTop=_*le),(xe||be||W?.request.sheet!==s||W.version!==F)&&A$1.current?.schedule(),null},Qr=async(n,s,u,v,w$1,F)=>{let P=G.current;if(!P||P!==n||!P.current||P.failure||!w$1())return "unsupported";let W=(P.session.editState.sheets??P.session.state.sheets).find(H=>H.id===s?.sheetId),z=s?.selection?.anchor??{row:s?.row,col:s?.col},V=H=>H&&Number.isInteger(H.row)&&Number.isInteger(H.col)&&H.row>=0&&H.row<1048576&&H.col>=0&&H.col<16384;if(!W||!V(z)||s.selection&&!V(s.selection.focus))return "missing-target";let he=null;try{let H=Ke();if(s.selection&&H){let S;if(!await c.select(s.selection,{...He(),apply:U=>!P.current||P.failure||!w$1()?!1:(S=U,Ye(W.index,U),!0)},W.index)||!S||!P.current||P.failure||!w$1())return "unsupported";s={...s,selection:S},z=S.anchor;}if(s.selection||W.index!==y.current){let S=s.selection?Fe(W.index,s.selection):void 0,Q=ae.current,U=null,_=null;he={owner:P,sheetId:W.id,clear:!s.selection,ticket:null},ht.current=he;let xe=P.session.onAck(be=>{let Rt=be.statuses.find(yt=>yt.seq===U?.seq);Rt&&(_=be.statuses.some(yt=>yt.seq!==U?.seq&&yt.committed)||!Rt.committed&&be.version!==F?null:be.version);});try{U=te.command({kind:"setActiveSheet",payload:{args:[W.index],target:{sheetId:W.id,range:{kind:"rowCol",start:z,end:z}},...S?{selection:S}:{},expectVersion:F}},{frame:void 0,dispatch(be){if(G.current!==P||!P.current||P.failure||!w$1())throw new w("document-replaced");return be()}}),he.ticket=U,await U.result,await new Promise(be=>{c.defer(Ke(),be,!1,be)||be();});}finally{xe();}if(!_||P.session.confirmedBasis.version!==_)return "stale-version";if(G.current!==P||!P.current||P.failure||!w$1()||ae.current>Q+1||y.current!==W.index||s.selection&&!m(m$1.current,s.selection))return "unsupported";s.selection||p(null),F=_;}let $=ae.current,le=await zo(P,W.index,z,u,w$1,F);if(le)return le;if(G.current!==P||!P.current||P.retiring||P.failure||!w$1()||ae.current!==$||y.current!==W.index)return "unsupported";if(P.session.confirmedBasis.version!==F)return "stale-version";if(s.selection){if(flushSync(()=>de(null)),G.current!==P||!P.current||P.retiring||P.failure||!w$1()||ae.current!==$||y.current!==W.index)return "unsupported";if(P.session.confirmedBasis.version!==F)return "stale-version";let S=A$1.current,Q=S?.painted,U=S?.captureCommandFrame(),_=he?.ticket?.seq;S&&_&&Q?.version===F&&U&&Xo(Q,{...U,navigation:Q.request.navigation})&&S.install({...P.session.commandIdentity,sheet:U.sheet,viewport:U.viewport,requestGeneration:U.requestGeneration,zoom:U.zoom,dpr:U.dpr,version:Q.version,epoch:P.session.confirmedBasis.epoch,sequence:Q.sequence,coversThroughSeq:_,displayList:Q.displayList,mergedRanges:[...Q.mergedRanges]},{...U,coversThroughSeq:_});}return v&&Se(),null}catch(H){if(H instanceof Oe){if(H.status.reason==="stale-version")return "stale-version";if(H.status.reason==="missing-target"||H.status.reason==="stale-target")return "missing-target"}if(H instanceof RangeError)return "missing-target";throw H}finally{ht.current===he&&(ht.current=null,G.current===P&&P.current&&!P.failure&&y.current!==k.current?.sheet&&er(true));}};Wr.current={selectCells:(n,s,u,v,w)=>Qr(n,structuredClone(s),"nearest",u,v,w),scrollToCell:(n,s,u,v,w)=>Qr(n,structuredClone(s),u,false,v,w)},useLayoutEffect(()=>{let n=()=>{pe.current!==null&&clearTimeout(pe.current),pe.current=null,fe.current=null,Te.current=null,ne.current=false,ie.current=null,_e.current=null;};if(je.beginLoad(),n(),J(null),C.reset(),I$1.current=void 0,de(null),ue(null),We(null),ct([]),Pt({}),bt(false),ve.current=null,X(b?.session.editState.sheets??b?.session.state.sheets??[]),ae.current+=1,Qt.current=null,O.current=null,nt.current++,ot.current=0,Jt.current=null,ht.current=null,!b)return;let s=new mr({generation:b.generation,commandIdentity:b.session.commandIdentity,capture:_t,isCurrent:()=>b.current&&!b.failure,sentSequence:()=>te.submittedThroughSeq,requestFrame:async P=>{b.ready&&await te.whenApplied(Math.min(P.coversThroughSeq??0,te.submittedThroughSeq));let W=Math.max(P.coversThroughSeq??0,b.session.throughSeq),z=await b.session.call.frame(P.viewport,{sheet:P.sheet});return {...z,coversThroughSeq:"coversThroughSeq"in z&&typeof z.coversThroughSeq=="number"?z.coversThroughSeq:W}},publish(P){let W=l$1.current,z=W?.getContext("2d");if(!W||!z)throw new Error("Canvas context is unavailable");let V=P.request;W.width=Math.round(V.width*V.dpr),W.height=Math.round(V.height*V.dpr),W.style.width=`${V.width}px`,W.style.height=`${V.height}px`,paintDisplayList(z,P.displayList,V.dpr*V.zoom),W.dataset.workerSequence=String(P.sequence),W.dataset.commandCoverage=String(P.coversThroughSeq??0),W.dataset.paintSource=P.source,W.dataset.workerZoom=String(V.zoom);},onInstalled(P){for(let z of pt)z<=s.coversThroughSeq&&pt.delete(z);for(let z of Qe.keys())z<=s.coversThroughSeq&&Qe.delete(z);q$1(P);let W=(b.session.editState.sheets??b.session.state.sheets).find(z=>z.index===P.request.sheet)?.id;je.presentGrid(W?{frame:P.displayList,version:P.version,sheetId:W,zoom:P.request.zoom,viewport:P.request.viewport}:null),P.coversThroughSeq!==void 0&&b.session.markPresented({...b.session.commandIdentity,coversThroughSeq:P.coversThroughSeq}),b.firstPaint();},onCovered(P){let W=l$1.current;W&&(W.dataset.commandCoverage=String(P)),C.advanceCoverage(P),b.session.markPresented({...b.session.commandIdentity,coversThroughSeq:P});},onError:P=>b.fail(P)});A$1.current=s;let u=new hr({source:s,context:()=>l$1.current?.getContext("2d")??null});Z.current=u;let v=b.session.editState.activeSheet??b.session.state.activeSheet;I$1.current=ee(v),g$1(v);let w=P=>{if(!b.current||b.failure||A$1.current!==s)return;T$1(P),I$1.current=ee(v);let W=me(v);p(selectionAt({row:0,col:0})),m(m$1.current,W)||c.select(W,{...He(),apply:z=>(Ye(v,z),true)},v),Ne(P);},F=b.session.initialPaint;return F?(w(F.sheetView),s.installInitial(F.frame)||s.schedule()):b.session.call.sheetView(v).then(P=>{w(P),s.schedule();}).catch(P=>b.fail(P)),b.beforeRetire=()=>{je.beginLoad(),n(),C.cancel(),te.retire(),K.dispose(),s.dispose();},()=>{n(),C.cancel(),u.dispose(),s.dispose(),te.retire(),K.dispose(),A$1.current===s&&(A$1.current=null),Z.current===u&&(Z.current=null);}},[b,te,K,_t]),useEffect(()=>{if(!b?.current||b.failure)return;let n=i$1.current;if(!n)return;let s=()=>{let v=A$1.current,w=_t(),F=v?.painted;F&&w&&(v?.coversThroughSeq??-1)>=te.submittedThroughSeq&&Xo(F,{...w,navigation:F.request.navigation})||v?.schedule();},u=new ResizeObserver(s);return u.observe(n),n.addEventListener("scroll",s,{passive:true}),s(),()=>{u.disconnect(),n.removeEventListener("scroll",s);}},[b,b?.failure,B$1,_t,te]),useEffect(()=>{if(typeof window.matchMedia!="function")return;let n,s=()=>{A$1.current?.schedule(),n?.removeEventListener("change",s),n=window.matchMedia(`(resolution: ${window.devicePixelRatio||1}dppx)`),n.addEventListener("change",s);};return s(),()=>n?.removeEventListener("change",s)},[]),useEffect(()=>{!b?.ready||d$1===k.current?.sheet||ht.current?.owner===b&&ht.current.sheetId===b.session.editState.sheets?.find(n=>n.index===d$1)?.id||er(true);},[b,d$1,er]);let tr=useRef({owner:null,readOnly:false});useLayoutEffect(()=>{if(!b?.ready||tr.current.owner===b&&tr.current.readOnly===!!t.readOnly)return;let n=tr.current;tr.current={owner:b,readOnly:!!t.readOnly},!(n.owner!==b&&!!b.session.editState.readOnly==!!t.readOnly)&&(t.readOnly&&(Xt.current(true),K.finish(),We(null),Te.current=null,fe.current=null,ue(null)),te.setReadOnly(!!t.readOnly).result.catch(Re));},[b,b?.ready,t.readOnly,te,K]),useEffect(()=>{b?.failure&&(Z.current?.dispose(),A$1.current?.dispose(),te.fail(b.failure),K.dispose(),Te.current=null,fe.current=null);},[b,b?.failure,te,K]);let it=n=>{let s=A$1.current?.captureCommandFrame()??void 0,u=ae.current;n.kind==="select"&&!K.ownsFocus?te.command(n,{frame:s,selectionRevision:u}).result.catch(Re):te.runAfterPendingInput(()=>te.command(n,{frame:s,selectionRevision:u}).result).catch(Re);},$o=()=>{let n=Ft();!Ae()||!n||it({kind:"applyOps",payload:{toolbar:{id:"clear",args:null,target:n},selection:n}});},en=n=>{let s=G.current;return !!(s?.ready&&!s.failure&&m$1.current&&(n==="copy"||Ae()))},Ko=n=>{if(n==="paste"){let W=F();return W.catch(()=>{}),{read:W}}let s=B(),u,v,w=new Promise((W,z)=>{u=W,v=z;});w.catch(()=>{});let F$1,P;try{if(typeof ClipboardItem=="function"&&typeof navigator.clipboard?.write=="function")F$1=navigator.clipboard.write([new ClipboardItem({"text/plain":w,"text/html":D({marker:s},w)})]),F$1.catch(()=>{});else if(n==="cut"&&typeof navigator.clipboard?.writeText!="function")throw new z("Cut requires clipboard write access")}catch(W){P={error:W};}return {write:F$1,resolve:u,reject:v,refused:P,marker:s}},Ho=(n,s)=>{if(!en(n)){s.reject?.(new w("editor-unavailable"));return}let u=G.current,v=m$1.current,w$1=y.current,F=ae.current,P=Fe(w$1,v),W=normalizeRange(v);if(n==="paste"){let _=null;te.clipboard(()=>{let be=s.read,Rt=r$1.pending;return te.runAfterPendingInput(async()=>(await Rt,be),true)},({text:be,html:Rt})=>{_=r$1.paste(u,be,W,Rt,w$1);let yt=_?[]:E(be),nn=_?.edits??[],Ar=0;_||yt.forEach((sn,Qo)=>{Ar=Math.max(Ar,sn.length-1),sn.forEach((ei,ti)=>nn.push({row:W.top+Qo,col:W.left+ti,input:ei}));});let on={anchor:{row:W.top,col:W.left},focus:{row:_?.bottom??W.top+Math.max(0,yt.length-1),col:_?.right??W.left+Ar}};return G.current===u&&ae.current===F&&!K.ownsFocus&&!c.isPending(Ke())&&dt(w$1,on,false,true),{kind:"editCells",payload:{args:[w$1,nn],target:P,selection:Fe(w$1,on)}}}).result.then(be=>{_&&r$1.consume(_,be.status==="applied"&&be.committed===true);}).catch(Re);return}let z=()=>{if(G.current!==u||!u.current||u.retiring)throw new w("document-replaced");if(u.failure)throw u.failure},{write:V,resolve:he,reject:H,refused:$,marker:le}=s;if($){H($.error),Re($.error);return}let S=r$1.begin(void 0,le),U=te.runAfterPendingInput(async()=>{z();let _=await d(u.session,w$1,v),xe=await u.session.call.cellInputs(w$1,Hi(_));return z(),{range:_,cells:xe.cells}},n==="cut"?true:"posted").then(async({range:_,cells:xe})=>{z();let be=toTsv(xe);V?(he(new Blob([be],{type:"text/plain"})),await V):await navigator.clipboard.writeText(be),z(),n==="copy"&&r$1.capture(S,{owner:u,sheet:w$1,range:_,cells:xe,cut:false},!!V);});r$1.pending=U.catch(()=>{}),n==="cut"?te.clipboard(()=>U,()=>({kind:"applyOps",payload:{toolbar:{id:"clear",args:null,target:P},selection:P}})).result.catch(xe=>{H(xe),Re(xe);}):U.catch(_=>{H(_),Re(_);});},Tr=(n,s)=>{if(!b?.ready||b.failure||K.isComposing("cell")||K.isComposing("formula"))return;K.commit("cell"),K.commit("formula");let u=s??me(n);c.select(u,{...He(),apply:v=>{let w=Fe(n,v);return Ye(n,v),s&&ft(n,v.anchor),it({kind:"setActiveSheet",payload:{args:[n],target:w,selection:w}}),true}},n,true);};rt.current=n=>{Tr(y.current,selectionAt(n)),Se();};let qr=(n,s,u,v,w=false,F=b?.generation)=>{if(!b?.ready||!b.current||b.retiring||F!==b.generation||b.failure||!w&&!Ae()||u===0&&v===0)return;let P=Fe(n,m$1.current??selectionAt({row:0,col:0}));it({kind:"moveChart",payload:{args:[n,s,u,v],target:P}}),ue(null);},rr=(n=false)=>{let s=fe.current;fe.current=null,pe.current!==null&&clearTimeout(pe.current),pe.current=null,s&&qr(s.sheet,s.id,s.dx,s.dy,n,s.generation);};Xt.current=rr;let nr=useRef({moveChart:qr,flushNudge:rr});nr.current={moveChart:qr,flushNudge:rr},useEffect(()=>{let n=u=>{let v=ne.current;ne.current=false,v&&u.button===0&&ce(F=>F+1);let w=Te.current;Te.current=null,w&&u.button===0?nr.current.moveChart(w.sheet,w.id,(u.clientX-w.x)/w.zoom,(u.clientY-w.y)/w.zoom,false,w.generation):ue(null);},s=()=>{ne.current=false,Te.current=null,ue(null),nr.current.flushNudge();};return window.addEventListener("mouseup",n),window.addEventListener("blur",s),()=>{window.removeEventListener("mouseup",n),window.removeEventListener("blur",s),pe.current!==null&&clearTimeout(pe.current);}},[]);let Uo=Q({document:()=>G.current?.current?G.current:null,onSaveRequest:t.onSaveRequest,fail:Re});io(a,{requestSave:Uo,session:()=>b?.session??null,coordinator:te,status:()=>b?.ready?"ready":b&&!b.failure||Ut?"loading":"empty",readOnly:()=>f$1.current.readOnly??false,collaborative:()=>f$1.current.collaboration!==void 0,generation:()=>b?.generation??0,mutation:()=>M.current,selection:()=>Ft()??null,frame:()=>A$1.current?.captureCommandFrame()??void 0,selectionRevision:()=>ae.current,view:()=>({sheet:y.current,selection:m$1.current,chartSelected:we.current!==null,zoom:D$1.current,capturedFormat:null,borderStyle:vt.current,borderColor:ge.current,proposals:Ot.current,proposalsAvailable:isProposalsAvailable(),proposalsPanelOpen:Me.current,pngExport:b?.session.pngExport===true}),formatToken:()=>j.current,formatRevision:()=>Ee.current,setFormatToken:We,setZoom:n=>re(n),setBorderStyle:n=>{vt.current=n;},setBorderColor:n=>{ge.current=n;},setProposalsPanelOpen:n=>{bt(n),n&&Yt(true);},markStale:(n,s)=>Pt(({[n]:u,...v})=>s?{...v,[n]:s}:v),refreshProposals:()=>Yt(),i18n:()=>f$1.current.i18n,translate:e,fail:n=>b?.fail(n),afterPaint:()=>te.whenPresented().then(()=>true,()=>false),deliver(n){if(f$1.current.onSave&&f$1.current.onSave(n),f$1.current.downloadOnSave??!f$1.current.onSave){let s=URL.createObjectURL(new Blob([new Uint8Array(n)],{type:$i})),u=document.createElement("a");u.href=s,u.download=f$1.current.fileName??"workbook.xlsx",document.body.appendChild(u),u.click(),u.remove(),URL.revokeObjectURL(s);}},deliverPng(n){let s=URL.createObjectURL(new Blob([new Uint8Array(n)],{type:"image/png"})),u=document.createElement("a");u.href=s,u.download=`${(f$1.current.fileName??"workbook.xlsx").replace(/\.xlsx$/i,"")}.png`,document.body.appendChild(u),u.click(),u.remove(),URL.revokeObjectURL(s);},focusGrid:Se,refuse:n=>J({code:n.code})}),P(a,o);let Go=useCallback(()=>{let n=m$1.current,s=y.current;if(!ke||j.current!==ke||!n||!Ae()||ne.current||Ce.current!==null||jo()===ve.current)return;let u=Fe(s,n),v=b,w=++Ee.current;Ce.current=w;let F=A$1.current?.captureCommandFrame()??void 0,P=ae.current;te.runAfterPendingInput(()=>te.command({kind:"applyFormat",payload:{target:u,formatToken:ke,selection:u}},{frame:F,selectionRevision:P}).result).then(()=>{G.current!==v||!v?.current||Ee.current!==w||(We(null),a.refresh());}).catch(Re).finally(()=>{Ce.current===w&&(Ce.current=null);});},[ke,b,te,oe]),Bt=n=>{let s=A$1.current?.painted,u=l$1.current;if(!s||s.request.sheet!==y.current||!u)return {cell:null,chart:null};let v=u.getBoundingClientRect(),w=(n.clientX-v.left)/s.request.zoom,F=(n.clientY-v.top)/s.request.zoom;return {cell:s.geometry?cellAtPoint(s.geometry,w,F):null,chart:chartRegionAtPoint(s.displayList.charts,w,F)}},tn=n=>{let s=m$1.current;!b?.ready||!Ae()||!s||(ft(y.current,s.anchor),K.open(n));},Vo=n=>{if(Dt(n)||!b?.ready||b.failure||K.cellInput?.contains(n.target)||K.isComposing("cell")||K.isComposing("formula"))return;K.commit("cell"),K.commit("formula"),rr();let{cell:s,chart:u}=Bt(n);if(ie.current=null,u){de({id:u.id,movable:u.movable}),Ae()&&u.movable&&n.button===0&&(Te.current={generation:b.generation,sheet:y.current,id:u.id,zoom:A$1.current?.painted?.request.zoom??D$1.current,x:n.clientX,y:n.clientY}),Se(),n.preventDefault();return}de(null);let v=m$1.current;if(!s||n.shiftKey&&!v)return;let w=n.shiftKey?extendTo(v,s,St()):selectionAt(i(s,Ct()));dt(y.current,w,true),it({kind:"select",payload:{selection:Fe(y.current,w)}}),ie.current=s,ne.current=true,Se();},_o=n=>{if(Dt(n)||b?.failure)return;let s=Te.current;if(s){ue({x:n.clientX-s.x,y:n.clientY-s.y}),n.currentTarget.style.cursor="move";return}let{cell:u,chart:v}=Bt(n);if(ne.current&&u&&m$1.current){let F=extendTo(m$1.current,u,St());dt(y.current,F,true),it({kind:"select",payload:{selection:Fe(y.current,F)}});return}let w=u&&A$1.current?.painted?hyperlinkAtCell(A$1.current.painted.displayList,u.row,u.col):null;n.currentTarget.style.cursor=v?.movable&&Ae()?"move":v||w?"pointer":"default",n.currentTarget.title=v?"":w?.tooltip??"";},Jo=n=>{if(Dt(n)||b?.failure)return;let{cell:s}=Bt(n),u=ie.current;ie.current=null;let v=A$1.current?.painted?.displayList;if(!s||!u||!v||s.row!==u.row||s.col!==u.col)return;let w=hyperlinkAtCell(v,s.row,s.col);if(!w)return;let F=safeExternalHyperlink(w);if(F){window.open(F,"_blank","noopener,noreferrer");return}let P=b?.session.editState.sheets??b?.session.state.sheets??[],W=w.location?parseHyperlinkLocation(w.location,P[y.current]?.name??""):null;if(!W)return;let z=P.findIndex(V=>V.name.toLowerCase()===W.sheetName.toLowerCase());z>=0&&Tr(z,selectionAt(W));},Zo=n=>{if(Dt(n)||!b?.ready||b.failure||!m$1.current||!k.current||K.isComposing("formula")||q(n))return;let s=n.metaKey||n.ctrlKey;if(K.getSnapshot().cell){if(K.cellInput||K.key("cell",n))return;if(K.cellKey(n)){n.preventDefault();return}if(n.key==="Enter")K.commit("cell",n.shiftKey?"up":"down");else if(n.key==="Tab")K.commit("cell",n.shiftKey?"left":"right");else if(n.key==="Escape")K.cancel();else return;n.preventDefault();return}let v=we.current;if(v){if(n.key==="Escape"){Te.current=null,fe.current=null,ue(null),de(null),n.preventDefault();return}let $=!s&&Ki[n.key];if($&&Ae()&&v.movable){let le=n.shiftKey?10:1,S=fe.current??{generation:b.generation,sheet:y.current,id:v.id,dx:0,dy:0};fe.current={...S,dx:S.dx+$[0]*le,dy:S.dy+$[1]*le},ue({x:fe.current.dx*D$1.current,y:fe.current.dy*D$1.current}),pe.current!==null&&clearTimeout(pe.current);let Q=b;pe.current=setTimeout(()=>{Q.current&&!Q.retiring&&G.current===Q&&nr.current.flushNudge();},250),n.preventDefault();}return}let w$1=($,le)=>{c.beforeInput({...He(),apply:S=>(Ye(y.current,S),true)},$,le)||$();};if(s&&["c","x","v"].includes(n.key.toLowerCase())){let $=n.key.toLowerCase()==="c"?"copy":n.key.toLowerCase()==="x"?"cut":"paste";if(en($)){let le=Ko($),S=()=>le.reject?.(new w("editor-unavailable"));w$1(()=>K.getSnapshot().cell?S():Ho($,le),S);}n.preventDefault();return}let F=l(n),P=selectionKeyReducer(m$1.current,n,St(),void 0,Gt(),Ct()).type==="move";if(F||P){let $={key:n.key,ctrlKey:n.ctrlKey,metaKey:n.metaKey,shiftKey:n.shiftKey,altKey:n.altKey},le=()=>{if(K.getSnapshot().cell){if(K.cellKey($))return;$.key==="Enter"?K.commit("cell",$.shiftKey?"up":"down"):$.key==="Tab"&&K.commit("cell",$.shiftKey?"left":"right");return}c.enqueue($,He());};if(c.defer(Ke(),le,true)){n.preventDefault();return}n.preventDefault(),c.enqueue(n,He());return}let W={key:n.key,shiftKey:n.shiftKey,metaKey:n.metaKey,ctrlKey:n.ctrlKey,altKey:n.altKey},z=W.shiftKey&&W.key!=="Tab"&&W.key!=="Enter",V=$=>z?$:selectionAt($.anchor),he=()=>{let $=m$1.current;if(!$||we.current)return;if(K.getSnapshot().cell){if(K.cellKey(W))return;W.key==="Enter"?K.commit("cell",W.shiftKey?"up":"down"):W.key==="Tab"?K.commit("cell",W.shiftKey?"left":"right"):W.key==="Escape"&&K.cancel();return}let le=selectionKeyReducer(V($),W,St(),void 0,Gt(),Ct());le.type==="move"?(dt(y.current,le.selection),ft(y.current,le.selection.focus),it({kind:"select",payload:{selection:Fe(y.current,le.selection)}})):le.type==="startEdit"?tn(le.initialInput):le.type==="clear"&&$o();};if(selectionKeyReducer(V(m$1.current),W,St(),void 0,Gt(),Ct()).type==="none"){W.key==="Escape"&&c.defer(Ke(),he,true)&&n.preventDefault();return}n.preventDefault(),c.defer(Ke(),he,false)||he();},Wt=E$1,Yo=useMemo(()=>jsx(Ui,{}),[]),rn=t.showToolbar===false?null:t.toolbar===void 0?t.readOnly?null:Yo:t.toolbar,Er=n=>je.managed?jsx(Ga,{host:je.host,placement:n,activations:je.activations.filter(s=>s.plugin.panel?.placement===n),available:Bo}):null,or=A$1.current?.painted;return jsx(I.Provider,{value:a.store,children:jsx(S.Provider,{value:true,children:jsx(T.Provider,{value:true,children:jsx(wo,{onNavigate:Kt,controller:K,presentation:C,run:b,active:d$1,selectedChart:Be!==null,error:!!qe,readOnly:!!t.readOnly,navigation:ae,children:jsxs("div",{ref:o,className:t.className,role:"application","aria-label":e("editor.appLabel"),onKeyDownCapture:n=>{!Dt(n)&&n.key==="Escape"&&(r$1.cancelCut(),We(null),a.refresh());},style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,color:"#202124",background:"#ffffff",fontFamily:"ui-sans-serif, system-ui, sans-serif",...t.style},children:[t.file&&!b?.ready&&!qe&&t.loadingIndicator,jsx(qo,{store:C,onChange:Go}),rn!=null&&jsx("div",{"data-testid":"xlsx-toolbar",style:{flex:"0 0 auto"},children:rn}),jsxs("div",{ref:Lo,"data-testid":"xlsx-workspace",style:{position:"relative",display:"flex",flex:1,minHeight:0},children:[Er("left"),jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0},children:[isProposalsAvailable()&&Ve&&jsx(xa,{proposals:at,staleFor:wt,style:{top:4,right:8,width:"min(320px, calc(100% - 16px))",maxHeight:"min(420px, calc(100% - 12px))"}}),jsxs("div",{ref:i$1,"data-testid":"xlsx-scroll",tabIndex:0,onKeyDown:Zo,onMouseDown:Vo,onMouseMove:_o,onClick:Jo,onDoubleClick:n=>{if(Dt(n)||Bt(n).chart)return;let s=Bt(n).cell,u=A$1.current?.painted?.displayList;s&&u&&hyperlinkAtCell(u,s.row,s.col)||tn();},onMouseLeave:n=>{n.currentTarget.style.cursor="default",n.currentTarget.title="";},style:{position:"relative",flex:1,overflow:"auto",minHeight:0,outline:"none"},children:[jsx(Ro,{store:C,zoom:B$1}),jsxs("div",{style:{position:"sticky",top:0,left:0,width:0,height:0},children:[jsx("canvas",{ref:l$1,style:{display:"block",position:"absolute",top:0,left:0}}),jsx(Io,{store:C,active:d$1,zoom:B$1,selectedChart:Be,chartOffset:Ie,controller:K,run:b,disabled:!!qe||!!t.readOnly}),jsx(Eo,{store:C,run:b,provider:t.collaboration?.provider,active:d$1,sheets:Wt}),je.managed&&jsx(Ba,{host:je.host,activations:je.activations,layerRef:je.overlayLayerRef,width:(or?.displayList.width??0)*(or?.request.zoom??B$1),height:(or?.displayList.height??0)*(or?.request.zoom??B$1)})]})]}),Er("bottom")]}),Er("right"),qe&&Wt.length===0&&jsx(ya,{kind:"open",details:qe.message}),!t.file&&!qe&&jsx("div",{"data-testid":"xlsx-empty",role:"status",style:{position:"absolute",inset:0,display:"grid",placeItems:"center",color:"#5f6368",pointerEvents:"none"},children:e("editor.openPrompt")})]}),jsx(To,{store:C,active:d$1,sheets:Wt}),se&&jsxs("div",{"data-testid":"xlsx-input-refusal",role:"alert",children:[r(se.code,{translate:e}).message,se.detail?`: ${se.detail}`:""]}),qe&&Wt.length>0&&jsx(ya,{kind:"stopped",details:qe.message}),Wt.length>0&&jsx("div",{"data-testid":"xlsx-sheet-tabs",role:"tablist","aria-label":e("editor.sheetTabsLabel"),style:{display:"flex",gap:2,padding:"4px 6px",borderTop:"1px solid #e0e0e0",background:"#fafafa",overflowX:"auto"},children:Wt.map(n=>jsx("button",{role:"tab","aria-selected":n.index===d$1,disabled:!!qe,onClick:()=>Tr(n.index),style:{border:"none",padding:"4px 12px",cursor:"pointer",background:n.index===d$1?"#ffffff":"transparent",borderBottom:n.index===d$1?`2px solid ${zi}`:"2px solid transparent",fontWeight:n.index===d$1?600:400},children:n.name},n.id))})]})})})})})}export{Nl as XlsxPeerlessWorkerEditor};
|