@opengrid-ui/plugin-excel 0.0.0-stage → 0.1.37
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/LICENSE +21 -0
- package/dist/LICENSE +21 -0
- package/dist/engine/read-csv.d.ts +5 -0
- package/dist/engine/workbook.test.d.ts +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +7 -0
- package/dist/llms.txt +164 -0
- package/dist/skills/opengrid/SKILL.md +24 -0
- package/dist/workbook/read.d.ts +2 -0
- package/dist/workbook/types.d.ts +35 -0
- package/dist/workbook/write.d.ts +9 -0
- package/dist/workbook/xml.d.ts +11 -0
- package/package.json +1 -6
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Han-wangyu and OpenGrid contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Han-wangyu and OpenGrid contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { writeWorkbook, rowsFromSnapshot } from './workbook/write.js';
|
|
2
|
+
export type { RowSnapshot } from './workbook/write.js';
|
|
3
|
+
export { readWorkbook } from './workbook/read.js';
|
|
4
|
+
export { readCSV } from './engine/read-csv.js';
|
|
5
|
+
export type { CSVOptions } from './engine/read-csv.js';
|
|
6
|
+
export type { ExportColumn, WorkbookCell, WorkbookOptions, WorkbookReadRow, WorkbookSheet, WorkbookStyle } from './workbook/types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{strToU8 as Y,Zip as ee,ZipDeflate as te}from"fflate";var v='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',R="http://schemas.openxmlformats.org/spreadsheetml/2006/main",I="http://schemas.openxmlformats.org/officeDocument/2006/relationships",P="http://schemas.openxmlformats.org/package/2006/relationships",K={"&":"&","<":"<",">":">",'"':""","'":"'"};function T(o){return o.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g,"").replace(/[&<>"']/g,e=>K[e])}function V(o){return"_x"+o.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")+"_"}function N(o,e=!1){let t=o.replace(/_(?=x[\da-fA-F]{4}_)|[\u0000-\u0008\u000b-\u001f\ud800-\udfff\ufffe\uffff]/gu,V);return T(e?t.replace(/[\t\n]/g,V):t)}function _(o){return o.replace(/_x([\da-fA-F]{4})_/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}function D(o){let e="";for(let t=o+1;t>0;t=Math.floor((t-1)/26))e=String.fromCharCode(65+(t-1)%26)+e;return e}function M(o){let e=0;for(let t of o.match(/^[A-Z]+/i)?.[0].toUpperCase()??"")e=e*26+t.charCodeAt(0)-64;return Math.max(0,e-1)}function j(o){let e=o.replace(/^#/,"");if(!/^(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e))throw new Error("Use six or eight hexadecimal digits for a workbook color");return(e.length===6?"FF"+e:e).toUpperCase()}function z(o){let e=[],t=['<font><sz val="11"/><name val="Calibri"/></font>'],r=['<fill><patternFill patternType="none"/></fill>','<fill><patternFill patternType="gray125"/></fill>'],a=['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];for(let s of o){let i=0,l=0,f=0;s.numberFormat&&(i=164+e.length,e.push(`<numFmt numFmtId="${i}" formatCode="${T(s.numberFormat)}"/>`)),(s.bold||s.fontColor)&&(l=t.length,t.push(`<font><sz val="11"/><name val="Calibri"/>${s.bold?"<b/>":""}${s.fontColor?`<color rgb="${j(s.fontColor)}"/>`:""}</font>`)),s.fillColor&&(f=r.length,r.push(`<fill><patternFill patternType="solid"><fgColor rgb="${j(s.fillColor)}"/><bgColor indexed="64"/></patternFill></fill>`));let u=s.align?`<alignment horizontal="${s.align}"/>`:"";a.push(`<xf xfId="0" borderId="0" fontId="${l}" fillId="${f}" numFmtId="${i}" applyFont="1" applyFill="1" applyNumberFormat="1" applyAlignment="${s.align?1:0}">${u}</xf>`)}return v+`<styleSheet xmlns="${R}">
|
|
2
|
+
<numFmts count="${e.length}">${e.join("")}</numFmts>
|
|
3
|
+
<fonts count="${t.length}">${t.join("")}</fonts><fills count="${r.length}">${r.join("")}</fills>
|
|
4
|
+
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
|
|
5
|
+
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
|
|
6
|
+
<cellXfs count="${a.length}">${a.join("")}</cellXfs>
|
|
7
|
+
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`}var oe="http://schemas.openxmlformats.org/package/2006/content-types",re=1048576,Z=16384,ne={bold:!0,fillColor:"EDF2FA",fontColor:"172534"};function se(o,e){let t=o.map((a,s)=>`<sheet name="${N(a.name,!0)}" sheetId="${s+1}" r:id="rId${s+1}"/>`).join(""),r=o.map((a,s)=>`<Relationship Id="rId${s+1}" Type="${I}/worksheet" Target="worksheets/sheet${s+1}.xml"/>`).join(""),n=o.map((a,s)=>`<Override PartName="/xl/worksheets/sheet${s+1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join("");return{"[Content_Types].xml":v+`<Types xmlns="${oe}"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>${n}</Types>`,"_rels/.rels":v+`<Relationships xmlns="${P}"><Relationship Id="rId1" Type="${I}/officeDocument" Target="xl/workbook.xml"/></Relationships>`,"xl/workbook.xml":v+`<workbook xmlns="${R}" xmlns:r="${I}"><sheets>${t}</sheets></workbook>`,"xl/_rels/workbook.xml.rels":v+`<Relationships xmlns="${P}">${r}<Relationship Id="rIdStyles" Type="${I}/styles" Target="styles.xml"/></Relationships>`,"xl/styles.xml":z(e)}}function ae(o,e,t){let r=o!==null&&typeof o=="object"?o.value:o,n=`<c r="${e}" s="${t}"`;return r===null?n+"/>":typeof r=="number"&&Number.isFinite(r)?n+`><v>${r}</v></c>`:typeof r=="boolean"?n+` t="b"><v>${Number(r)}</v></c>`:n+` t="inlineStr"><is><t xml:space="preserve">${N(String(r))}</t></is></c>`}function ie(o,e,t){let r=o!==null&&typeof o=="object"?o.style:void 0;return t.get(r??e??"")??0}function le(o){if(!o.length)throw new Error("A workbook requires at least one sheet");let e=new Set;for(let t of o){if(!t.name||t.name.length>31||/[\\/?*:[\]]/.test(t.name)||e.has(t.name.toLowerCase()))throw new Error(`Invalid or duplicate sheet name: ${t.name}`);if(e.add(t.name.toLowerCase()),t.columns.length>Z)throw new Error("A sheet cannot exceed 16,384 columns")}}function W(o,e){return new Promise((t,r)=>{let n=()=>r(e.reason);e.aborted?n():e.addEventListener("abort",n,{once:!0}),o.then(t,r).finally(()=>e.removeEventListener("abort",n))})}async function*ce(o,e){let t=o[Symbol.asyncIterator](),r=!1;try{for(;;){e.throwIfAborted();let n=await W(t.next(),e);if(n.done){r=!0;return}e.throwIfAborted(),yield n.value}}finally{if(!r&&t.return){let n=Promise.resolve().then(()=>t.return?.());await W(n,e).catch(()=>{})}}}async function fe(o,e={}){e.signal?.throwIfAborted(),le(o);let t=e.sink?.getWriter(),r=new AbortController,{signal:n}=r,a=()=>r.abort(e.signal?.reason);e.signal?.addEventListener("abort",a,{once:!0}),t?.closed.catch(m=>r.abort(m));let s=[],i=!1,l=new ee((m,b,y)=>{if(m){r.abort(m);return}s.push(b),i=y});async function f(){if(n.throwIfAborted(),!!t){for(let m of s)n.throwIfAborted(),await W(t.write(m),n);s.length=0}}function u(m){let b=new te(m,{level:3});return l.add(b),(y,x=!1)=>b.push(Y(y),x)}try{let m=[["__header",ne],...Object.entries(e.styles??{})],b=new Map(m.map(([h],c)=>[h,c+1]));for(let[h,c]of Object.entries(se(o,m.map(([,g])=>g))))u(h)(c,!0);await f();let y=performance.now();for(let[h,c]of o.entries()){let F=function(w,k){if(S++,S>re||w.length>Z)throw new Error("The sheet exceeds Excel worksheet dimensions");C+=`<row r="${S}">${w.map((U,O)=>{let J=ie(U,k?"__header":c.columns[O]?.style,b);return ae(U,D(O)+String(S),J)}).join("")}</row>`};var d=F;n.throwIfAborted();let g=u(`xl/worksheets/sheet${h+1}.xml`),$=c.columns.map(({width:w},k)=>w===void 0?"":`<col min="${k+1}" max="${k+1}" width="${w}" customWidth="1"/>`).join("");g(v+`<worksheet xmlns="${R}">${$?`<cols>${$}</cols>`:""}<sheetData>`);let S=0,C="";for(let w of c.headers??[c.columns.map(k=>k.header)])F(w,!0);let G=Symbol.asyncIterator in c.rows?ce(c.rows,n):c.rows;for await(let w of G)n.throwIfAborted(),F(w,!1),S%256===0&&(g(C),C="",await f(),performance.now()-y>=8&&(await new Promise(k=>setTimeout(k,0)),n.throwIfAborted(),y=performance.now()));n.throwIfAborted();let Q=c.merges?.length?`<mergeCells count="${c.merges.length}">${c.merges.map(w=>`<mergeCell ref="${T(w)}"/>`).join("")}</mergeCells>`:"";g(C+"</sheetData>"+Q+"</worksheet>",!0),await f()}if(l.end(),await f(),n.throwIfAborted(),!i)throw new Error("Incomplete workbook archive");await t?.close();let x=new Uint8Array(s.reduce((h,c)=>h+c.length,0)),p=0;for(let h of s)x.set(h,p),p+=h.length;return x}catch(m){throw l.terminate(),t&&await W(t.abort(m),n).catch(()=>{}),m}finally{e.signal?.removeEventListener("abort",a),t?.releaseLock()}}async function*me(o,e=512){if(!Number.isInteger(e)||e<=0)throw new Error("Snapshot blocks must have positive integer size");let{revision:t,total:r}=o;for(let n=0;n<r;n+=e){let a=Math.min(r,n+e),s=await o.read([n,a],t);if(s.length!==a-n)throw new Error("Snapshot size changed during export");yield*s}}import{SaxesParser as E}from"saxes";import{unzipRaw as ue}from"unzipit";var X=new URL("https://workbook.invalid/"),de=["http://schemas.openxmlformats.org/officeDocument/2006/relationships","http://purl.oclc.org/ooxml/officeDocument/relationships"],pe=64*1024,A=o=>o.slice(o.lastIndexOf(":")+1);function B(o){let e,t=!1,r=n=>{e!==void 0&&(e+=n)};return o.on("text",r),o.on("cdata",r),{open(n){n==="rPh"&&(t=!0),!t&&(n==="v"||n==="t")&&(e="")},close(n){if(n==="rPh"&&(t=!1),n!=="v"&&n!=="t"||e===void 0)return"";let a=_(e);return e=void 0,a}}}async function*H(o,e){e?.throwIfAborted();let t=(await o.stream({chunkSize:pe})).getReader(),r=new TextDecoder,n=()=>t.cancel().catch(()=>{}),a=()=>{n()};e?.addEventListener("abort",a,{once:!0});try{for(e?.throwIfAborted();;){let{value:s,done:i}=await t.read();if(e?.throwIfAborted(),yield r.decode(s,{stream:!i}),i)break}}finally{e?.removeEventListener("abort",a),await n(),t.releaseLock()}}async function L(o,e,t){for await(let r of H(o,t))e.write(r);e.close()}function he(o,e,t){if(o==="inlineStr"||o==="str"||o==="d"||o==="e")return e;if(o==="s")return t[Number(e)]??null;if(o==="b")return e==="1"||e==="true";if(e==="")return null;let r=Number(e);return Number.isFinite(r)?r:e}function we(o,e,t){let r=new E({xmlns:!1}),n=B(r),a=0,s=[],i;return r.on("opentag",l=>{let f=A(l.name);switch(n.open(f),f){case"row":a=Number(l.attributes.r||a+1),s=[];break;case"c":i={column:l.attributes.r?M(l.attributes.r):s.length,type:l.attributes.t??"n",text:""};break}}),r.on("closetag",l=>{let f=A(l.name),u=n.close(f);switch(i&&u&&(i.text+=u),f){case"c":{if(!i)break;for(;s.length<i.column;)s.push(null);s[i.column]=he(i.type,i.text,e),i=void 0;break}case"row":t.push({sheet:o,row:a,cells:s});break}}),r}function be(o){let e=new E({xmlns:!1}),t=B(e),r="";return e.on("opentag",n=>{let a=A(n.name);a==="si"&&(r=""),t.open(a)}),e.on("closetag",n=>{let a=A(n.name);r+=t.close(a),a==="si"&&o.push(r)}),e}async function q(o,e,t){let r=new Map;if(!o)return r;let n=new URL(e,X),a=new E({xmlns:!1});return a.on("opentag",s=>{if(A(s.name)!=="Relationship")return;let{Id:i,Target:l,Type:f,TargetMode:u}=s.attributes;if(!i||!l||u==="External")return;let d=new URL(l,n);d.origin===X.origin&&r.set(i,{path:d.pathname.slice(1),type:f?.split("/").pop()})}),await L(o,a,t),r}async function ge(o,e){let t=[],r=new E({xmlns:!0});return r.on("opentag",n=>{if(n.local!=="sheet")return;let a=n.attributes.name?.value,s=Object.values(n.attributes).find(i=>i.local==="id"&&de.includes(i.uri));a&&s?.value&&t.push({id:s.value,name:_(a)})}),await L(o,r,e),t}async function*ye(o,e){e?.throwIfAborted();let{entries:t}=await ue(o);e?.throwIfAborted();let r=new Map(t.map(p=>[p.name,p])),a=[...(await q(r.get("_rels/.rels"),"",e)).values()].find(p=>p.type==="officeDocument")?.path??"xl/workbook.xml",s=r.get(a);if(!s)throw new Error("The workbook part is missing");let i=a.lastIndexOf("/")+1,l=a.slice(0,i),f=`${l}_rels/${a.slice(i)}.rels`,u=await q(r.get(f),a,e),m=(await ge(s,e)).flatMap(({id:p,name:h})=>{let c=u.get(p);return c&&(!c.type||c.type==="worksheet")?[{name:h,path:c.path}]:[]});if(!m.length)throw new Error("The workbook does not contain any readable worksheets");let b=[],y=[...u.values()].find(p=>p.type==="sharedStrings")?.path??`${l}sharedStrings.xml`,x=r.get(y);x&&await L(x,be(b),e);for(let{name:p,path:h}of m){let c=r.get(h);if(!c)throw new Error(`The worksheet part is missing for ${p}`);let g=[],$=we(p,b,g);for await(let S of H(c,e)){$.write(S);for(let C of g)e?.throwIfAborted(),yield C;g.length=0}$.close()}}async function*ke(o){let e=o instanceof Blob?o.stream():o;if("getReader"in e){let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)return;yield n}}finally{await t.cancel(),t.releaseLock()}}else yield*e}async function*xe(o,e={}){let t=e.delimiter??",";if(t.length!==1||/["\r\n]/.test(t))throw new Error("Choose a single CSV delimiter");let r=new TextDecoder,n=!1,a=!1,s=!1,i="",l=[];function*f(u){for(let d of u)if(!(s&&(s=!1,d===`
|
|
8
|
+
`))){if(n)if(a){if(a=!1,d==='"'){i+='"';continue}n=!1}else{d==='"'?a=!0:i+=d;continue}if(d==='"'){if(i.length)throw new Error("Unexpected quote inside a CSV field");n=!0}else d===t?(l.push(i),i=""):d===`
|
|
9
|
+
`||d==="\r"?(yield[...l,i],l=[],i="",s=d==="\r"):i+=d}}for await(let u of ke(o)){if(e.signal?.aborted)throw e.signal.reason;yield*f(r.decode(u,{stream:!0}))}if(yield*f(r.decode()),n&&!a)throw new Error("Unclosed quoted CSV field");(i.length||l.length||a)&&(yield[...l,i])}export{xe as readCSV,ye as readWorkbook,me as rowsFromSnapshot,fe as writeWorkbook};
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/workbook/write.ts", "../src/workbook/xml.ts", "../src/workbook/read.ts", "../src/engine/read-csv.ts"],
|
|
4
|
+
"sourcesContent": ["import { strToU8, Zip, ZipDeflate } from 'fflate';\nimport type { CellValue } from '@opengrid-ui/core/engine';\nimport type { WorkbookCell, WorkbookOptions, WorkbookSheet, WorkbookStyle } from './types';\nimport { excelColumn, mainNS, officeNS, packageNS, spreadsheetString, styleXML, xml, xmlHeader } from './xml';\n\nconst contentNS = 'http://schemas.openxmlformats.org/package/2006/content-types';\nconst maxRows = 1_048_576;\nconst maxColumns = 16_384;\nconst headerStyle: WorkbookStyle = { bold: true, fillColor: 'EDF2FA', fontColor: '172534' };\ntype Row = readonly (CellValue | WorkbookCell)[];\n\nfunction xmlParts(sheets: readonly WorkbookSheet[], styles: readonly WorkbookStyle[]) {\n const rows = sheets.map((sheet, index) => `<sheet name=\"${spreadsheetString(sheet.name, true)}\" sheetId=\"${index + 1}\" r:id=\"rId${index + 1}\"/>`).join('');\n const entries = sheets.map((_, index) => `<Relationship Id=\"rId${index + 1}\" Type=\"${officeNS}/worksheet\" Target=\"worksheets/sheet${index + 1}.xml\"/>`).join('');\n const declarations = sheets.map((_, index) => `<Override PartName=\"/xl/worksheets/sheet${index + 1}.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>`).join('');\n return {\n '[Content_Types].xml': xmlHeader + `<Types xmlns=\"${contentNS}\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/><Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/><Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/>${declarations}</Types>`,\n '_rels/.rels': xmlHeader + `<Relationships xmlns=\"${packageNS}\"><Relationship Id=\"rId1\" Type=\"${officeNS}/officeDocument\" Target=\"xl/workbook.xml\"/></Relationships>`,\n 'xl/workbook.xml': xmlHeader + `<workbook xmlns=\"${mainNS}\" xmlns:r=\"${officeNS}\"><sheets>${rows}</sheets></workbook>`,\n 'xl/_rels/workbook.xml.rels': xmlHeader + `<Relationships xmlns=\"${packageNS}\">${entries}<Relationship Id=\"rIdStyles\" Type=\"${officeNS}/styles\" Target=\"styles.xml\"/></Relationships>`,\n 'xl/styles.xml': styleXML(styles),\n };\n}\n\nfunction cellXML(cell: CellValue | WorkbookCell, reference: string, style: number) {\n const value = cell !== null && typeof cell === 'object' ? cell.value : cell;\n const tag = `<c r=\"${reference}\" s=\"${style}\"`;\n if (value === null) return tag + '/>';\n if (typeof value === 'number' && Number.isFinite(value)) return tag + `><v>${value}</v></c>`;\n if (typeof value === 'boolean') return tag + ` t=\"b\"><v>${Number(value)}</v></c>`;\n return tag + ` t=\"inlineStr\"><is><t xml:space=\"preserve\">${spreadsheetString(String(value))}</t></is></c>`;\n}\n\nfunction styleAt(cell: CellValue | WorkbookCell, style: string | undefined, styles: ReadonlyMap<string, number>) {\n const override = cell !== null && typeof cell === 'object' ? cell.style : undefined;\n return styles.get(override ?? style ?? '') ?? 0;\n}\n\nfunction validateSheets(sheets: readonly WorkbookSheet[]) {\n if (!sheets.length) throw new Error('A workbook requires at least one sheet');\n const names = new Set<string>();\n for (const sheet of sheets) {\n if (!sheet.name || sheet.name.length > 31 || /[\\\\/?*:[\\]]/.test(sheet.name) || names.has(sheet.name.toLowerCase())) {\n throw new Error(`Invalid or duplicate sheet name: ${sheet.name}`);\n }\n names.add(sheet.name.toLowerCase());\n if (sheet.columns.length > maxColumns) throw new Error('A sheet cannot exceed 16,384 columns');\n }\n}\n\nfunction waitForWork<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n const cancel = () => reject(signal.reason);\n if (signal.aborted) cancel();\n else signal.addEventListener('abort', cancel, { once: true });\n void work.then(resolve, reject).finally(() => signal.removeEventListener('abort', cancel));\n });\n}\n\nasync function* readRows(rows: AsyncIterable<Row>, signal: AbortSignal) {\n const iterator = rows[Symbol.asyncIterator]();\n let done = false;\n try {\n while (true) {\n signal.throwIfAborted();\n const next = await waitForWork(iterator.next(), signal);\n if (next.done) {\n done = true;\n return;\n }\n signal.throwIfAborted();\n yield next.value;\n }\n } finally {\n if (!done && iterator.return) {\n const close = Promise.resolve().then(() => iterator.return?.());\n await waitForWork(close, signal).catch(() => {});\n }\n }\n}\n\nexport async function writeWorkbook(sheets: readonly WorkbookSheet[], options: WorkbookOptions = {}): Promise<Uint8Array> {\n options.signal?.throwIfAborted();\n validateSheets(sheets);\n const writer = options.sink?.getWriter();\n const operation = new AbortController();\n const { signal } = operation;\n const cancel = () => operation.abort(options.signal?.reason);\n options.signal?.addEventListener('abort', cancel, { once: true });\n void writer?.closed.catch(error => operation.abort(error));\n const chunks: Uint8Array[] = [];\n let finished = false;\n const zip = new Zip((error, chunk, final) => {\n if (error) { operation.abort(error); return; }\n chunks.push(chunk);\n finished = final;\n });\n\n async function flush() {\n signal.throwIfAborted();\n if (!writer) return;\n for (const chunk of chunks) {\n signal.throwIfAborted();\n await waitForWork(writer.write(chunk), signal);\n }\n chunks.length = 0;\n }\n\n function file(name: string) {\n const stream = new ZipDeflate(name, { level: 3 });\n zip.add(stream);\n return (value: string, final = false) => stream.push(strToU8(value), final);\n }\n\n try {\n const entries = [['__header', headerStyle], ...Object.entries(options.styles ?? {})] as const;\n const styleIds = new Map(entries.map(([name], index) => [name, index + 1]));\n for (const [name, contents] of Object.entries(xmlParts(sheets, entries.map(([, style]) => style)))) file(name)(contents, true);\n await flush();\n let started = performance.now();\n for (const [index, sheet] of sheets.entries()) {\n signal.throwIfAborted();\n const write = file(`xl/worksheets/sheet${index + 1}.xml`);\n const widths = sheet.columns.map(({ width }, column) => width === undefined ? '' : `<col min=\"${column + 1}\" max=\"${column + 1}\" width=\"${width}\" customWidth=\"1\"/>`).join('');\n write(xmlHeader + `<worksheet xmlns=\"${mainNS}\">${widths ? `<cols>${widths}</cols>` : ''}<sheetData>`);\n let row = 0;\n let buffer = '';\n function append(cells: Row, header: boolean) {\n row++;\n if (row > maxRows || cells.length > maxColumns) throw new Error('The sheet exceeds Excel worksheet dimensions');\n buffer += `<row r=\"${row}\">${cells.map((cell, column) => {\n const style = styleAt(cell, header ? '__header' : sheet.columns[column]?.style, styleIds);\n return cellXML(cell, excelColumn(column) + String(row), style);\n }).join('')}</row>`;\n }\n for (const fields of sheet.headers ?? [sheet.columns.map(column => column.header)]) append(fields, true);\n const rows = Symbol.asyncIterator in sheet.rows ? readRows(sheet.rows, signal) : sheet.rows;\n for await (const cells of rows) {\n signal.throwIfAborted();\n append(cells, false);\n if (row % 256 === 0) {\n write(buffer);\n buffer = '';\n await flush();\n if (performance.now() - started >= 8) {\n await new Promise<void>(resolve => setTimeout(resolve, 0));\n signal.throwIfAborted();\n started = performance.now();\n }\n }\n }\n signal.throwIfAborted();\n const merges = sheet.merges?.length ? `<mergeCells count=\"${sheet.merges.length}\">${sheet.merges.map(range => `<mergeCell ref=\"${xml(range)}\"/>`).join('')}</mergeCells>` : '';\n write(buffer + '</sheetData>' + merges + '</worksheet>', true);\n await flush();\n }\n zip.end();\n await flush();\n signal.throwIfAborted();\n if (!finished) throw new Error('Incomplete workbook archive');\n await writer?.close();\n const bytes = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n } catch (error) {\n zip.terminate();\n if (writer) await waitForWork(writer.abort(error), signal).catch(() => {});\n throw error;\n } finally {\n options.signal?.removeEventListener('abort', cancel);\n writer?.releaseLock();\n }\n}\n\nexport interface RowSnapshot {\n total: number;\n revision: string | number;\n read(range: readonly [number, number], revision: string | number): Promise<readonly (readonly (CellValue | WorkbookCell)[])[]>;\n}\n\nexport async function* rowsFromSnapshot(snapshot: RowSnapshot, page = 512) {\n if (!Number.isInteger(page) || page <= 0) throw new Error('Snapshot blocks must have positive integer size');\n const { revision, total } = snapshot;\n for (let start = 0; start < total; start += page) {\n const end = Math.min(total, start + page);\n const rows = await snapshot.read([start, end], revision);\n if (rows.length !== end - start) throw new Error('Snapshot size changed during export');\n yield* rows;\n }\n}\n", "import type { WorkbookStyle } from './types';\n\nexport const xmlHeader = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>';\nexport const mainNS = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';\nexport const officeNS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';\nexport const packageNS = 'http://schemas.openxmlformats.org/package/2006/relationships';\n\nconst escaped: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' };\nexport function xml(text: string): string {\n return text.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\ufffe\\uffff]/g, '')\n .replace(/[&<>\"']/g, character => escaped[character]!);\n}\n\nfunction escapeCodeUnit(character: string) {\n return '_x' + character.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0') + '_';\n}\n\nexport function spreadsheetString(text: string, attribute = false): string {\n const value = text.replace(/_(?=x[\\da-fA-F]{4}_)|[\\u0000-\\u0008\\u000b-\\u001f\\ud800-\\udfff\\ufffe\\uffff]/gu, escapeCodeUnit);\n return xml(attribute ? value.replace(/[\\t\\n]/g, escapeCodeUnit) : value);\n}\n\nexport function decodeSpreadsheetString(text: string): string {\n return text.replace(/_x([\\da-fA-F]{4})_/g, (_, code: string) => String.fromCharCode(Number.parseInt(code, 16)));\n}\n\nexport function excelColumn(index: number): string {\n let text = '';\n for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) {\n text = String.fromCharCode(65 + ((value - 1) % 26)) + text;\n }\n return text;\n}\n\nexport function columnOffset(reference: string): number {\n let offset = 0;\n for (const char of reference.match(/^[A-Z]+/i)?.[0].toUpperCase() ?? '') offset = offset * 26 + char.charCodeAt(0) - 64;\n return Math.max(0, offset - 1);\n}\n\nfunction color(value: string): string {\n const hex = value.replace(/^#/, '');\n if (!/^(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) throw new Error('Use six or eight hexadecimal digits for a workbook color');\n return (hex.length === 6 ? 'FF' + hex : hex).toUpperCase();\n}\n\nexport function styleXML(styles: readonly WorkbookStyle[]) {\n const formats: string[] = [];\n const fonts = ['<font><sz val=\"11\"/><name val=\"Calibri\"/></font>'];\n const fills = ['<fill><patternFill patternType=\"none\"/></fill>', '<fill><patternFill patternType=\"gray125\"/></fill>'];\n const base = '<xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\"/>';\n const xfs = [base];\n for (const style of styles) {\n let numFmtId = 0;\n let fontId = 0;\n let fillId = 0;\n if (style.numberFormat) {\n numFmtId = 164 + formats.length;\n formats.push(`<numFmt numFmtId=\"${numFmtId}\" formatCode=\"${xml(style.numberFormat)}\"/>`);\n }\n if (style.bold || style.fontColor) {\n fontId = fonts.length;\n fonts.push(`<font><sz val=\"11\"/><name val=\"Calibri\"/>${style.bold ? '<b/>' : ''}${style.fontColor ? `<color rgb=\"${color(style.fontColor)}\"/>` : ''}</font>`);\n }\n if (style.fillColor) {\n fillId = fills.length;\n fills.push(`<fill><patternFill patternType=\"solid\"><fgColor rgb=\"${color(style.fillColor)}\"/><bgColor indexed=\"64\"/></patternFill></fill>`);\n }\n const alignment = style.align ? `<alignment horizontal=\"${style.align}\"/>` : '';\n xfs.push(`<xf xfId=\"0\" borderId=\"0\" fontId=\"${fontId}\" fillId=\"${fillId}\" numFmtId=\"${numFmtId}\" applyFont=\"1\" applyFill=\"1\" applyNumberFormat=\"1\" applyAlignment=\"${style.align ? 1 : 0}\">${alignment}</xf>`);\n }\n return xmlHeader + `<styleSheet xmlns=\"${mainNS}\">\n <numFmts count=\"${formats.length}\">${formats.join('')}</numFmts>\n <fonts count=\"${fonts.length}\">${fonts.join('')}</fonts><fills count=\"${fills.length}\">${fills.join('')}</fills>\n <borders count=\"1\"><border><left/><right/><top/><bottom/><diagonal/></border></borders>\n <cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>\n <cellXfs count=\"${xfs.length}\">${xfs.join('')}</cellXfs>\n <cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles></styleSheet>`;\n}\n", "import { SaxesParser } from 'saxes';\nimport { unzipRaw } from 'unzipit';\nimport type { ZipEntry } from 'unzipit';\nimport type { CellValue } from '@opengrid-ui/core/engine';\nimport type { WorkbookReadRow } from './types';\nimport { columnOffset, decodeSpreadsheetString } from './xml';\n\nconst packageRoot = new URL('https://workbook.invalid/');\nconst relationshipNamespaces = [\n 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',\n 'http://purl.oclc.org/ooxml/officeDocument/relationships',\n];\nconst xmlChunkSize = 64 * 1024;\nconst leaf = (name: string) => name.slice(name.lastIndexOf(':') + 1);\n\nfunction valueText(parser: SaxesParser<{ xmlns: false }>) {\n let current: string | undefined;\n let phonetic = false;\n const capture = (text: string) => { if (current !== undefined) current += text; };\n parser.on('text', capture);\n parser.on('cdata', capture);\n return {\n open(tag: string) {\n if (tag === 'rPh') phonetic = true;\n if (!phonetic && (tag === 'v' || tag === 't')) current = '';\n },\n close(tag: string) {\n if (tag === 'rPh') phonetic = false;\n if ((tag !== 'v' && tag !== 't') || current === undefined) return '';\n const value = decodeSpreadsheetString(current);\n current = undefined;\n return value;\n },\n };\n}\n\nasync function* xmlChunks(entry: ZipEntry, signal?: AbortSignal) {\n signal?.throwIfAborted();\n const reader = (await entry.stream({ chunkSize: xmlChunkSize })).getReader();\n const decoder = new TextDecoder();\n const cancel = () => reader.cancel().catch(() => {});\n const abort = () => { void cancel(); };\n signal?.addEventListener('abort', abort, { once: true });\n try {\n signal?.throwIfAborted();\n while (true) {\n const { value, done } = await reader.read();\n signal?.throwIfAborted();\n yield decoder.decode(value, { stream: !done });\n if (done) break;\n }\n } finally {\n signal?.removeEventListener('abort', abort);\n await cancel();\n reader.releaseLock();\n }\n}\n\nasync function parsePart(entry: ZipEntry, parser: Pick<SaxesParser, 'write' | 'close'>, signal?: AbortSignal) {\n for await (const text of xmlChunks(entry, signal)) parser.write(text);\n parser.close();\n}\n\nfunction scalar(kind: string, text: string, shared: readonly string[]): CellValue {\n if (kind === 'inlineStr' || kind === 'str' || kind === 'd' || kind === 'e') return text;\n if (kind === 's') return shared[Number(text)] ?? null;\n if (kind === 'b') return text === '1' || text === 'true';\n if (text === '') return null;\n const value = Number(text);\n return Number.isFinite(value) ? value : text;\n}\n\nfunction sheetParser(sheet: string, strings: readonly string[], output: WorkbookReadRow[]) {\n const parser = new SaxesParser({ xmlns: false });\n const text = valueText(parser);\n let row = 0;\n let cells: CellValue[] = [];\n let cell: { column: number; type: string; text: string } | undefined;\n\n parser.on('opentag', tag => {\n const kind = leaf(tag.name);\n text.open(kind);\n switch (kind) {\n case 'row': row = Number(tag.attributes.r || row + 1); cells = []; break;\n case 'c': cell = { column: tag.attributes.r ? columnOffset(tag.attributes.r) : cells.length, type: tag.attributes.t ?? 'n', text: '' }; break;\n }\n });\n parser.on('closetag', tag => {\n const kind = leaf(tag.name);\n const value = text.close(kind);\n if (cell && value) cell.text += value;\n switch (kind) {\n case 'c': {\n if (!cell) break;\n while (cells.length < cell.column) cells.push(null);\n cells[cell.column] = scalar(cell.type, cell.text, strings);\n cell = undefined;\n break;\n }\n case 'row': output.push({ sheet, row, cells }); break;\n }\n });\n return parser;\n}\n\nfunction sharedStringsParser(strings: string[]) {\n const parser = new SaxesParser({ xmlns: false });\n const text = valueText(parser);\n let value = '';\n parser.on('opentag', tag => {\n const kind = leaf(tag.name);\n if (kind === 'si') value = '';\n text.open(kind);\n });\n parser.on('closetag', tag => {\n const kind = leaf(tag.name);\n value += text.close(kind);\n if (kind === 'si') strings.push(value);\n });\n return parser;\n}\n\nasync function readRelationships(entry: ZipEntry | undefined, source: string, signal?: AbortSignal) {\n const links = new Map<string, { path: string; type: string | undefined }>();\n if (!entry) return links;\n const base = new URL(source, packageRoot);\n const parser = new SaxesParser({ xmlns: false });\n parser.on('opentag', tag => {\n if (leaf(tag.name) !== 'Relationship') return;\n const { Id, Target, Type, TargetMode } = tag.attributes;\n if (!Id || !Target || TargetMode === 'External') return;\n const part = new URL(Target, base);\n if (part.origin === packageRoot.origin) links.set(Id, { path: part.pathname.slice(1), type: Type?.split('/').pop() });\n });\n await parsePart(entry, parser, signal);\n return links;\n}\n\nasync function workbookTabs(entry: ZipEntry, signal?: AbortSignal) {\n const tabs: { id: string; name: string }[] = [];\n const parser = new SaxesParser({ xmlns: true });\n parser.on('opentag', tag => {\n if (tag.local !== 'sheet') return;\n const name = tag.attributes.name?.value;\n const reference = Object.values(tag.attributes).find(attr => attr.local === 'id' && relationshipNamespaces.includes(attr.uri));\n if (name && reference?.value) tabs.push({ id: reference.value, name: decodeSpreadsheetString(name) });\n });\n await parsePart(entry, parser, signal);\n return tabs;\n}\n\nexport async function* readWorkbook(input: Blob, signal?: AbortSignal): AsyncGenerator<WorkbookReadRow> {\n signal?.throwIfAborted();\n const { entries } = await unzipRaw(input);\n signal?.throwIfAborted();\n const parts = new Map(entries.map(entry => [entry.name, entry]));\n const rootLinks = await readRelationships(parts.get('_rels/.rels'), '', signal);\n const workbookPath = [...rootLinks.values()].find(link => link.type === 'officeDocument')?.path ?? 'xl/workbook.xml';\n const workbook = parts.get(workbookPath);\n if (!workbook) throw new Error('The workbook part is missing');\n const separator = workbookPath.lastIndexOf('/') + 1;\n const folder = workbookPath.slice(0, separator);\n const relationshipsPath = `${folder}_rels/${workbookPath.slice(separator)}.rels`;\n const links = await readRelationships(parts.get(relationshipsPath), workbookPath, signal);\n const tabs = await workbookTabs(workbook, signal);\n const worksheets = tabs.flatMap(({ id, name }) => {\n const link = links.get(id);\n return link && (!link.type || link.type === 'worksheet') ? [{ name, path: link.path }] : [];\n });\n if (!worksheets.length) throw new Error('The workbook does not contain any readable worksheets');\n\n const strings: string[] = [];\n const stringsPath = [...links.values()].find(link => link.type === 'sharedStrings')?.path ?? `${folder}sharedStrings.xml`;\n const table = parts.get(stringsPath);\n if (table) await parsePart(table, sharedStringsParser(strings), signal);\n\n for (const { name, path } of worksheets) {\n const entry = parts.get(path);\n if (!entry) throw new Error(`The worksheet part is missing for ${name}`);\n const rows: WorkbookReadRow[] = [];\n const parser = sheetParser(name, strings, rows);\n for await (const text of xmlChunks(entry, signal)) {\n parser.write(text);\n for (const row of rows) {\n signal?.throwIfAborted();\n yield row;\n }\n rows.length = 0;\n }\n parser.close();\n }\n}\n", "export interface CSVOptions { delimiter?: string; signal?: AbortSignal }\n\nasync function* source(input: Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>) {\n const stream = input instanceof Blob ? input.stream() : input;\n if ('getReader' in stream) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n await reader.cancel();\n reader.releaseLock();\n }\n } else {\n yield* stream;\n }\n}\n\nexport async function* readCSV(input: Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>, options: CSVOptions = {}) {\n const delimiter = options.delimiter ?? ',';\n if (delimiter.length !== 1 || /[\"\\r\\n]/.test(delimiter)) throw new Error('Choose a single CSV delimiter');\n const decoder = new TextDecoder();\n let quoted = false;\n let seenQuote = false;\n let skipLF = false;\n let field = '';\n let row: string[] = [];\n function* read(text: string) {\n for (const char of text) {\n if (skipLF) {\n skipLF = false;\n if (char === '\\n') continue;\n }\n if (quoted) {\n if (seenQuote) {\n seenQuote = false;\n if (char === '\"') { field += '\"'; continue; }\n quoted = false;\n } else {\n if (char === '\"') seenQuote = true;\n else field += char;\n continue;\n }\n }\n if (char === '\"') {\n if (field.length) throw new Error('Unexpected quote inside a CSV field');\n quoted = true;\n } else if (char === delimiter) {\n row.push(field);\n field = '';\n } else if (char === '\\n' || char === '\\r') {\n yield [...row, field];\n row = [];\n field = '';\n skipLF = char === '\\r';\n } else {\n field += char;\n }\n }\n }\n for await (const bytes of source(input)) {\n if (options.signal?.aborted) throw options.signal.reason;\n yield* read(decoder.decode(bytes, { stream: true }));\n }\n yield* read(decoder.decode());\n if (quoted && !seenQuote) throw new Error('Unclosed quoted CSV field');\n if (field.length || row.length || seenQuote) yield [...row, field];\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,WAAAA,EAAS,OAAAC,GAAK,cAAAC,OAAkB,SCElC,IAAMC,EAAY,0DACZC,EAAS,4DACTC,EAAW,sEACXC,EAAY,+DAEnBC,EAAkC,CAAE,IAAK,QAAS,IAAK,OAAQ,IAAK,OAAQ,IAAK,SAAU,IAAK,QAAS,EACxG,SAASC,EAAIC,EAAsB,CACxC,OAAOA,EAAK,QAAQ,wDAAyD,EAAE,EAC5E,QAAQ,WAAYC,GAAaH,EAAQG,CAAS,CAAE,CACzD,CAEA,SAASC,EAAeD,EAAmB,CACzC,MAAO,KAAOA,EAAU,WAAW,CAAC,EAAE,SAAS,EAAE,EAAE,YAAY,EAAE,SAAS,EAAG,GAAG,EAAI,GACtF,CAEO,SAASE,EAAkBH,EAAcI,EAAY,GAAe,CACzE,IAAMC,EAAQL,EAAK,QAAQ,+EAAgFE,CAAc,EACzH,OAAOH,EAAIK,EAAYC,EAAM,QAAQ,UAAWH,CAAc,EAAIG,CAAK,CACzE,CAEO,SAASC,EAAwBN,EAAsB,CAC5D,OAAOA,EAAK,QAAQ,sBAAuB,CAACO,EAAGC,IAAiB,OAAO,aAAa,OAAO,SAASA,EAAM,EAAE,CAAC,CAAC,CAChH,CAEO,SAASC,EAAYC,EAAuB,CACjD,IAAIV,EAAO,GACX,QAASK,EAAQK,EAAQ,EAAGL,EAAQ,EAAGA,EAAQ,KAAK,OAAOA,EAAQ,GAAK,EAAE,EACxEL,EAAO,OAAO,aAAa,IAAOK,EAAQ,GAAK,EAAG,EAAIL,EAExD,OAAOA,CACT,CAEO,SAASW,EAAaC,EAA2B,CACtD,IAAIC,EAAS,EACb,QAAWC,KAAQF,EAAU,MAAM,UAAU,IAAI,CAAC,EAAE,YAAY,GAAK,GAAIC,EAASA,EAAS,GAAKC,EAAK,WAAW,CAAC,EAAI,GACrH,OAA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AAU,IAAI,YAChBC,EAAS,GACTC,EAAY,GACZC,EAAS,GACTC,EAAQ,GACRC,EAAgB,CAAC,EACrB,SAAUC,EAAKC,EAAc,CAC3B,QAAWC,KAAQD,EACjB,GAAI,EAAAJ,IACFA,EAAS,GACLK,IAAS;AAAA,IAEf,IAAIP,EACF,GAAIC,EAAW,CAEb,GADAA,EAAY,GACRM,IAAS,IAAK,CAAEJ,GAAS,IAAK,QAAU,CAC5CH,EAAS,EACX,KAAO,CACDO,IAAS,IAAKN,EAAY,GACzBE,GAASI,EACd,QACF,CAEF,GAAIA,IAAS,IAAK,CAChB,GAAIJ,EAAM,OAAQ,MAAM,IAAI,MAAM,qCAAqC,EACvEH,EAAS,EACX,MAAWO,IAAST,GAClBM,EAAI,KAAKD,CAAK,EACdA,EAAQ,IACCI,IAAS;AAAA,GAAQA,IAAS,MACnC,KAAM,CAAC,GAAGH,EAAKD,CAAK,EACpBC,EAAM,CAAC,EACPD,EAAQ,GACRD,EAASK,IAAS,MAElBJ,GAASI,EAGf,CACA,cAAiBC,KAASlB,GAAOC,CAAK,EAAG,CACvC,GAAIM,EAAQ,QAAQ,QAAS,MAAMA,EAAQ,OAAO,OAClD,MAAOQ,EAAKN,EAAQ,OAAOS,EAAO,CAAE,OAAQ,EAAK,CAAC,CAAC,CACrD,CAEA,GADA,MAAOH,EAAKN,EAAQ,OAAO,CAAC,EACxBC,GAAU,CAACC,EAAW,MAAM,IAAI,MAAM,2BAA2B,GACjEE,EAAM,QAAUC,EAAI,QAAUH,KAAW,KAAM,CAAC,GAAGG,EAAKD,CAAK,EACnE",
|
|
6
|
+
"names": ["strToU8", "Zip", "ZipDeflate", "xmlHeader", "mainNS", "officeNS", "packageNS", "escaped", "xml", "text", "character", "escapeCodeUnit", "spreadsheetString", "attribute", "value", "decodeSpreadsheetString", "_", "code", "excelColumn", "index", "columnOffset", "reference", "offset", "char", "color", "hex", "styleXML", "styles", "formats", "fonts", "fills", "xfs", "style", "numFmtId", "fontId", "fillId", "alignment", "contentNS", "maxRows", "maxColumns", "headerStyle", "xmlParts", "sheets", "styles", "rows", "sheet", "index", "spreadsheetString", "entries", "_", "officeNS", "declarations", "xmlHeader", "packageNS", "mainNS", "styleXML", "cellXML", "cell", "reference", "style", "value", "tag", "styleAt", "override", "validateSheets", "names", "waitForWork", "work", "signal", "resolve", "reject", "cancel", "readRows", "iterator", "done", "next", "close", "writeWorkbook", "options", "writer", "operation", "error", "chunks", "finished", "zip", "Zip", "chunk", "final", "flush", "file", "name", "stream", "ZipDeflate", "strToU8", "styleIds", "contents", "started", "append", "cells", "header", "row", "buffer", "column", "excelColumn", "write", "widths", "width", "fields", "merges", "range", "xml", "bytes", "total", "offset", "rowsFromSnapshot", "snapshot", "page", "revision", "start", "end", "SaxesParser", "unzipRaw", "packageRoot", "relationshipNamespaces", "xmlChunkSize", "leaf", "name", "valueText", "parser", "current", "phonetic", "capture", "text", "tag", "value", "decodeSpreadsheetString", "xmlChunks", "entry", "signal", "reader", "decoder", "cancel", "abort", "done", "parsePart", "scalar", "kind", "shared", "sheetParser", "sheet", "strings", "output", "SaxesParser", "row", "cells", "cell", "columnOffset", "sharedStringsParser", "readRelationships", "source", "links", "base", "Id", "Target", "Type", "TargetMode", "part", "workbookTabs", "tabs", "reference", "attr", "readWorkbook", "input", "entries", "unzipRaw", "parts", "workbookPath", "link", "workbook", "separator", "folder", "relationshipsPath", "worksheets", "id", "stringsPath", "table", "path", "rows", "source", "input", "stream", "reader", "done", "value", "readCSV", "options", "delimiter", "decoder", "quoted", "seenQuote", "skipLF", "field", "row", "read", "text", "char", "bytes"]
|
|
7
|
+
}
|
package/dist/llms.txt
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# OpenGrid
|
|
2
|
+
|
|
3
|
+
OpenGrid is an MIT-licensed React data grid for CRUD, large local datasets, and spreadsheet editing. Use it with Arco Design, Ant Design, or the host-neutral ProGrid.
|
|
4
|
+
|
|
5
|
+
[Live documentation and sandbox](https://han-wangyu.github.io/opengrid-ui/) · [GitHub releases](https://github.com/Han-wangyu/opengrid-ui/releases) · [简体中文](https://han-wangyu.github.io/opengrid-ui/?lang=zh)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Install the Core and Pro packages from npm.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @opengrid-ui/core @opengrid-ui/pro
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
GitHub Releases also provides versioned tarballs with SHA-256 checksums.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
release=https://github.com/Han-wangyu/opengrid-ui/releases/download/v0.1.37
|
|
19
|
+
npm install "$release/opengrid-ui-core-0.1.37.tgz" "$release/opengrid-ui-pro-0.1.37.tgz"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```tsx
|
|
23
|
+
import { ProGrid } from '@opengrid-ui/pro';
|
|
24
|
+
import '@opengrid-ui/core/styles.css';
|
|
25
|
+
import '@opengrid-ui/pro/styles.css';
|
|
26
|
+
|
|
27
|
+
const rows = [{ id: 'A-104', name: 'Lumen', amount: 230 }];
|
|
28
|
+
|
|
29
|
+
export function Invoices() {
|
|
30
|
+
return (
|
|
31
|
+
<ProGrid
|
|
32
|
+
label="Invoices"
|
|
33
|
+
rows={rows}
|
|
34
|
+
getRowId={row => row.id}
|
|
35
|
+
columns={[
|
|
36
|
+
{ id: 'name', title: 'Account', query: true },
|
|
37
|
+
{ id: 'amount', title: 'Amount', valueType: 'money', sortable: true },
|
|
38
|
+
]}
|
|
39
|
+
/>
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
For native tokens and scoped tooltips, install `@opengrid-ui/arco` or `@opengrid-ui/antd` and import its `ProGrid`. Check the peer versions and React 19 setup in the [packed React and TypeScript compatibility matrix](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/compat-matrix.spec.md).
|
|
45
|
+
|
|
46
|
+
ProGrid automatically sorts and filters local datasets above 5,000 rows in a Worker. Plain pages slice the supplied data directly. The [local query contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#local-datasets) describes refresh and data ownership.
|
|
47
|
+
|
|
48
|
+
Pass `pageData` for a page already fetched by the host. Send the current rows and full result count, and use `pager={false}` to keep the host's pagination controls. [Host-owned pages](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#host-owned-pages)
|
|
49
|
+
|
|
50
|
+
Enable cell editing by passing a `spreadsheet.commit` handler. Pro uses each column's value type for the editor and respects column-level edit permissions during inline edits and pastes. The [Pro contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#spreadsheet-editors) describes value adapters and custom editors.
|
|
51
|
+
|
|
52
|
+
Enable Core header reordering with `<Grid columnReordering />`. Drag the grip, activate two grips, or focus a grip and press an arrow key. The [Core contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/core-engine.spec.md#column-reordering) covers grouped headers and storing column order.
|
|
53
|
+
|
|
54
|
+
Use `useServerTree` with Core to expand remote groups in place. The [server-side row model contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) describes block requests, projections and retries.
|
|
55
|
+
|
|
56
|
+
Configure a pivot report with `PivotSidebar`. The sidebar controls result columns, filters and grouping, and applies filters through the existing pivot Worker. [Pivot sidebar](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#pivot-sidebar)
|
|
57
|
+
|
|
58
|
+
The installed packages include `dist/llms.txt` and `dist/skills/opengrid/SKILL.md`. Coding agents can read the guide and migration instructions from the same version as the installed package.
|
|
59
|
+
|
|
60
|
+
## Packages
|
|
61
|
+
|
|
62
|
+
| Package | Provides |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `core` | Real DOM virtualization, column pinning and reordering, keyboard selection, TSV, edit transactions and Worker data windows |
|
|
65
|
+
| `pro` | Query schema, tabs, controlled state, URL history, preferences and paged selection |
|
|
66
|
+
| `arco`, `antd` | Scoped tokens, locale and column migration |
|
|
67
|
+
| `engine-wasm` | Numeric sort, filter and aggregation, plus [incremental formula sessions](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#formulas) |
|
|
68
|
+
| `plugin-pivot` | Grouping, [Worker and WASM pivot views](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md#pivot), advanced filters and [lazy server groups](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) |
|
|
69
|
+
| `plugin-excel` | Styled multi-sheet XLSX and streaming CSV/XLSX IO ([workbook text contract](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/excel.spec.md)) |
|
|
70
|
+
| `plugin-charts` | Sparklines, conditional formatting and [charts from a spreadsheet selection](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/charts.spec.md) |
|
|
71
|
+
|
|
72
|
+
## Verify
|
|
73
|
+
|
|
74
|
+
Use Node.js 22, Corepack, and stable Rust with the WebAssembly target for repository builds. Consumers install the already-built packages.
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
corepack enable
|
|
78
|
+
rustup target add wasm32-unknown-unknown --toolchain stable
|
|
79
|
+
pnpm install --frozen-lockfile
|
|
80
|
+
pnpm exec playwright install chromium
|
|
81
|
+
pnpm verify:m4
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The [live comparison](https://han-wangyu.github.io/opengrid-ui/benchmark/?engine=compare) sends the same navigation and sort commands to the JS and Rust/WASM workers on 50,000 or 500,000 rows. The [reference benchmarks](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/benchmarks/m5-reference.json) measure each engine independently. Read [AGENTS.md](https://github.com/Han-wangyu/opengrid-ui/blob/main/AGENTS.md), the [contribution guide](https://github.com/Han-wangyu/opengrid-ui/blob/main/CONTRIBUTING.md), or the [agent skill](https://github.com/Han-wangyu/opengrid-ui/blob/main/skills/opengrid/SKILL.md) before changing the public contract.
|
|
85
|
+
|
|
86
|
+
# OpenGrid architecture
|
|
87
|
+
|
|
88
|
+
OpenGrid is a client-side React toolkit for CRUD pages, large datasets, and spreadsheet editing. It is independently maintained and MIT licensed.
|
|
89
|
+
|
|
90
|
+
| Layer | Ownership |
|
|
91
|
+
| --- | --- |
|
|
92
|
+
| Arco and AntD adapters | Host tokens, scoped overlays and locale, migration converters |
|
|
93
|
+
| Pro | Column schema, form and tabs, query store, column preferences, toolbar, and paged selection |
|
|
94
|
+
| Core | TanStack column model, React external-store bridge, DOM viewport, and spreadsheet interactions |
|
|
95
|
+
| Compute and optional plugins | JavaScript worker, Rust WebAssembly, pivot, Excel, and charts |
|
|
96
|
+
|
|
97
|
+
The data plane accepts a columnar dataset, materializes sorted or filtered views, returns only the requested viewport, and applies versioned edit transactions. A dataset epoch and query generation help callers discard late responses. Paged CRUD renders supplied rows directly. Its query state has one commit point with cancellation, stale response rejection, URL synchronization and separate tab counts.
|
|
98
|
+
|
|
99
|
+
React 17 and TypeScript 4 are supported targets alongside React 18 and 19. All packages are tested from packed artifacts in isolated applications. The [compatibility matrix](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/compat-matrix.spec.md) checks published declarations with legacy Node, Node16, NodeNext, and Bundler resolution as supported by each compiler. Core emits scoped styles. Adapters map host visual tokens into each instance and attach overlays within the instance. When a React 17 Ant Design host enables CSS variables, an explicit light or dark grid theme gets a stable key for that mounted instance.
|
|
100
|
+
|
|
101
|
+
The [milestones](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/ROADMAP.md) define observable launch criteria. [Package contracts](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/specs/) and [decision records](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/adr/) define behavior and document changes.
|
|
102
|
+
|
|
103
|
+
The first virtualizer uses an eight-million-pixel physical scroll track and arithmetic row coordinates. It measures its live viewport and keeps an overscanned window plus a prefetched worker chunk. The reference benchmark runs one engine at a time in Chromium against the production build. The 500,000-row scroll gate captures the sampled renderer JavaScript heap peak in the same trace window as the frame measurements. The public comparison starts both engines on identical datasets and displays each panel's ingestion, paint and sort timings while the two engines share the browser.
|
|
104
|
+
|
|
105
|
+
Spreadsheet keyboard navigation reveals the target row within the visible body. Core computes the nearest logical offset from the row's bounds and projects it onto the physical track, accounting for sticky headers and pinned rows.
|
|
106
|
+
|
|
107
|
+
Spreadsheet focus uses the current selection, the last selected position, or the first mounted cell in the visible window. Focus entry can remount a virtualized cell on both axes. Active descendant IDs refer to mounted cells, and pointer focus follows the cell being clicked.
|
|
108
|
+
|
|
109
|
+
Keyboard shortcuts for selecting an entire sheet, row or column preserve the active cell independently of the range endpoints. The focus owner associates the retained cell with the accepted range by its coordinates, including for host-controlled selections.
|
|
110
|
+
|
|
111
|
+
Clipboard copy captures the selected ranges and reads them in bounded windows. Each completed window is encoded as TSV; the browser consumes the text as a single clipboard item. A promised payload lets the clipboard write start during the original user gesture.
|
|
112
|
+
|
|
113
|
+
For master/detail layouts, the virtualizer retains visual row positions. The spreadsheet indexes the expanded detail positions to move between data rows and to apply clipboard and fill operations in data order.
|
|
114
|
+
|
|
115
|
+
Core's opt-in column reordering applies sibling preferences to the definitions passed to TanStack. A pointer drag resolves the destination against logical column boxes and holds capture on the header while center columns virtualize. The same sibling rules serve keyboard moves and successive grip activation.
|
|
116
|
+
|
|
117
|
+
The horizontal virtualizer stores column offsets and pin boundaries with the layout. A binary search locates the first visible center column. The mounted leaves identify the grouped headers using a per-pane ancestry index, so horizontal scroll work follows the visible columns, pinned columns and header depth.
|
|
118
|
+
|
|
119
|
+
Local [merged cells](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/core-engine.spec.md#merged-cells) use a rectangle index over logical rows and columns. The viewport mounts each intersecting merge once, preserves the anchor used for accessibility and edits, and clips its paint to the scaled track beneath pinned columns.
|
|
120
|
+
|
|
121
|
+
Pro's committed query is distinct from form drafts and asynchronously restored column preferences. An opt-in saved query read waits up to its configured deadline. The first commit combines the resulting fields with the current URL and controlled props, replaces the history entry, and starts rows and category counts. A single query slot tracks active requests by normalized key, aborts superseded work and checks each generation. A separate slot handles category counts. A pending query intent can receive controlled acknowledgements across renders. The controller keeps its staged fields out of the accepted query until they are all confirmed. Export consumers receive the query corresponding to the last accepted batch of rows. For full-query Excel export, Pro opens a host-provided revision and passes ordered, validated blocks to the workbook handler. The Excel plugin owns file encoding. Migration converters preserve native field paths and emit diagnostics for callbacks with different semantics.
|
|
122
|
+
|
|
123
|
+
Category tabs track keyboard focus within each visible list. The committed query supplies the selected path and labels the shared grid panel. Host changes to the query view and a Pro-owned page reset use a single query commit.
|
|
124
|
+
|
|
125
|
+
Each URL-synchronized grid tracks its own decoded query in browser history. Only navigation that changes that query enters the controller's replay path, preserving pending input in other grids on the page.
|
|
126
|
+
|
|
127
|
+
The query form and the header filter dialog share schema inputs. Header filter edits stay local until an explicit column change. The accepted column value is copied into the query form while its other drafts are preserved. The header dialog mounts in the owning theme container.
|
|
128
|
+
|
|
129
|
+
Pro feeds Core header moves into the same column preference as the toolbar. It reconciles the visible heading tree with the schema's hidden leaves and uses the current visible pin panes for export order.
|
|
130
|
+
|
|
131
|
+
For large local Pro queries, the browser Worker caches sort and filter columns and returns a page of original row positions. Core's compute protocol serves applications that supply full columnar datasets and edit transactions. Both paths avoid feeding the complete row model through TanStack.
|
|
132
|
+
|
|
133
|
+
When an application supplies [host-owned pages](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/pro-crud.spec.md#host-owned-pages), Pro keeps the same query intent handling and renders the page supplied by the host. The host controls page loading, retry and the authoritative result metadata.
|
|
134
|
+
|
|
135
|
+
Spreadsheet mode adds a coordinate selection model and an on-demand cell editor. Core sends scalar values through validation and the edit interface, which accepts an authoritative transaction ACK and inverse patches. Pro selects editors and edit permissions through the same column schema used for display, search and filters. A recovering Worker client captures submitted inputs, replays confirmed batches against its owned dataset checkpoint, rebuilds active views and then resumes queued work.
|
|
136
|
+
|
|
137
|
+
The [compute protocol](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/wasm-protocol.spec.md) reuses the row order when a view's definition and dependencies remain current. Spreadsheet actions bridge to one edit transaction, and recovery retries an interrupted edit with its original transaction ID.
|
|
138
|
+
|
|
139
|
+
[Selection summaries](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/core-engine.spec.md#selection-summaries) run against Worker views when the spreadsheet uses raw source values. Sheets with custom value projections read bounded blocks and yield between batches of main-thread work.
|
|
140
|
+
|
|
141
|
+
Enterprise features are explicit imports. Core supports pinned rows, dynamic heights, local cell spans, row drag, trees and nested details. Each nested grid handles its own spreadsheet input. The pivot plugin owns grouping, aggregation, filters and server-side blocks. The Excel plugin indexes the ZIP directory and streams worksheet parts in workbook tab order. Its writer flushes compressed batches against sink backpressure and observes cancellation while waiting on rows or writes. The Charts plugin renders inline sparklines and conditional formats and maps a Core spreadsheet selection to a chart adapter's series and categories. The Rust worker shares the JS transaction and viewport contract while providing native numeric sorting, filters and aggregates.
|
|
142
|
+
|
|
143
|
+
The [server-side tree](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/ssrm.spec.md) keeps a sparse list of spans for the expanded hierarchy. Core reads the requested window through its tree source capability and renders loaded siblings while child blocks resolve. New windows release abandoned requests and reuse in-flight blocks where both windows overlap.
|
|
144
|
+
|
|
145
|
+
[Pivot and formula sessions](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/specs/analytics.spec.md) use dedicated Workers when their workflows become active. Large pivot views batch numeric reducers through a lazily loaded Rust kernel. JavaScript retains the layout and source-order semantics, the Worker reuses projected columns, and the host applies custom reducers. Formula sessions keep the dependency graph off the main thread, resume formulas as their references resolve, and use acknowledged raw values for recovery.
|
|
146
|
+
|
|
147
|
+
The pivot session applies filters against its cached projections before aggregation. Sidebar filter drafts stay in the UI until the host applies them. Report-column visibility and order change the rendered columns without a pivot computation.
|
|
148
|
+
|
|
149
|
+
# Roadmap
|
|
150
|
+
|
|
151
|
+
| Milestone | Deliverables | Exit criteria |
|
|
152
|
+
| --- | --- | --- |
|
|
153
|
+
| M0 | Workspace, published contracts, fixtures, structured verification | React 17/TS4, 18 and 19 packed hosts typecheck, build and run |
|
|
154
|
+
| M1 | Two-dimensional virtual grid, pinned columns, grouped headers, resizing, reordering, worker sorting, native themes, benchmark | 500,000 rows reach the final row and meet agreed paint, scroll, sort and size budgets. Column moves work across the virtual window, and four theme snapshots and dual-locale isolation pass |
|
|
155
|
+
| M2 | Pro schema, value types, tabs, forms, toolbar, persistence, URL, selection, migration adapters | Migrated Arco and AntD examples pass request-race, StrictMode, history and persistence cases |
|
|
156
|
+
| M3 | Range selection, fill handle, TSV, keyboard, editing, undo/redo, aggregates, context menu | Cross-window edit and undo after worker recovery pass on 500,000 rows. IME editing passes in browser |
|
|
157
|
+
| M4 | Grouping, pivot, SSRM with inline expansion, filters, detail, dynamic rows, merging, row drag, tree, Excel, charts, Rust/WASM formulas | Shared engine contract passes in both engines. WASM sort and size budgets pass. The server tree reaches the end of a large group with bounded block reads |
|
|
158
|
+
| M5 | Bilingual documentation, sandbox, benchmark, agent skill, published packages and React 17 adoption pilot | All verification layers pass. Docs and npm packages are reachable. The pilot passes on the agreed real list page |
|
|
159
|
+
|
|
160
|
+
The two first-release scenarios are a production-style Pro migration and a 500,000-row virtual grid. Performance claims require a recorded Chromium run and reference machine.
|
|
161
|
+
|
|
162
|
+
## First delivery
|
|
163
|
+
|
|
164
|
+
The nine packages are available from npm and as versioned GitHub release tarballs. The M5 gate checks the deployed documentation and both distribution channels. An internal rollout remains pending. See the [status board](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/progress/STATUS.md) and [publishing workflow](https://github.com/Han-wangyu/opengrid-ui/blob/main/docs/releasing.md).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: opengrid
|
|
3
|
+
description: Build and migrate OpenGrid React tables, CRUD pages, virtual grids, and spreadsheet interactions with Arco Design or Ant Design.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# OpenGrid
|
|
7
|
+
|
|
8
|
+
Use this skill when adding an OpenGrid table or migrating native Arco or Ant Design columns.
|
|
9
|
+
|
|
10
|
+
1. Match the host's React, TypeScript, and design-system versions against the compatibility matrix. Use the public tarballs from the tagged GitHub release.
|
|
11
|
+
2. Import `@opengrid-ui/core/styles.css` and also `@opengrid-ui/pro/styles.css` when rendering ProGrid.
|
|
12
|
+
3. Pick `@opengrid-ui/pro` for a host-neutral CRUD UI or the `arco` and `antd` adapter package for native tokens, locale, and overlays. Set a stable row ID.
|
|
13
|
+
4. Declare fields, labels, search controls, and renderers in one column schema. Native converters return diagnostics. Resolve any diagnostic relevant to the current page.
|
|
14
|
+
5. Use the single request callback for remote CRUD. Pass AbortSignal to the API and keep pagination and controls in the supplied dual-mode contract. Keep URL ownership with one layer.
|
|
15
|
+
6. ProGrid sorts and filters local `rows` above 5,000 records in a Worker. For a large columnar dataset and explicit viewport control, initialize an engine, create a view, and pass `computedSource(engine, view)` to Core. Only enable spreadsheet writes when an authoritative transaction handler is available.
|
|
16
|
+
7. Pass `columnReordering` to Core to expose drag, tap and keyboard moves. Use `columnReordering={{ order, onOrderChange }}` for a persisted order of group and leaf IDs. Each gesture stays within the original group and pin pane.
|
|
17
|
+
8. For inline server groups, use `useServerTree` from the pivot plugin and pass its source to Core. Keep the provider and accessors stable, and return each path's total with its requested block. Include group and row identity fields in every projection.
|
|
18
|
+
9. When a host request hook returns an already paginated result, pass `pageData={{ rows, total, loading }}`. Keep the host request and URL wiring through the existing query callbacks. Use `pager={false}` to keep the host's pager.
|
|
19
|
+
10. For a configurable pivot report, use `PivotSidebar` with `columnSettings` and `filters`. Send the applied expression to `usePivot` and render `visiblePivotColumns` from the report. Import the pivot sidebar stylesheet once in the host.
|
|
20
|
+
7. For chart actions, use the Charts plugin's `chartMenuItem` in `spreadsheet.contextMenu` and render the `ChartRange` delivered to your app. The selection reader works with local rows and computed viewports.
|
|
21
|
+
8. Use `usePivot` to tie a pivot Worker to a React view. Use `createFormulaSession` for background formula recalculation and dispose it when leaving the workflow.
|
|
22
|
+
9. Validate via an isolated consumer install and its actual host build. Exercise deep links, focus, overlays, edit/undo and representative scrolling with Chromium.
|
|
23
|
+
|
|
24
|
+
See [API contracts](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/specs), the [live sandbox](https://han-wangyu.github.io/opengrid-ui/) and the [benchmark methodology](https://github.com/Han-wangyu/opengrid-ui/tree/main/docs/benchmarks).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
export interface WorkbookStyle {
|
|
3
|
+
bold?: boolean;
|
|
4
|
+
fontColor?: string;
|
|
5
|
+
fillColor?: string;
|
|
6
|
+
align?: 'left' | 'center' | 'right';
|
|
7
|
+
numberFormat?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface WorkbookCell {
|
|
10
|
+
value: CellValue;
|
|
11
|
+
style?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ExportColumn {
|
|
14
|
+
id: string;
|
|
15
|
+
header: string;
|
|
16
|
+
width?: number;
|
|
17
|
+
style?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface WorkbookSheet {
|
|
20
|
+
name: string;
|
|
21
|
+
columns: readonly ExportColumn[];
|
|
22
|
+
rows: Iterable<readonly (CellValue | WorkbookCell)[]> | AsyncIterable<readonly (CellValue | WorkbookCell)[]>;
|
|
23
|
+
headers?: readonly (readonly (CellValue | WorkbookCell)[])[];
|
|
24
|
+
merges?: readonly string[];
|
|
25
|
+
}
|
|
26
|
+
export interface WorkbookOptions {
|
|
27
|
+
styles?: Readonly<Record<string, WorkbookStyle>>;
|
|
28
|
+
sink?: WritableStream<Uint8Array>;
|
|
29
|
+
signal?: AbortSignal;
|
|
30
|
+
}
|
|
31
|
+
export interface WorkbookReadRow {
|
|
32
|
+
sheet: string;
|
|
33
|
+
row: number;
|
|
34
|
+
cells: CellValue[];
|
|
35
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CellValue } from '@opengrid-ui/core/engine';
|
|
2
|
+
import type { WorkbookCell, WorkbookOptions, WorkbookSheet } from './types.js';
|
|
3
|
+
export declare function writeWorkbook(sheets: readonly WorkbookSheet[], options?: WorkbookOptions): Promise<Uint8Array>;
|
|
4
|
+
export interface RowSnapshot {
|
|
5
|
+
total: number;
|
|
6
|
+
revision: string | number;
|
|
7
|
+
read(range: readonly [number, number], revision: string | number): Promise<readonly (readonly (CellValue | WorkbookCell)[])[]>;
|
|
8
|
+
}
|
|
9
|
+
export declare function rowsFromSnapshot(snapshot: RowSnapshot, page?: number): AsyncGenerator<readonly (WorkbookCell | CellValue)[], void, unknown>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { WorkbookStyle } from './types.js';
|
|
2
|
+
export declare const xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
|
|
3
|
+
export declare const mainNS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
|
4
|
+
export declare const officeNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
5
|
+
export declare const packageNS = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
6
|
+
export declare function xml(text: string): string;
|
|
7
|
+
export declare function spreadsheetString(text: string, attribute?: boolean): string;
|
|
8
|
+
export declare function decodeSpreadsheetString(text: string): string;
|
|
9
|
+
export declare function excelColumn(index: number): string;
|
|
10
|
+
export declare function columnOffset(reference: string): number;
|
|
11
|
+
export declare function styleXML(styles: readonly WorkbookStyle[]): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@opengrid-ui/plugin-excel",
|
|
3
|
-
"version": "0.0.0-stage",
|
|
4
|
-
"stub": true,
|
|
5
|
-
"description": "Temporary package placeholder for staged publishing"
|
|
6
|
-
}
|
|
1
|
+
{"name":"@opengrid-ui/plugin-excel","version":"0.1.37","license":"MIT","type":"module","repository":{"type":"git","url":"git+https://github.com/Han-wangyu/opengrid-ui.git","directory":"packages/plugin-excel"},"files":["dist","LICENSE"],"main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"}},"sideEffects":false,"publishConfig":{"access":"public"},"scripts":{"build":"node ../../scripts/build-package.mjs"},"dependencies":{"fflate":"0.8.3","saxes":"6.0.0","unzipit":"2.1.1"},"devDependencies":{"@opengrid-ui/core":"workspace:^"}}
|
package/README.md
DELETED