@betteroffice/xlsx-react 0.0.5 → 0.0.6
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 +22 -1
- package/dist/index.d.ts +28 -4
- package/dist/index.js +1 -1
- package/package.json +16 -3
package/README.md
CHANGED
|
@@ -46,6 +46,27 @@ export function App() {
|
|
|
46
46
|
|
|
47
47
|
Props: `file` (a `Uint8Array` of `.xlsx` bytes — omit it to render an empty
|
|
48
48
|
frame), `fileName`, `onSave`, `onReady` (a handle for host/agent-driven edits),
|
|
49
|
-
and
|
|
49
|
+
`collaboration` (opens a network-ready replica and repaints peer updates), and
|
|
50
|
+
`className`.
|
|
51
|
+
|
|
52
|
+
Attach a transport provider from `onReady`:
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
import { CollaborationProvider } from "@betteroffice/xlsx/collaboration";
|
|
56
|
+
|
|
57
|
+
export function CollaborativeWorkbook() {
|
|
58
|
+
return (
|
|
59
|
+
<XlsxEditor
|
|
60
|
+
file={file}
|
|
61
|
+
collaboration={{ clientId }}
|
|
62
|
+
onReady={({ handle }) => {
|
|
63
|
+
const provider = new CollaborationProvider(handle, transport);
|
|
64
|
+
provider.connect();
|
|
65
|
+
return () => provider.destroy();
|
|
66
|
+
}}
|
|
67
|
+
/>
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
50
71
|
|
|
51
72
|
Docs: https://betteroffice.dev · Apache-2.0.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
+
import { ReactNode } from 'react';
|
|
2
3
|
import { WorkbookHandle } from '@betteroffice/xlsx';
|
|
4
|
+
import { CollaborationReplica } from '@betteroffice/xlsx/collaboration';
|
|
5
|
+
import { Translations, TFunction } from '@betteroffice/xlsx-i18n';
|
|
3
6
|
|
|
4
7
|
/**
|
|
5
8
|
* The imperative surface handed to {@link XlsxEditorProps.onReady}: the open
|
|
@@ -10,6 +13,14 @@ interface XlsxEditorApi {
|
|
|
10
13
|
handle: WorkbookHandle;
|
|
11
14
|
refreshProposals: () => void;
|
|
12
15
|
}
|
|
16
|
+
interface XlsxEditorCollaborationOptions {
|
|
17
|
+
/** Peer-unique Yrs client ID. Generated securely when omitted. */
|
|
18
|
+
clientId?: number;
|
|
19
|
+
/** Shared Yrs state applied before the replica is exposed. */
|
|
20
|
+
initialUpdate?: Uint8Array;
|
|
21
|
+
/** Receive the editor-owned collaboration replica. */
|
|
22
|
+
onReplica?: (replica: CollaborationReplica | null) => void;
|
|
23
|
+
}
|
|
13
24
|
/**
|
|
14
25
|
* Props for {@link XlsxEditor}.
|
|
15
26
|
*/
|
|
@@ -20,17 +31,30 @@ interface XlsxEditorProps {
|
|
|
20
31
|
fileName?: string;
|
|
21
32
|
/** Receive saved bytes instead of triggering a browser download. */
|
|
22
33
|
onSave?: (bytes: Uint8Array) => void;
|
|
34
|
+
/** Open a network-ready Yrs replica and repaint when peer updates arrive. */
|
|
35
|
+
collaboration?: XlsxEditorCollaborationOptions;
|
|
36
|
+
i18n?: Translations;
|
|
23
37
|
/**
|
|
24
38
|
* Called when a workbook opens, with a handle to stage agent proposals and a
|
|
25
39
|
* way to refresh the panel afterward. Enables demo/host agents without
|
|
26
|
-
* exposing the wasm object through the render tree.
|
|
40
|
+
* exposing the wasm object through the render tree. A returned cleanup runs
|
|
41
|
+
* before the workbook is replaced or disposed.
|
|
27
42
|
*/
|
|
28
|
-
onReady?: (api: XlsxEditorApi) => void;
|
|
43
|
+
onReady?: (api: XlsxEditorApi) => void | (() => void);
|
|
29
44
|
className?: string;
|
|
30
45
|
}
|
|
31
46
|
/**
|
|
32
47
|
* The xlsx editor React component.
|
|
33
48
|
*/
|
|
34
|
-
declare function XlsxEditor({
|
|
49
|
+
declare function XlsxEditor({ i18n, ...props }: XlsxEditorProps): react.JSX.Element;
|
|
50
|
+
|
|
51
|
+
interface LocaleProviderProps {
|
|
52
|
+
i18n?: Translations;
|
|
53
|
+
children: ReactNode;
|
|
54
|
+
}
|
|
55
|
+
declare function LocaleProvider({ i18n, children }: LocaleProviderProps): react.JSX.Element;
|
|
56
|
+
declare function useTranslation(): {
|
|
57
|
+
t: TFunction;
|
|
58
|
+
};
|
|
35
59
|
|
|
36
|
-
export { XlsxEditor, type XlsxEditorApi, type XlsxEditorProps };
|
|
60
|
+
export { LocaleProvider, type LocaleProviderProps, XlsxEditor, type XlsxEditorApi, type XlsxEditorCollaborationOptions, type XlsxEditorProps, useTranslation };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {useRef,useState,useMemo,useCallback,useEffect}from'react';import {isPngExportAvailable,isProposalsAvailable,initWasm,openWorkbook,selectionAt,paintDisplayList,buildA11yGrid,cellAtPoint,moveFocus,normalizeRange,toTsv,fromTsv,StaleProposalError,selectionKeyReducer,extendTo,rangeRect,cellRect}from'@betteroffice/xlsx';import {jsxs,jsx}from'react/jsx-runtime';var h={toolbar:{formulaPlaceholder:"Enter a value or formula",nameBoxPlaceholder:"Name box",undo:"Undo",redo:"Redo",save:"Save",exportPng:"Export PNG"},editor:{openError:"Couldn't open this workbook",sheetTabsLabel:"Sheets",appLabel:"Spreadsheet editor"},proposals:{toolbarButton:"Proposals",panelLabel:"Agent proposals",empty:"No pending proposals",cellCount:"{count} cells",cellCountOne:"1 cell",changeArrow:"\u2192",accept:"Accept",reject:"Reject",forceApply:"Force apply",staleWarning:"Cells changed since proposed: {cells}"},a11y:{gridLabel:"Spreadsheet grid",cellAnnouncement:"{address}, {value}",emptyCellAnnouncement:"{address}, empty",selectionAnnouncement:"Selected {count} cells",editingAnnouncement:"Editing {address}",rowHeaderLabel:"Row {row}",columnHeaderLabel:"Column {column}",cellLabel:"{address}, {value}",cellLabelSelected:"{address}, {value}, selected",emptyCellLabel:"{address}, empty",emptyCellLabelSelected:"{address}, empty, selected"}};function De({rect:r,color:a,newText:c,agentId:b}){return jsxs("div",{"data-testid":"xlsx-proposal-decoration","aria-hidden":"true",style:{position:"absolute",left:r.x,top:r.y,width:r.w,height:r.h,boxSizing:"border-box",border:`1.5px dashed ${a}`,pointerEvents:"none",overflow:"hidden"},children:[jsx("span",{style:{position:"absolute",left:0,right:0,bottom:1,textAlign:"center",opacity:.6,color:a,font:"11px system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",padding:"0 2px"},children:c}),jsx("span",{title:`${b}: ${c}`,style:{position:"absolute",top:0,right:0,width:6,height:6,background:a,pointerEvents:"auto"}})]})}var Ae=["#7c3aed","#0891b2","#c2410c","#4d7c0f","#be185d","#1d4ed8"];function nt(r){let a=2166136261;for(let c=0;c<r.length;c++)a^=r.charCodeAt(c),a=Math.imul(a,16777619);return (a>>>0)%Ae.length}function re(r){return Ae[nt(r)]}var M=h.proposals;function Me(r,a){return r.replace(/\{(\w+)\}/g,(c,b)=>String(a[b]??""))}function rt(r){return r===1?M.cellCountOne:Me(M.cellCount,{count:r})}function Ie({proposals:r,staleFor:a,onAccept:c,onReject:b}){return jsx("div",{"data-testid":"xlsx-proposals-panel",role:"region","aria-label":M.panelLabel,style:{position:"absolute",top:"100%",right:0,marginTop:4,width:320,maxHeight:420,overflowY:"auto",background:"#ffffff",border:"1px solid #d0d0d0",borderRadius:6,boxShadow:"0 6px 24px rgba(0, 0, 0, 0.16)",padding:8,zIndex:10,font:"13px system-ui, sans-serif",textAlign:"left"},children:r.length===0?jsx("div",{style:{padding:12,color:"#707070",textAlign:"center"},children:M.empty}):r.map(u=>{let i=re(u.agentId),P=a[u.id];return jsxs("div",{"data-testid":"xlsx-proposal","data-proposal-id":u.id,style:{borderLeft:`3px solid ${i}`,padding:"8px 10px",marginBottom:8,background:"#fafafa",borderRadius:4},children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[jsx("strong",{style:{color:i},children:u.agentId}),jsx("span",{style:{color:"#707070",fontSize:12},children:rt(u.cells.length)})]}),u.note&&jsx("div",{style:{color:"#404040",margin:"4px 0"},children:u.note}),jsx("ul",{style:{listStyle:"none",margin:"6px 0",padding:0},children:u.cells.map(d=>jsxs("li",{"data-testid":"xlsx-proposal-cell",style:{fontVariantNumeric:"tabular-nums",lineHeight:1.5},children:[jsx("strong",{"data-testid":"xlsx-proposal-cell-a1",children:d.a1}),":"," ",jsx("span",{style:{color:"#909090"},children:d.oldText||"\u2205"})," ",M.changeArrow," ",jsx("span",{"data-testid":"xlsx-proposal-cell-new",style:{color:i},children:d.newText})]},d.a1))}),P&&P.length>0&&jsx("div",{"data-testid":"xlsx-proposal-stale",role:"alert",style:{color:"#b45309",background:"#fef3c7",borderRadius:4,padding:"4px 6px",margin:"4px 0",fontSize:12},children:Me(M.staleWarning,{cells:P.join(", ")})}),jsxs("div",{style:{display:"flex",gap:6,marginTop:4},children:[jsx("button",{"data-testid":"xlsx-proposal-accept",onClick:()=>c(u.id),style:{padding:"3px 10px",cursor:"pointer"},children:M.accept}),P&&P.length>0&&jsx("button",{"data-testid":"xlsx-proposal-force",onClick:()=>c(u.id,true),style:{padding:"3px 10px",cursor:"pointer",color:"#b45309"},children:M.forceApply}),jsx("button",{"data-testid":"xlsx-proposal-reject",onClick:()=>b(u.id),style:{padding:"3px 10px",cursor:"pointer"},children:M.reject})]})]},u.id)})})}var H=96,K=24,U="#217346",bt="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function mt(r,a){let c=[{op:"fillRect",x:0,y:0,w:r,h:a,color:"#ffffff"}],b=Math.ceil(r/H),u=Math.ceil(a/K);for(let i=0;i<=b;i++)c.push({op:"line",x1:i*H,y1:0,x2:i*H,y2:a,width:1,color:"#e0e0e0"});for(let i=0;i<=u;i++)c.push({op:"line",x1:0,y1:i*K,x2:r,y2:i*K,width:1,color:"#e0e0e0"});return c.push({op:"fillRect",x:0,y:0,w:r,h:K,color:"#f3f3f3"}),c.push({op:"fillRect",x:0,y:0,w:H,h:a,color:"#f3f3f3"}),c.push({op:"text",x:H+8,y:K+18,text:"OpenOOXML xlsx",fontSize:14,color:"#202020",clip:{x:H,y:K,w:H*3,h:K},align:"left"}),{width:r,height:a,commands:c}}function Ke(r,a){if(!r||r.length<2)return a;let c=[];for(let u=1;u<r.length;u++)c.push(r[u]-r[u-1]);c.sort((u,i)=>u-i);let b=c[c.length>>1];return b>0?b:a}function yt(r,a,c){let b=Ke(r?.grid?.rowOffsets,K),u=Ke(r?.grid?.colOffsets,H),i=Math.max(1,Math.round(a.contentHeight/b))+1,P=Math.max(1,Math.round(a.contentWidth/u))+1,d=Math.max(1,Math.floor(c/b));return {rows:i,cols:P,rowsPerPage:d}}function We(r,a,c){let b=new Blob([new Uint8Array(r)],{type:c}),u=URL.createObjectURL(b),i=document.createElement("a");i.href=u,i.download=a,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(u);}function vt(r){return `${(r??"workbook.xlsx").replace(/\.xlsx$/i,"")}.png`}var wt={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"};function Et({file:r,fileName:a,onSave:c,onReady:b,className:u}){let i=useRef(null),P=useRef(null),d=useRef(null),ie=useRef(null),O=useRef(null),me=useRef(null),ce=useRef(false),_=useRef(false),ye=useRef(b);ye.current=b;let[p,W]=useState(null),[de,m]=useState(null),[G,Be]=useState(null),[s,E]=useState(null),[S,$]=useState(null),[ve,ue]=useState(null),[Y,X]=useState(null),[we,Oe]=useState(0),[V,q]=useState([]),[Ee,Se]=useState(false),[$e,J]=useState({}),x=p?.activeSheet??0,ke=useMemo(()=>isPngExportAvailable(),[]),Xe=useMemo(()=>isProposalsAvailable(),[]),B=useCallback(()=>{let e=d.current;if(!e){q([]);return}try{q(e.listProposals());}catch{q([]);}},[]);useEffect(()=>{if($(null),X(null),q([]),J({}),Se(false),!r){d.current=null,W(null),E(null),m(null);return}d.current=null,W(null),E(null);let e=null,t=false;return initWasm().then(()=>{if(!t)try{e=openWorkbook(r),d.current=e,W(e.sheetInfo()),E(selectionAt({row:0,col:0})),m(null),B(),ye.current?.({handle:e,refreshProposals:B});}catch(o){d.current=null,W(null),E(null),m(o instanceof Error?o.message:String(o));}},o=>{t||(d.current=null,W(null),E(null),m(o instanceof Error?o.message:String(o)));}),()=>{t=true,e?.dispose(),d.current=null;}},[r,B]);let pe=useCallback(()=>{let e=i.current,t=P.current;if(!e||!t)return;let o=t.getContext("2d");if(!o)return;let n=window.devicePixelRatio||1,l=e.clientWidth,w=e.clientHeight;if(l===0||w===0)return;t.width=Math.round(l*n),t.height=Math.round(w*n),t.style.width=`${l}px`,t.style.height=`${w}px`;let y=d.current,A;if(y)try{A=y.displayList({x:e.scrollLeft,y:e.scrollTop,width:l,height:w});}catch{return}else A=mt(l,w);paintDisplayList(o,A,n),ie.current=A,Be(A);},[]);useEffect(()=>{let e=i.current;if(!e)return;let t=()=>{O.current==null&&(O.current=requestAnimationFrame(()=>{O.current=null,pe();}));};pe(),e.addEventListener("scroll",t,{passive:true});let o=new ResizeObserver(t);return o.observe(e),()=>{e.removeEventListener("scroll",t),o.disconnect(),O.current!=null&&(cancelAnimationFrame(O.current),O.current=null);}},[pe,p,de,we]),useEffect(()=>{let e=d.current;if(!e||!s||!p){ue(null);return}try{ue(e.cell(x,s.focus.row,s.focus.col));}catch{ue(null);}},[s,p,x,we]),useEffect(()=>{let e=()=>{ce.current=false;};return window.addEventListener("mouseup",e),()=>window.removeEventListener("mouseup",e)},[]);let Q=useMemo(()=>!G||!p?null:buildA11yGrid(G,s,p.sheetNames[x]??"",h.a11y),[G,s,p,x]),L=useCallback(()=>{i.current?.focus({preventScroll:true});},[]);useEffect(()=>{S&&me.current?.focus({preventScroll:true});},[S]);let v=useCallback(e=>{W(e.sheetInfo),Oe(t=>t+1);},[]),D=useCallback(()=>yt(ie.current,p,i.current?.clientHeight??0),[p]),Z=useCallback((e,t)=>{let o=P.current,n=ie.current?.grid;if(!o||!n)return null;let l=o.getBoundingClientRect();return cellAtPoint(n,e-l.left,t-l.top)},[]),ee=useCallback(e=>{let t=d.current;if(!t||!s)return;let{row:o,col:n}=s.focus,l=e??"";if(e===void 0)try{l=t.cell(x,o,n).input;}catch{l="";}$({row:o,col:n,value:l});},[s,x]),fe=useCallback(e=>{let t=d.current;if(!t||!S)return;_.current=true;let{row:o,col:n,value:l}=S;try{v(t.editCell(x,o,n,l));}catch(y){m(y instanceof Error?y.message:String(y));}$(null);let w=selectionAt({row:o,col:n});E(e?moveFocus(w,e,{limits:D()}):w),L();},[S,x,v,D,L]),Fe=useCallback(()=>{_.current=true,$(null),L();},[L]),te=useCallback(()=>{let e=d.current;if(!e||!s)return;let t=normalizeRange(s),o=[];for(let n=t.top;n<=t.bottom;n++)for(let l=t.left;l<=t.right;l++)o.push({row:n,col:l,input:""});try{v(e.editCells(x,o));}catch(n){m(n instanceof Error?n.message:String(n));}},[s,x,v]),oe=useCallback(async()=>{let e=d.current;if(!e||!s)return;let t=normalizeRange(s);try{let o=e.cell(x,t.top,t.left).a1,n=e.cell(x,t.bottom,t.right).a1,l=e.rangeCells(x,`${o}:${n}`),w=toTsv(l.map(y=>y.map(A=>({input:A.input,isFormula:A.isFormula}))));await navigator.clipboard.writeText(w);}catch{}},[s,x]),Pe=useCallback(async()=>{await oe(),te();},[oe,te]),Ce=useCallback(async()=>{let e=d.current;if(!e||!s)return;let t;try{t=await navigator.clipboard.readText();}catch{return}let o=fromTsv(t);if(o.length===0)return;let n=normalizeRange(s),l=[],w=1;o.forEach((y,A)=>{w=Math.max(w,y.length),y.forEach((Ze,et)=>l.push({row:n.top+A,col:n.left+et,input:Ze}));});try{v(e.editCells(x,l));}catch(y){m(y instanceof Error?y.message:String(y));return}E({anchor:{row:n.top,col:n.left},focus:{row:n.top+o.length-1,col:n.left+w-1}});},[s,x,v]),he=useCallback(()=>{let e=d.current;if(e)try{v(e.undo());}catch(t){m(t instanceof Error?t.message:String(t));}},[v]),ne=useCallback(()=>{let e=d.current;if(e)try{v(e.redo());}catch(t){m(t instanceof Error?t.message:String(t));}},[v]),ze=useCallback((e,t)=>{let o=d.current;if(o)try{v(o.acceptProposal(e,{force:t})),J(({[e]:n,...l})=>l),B(),L();}catch(n){n instanceof StaleProposalError?J(l=>({...l,[e]:n.cells})):m(n instanceof Error?n.message:String(n));}},[v,B,L]),Ne=useCallback(e=>{let t=d.current;if(t)try{t.rejectProposal(e),J(({[e]:o,...n})=>n),B();}catch(o){m(o instanceof Error?o.message:String(o));}},[B]),ge=useCallback(()=>{let e=d.current;if(e)try{let t=e.save();c?c(t):We(t,a??"workbook.xlsx",bt);}catch(t){m(t instanceof Error?t.message:String(t));}},[c,a]),je=useCallback(()=>{let e=d.current,t=i.current;if(!(!e||!t))try{let o=e.renderPng({x:t.scrollLeft,y:t.scrollTop,width:t.clientWidth,height:t.clientHeight});We(o,vt(a),"image/png");}catch(o){m(o instanceof Error?o.message:String(o));}},[a]),Re=useCallback(e=>{let t=d.current;if(!t||!s||Y==null)return;let{row:o,col:n}=s.focus;try{v(t.editCell(x,o,n,Y));}catch(l){m(l instanceof Error?l.message:String(l));}X(null),e&&E(l=>l&&moveFocus(l,e,{limits:D()}));},[s,Y,x,v,D]),Ue=useCallback(e=>{if(!d.current||!s||!p||S)return;let o=e.metaKey||e.ctrlKey,n=e.key.toLowerCase();if(o){if(n==="c"){oe(),e.preventDefault();return}if(n==="v"){Ce(),e.preventDefault();return}if(n==="x"){Pe(),e.preventDefault();return}if(n==="z"){e.shiftKey?ne():he(),e.preventDefault();return}if(n==="y"){ne(),e.preventDefault();return}if(n==="s"){ge(),e.preventDefault();return}}let l=selectionKeyReducer(s,{key:e.key,shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey},D());switch(l.type){case "move":E(l.selection),e.preventDefault();break;case "startEdit":ee(l.initialInput),e.preventDefault();break;case "clear":te(),e.preventDefault();break;}},[s,p,S,D,oe,Ce,Pe,he,ne,ge,ee,te]),_e=useCallback(e=>{if(!s)return;let t=Z(e.clientX,e.clientY);t&&(e.shiftKey?E(o=>o&&extendTo(o,t,D())):E(selectionAt(t)),ce.current=true,L());},[s,Z,D,L]),Ge=useCallback(e=>{if(!ce.current)return;let t=Z(e.clientX,e.clientY);t&&E(o=>o&&extendTo(o,t,D()));},[Z,D]),Ye=useCallback(()=>{s&&ee();},[s,ee]),T=G?.grid,F=T&&s?rangeRect(T,normalizeRange(s)):null,z=T&&s?cellRect(T,s.focus.row,s.focus.col):null,N=T&&S?cellRect(T,S.row,S.col):null,Ve=p?p.contentWidth:void 0,qe=p?p.contentHeight:void 0,Je=Y??ve?.input??"",Qe=e=>{let t=d.current;if(t)try{t.setActiveSheet(e);let o=i.current;o&&(o.scrollLeft=0,o.scrollTop=0),E(selectionAt({row:0,col:0})),$(null),X(null),W(t.sheetInfo());}catch(o){m(o instanceof Error?o.message:String(o));}};return jsxs("div",{className:u,role:"application","aria-label":h.editor.appLabel,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%"},children:[jsxs("div",{"data-testid":"xlsx-toolbar",style:{display:"flex",gap:6,alignItems:"center",padding:"4px 6px",borderBottom:"1px solid #e0e0e0",background:"#fafafa"},children:[jsx("button",{"data-testid":"xlsx-save",onClick:ge,disabled:!p,style:{padding:"4px 12px",cursor:p?"pointer":"default"},children:h.toolbar.save}),jsx("button",{"data-testid":"xlsx-export-png",onClick:je,disabled:!p||!ke,title:h.toolbar.exportPng,style:{padding:"4px 12px",cursor:p&&ke?"pointer":"default"},children:h.toolbar.exportPng}),jsx("button",{"data-testid":"xlsx-undo",onClick:he,disabled:!p,"aria-label":h.toolbar.undo,title:h.toolbar.undo,style:{padding:"4px 10px"},children:"\u21B6"}),jsx("button",{"data-testid":"xlsx-redo",onClick:ne,disabled:!p,"aria-label":h.toolbar.redo,title:h.toolbar.redo,style:{padding:"4px 10px"},children:"\u21B7"}),jsx("input",{"data-testid":"xlsx-name-box",readOnly:true,value:ve?.a1??"",placeholder:h.toolbar.nameBoxPlaceholder,"aria-label":h.toolbar.nameBoxPlaceholder,style:{width:72,textAlign:"center"}}),jsx("input",{"data-testid":"xlsx-formula-input",value:Je,placeholder:h.toolbar.formulaPlaceholder,"aria-label":h.toolbar.formulaPlaceholder,disabled:!p,onChange:e=>X(e.target.value),onKeyDown:e=>{e.key==="Enter"?(Re(e.shiftKey?"up":"down"),L(),e.preventDefault()):e.key==="Escape"&&(X(null),L(),e.preventDefault());},onBlur:()=>Re(),style:{flex:1,minWidth:0}}),Xe&&jsxs("div",{style:{position:"relative"},children:[jsxs("button",{"data-testid":"xlsx-proposals-button",onClick:()=>Se(e=>!e),disabled:!p,"aria-expanded":Ee,"aria-label":h.proposals.panelLabel,style:{padding:"4px 12px",cursor:p?"pointer":"default"},children:[h.proposals.toolbarButton,V.length>0&&jsx("span",{"data-testid":"xlsx-proposals-count",style:{marginLeft:6,padding:"0 6px",borderRadius:8,background:U,color:"#ffffff",fontSize:12},children:V.length})]}),Ee&&jsx(Ie,{proposals:V,staleFor:$e,onAccept:ze,onReject:Ne})]})]}),jsxs("div",{ref:i,"data-testid":"xlsx-scroll",tabIndex:0,onKeyDown:Ue,onMouseDown:_e,onMouseMove:Ge,onDoubleClick:Ye,style:{position:"relative",flex:1,overflow:"auto",minHeight:0,outline:"none"},children:[jsx("div",{style:{position:"absolute",top:0,left:0,width:Ve??"100%",height:qe??"100%"}}),jsxs("div",{style:{position:"sticky",top:0,left:0,width:0,height:0},children:[jsx("canvas",{ref:P,style:{display:"block",position:"absolute",top:0,left:0}}),jsxs("div",{"data-testid":"xlsx-overlay-host",style:{position:"absolute",top:0,left:0,width:0,height:0,pointerEvents:"none"},children:[F&&jsx("div",{"data-testid":"xlsx-selection",style:{position:"absolute",left:F.x,top:F.y,width:F.w,height:F.h,boxSizing:"border-box",border:`1px solid ${U}`,background:"rgba(33, 115, 70, 0.12)"}}),z&&!S&&jsx("div",{style:{position:"absolute",left:z.x,top:z.y,width:z.w,height:z.h,boxSizing:"border-box",border:`2px solid ${U}`}}),T&&V.flatMap(e=>e.cells.map(t=>{if(t.sheet!==x)return null;let o=cellRect(T,t.row,t.col);return o?jsx(De,{rect:o,color:re(e.agentId),newText:t.newText,agentId:e.agentId},`${e.id}:${t.a1}`):null})),S&&N&&jsx("input",{ref:me,"data-testid":"xlsx-cell-editor",value:S.value,onChange:e=>$(t=>t&&{...t,value:e.target.value}),onKeyDown:e=>{e.stopPropagation(),e.key==="Enter"?(fe(e.shiftKey?"up":"down"),e.preventDefault()):e.key==="Tab"?(fe(e.shiftKey?"left":"right"),e.preventDefault()):e.key==="Escape"&&(Fe(),e.preventDefault());},onBlur:()=>{if(_.current){_.current=false;return}fe();},style:{position:"absolute",left:N.x,top:N.y,width:N.w,height:N.h,boxSizing:"border-box",border:`2px solid ${U}`,padding:"0 3px",font:"13px system-ui, sans-serif",background:"#ffffff",pointerEvents:"auto",outline:"none"}})]})]})]}),Q&&jsxs("div",{style:wt,role:"grid","aria-label":Q.label,children:[jsxs("div",{role:"row",children:[jsx("span",{role:"columnheader"}),Q.columnHeaders.map(e=>jsx("span",{role:"columnheader",children:e.label},e.col))]}),Q.rows.map(e=>jsxs("div",{role:"row",children:[jsx("span",{role:"rowheader",children:e.header}),e.cells.map(t=>jsx("span",{role:"gridcell","aria-selected":t.selected,children:t.label},t.col))]},e.row))]}),de&&jsxs("div",{"data-testid":"xlsx-error",role:"alert",style:{position:"absolute",inset:0,display:"grid",placeItems:"center",padding:16,textAlign:"center",color:"#b00020"},children:[h.editor.openError,": ",de]}),p&&p.sheetNames.length>0&&jsx("div",{"data-testid":"xlsx-sheet-tabs",role:"tablist","aria-label":h.editor.sheetTabsLabel,style:{display:"flex",gap:2,padding:"4px 6px",borderTop:"1px solid #e0e0e0",background:"#fafafa",overflowX:"auto"},children:p.sheetNames.map((e,t)=>{let o=t===p.activeSheet;return jsx("button",{role:"tab","aria-selected":o,onClick:()=>Qe(t),style:{border:"none",padding:"4px 12px",cursor:"pointer",borderBottom:o?`2px solid ${U}`:"2px solid transparent",fontWeight:o?600:400,background:o?"#ffffff":"transparent"},children:e},t)})})]})}export{Et as XlsxEditor};
|
|
1
|
+
import {createContext,useMemo,useContext,useRef,useState,useEffect,useCallback}from'react';import {isPngExportAvailable,isProposalsAvailable,initWasm,openWorkbook,selectionAt,paintDisplayList,buildA11yGrid,cellAtPoint,moveFocus,normalizeRange,toTsv,fromTsv,StaleProposalError,selectionKeyReducer,extendTo,rangeRect,cellRect}from'@betteroffice/xlsx';import {en,deepMerge,createT}from'@betteroffice/xlsx-i18n';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Ye=createContext(en),Ve=createContext("en");function de({i18n:r,children:i}){let u=typeof r?._lang=="string"?r._lang:"en",f=useMemo(()=>deepMerge(en,r),[r]);return jsx(Ve.Provider,{value:u,children:jsx(Ye.Provider,{value:f,children:i})})}function N(){let r=useContext(Ye),i=useContext(Ve);return {t:useMemo(()=>createT(r,i),[r,i])}}function qe({rect:r,color:i,newText:u,agentId:f}){return jsxs("div",{"data-testid":"xlsx-proposal-decoration","aria-hidden":"true",style:{position:"absolute",left:r.x,top:r.y,width:r.w,height:r.h,boxSizing:"border-box",border:`1.5px dashed ${i}`,pointerEvents:"none",overflow:"hidden"},children:[jsx("span",{style:{position:"absolute",left:0,right:0,bottom:1,textAlign:"center",opacity:.6,color:i,font:"11px system-ui, sans-serif",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",padding:"0 2px"},children:u}),jsx("span",{title:`${f}: ${u}`,style:{position:"absolute",top:0,right:0,width:6,height:6,background:i,pointerEvents:"auto"}})]})}var Je=["#7c3aed","#0891b2","#c2410c","#4d7c0f","#be185d","#1d4ed8"];function Pt(r){let i=2166136261;for(let u=0;u<r.length;u++)i^=r.charCodeAt(u),i=Math.imul(i,16777619);return (i>>>0)%Je.length}function ue(r){return Je[Pt(r)]}function Qe({proposals:r,staleFor:i,onAccept:u,onReject:f,style:y}){let{t:x}=N();return jsx("div",{"data-testid":"xlsx-proposals-panel",role:"region","aria-label":x("proposals.panelLabel"),style:{position:"absolute",top:"100%",right:0,marginTop:4,width:320,maxHeight:420,overflowY:"auto",background:"#ffffff",border:"1px solid #d0d0d0",borderRadius:10,boxShadow:"0 6px 24px rgba(0, 0, 0, 0.16)",padding:8,zIndex:10,font:"13px system-ui, sans-serif",textAlign:"left",...y},children:r.length===0?jsx("div",{style:{padding:12,color:"#707070",textAlign:"center"},children:x("proposals.empty")}):r.map(n=>{let w=ue(n.agentId),H=i[n.id];return jsxs("div",{"data-testid":"xlsx-proposal","data-proposal-id":n.id,style:{borderLeft:`3px solid ${w}`,padding:"8px 10px",marginBottom:8,background:"#fafafa",borderRadius:4},children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[jsx("strong",{style:{color:w},children:n.agentId}),jsx("span",{style:{color:"#707070",fontSize:12},children:x("proposals.cellCount",{count:n.cells.length})})]}),n.note&&jsx("div",{style:{color:"#404040",margin:"4px 0"},children:n.note}),jsx("ul",{style:{listStyle:"none",margin:"6px 0",padding:0},children:n.cells.map(A=>jsxs("li",{"data-testid":"xlsx-proposal-cell",style:{fontVariantNumeric:"tabular-nums",lineHeight:1.5},children:[jsx("strong",{"data-testid":"xlsx-proposal-cell-a1",children:A.a1}),":"," ",jsx("span",{style:{color:"#909090"},children:A.oldText||"\u2205"})," ",x("proposals.changeArrow")," ",jsx("span",{"data-testid":"xlsx-proposal-cell-new",style:{color:w},children:A.newText})]},A.a1))}),H&&H.length>0&&jsx("div",{"data-testid":"xlsx-proposal-stale",role:"alert",style:{color:"#b45309",background:"#fef3c7",borderRadius:4,padding:"4px 6px",margin:"4px 0",fontSize:12},children:x("proposals.staleWarning",{cells:H.join(", ")})}),jsxs("div",{style:{display:"flex",gap:6,marginTop:4},children:[jsx("button",{"data-testid":"xlsx-proposal-accept",onClick:()=>u(n.id),style:{padding:"3px 10px",cursor:"pointer"},children:x("proposals.accept")}),H&&H.length>0&&jsx("button",{"data-testid":"xlsx-proposal-force",onClick:()=>u(n.id,true),style:{padding:"3px 10px",cursor:"pointer",color:"#b45309"},children:x("proposals.forceApply")}),jsx("button",{"data-testid":"xlsx-proposal-reject",onClick:()=>f(n.id),style:{padding:"3px 10px",cursor:"pointer"},children:x("proposals.reject")})]})]},n.id)})})}var K=96,O=24,be="#217346",lt=46,Ot="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function zt(r,i,u){let f=[{op:"fillRect",x:0,y:0,w:r,h:i,color:"#ffffff"}],y=Math.ceil(r/K),x=Math.ceil(i/O);for(let n=0;n<=y;n++)f.push({op:"line",x1:n*K,y1:0,x2:n*K,y2:i,width:1,color:"#e0e0e0"});for(let n=0;n<=x;n++)f.push({op:"line",x1:0,y1:n*O,x2:r,y2:n*O,width:1,color:"#e0e0e0"});return f.push({op:"fillRect",x:0,y:0,w:r,h:O,color:"#f3f3f3"}),f.push({op:"fillRect",x:0,y:0,w:K,h:i,color:"#f3f3f3"}),f.push({op:"text",x:K+8,y:O+18,text:u,fontSize:14,color:"#202020",clip:{x:K,y:O,w:K*3,h:O},align:"left"}),{width:r,height:i,commands:f}}function ot(r,i){if(!r||r.length<2)return i;let u=[];for(let y=1;y<r.length;y++)u.push(r[y]-r[y-1]);u.sort((y,x)=>y-x);let f=u[u.length>>1];return f>0?f:i}function Ft(r,i,u){let f=ot(r?.grid?.rowOffsets,O),y=ot(r?.grid?.colOffsets,K),x=Math.max(1,Math.round(i.contentHeight/f))+1,n=Math.max(1,Math.round(i.contentWidth/y))+1,w=Math.max(1,Math.floor(u/f));return {rows:x,cols:n,rowsPerPage:w}}function nt(r,i,u){let f=new Blob([new Uint8Array(r)],{type:u}),y=URL.createObjectURL(f),x=document.createElement("a");x.href=y,x.download=i,document.body.appendChild(x),x.click(),x.remove(),URL.revokeObjectURL(y);}function $t(r){return `${(r??"workbook.xlsx").replace(/\.xlsx$/i,"")}.png`}var Ut={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},M={shell:{flex:"0 0 auto",minHeight:lt,padding:"4px 0 5px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",color:"#0f172a",boxSizing:"border-box"},rail:{display:"flex",alignItems:"center",minHeight:36,margin:"0 8px",padding:"4px 8px",borderRadius:999,background:"#f1f5f9",boxSizing:"border-box",overflowX:"auto",overflowY:"hidden"},group:{display:"inline-flex",alignItems:"center",gap:1,padding:"0 6px",borderRight:"1px solid rgba(226, 232, 240, 0.9)",flex:"0 0 auto"},formulaGroup:{display:"flex",alignItems:"center",gap:4,flex:"1 1 320px",minWidth:240,padding:"0 6px",borderRight:"1px solid rgba(226, 232, 240, 0.9)"},nameBox:{appearance:"none",width:64,height:28,flex:"0 0 auto",boxSizing:"border-box",border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#0f172a",font:"600 12px ui-monospace, SFMono-Regular, Menlo, monospace",textAlign:"center",outlineColor:"#2563eb"},formulaMark:{display:"grid",placeItems:"center",width:20,height:28,flex:"0 0 auto",color:"#64748b",font:"italic 700 12px Georgia, serif",userSelect:"none"},formulaInput:{appearance:"none",flex:"1 1 260px",minWidth:140,height:28,boxSizing:"border-box",border:"1px solid #e2e8f0",borderRadius:6,padding:"0 8px",background:"#ffffff",color:"#0f172a",font:"13px ui-sans-serif, system-ui, sans-serif",outlineColor:"#2563eb"},proposals:{marginLeft:"auto",paddingLeft:6,flex:"0 0 auto"},count:{display:"inline-grid",placeItems:"center",minWidth:15,height:15,marginLeft:-3,padding:"0 4px",borderRadius:8,background:"#0f172a",color:"#ffffff",fontSize:10,fontWeight:700,lineHeight:1,boxSizing:"border-box"}};function q(r,i=false){return {appearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:2,width:28,height:28,padding:0,border:0,borderRadius:6,background:i?"#0f172a":"transparent",color:r?i?"#ffffff":"#64748b":"#94a3b8",cursor:r?"pointer":"default",opacity:r?1:.32}}function J({name:r}){return jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{flex:"0 0 auto"},children:[r==="save"&&jsx("path",{d:"M12 3v11m0 0 4-4m-4 4-4-4M5 19h14"}),r==="image"&&jsxs(Fragment,{children:[jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),jsx("circle",{cx:"8.5",cy:"9.5",r:"1.25"}),jsx("path",{d:"m6 17 4.5-4.5 3.25 3.25L16 13.5l2 2"})]}),r==="undo"&&jsx("path",{d:"m9 7-5 5 5 5M5 12h9a6 6 0 0 1 6 6"}),r==="redo"&&jsx("path",{d:"m15 7 5 5-5 5m4-5h-9a6 6 0 0 0-6 6"}),r==="proposals"&&jsxs(Fragment,{children:[jsx("path",{d:"m12 3 1.25 3.75L17 8l-3.75 1.25L12 13l-1.25-3.75L7 8l3.75-1.25L12 3Z"}),jsx("path",{d:"m18 14 .75 2.25L21 17l-2.25.75L18 20l-.75-2.25L15 17l2.25-.75L18 14Z"})]})]})}function Nt({i18n:r,...i}){return jsx(de,{i18n:r,children:jsx(_t,{...i})})}function _t({file:r,fileName:i,onSave:u,collaboration:f,onReady:y,className:x}){let{t:n}=N(),w=f!==void 0,H=f?.clientId,A=f?.initialUpdate,Q=f?.onReplica,De=useRef(null),z=useRef(null),xe=useRef(null),b=useRef(null),he=useRef(null),$=useRef(null),Te=useRef(null),me=useRef(false),ee=useRef(false),Ie=useRef(y);Ie.current=y;let[d,X]=useState(null),[ye,v]=useState(null),[te,at]=useState(null),[c,C]=useState(null),[E,U]=useState(null),[Me,ve]=useState(null),[oe,_]=useState(null),[He,it]=useState(lt),[Ae,Xe]=useState(0),[j,ne]=useState([]),[we,Be]=useState(false),[Le,We]=useState(null),[st,G]=useState({}),m=d?.activeSheet??0,Ke=useMemo(()=>isPngExportAvailable(),[]),Oe=useMemo(()=>isProposalsAvailable(),[]);useEffect(()=>{let e=De.current;if(!e)return;let t=()=>it(e.offsetHeight);t();let o=new ResizeObserver(t);return o.observe(e),()=>o.disconnect()},[]);let B=useCallback(()=>{let e=b.current;if(!e){ne([]);return}try{ne(e.listProposals());}catch{ne([]);}},[]);useEffect(()=>{if(U(null),_(null),ne([]),G({}),Be(false),We(null),!r){b.current=null,X(null),C(null),v(null);return}b.current=null,X(null),C(null);let e=null,t=()=>{},o=()=>{},l=false,a=()=>{let p=o;o=()=>{};try{p();}catch{}};return initWasm().then(()=>{if(!l)try{e=openWorkbook(r,{collaborative:w,clientId:H}),A&&e.applyUpdate(A.slice()),b.current=e,t=e.onUpdate(()=>{if(!(l||!e))try{X(e.sheetInfo()),Xe(h=>h+1),G({}),B(),v(null);}catch(h){v(h instanceof Error?h.message:String(h));}}),X(e.sheetInfo()),C(selectionAt({row:0,col:0})),We(e),v(null),B();let p=Ie.current?.({handle:e,refreshProposals:B});typeof p=="function"&&(o=p);}catch(p){a(),t(),t=()=>{},e?.dispose(),e=null,b.current=null,X(null),C(null),v(p instanceof Error?p.message:String(p));}},p=>{l||(b.current=null,X(null),C(null),v(p instanceof Error?p.message:String(p)));}),()=>{l=true,a(),t(),e?.dispose(),b.current=null;}},[r,w,H,A,B]),useEffect(()=>{if(!(!Q||!Le))return Q(Le),()=>Q(null)},[Q,Le]);let Se=useCallback(()=>{let e=z.current,t=xe.current;if(!e||!t)return;let o=t.getContext("2d");if(!o)return;let l=window.devicePixelRatio||1,a=e.clientWidth,p=e.clientHeight;if(a===0||p===0)return;t.width=Math.round(a*l),t.height=Math.round(p*l),t.style.width=`${a}px`,t.style.height=`${p}px`;let h=b.current,T;if(h)try{T=h.displayList({x:e.scrollLeft,y:e.scrollTop,width:a,height:p});}catch{return}else T=zt(a,p,n("editor.demoCellText"));paintDisplayList(o,T,l),he.current=T,at(T);},[n]);useEffect(()=>{let e=z.current;if(!e)return;let t=()=>{$.current==null&&($.current=requestAnimationFrame(()=>{$.current=null,Se();}));};Se(),e.addEventListener("scroll",t,{passive:true});let o=new ResizeObserver(t);return o.observe(e),()=>{e.removeEventListener("scroll",t),o.disconnect(),$.current!=null&&(cancelAnimationFrame($.current),$.current=null);}},[Se,d,ye,Ae]),useEffect(()=>{let e=b.current;if(!e||!c||!d){ve(null);return}try{ve(e.cell(m,c.focus.row,c.focus.col));}catch{ve(null);}},[c,d,m,Ae]),useEffect(()=>{let e=()=>{me.current=false;};return window.addEventListener("mouseup",e),()=>window.removeEventListener("mouseup",e)},[]);let re=useMemo(()=>!te||!d?null:buildA11yGrid(te,c,d.sheetNames[m]??"",{gridLabel:n("a11y.gridLabel"),rowHeaderLabel:n("a11y.rowHeaderLabel"),columnHeaderLabel:n("a11y.columnHeaderLabel"),cellLabel:n("a11y.cellLabel"),cellLabelSelected:n("a11y.cellLabelSelected"),emptyCellLabel:n("a11y.emptyCellLabel"),emptyCellLabelSelected:n("a11y.emptyCellLabelSelected")}),[te,c,d,m,n]),k=useCallback(()=>{z.current?.focus({preventScroll:true});},[]);useEffect(()=>{E&&Te.current?.focus({preventScroll:true});},[E]);let S=useCallback(e=>{X(e.sheetInfo),Xe(t=>t+1);},[]),D=useCallback(()=>Ft(he.current,d,z.current?.clientHeight??0),[d]),le=useCallback((e,t)=>{let o=xe.current,l=he.current?.grid;if(!o||!l)return null;let a=o.getBoundingClientRect();return cellAtPoint(l,e-a.left,t-a.top)},[]),ae=useCallback(e=>{let t=b.current;if(!t||!c)return;let{row:o,col:l}=c.focus,a=e??"";if(e===void 0)try{a=t.cell(m,o,l).input;}catch{a="";}U({row:o,col:l,value:a});},[c,m]),Ce=useCallback(e=>{let t=b.current;if(!t||!E)return;ee.current=true;let{row:o,col:l,value:a}=E;try{S(t.editCell(m,o,l,a));}catch(h){v(h instanceof Error?h.message:String(h));}U(null);let p=selectionAt({row:o,col:l});C(e?moveFocus(p,e,{limits:D()}):p),k();},[E,m,S,D,k]),ct=useCallback(()=>{ee.current=true,U(null),k();},[k]),ie=useCallback(()=>{let e=b.current;if(!e||!c)return;let t=normalizeRange(c),o=[];for(let l=t.top;l<=t.bottom;l++)for(let a=t.left;a<=t.right;a++)o.push({row:l,col:a,input:""});try{S(e.editCells(m,o));}catch(l){v(l instanceof Error?l.message:String(l));}},[c,m,S]),se=useCallback(async()=>{let e=b.current;if(!e||!c)return;let t=normalizeRange(c);try{let o=e.cell(m,t.top,t.left).a1,l=e.cell(m,t.bottom,t.right).a1,a=e.rangeCells(m,`${o}:${l}`),p=toTsv(a.map(h=>h.map(T=>({input:T.input,isFormula:T.isFormula}))));await navigator.clipboard.writeText(p);}catch{}},[c,m]),ze=useCallback(async()=>{await se(),ie();},[se,ie]),Fe=useCallback(async()=>{let e=b.current;if(!e||!c)return;let t;try{t=await navigator.clipboard.readText();}catch{return}let o=fromTsv(t);if(o.length===0)return;let l=normalizeRange(c),a=[],p=1;o.forEach((h,T)=>{p=Math.max(p,h.length),h.forEach((wt,Lt)=>a.push({row:l.top+T,col:l.left+Lt,input:wt}));});try{S(e.editCells(m,a));}catch(h){v(h instanceof Error?h.message:String(h));return}C({anchor:{row:l.top,col:l.left},focus:{row:l.top+o.length-1,col:l.left+p-1}});},[c,m,S]),Ee=useCallback(()=>{let e=b.current;if(!(!e||w))try{S(e.undo());}catch(t){v(t instanceof Error?t.message:String(t));}},[S,w]),ce=useCallback(()=>{let e=b.current;if(!(!e||w))try{S(e.redo());}catch(t){v(t instanceof Error?t.message:String(t));}},[S,w]),dt=useCallback((e,t)=>{let o=b.current;if(o)try{S(o.acceptProposal(e,{force:t})),G(({[e]:l,...a})=>a),B(),k();}catch(l){l instanceof StaleProposalError?G(a=>({...a,[e]:l.cells})):v(l instanceof Error?l.message:String(l));}},[S,B,k]),ut=useCallback(e=>{let t=b.current;if(t)try{t.rejectProposal(e),G(({[e]:o,...l})=>l),B();}catch(o){v(o instanceof Error?o.message:String(o));}},[B]),Pe=useCallback(()=>{let e=b.current;if(e)try{let t=e.save();u?u(t):nt(t,i??"workbook.xlsx",Ot);}catch(t){v(t instanceof Error?t.message:String(t));}},[u,i]),pt=useCallback(()=>{let e=b.current,t=z.current;if(!(!e||!t))try{let o=e.renderPng({x:t.scrollLeft,y:t.scrollTop,width:t.clientWidth,height:t.clientHeight});nt(o,$t(i),"image/png");}catch(o){v(o instanceof Error?o.message:String(o));}},[i]),$e=useCallback(e=>{let t=b.current;if(!t||!c||oe==null)return;let{row:o,col:l}=c.focus;try{S(t.editCell(m,o,l,oe));}catch(a){v(a instanceof Error?a.message:String(a));}_(null),e&&C(a=>a&&moveFocus(a,e,{limits:D()}));},[c,oe,m,S,D]),ft=useCallback(e=>{if(!b.current||!c||!d||E)return;let o=e.metaKey||e.ctrlKey,l=e.key.toLowerCase();if(o){if(l==="c"){se(),e.preventDefault();return}if(l==="v"){Fe(),e.preventDefault();return}if(l==="x"){ze(),e.preventDefault();return}if(l==="z"){e.shiftKey?ce():Ee(),e.preventDefault();return}if(l==="y"){ce(),e.preventDefault();return}if(l==="s"){Pe(),e.preventDefault();return}}let a=selectionKeyReducer(c,{key:e.key,shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey},D());switch(a.type){case "move":C(a.selection),e.preventDefault();break;case "startEdit":ae(a.initialInput),e.preventDefault();break;case "clear":ie(),e.preventDefault();break;}},[c,d,E,D,se,Fe,ze,Ee,ce,Pe,ae,ie]),gt=useCallback(e=>{if(!c)return;let t=le(e.clientX,e.clientY);t&&(e.shiftKey?C(o=>o&&extendTo(o,t,D())):C(selectionAt(t)),me.current=true,k());},[c,le,D,k]),bt=useCallback(e=>{if(!me.current)return;let t=le(e.clientX,e.clientY);t&&C(o=>o&&extendTo(o,t,D()));},[le,D]),xt=useCallback(()=>{c&&ae();},[c,ae]),W=te?.grid,Y=W&&c?rangeRect(W,normalizeRange(c)):null,V=W&&c?cellRect(W,c.focus.row,c.focus.col):null,Z=W&&E?cellRect(W,E.row,E.col):null,ht=d?d.contentWidth:void 0,mt=d?d.contentHeight:void 0,yt=oe??Me?.input??"",vt=e=>{let t=b.current;if(t)try{t.setActiveSheet(e);let o=z.current;o&&(o.scrollLeft=0,o.scrollTop=0),C(selectionAt({row:0,col:0})),U(null),_(null),X(t.sheetInfo());}catch(o){v(o instanceof Error?o.message:String(o));}};return jsxs("div",{className:x,role:"application","aria-label":n("editor.appLabel"),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"},children:[jsx("div",{ref:De,"data-testid":"xlsx-toolbar",style:M.shell,children:jsxs("div",{style:M.rail,role:"group","aria-label":n("toolbar.actionsLabel"),children:[jsxs("div",{style:{...M.group,paddingLeft:0},role:"group","aria-label":n("toolbar.fileActionsLabel"),children:[jsx("button",{type:"button","data-testid":"xlsx-save",onClick:Pe,disabled:!d,"aria-label":n("toolbar.save"),title:n("toolbar.save"),style:q(!!d),children:jsx(J,{name:"save"})}),jsx("button",{type:"button","data-testid":"xlsx-export-png",onClick:pt,disabled:!d||!Ke,"aria-label":n("toolbar.exportPng"),title:n("toolbar.exportPng"),style:q(!!(d&&Ke)),children:jsx(J,{name:"image"})})]}),jsxs("div",{style:M.group,role:"group","aria-label":n("toolbar.historyLabel"),children:[jsx("button",{type:"button","data-testid":"xlsx-undo",onClick:Ee,disabled:!d||w,"aria-label":n("toolbar.undo"),title:n("toolbar.undo"),style:q(!!(d&&!w)),children:jsx(J,{name:"undo"})}),jsx("button",{type:"button","data-testid":"xlsx-redo",onClick:ce,disabled:!d||w,"aria-label":n("toolbar.redo"),title:n("toolbar.redo"),style:q(!!(d&&!w)),children:jsx(J,{name:"redo"})})]}),jsxs("div",{style:M.formulaGroup,role:"group","aria-label":n("toolbar.formulaBarLabel"),children:[jsx("input",{"data-testid":"xlsx-name-box",readOnly:true,value:Me?.a1??"",placeholder:n("toolbar.nameBoxPlaceholder"),"aria-label":n("toolbar.nameBoxPlaceholder"),style:M.nameBox}),jsx("span",{style:M.formulaMark,"aria-hidden":"true",children:"fx"}),jsx("input",{"data-testid":"xlsx-formula-input",value:yt,placeholder:n("toolbar.formulaPlaceholder"),"aria-label":n("toolbar.formulaPlaceholder"),disabled:!d,onChange:e=>_(e.target.value),onKeyDown:e=>{e.key==="Enter"?($e(e.shiftKey?"up":"down"),k(),e.preventDefault()):e.key==="Escape"&&(_(null),k(),e.preventDefault());},onBlur:()=>$e(),style:M.formulaInput})]}),Oe&&jsx("div",{style:M.proposals,children:jsxs("button",{type:"button","data-testid":"xlsx-proposals-button",onClick:()=>Be(e=>!e),disabled:!d,"aria-expanded":we,"aria-label":n("proposals.panelLabel"),title:n("proposals.panelLabel"),style:{...q(!!d,we),width:j.length>0?42:28},children:[jsx(J,{name:"proposals"}),j.length>0&&jsx("span",{"data-testid":"xlsx-proposals-count",style:M.count,children:j.length})]})})]})}),Oe&&we&&jsx(Qe,{proposals:j,staleFor:st,onAccept:dt,onReject:ut,style:{top:He+4,right:8,width:"min(320px, calc(100% - 16px))",maxHeight:`min(420px, calc(100% - ${He+12}px))`}}),jsxs("div",{ref:z,"data-testid":"xlsx-scroll",tabIndex:0,onKeyDown:ft,onMouseDown:gt,onMouseMove:bt,onDoubleClick:xt,style:{position:"relative",flex:1,overflow:"auto",minHeight:0,outline:"none"},children:[jsx("div",{style:{position:"absolute",top:0,left:0,width:ht??"100%",height:mt??"100%"}}),jsxs("div",{style:{position:"sticky",top:0,left:0,width:0,height:0},children:[jsx("canvas",{ref:xe,style:{display:"block",position:"absolute",top:0,left:0}}),jsxs("div",{"data-testid":"xlsx-overlay-host",style:{position:"absolute",top:0,left:0,width:0,height:0,pointerEvents:"none"},children:[Y&&jsx("div",{"data-testid":"xlsx-selection",style:{position:"absolute",left:Y.x,top:Y.y,width:Y.w,height:Y.h,boxSizing:"border-box",border:`1px solid ${be}`,background:"rgba(33, 115, 70, 0.12)"}}),V&&!E&&jsx("div",{style:{position:"absolute",left:V.x,top:V.y,width:V.w,height:V.h,boxSizing:"border-box",border:`2px solid ${be}`}}),W&&j.flatMap(e=>e.cells.map(t=>{if(t.sheet!==m)return null;let o=cellRect(W,t.row,t.col);return o?jsx(qe,{rect:o,color:ue(e.agentId),newText:t.newText,agentId:e.agentId},`${e.id}:${t.a1}`):null})),E&&Z&&jsx("input",{ref:Te,"data-testid":"xlsx-cell-editor",value:E.value,onChange:e=>U(t=>t&&{...t,value:e.target.value}),onKeyDown:e=>{e.stopPropagation(),e.key==="Enter"?(Ce(e.shiftKey?"up":"down"),e.preventDefault()):e.key==="Tab"?(Ce(e.shiftKey?"left":"right"),e.preventDefault()):e.key==="Escape"&&(ct(),e.preventDefault());},onBlur:()=>{if(ee.current){ee.current=false;return}Ce();},style:{position:"absolute",left:Z.x,top:Z.y,width:Z.w,height:Z.h,boxSizing:"border-box",border:`2px solid ${be}`,padding:"0 3px",font:"13px system-ui, sans-serif",background:"#ffffff",pointerEvents:"auto",outline:"none"}})]})]})]}),re&&jsxs("div",{style:Ut,role:"grid","aria-label":re.label,children:[jsxs("div",{role:"row",children:[jsx("span",{role:"columnheader"}),re.columnHeaders.map(e=>jsx("span",{role:"columnheader",children:e.label},e.col))]}),re.rows.map(e=>jsxs("div",{role:"row",children:[jsx("span",{role:"rowheader",children:e.header}),e.cells.map(t=>jsx("span",{role:"gridcell","aria-selected":t.selected,children:t.label},t.col))]},e.row))]}),ye&&jsxs("div",{"data-testid":"xlsx-error",role:"alert",style:{position:"absolute",inset:0,display:"grid",placeItems:"center",padding:16,textAlign:"center",color:"#b00020"},children:[n("editor.openError"),": ",ye]}),d&&d.sheetNames.length>0&&jsx("div",{"data-testid":"xlsx-sheet-tabs",role:"tablist","aria-label":n("editor.sheetTabsLabel"),style:{display:"flex",gap:2,padding:"4px 6px",borderTop:"1px solid #e0e0e0",background:"#fafafa",overflowX:"auto"},children:d.sheetNames.map((e,t)=>{let o=t===d.activeSheet;return jsx("button",{role:"tab","aria-selected":o,onClick:()=>vt(t),style:{border:"none",padding:"4px 12px",cursor:"pointer",borderBottom:o?`2px solid ${be}`:"2px solid transparent",fontWeight:o?600:400,background:o?"#ffffff":"transparent"},children:e},t)})})]})}export{de as LocaleProvider,Nt as XlsxEditor,N as useTranslation};
|
package/package.json
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@betteroffice/xlsx-react",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "React
|
|
3
|
+
"version": "0.0.6",
|
|
4
|
+
"description": "Excel-faithful React XLSX spreadsheet editor and viewer — full OOXML fidelity, real-time human + AI agent collaboration.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"xlsx",
|
|
7
|
+
"excel",
|
|
8
|
+
"spreadsheet",
|
|
9
|
+
"ooxml",
|
|
10
|
+
"editor",
|
|
11
|
+
"viewer",
|
|
12
|
+
"react",
|
|
13
|
+
"collaborative",
|
|
14
|
+
"real-time",
|
|
15
|
+
"ai-agent"
|
|
16
|
+
],
|
|
5
17
|
"type": "module",
|
|
6
18
|
"sideEffects": false,
|
|
7
19
|
"main": "./dist/index.js",
|
|
@@ -21,7 +33,8 @@
|
|
|
21
33
|
"typecheck": "tsc --noEmit -p ."
|
|
22
34
|
},
|
|
23
35
|
"dependencies": {
|
|
24
|
-
"@betteroffice/xlsx": "0.0.
|
|
36
|
+
"@betteroffice/xlsx": "0.0.6",
|
|
37
|
+
"@betteroffice/xlsx-i18n": "0.0.6"
|
|
25
38
|
},
|
|
26
39
|
"peerDependencies": {
|
|
27
40
|
"react": "^18.0.0 || ^19.0.0",
|