@8sheets/data-grid 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/a11y/cell-alt-text.js +1 -1
- package/api/serialize.js +1 -1
- package/api/style-refs.js +1 -1
- package/calc/adjust.js +1 -1
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/array.js +1 -1
- package/calc/functions/database.js +1 -1
- package/calc/functions/date.js +1 -1
- package/calc/functions/engineering.js +1 -1
- package/calc/functions/financial.js +1 -1
- package/calc/functions/helpers.js +1 -1
- package/calc/functions/index.js +3 -2
- package/calc/functions/info.js +1 -1
- package/calc/functions/logical.js +1 -1
- package/calc/functions/lookup.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/functions/stat.js +1 -1
- package/calc/functions/text.js +1 -1
- package/calc/parser.js +2 -2
- package/calc/shown-refs.js +1 -0
- package/calc/values.js +1 -1
- package/calcx/calc-control.js +1 -0
- package/calcx/external-read.js +1 -1
- package/calcx/external.js +1 -1
- package/calcx/lang/convert.js +1 -1
- package/cells/axis-ops.js +1 -1
- package/cells/book-css.js +7 -2
- package/cells/cell-styles-xml.js +1 -1
- package/cells/cf-engine.js +1 -1
- package/cells/cf-file.js +1 -1
- package/cells/docprops-xml.js +2 -2
- package/cells/filter-eval.js +1 -0
- package/cells/filter-file.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/find.js +1 -1
- package/cells/goto.js +1 -1
- package/cells/link-model.js +1 -0
- package/cells/name-box.js +1 -1
- package/cells/note-box.js +3 -0
- package/cells/options.js +1 -1
- package/cells/outline-column.js +1 -1
- package/cells/protected-menu.js +1 -0
- package/cells/rich-data-xml.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/cells/sheet-views-file.js +2 -0
- package/cells/shift-check.js +1 -1
- package/cells/sort-compare.js +1 -0
- package/cells/ui-kit.js +1 -1
- package/cells/undo-group.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/address.js +1 -1
- package/core/autofill.js +1 -1
- package/core/axis.js +1 -1
- package/core/cond-format.js +1 -1
- package/core/culture.js +5 -1
- package/core/custom-views.js +1 -1
- package/core/data-tools.js +1 -0
- package/core/date-codes.js +1 -0
- package/core/default-names.js +1 -1
- package/core/edit-ranges.js +1 -0
- package/core/formula-refs.js +1 -1
- package/core/host-rules.js +1 -0
- package/core/input.js +1 -1
- package/core/numfmt.js +1 -1
- package/core/precision.js +1 -0
- package/core/protection.js +1 -1
- package/core/region-input.js +1 -1
- package/core/rule-refs.js +1 -0
- package/core/shared-view.js +1 -0
- package/core/sheet.js +1 -1
- package/core/sparklines.js +1 -1
- package/core/sparse.js +1 -1
- package/core/spills.js +1 -0
- package/core/strings.js +1 -1
- package/core/structure.js +1 -1
- package/core/table-columns.js +1 -0
- package/core/tables.js +2 -2
- package/core/validation-ranges.js +1 -1
- package/core/whatif.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/formula.js +1 -1
- package/datasheets/manager.js +1 -1
- package/datasheets/path-binding.js +1 -1
- package/datasheets/persist-writer.js +1 -1
- package/datasheets/persist.js +1 -1
- package/datasheets/report.js +1 -1
- package/extras/getdata/persist.js +2 -2
- package/extras/getdata/rows.js +1 -1
- package/extras/getdata/shared-steps.js +1 -0
- package/extras/getdata/steps-formula.js +1 -0
- package/extras/getdata/steps-more.js +1 -0
- package/extras/getdata/steps-tables.js +1 -0
- package/extras/getdata/steps.js +1 -1
- package/i18n/de/a11y.js +1 -0
- package/i18n/de/cells.js +2 -0
- package/i18n/de/charts.js +1 -0
- package/i18n/de/common.js +1 -0
- package/i18n/de/datasheets.js +1 -0
- package/i18n/de/format.js +1 -0
- package/i18n/de/misc.js +1 -0
- package/i18n/de/pivot.js +1 -0
- package/i18n/de/proofing.js +1 -0
- package/i18n/de/ribbon.js +1 -0
- package/i18n/de/shapes.js +1 -0
- package/i18n/de/shell.js +3 -0
- package/i18n/de/touch.js +1 -0
- package/i18n/de.js +1 -0
- package/i18n/en/cells.js +2 -1
- package/i18n/en/charts.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/misc.js +1 -1
- package/i18n/en/pivot.js +1 -1
- package/i18n/en/proofing.js +1 -1
- package/i18n/en/ribbon.js +1 -1
- package/i18n/en/shapes.js +1 -1
- package/i18n/en/shell.js +3 -2
- package/i18n/en/touch.js +1 -1
- package/i18n/es/a11y.js +1 -0
- package/i18n/es/cells.js +2 -0
- package/i18n/es/charts.js +1 -0
- package/i18n/es/common.js +1 -0
- package/i18n/es/datasheets.js +1 -0
- package/i18n/es/format.js +1 -0
- package/i18n/es/misc.js +1 -0
- package/i18n/es/pivot.js +1 -0
- package/i18n/es/proofing.js +1 -0
- package/i18n/es/ribbon.js +1 -0
- package/i18n/es/shapes.js +1 -0
- package/i18n/es/shell.js +3 -0
- package/i18n/es/touch.js +1 -0
- package/i18n/es.js +1 -0
- package/i18n/fr/a11y.js +1 -0
- package/i18n/fr/cells.js +2 -0
- package/i18n/fr/charts.js +1 -0
- package/i18n/fr/common.js +1 -0
- package/i18n/fr/datasheets.js +1 -0
- package/i18n/fr/format.js +1 -0
- package/i18n/fr/misc.js +1 -0
- package/i18n/fr/pivot.js +1 -0
- package/i18n/fr/proofing.js +1 -0
- package/i18n/fr/ribbon.js +1 -0
- package/i18n/fr/shapes.js +1 -0
- package/i18n/fr/shell.js +3 -0
- package/i18n/fr/touch.js +1 -0
- package/i18n/fr.js +1 -0
- package/i18n/index.js +1 -1
- package/i18n/languages.js +1 -1
- package/i18n/pl/cells.js +2 -1
- package/i18n/pl/charts.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/misc.js +1 -1
- package/i18n/pl/pivot.js +1 -1
- package/i18n/pl/proofing.js +1 -1
- package/i18n/pl/ribbon.js +1 -1
- package/i18n/pl/shapes.js +1 -1
- package/i18n/pl/shell.js +3 -2
- package/i18n/pl/touch.js +1 -1
- package/io/blob-sink.js +1 -0
- package/io/canonical-xml.js +1 -0
- package/io/client.js +1 -1
- package/io/crypto/cfb-build.js +1 -0
- package/io/crypto/cfb-read.js +1 -1
- package/io/crypto/cfb-write.js +1 -1
- package/io/crypto/errors.js +1 -1
- package/io/csv.js +8 -8
- package/io/encoding.js +1 -0
- package/io/foreign-sheets.js +2 -2
- package/io/io.worker.js +1 -1
- package/io/open-package.js +1 -0
- package/io/package-paths.js +1 -1
- package/io/plan.js +1 -1
- package/io/text-split.js +3 -3
- package/io/xls/chart-sheet.js +1 -0
- package/io/xls/chart.js +1 -0
- package/io/xls/crypt.js +1 -0
- package/io/xls/dml-color.js +1 -0
- package/io/xls/drawing.js +1 -0
- package/io/xls/formula.js +1 -0
- package/io/xls/geometry.js +1 -0
- package/io/xls/index.js +1 -0
- package/io/xls/pictures.js +1 -0
- package/io/xls/pivot.js +1 -0
- package/io/xls/props.js +1 -0
- package/io/xls/records.js +1 -0
- package/io/xls/shapes.js +1 -0
- package/io/xls/sheet-ext.js +1 -0
- package/io/xls/sheet.js +1 -0
- package/io/xls/styles.js +1 -0
- package/io/xls/vba.js +1 -0
- package/io/xls/workbook.js +1 -0
- package/io/xlsb/filter.js +1 -0
- package/io/xlsb/formula.js +2 -0
- package/io/xlsb/functions.js +1 -0
- package/io/xlsb/index.js +1 -0
- package/io/xlsb/parts.js +1 -0
- package/io/xlsb/pivot.js +1 -0
- package/io/xlsb/records.js +1 -0
- package/io/xlsb/sheet-ext.js +1 -0
- package/io/xlsb/sheet.js +1 -0
- package/io/xlsb/slicer.js +1 -0
- package/io/xlsb/styles.js +1 -0
- package/io/xlsb/workbook.js +1 -0
- package/io/xlsb/xml.js +2 -0
- package/io/xlsx-read.js +1 -1
- package/io/xlsx-styles.js +2 -2
- package/io/xlsx-tail.js +1 -1
- package/io/xlsx-write.js +2 -2
- package/io/xml-escape.js +1 -1
- package/io/xml-scan.js +2 -2
- package/io/zip-reader.js +1 -1
- package/objects/chart-model.js +1 -1
- package/objects/drawing-xml.js +1 -1
- package/package.json +1 -1
- package/pivot/calc-items.js +1 -0
- package/pivot/engine.js +1 -1
- package/pivot/xml.js +2 -2
- package/print/note-pages.js +2 -0
- package/print/page-setup.js +1 -1
- package/print/paginate.js +1 -1
- package/print/pdf-crypt.js +1 -0
- package/print/pdf-links.js +1 -0
- package/print/pdf-tags.js +1 -0
- package/print/pdf.js +24 -13
- package/print/render-page.js +3 -3
- package/print/shown-notes.js +1 -0
- package/shapes/form-xml.js +1 -1
- package/slicers/custom-styles.js +1 -1
- package/slicers/format.js +1 -1
- package/slicers/structured.js +1 -1
- package/slicers/write.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/menu-base.js +1 -1
- package/ui/protection-ui.js +1 -1
package/datasheets/formula.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHUNK_BITS as C,CHUNK_MASK as b,CHUNK_SIZE as A,EMPTY as F,NUM as R,Sheet as L}from"../core/sheet.js";import{colName as M}from"../core/address.js";import{Engine as S}from"../calc/engine.js";import{toFileFormula as $}from"../calc/parser.js";import{Arr as D,ERR as _,Lambda as O,Ref as I,RefList as K,XlError as N}from"../calc/values.js";import{extractWindowCalls as T}from"./window.js";const v=()=>({kinds:new Uint8Array(A),values:new Float64Array(A),styles:null});function E(h,e,t){const s=h.table,{kinds:i,values:u}=e,n=Math.min(A,s.rowCount-t),{data:
|
|
1
|
+
import{CHUNK_BITS as C,CHUNK_MASK as b,CHUNK_SIZE as A,EMPTY as F,NUM as R,Sheet as L}from"../core/sheet.js";import{colName as M}from"../core/address.js";import{Engine as S}from"../calc/engine.js";import{toFileFormula as $}from"../calc/parser.js";import{Arr as D,ERR as _,Lambda as O,Ref as I,RefList as K,XlError as N}from"../calc/values.js";import{extractWindowCalls as T}from"./window.js";const v=()=>({kinds:new Uint8Array(A),values:new Float64Array(A),styles:null});function E(h,e,t){const s=h.table,{kinds:i,values:u}=e,n=Math.min(A,s.rowCount-t),{data:f,kinds:m,isString:r}=h,a=h.type==="boolean";if(n<=0){i.fill(0);return}if(r)for(let o=0;o<n;o++){const l=f[t+o];i[o]=l<0?0:2,u[o]=l}else if(m!==null)for(let o=0;o<n;o++)i[o]=m[t+o],u[o]=f[t+o];else{const o=a?3:R;for(let l=0;l<n;l++){const d=f[t+l];d!==d?i[l]=F:(i[l]=o,u[l]=d)}}if(n<A&&i.fill(0,n),s.deletedCount>0){const{alive:o}=s;for(let l=0;l<n;l++)o[t+l]===0&&(i[l]=F)}}function V(h,e){let t="",s="";for(let i=0;i<h.length;i++){const u=h[i];if(u==='"'){t+=e(s),s="";let n=i+1;for(;!(n>=h.length);)if(h[n]==='"')if(h[n+1]==='"')n+=2;else break;else n++;t+=h.slice(i,n+1),i=n}else s+=u}return t+e(s)}const H=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,B=/\[(@?)\[?([^[\]]+?)\]?\]/g;class Z{constructor(e){this.manager=e,this.engine=null,this.sheets=new Map}_engineFor(){return this.engine===null&&(this.engine=new S({sheets:[],strings:this.manager.strings,dateOffset:0}),this.engine.legacy=!0),this.engine}_sheet(e){let t=this.sheets.get(e);return t===void 0&&(t=new L(`__data_${e.name}`),this.sheets.set(e,t)),t.maxRow=e.rowCount-1,t.maxCol=e.columns.length-1,t}bind(e){const t=e.table,s=new Set;let i=!1,u=!1;const n=T(String(e.formula).replace(/^=/,""),t,m=>{s.add(m.name),i=!0}),f=V(n,m=>m.replace(H,(r,a,o)=>{const l=o.trim();if(!l.includes("."))return r;const d=t.rollupColumn(a.toUpperCase(),l);return d?(s.add(d.name),`$${M(d.index)}1`):r}).replace(B,(r,a,o)=>{const l=o.trim(),d=t.column(l);if(!d)return u=!0,"#NAME?";s.add(d.name);const y=M(d.index);return a==="@"?`$${y}1`:(i=!0,`$${y}:$${y}`)}));if(e.deps=[...s],e.rangeDep=i,e.stale=!0,e.compiled=null,u){e.compiled={fn:()=>_.NAME,ok:!1};return}try{const r=this._engineFor().template($(f),0,e.index);e.compiled={fn:r.fn,ok:!r.external}}catch{e.compiled={fn:()=>_.NAME,ok:!1}}this._hasCycle(e)&&(e.compiled={fn:()=>_.REF,ok:!1},e.deps=[])}_hasCycle(e){const t=e.table,s=new Set,i=u=>{if(u===e.name)return!0;if(s.has(u))return!1;s.add(u);const n=t.column(u);return n?n.deps.some(i):!1};return e.deps.some(i)}_evaluate(e,t,s,i,u){let n;try{n=e(t,s,i)}catch(f){return f instanceof N?f:_.VALUE}if(n instanceof I||n instanceof K)try{n=u.refAuto(n,t,s)}catch(f){return f instanceof N?f:_.VALUE}return n instanceof D&&(n=n.data[0]),n instanceof O?_.CALC:typeof n=="number"&&!Number.isFinite(n)?_.NUM:n===void 0?null:n}computeAll(e){const t=e.table;e.compiled===null&&this.bind(e);const s=e.deps.map(p=>t.column(p));for(const p of s)t.ensure(p);const i=this._engineFor(),u=this._sheet(t),n=t.rowCount,{fn:f}=e.compiled,m=e.index,r=n+b>>>C,a=u.columns;a.length=0;const o=s.map(()=>v());for(const p of s)a[p.index]=[];if(e.rangeDep)for(const p of s){const x=a[p.index];for(let k=0;k<r;k++){const c=v();E(p,c,k<<C),x[k]=c}}const l=t.alive,d=t.deletedCount>0;e.kinds=null;const y=e.data,w=!e.isString;for(let p=0;p<r;p++){const x=p<<C;if(!e.rangeDep)for(let c=0;c<s.length;c++){const g=a[s[c].index];E(s[c],o[c],x),p>0&&(g[p-1]=void 0),g[p]=o[c]}const k=Math.min(n,x+A);for(let c=x;c<k;c++){if(d&&l[c]===0){e.put(c,null);continue}const g=this._evaluate(f,c,m,u,i);w&&e.kinds===null&&typeof g=="number"?y[c]=g:e.type==="any"||g===null||typeof g=="number"?e.put(c,g):e.put(c,e.type==="any"?g:U(e,g))}}a.length=0}computeRow(e,t){const s=e.table;e.compiled===null&&this.bind(e);const i=e.deps.map(r=>s.column(r));for(const r of i)r.stale&&s.ensure(r);const u=this._engineFor(),n=this._sheet(s),f=n.columns;f.length=0;const m=t>>>C;for(const r of i){const a=v();E(r,a,m<<C),f[r.index]=[],f[r.index][m]=a}if(s.alive[t]===0)e.put(t,null);else{const r=this._evaluate(e.compiled.fn,t,e.index,n,u);e.put(t,typeof r=="number"||r===null||e.type==="any"?r:U(e,r))}e.revision++,f.length=0}evaluateOnce(e,t,s){const i={table:e,index:e.columns.length,formula:s,deps:[],name:"\0temp",compiled:null};this.bind(i);const u=i.deps.map(a=>e.column(a));for(const a of u)e.ensure(a);const n=this._sheet(e),f=n.columns;f.length=0;const m=t>>>C;for(const a of u)if(f[a.index]=[],i.rangeDep){const o=e.rowCount+b>>>C;for(let l=0;l<o;l++){const d=v();E(a,d,l<<C),f[a.index][l]=d}}else{const o=v();E(a,o,m<<C),f[a.index][m]=o}const r=this._evaluate(i.compiled.fn,t,i.index,n,this._engineFor());return f.length=0,r}}function U(h,e){try{return h.coerce(e)}catch{return null}}export{Z as FormulaColumns,E as fillRawChunk};
|
package/datasheets/manager.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./query-function.js";import{Sheet as u}from"../core/sheet.js";import{DataManager as l}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as
|
|
1
|
+
import"./query-function.js";import{Sheet as u}from"../core/sheet.js";import{DataManager as l}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as c}from"./table-sheet.js";import{createPlanTable as m,GanttSheet as f}from"./gantt.js";import{ReportTemplate as g}from"./report.js";import{TableBinding as p}from"./bind.js";import{CellPathBinding as S,RowsBinding as b}from"./path-binding.js";import{attachDataEntry as w}from"./report-entry.js";import{buildDataSheetPackage as _,dataSheetsFromJSON as v,dataSheetsToJSON as T,readDataSheetPackage as k,rowBatches as B}from"./persist.js";class O{constructor(e){this.book=e,this.manager=new l(e),e.dataSheets=this,this.sheets=[],this.bindings=[],this.reports=[],this.loaded=!1,this.onSheetAdded=null,this.savedSheets=null,this.loadNotes=[],this._hookInput(e)}_hookInput(e){if(e.setInputRouted)return;e.setInputRouted=!0;const t=e.setInput;e.setInput=function(r,i,n,a,d){const{sheet:h}=r;if(!(h.routeInput!==void 0&&h.routeInput(r,i,n,a)))return t.call(this,r,i,n,a,d)}}_uniqueName(e){const t=r=>this.book.sheets.some(i=>i.name.toLowerCase()===r.toLowerCase());let s=e;for(let r=2;t(s);r++)s=`${e}${r}`;return s}_insert(e,t=!0,s=null){const{book:r}=this;r.sheets.push(e),t&&(r.activeSheet=r.sheets.length-1),r.structureEdited=!0,r.engine?.sheetsChanged(),s?.(),r._emit("sheets")}_registerSheet(e){this.sheets.push(e),this.onSheetAdded?.(e)}_registerBinding(e){this.bindings.push(e),this.onSheetAdded?.(e.sheet)}isDataSheet(e){return e.isVirtual===!0}addTableFromSheetTable(e,t=null){const s=e,r=this.manager.addTable(t??`${s.name} Data`);return r.loadSheet(this.book,s.sheet,{r0:s.r0,c0:s.c0,r1:s.r1-s.totalsRows,c1:s.c1}),r}addTable(e,t){return this.manager.addTable(e,t)}addTableSheet(e,t,s={},r={}){const i=this.manager.table(t),n=s instanceof o?s:new o(i,s),a=new c(this.book,this._uniqueName(e),n,r);return this._insert(a,r.activate!==!1,()=>this._registerSheet(a)),a}addGanttSheet(e,t=null,s={}){const r=Array.isArray(t)?t:[],i=t&&!Array.isArray(t)?this.manager.table(t):m(this.manager,this._freeTable(`${e} Tasks`),r),n=new f(this.book,this._uniqueName(e),i,s);return this._insert(n,s.activate!==!1,()=>this._registerSheet(n)),n}_freeTable(e){let t=e;for(let s=2;this.manager.tables.has(t);s++)t=`${e} ${s}`;return t}addReportSheet(e,t={}){const s=new u(this._uniqueName(e));let r=null;return this._insert(s,t.activate!==!1,()=>{r=new g(this.manager,s,t),this.reports.push(r),this.onSheetAdded?.(s)}),r}bindPaths(e,t=null,s={}){const r=new S(this.book,e,t,s);return this._registerBinding(r),r}bindRows(e,t,s,r={}){const i=new b(this.book,e,t,s,r);return this._registerBinding(i),i}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return w(this.book,e,e.output)}toJSON(e){return T(this,e)}rowBatches(e){return B(this.manager.table(e))}fromJSON(e){return v(e,this),this}bindTable(e,t,s,r={}){const i=new p(this.book,e,t,s,r);return this._registerBinding(i),i}removeBinding(e){e.unbind(),this.bindings=this.bindings.filter(t=>t!==e)}_pruneDeleted(){const e=new Set(this.book.sheets);this.sheets=this.sheets.filter(t=>e.has(t)),this.bindings=this.bindings.filter(t=>e.has(t.sheet)),this.reports=this.reports.filter(t=>e.has(t.sheet))}prepareSave(){this._pruneDeleted();for(const e of this.sheets)e.prepareSave();this.savedSheets=this.sheets.slice()}async savePackage(){for(const t of this.sheets)t.savePlanned?.();const e=await _(this);return e.parts.length===0&&!this.loaded?null:e}finishSave(){for(const e of this.savedSheets??[])e.finishSave();this.savedSheets=null}async load(e){return k(e,this)}}export{O as DataSheets};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{FORMULA as k,STR as q}from"../core/sheet.js";import{cellRef as B,colName as F,MAX_COLS as m}from"../core/address.js";import{translateFormula as T}from"../core/formula-refs.js";import{createTable as R,resizeTable as v}from"../core/tables.js";import{hookSheet as U,rawCells as p,TableBinding as $,unhookSheet as E,valueOfWrite as L,writeRaw as O}from"./bind.js";import{DataError as S}from"./data.js";import{getPath as y,setPath as w}from"./remote.js";const g=(i,t)=>i*m+t;function _(i){const t=i.book.dataSheets;t&&(t.bindings=t.bindings.filter(e=>e!==i)),i.unbind()}function C(i,t){const e=i.usedRange(),{captions:s,rows:r}=i.exportRows();switch(t){case"json":return JSON.stringify(r,null,2);case"csv":{const o=n=>{const h=n==null?"":String(n);return/[",\n]/.test(h)?`"${h.replace(/"/g,'""')}"`:h};return[s.map(o).join(","),...r.map(n=>s.map(h=>o(n[h])).join(","))].join(`\r
|
|
2
|
-
`)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class A{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},U(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,L(this.book.strings,s,r))}}class H extends A{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,M(n),{overLimitAsText:!0})}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const M=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class N extends A{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??z(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((a
|
|
2
|
+
`)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class A{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},U(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,L(this.book.strings,s,r))}}class H extends A{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,M(n),{overLimitAsText:!0})}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const M=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class N extends A{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??z(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((l,a)=>{const u=s.col+a;l.width&&t.cols.setSize(u,l.width),this.headerRows&&p.setCell.call(t,s.row,u,q,e.strings.add(l.caption??M(l.path??`Column${a+1}`)));const b=this._styleOf(l.format);if(l.formula){const d=String(l.formula).replace(/^=/,"");for(let f=0;f<r.length;f++)p.setCell.call(t,n+f,u,k,0),p.setFormula.call(t,n+f,u,{f:T(d,f,0),typed:!0}),b&&p.setStyle.call(t,n+f,u,b);return}for(let d=0;d<r.length;d++){const f=y(r[d],l.path);O(t,e.strings,n+d,u,f===void 0?null:f),b&&t.cellStyle(n+d,u)===0&&p.setStyle.call(t,n+d,u,b)}});for(let l=r.length;l<this.lastRows;l++)for(let a=0;a<o.length;a++)p.setCell.call(t,n+l,s.col+a,0,0),p.setFormula.call(t,n+l,s.col+a,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((l,a)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+a,s.col+a)}),this._notify(c,x),this.table&&this.book.engine){const l=this.anchor,a={r0:l.row,c0:l.col,r1:l.row+Math.max(1,r.length),c1:l.col+o.length-1};this.table.r1!==a.r1&&v(this.book,this.table,a,{cells:!1})}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function z(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}N.prototype.exportAs=function(t){return C(this,t)},$.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function I(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=I(e);return t}return null}export{H as CellPathBinding,N as RowsBinding,B as cellRef,F as colName,C as exportBinding,I as sampleOf,j as schemaOf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>"
|
|
1
|
+
const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>",()=>`${e}</Types>`)}function L(a,o){let t=a.replace(new RegExp(`<Relationship\\b[^>]*Type="${h(w)}"[^>]*/>`,"g"),"").replace(/<Relationship\b[^>]*Target="\/?(?:\.\.\/)?customXml\/ds8c[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[]){const r=s.replace(/^customXml\//,"");t=t.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*customXml/${h(r)}"[^>]*/>`),"")}const e=(o?.parts??[]).map((s,r)=>`<Relationship Id="rId8cDs${r+1}" Type="${b}" Target="/${s.file}"/>`).join("");return t.replace("</Relationships>",()=>`${e}</Relationships>`)}async function T(a,o){const t=new Uint8Array(262144);let e=0,s=0,r=0,i=0;const f=async()=>{e>0&&(await o(t.slice(0,e)),e=0)};for await(const p of a){let l=0;const d=p.length;if(i>0)if(i===1&&d>=2){const c=s<<16|p[0]<<8|p[1];l=2,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else if(i===2&&d>=1){const c=s<<16|r<<8|p[0];l=1,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else{i===1&&d===1&&(r=p[0],i=2);continue}for(;l+2<d;){e+4>t.length&&await f();const c=p[l]<<16|p[l+1]<<8|p[l+2];t[e]=n[c>>18],t[e+1]=n[c>>12&63],t[e+2]=n[c>>6&63],t[e+3]=n[c&63],e+=4,l+=3}l<d&&(s=p[l],i=1,l+1<d&&(r=p[l+1],i=2)),e+8>t.length&&await f()}i===1?(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4],t[e++]=61,t[e++]=61):i===2&&(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4|r>>4],t[e++]=n[(r&15)<<2],t[e++]=61),await f()}async function*E(a){const o=a.stream().getReader();for(;;){const{done:t,value:e}=await o.read();if(t)return;yield e}}async function N(a,o,t){for(const e of o?.parts??[]){t?.add(e.file);const s=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
2
|
<d xmlns="${x}" n="${e.name}" b="${e.bytes}">`;await a.add(e.file,async r=>{await r(m.encode(s)),await T(E(e.blob),r),await r(m.encode("</d>"))},{large:e.blob.size>2952790016})}}export{y as CUSTOM_XML_TYPE,S as MANIFEST_NAME,x as NS,X as partFileName,D as patchDataSheetContentTypes,L as patchDataSheetWorkbookRels,C as skipOldDataSheetParts,N as writeDataSheetParts};
|
package/datasheets/persist.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeBytes as Y}from"../core/strings.js";import{MANIFEST_NAME as L,NS as q,partFileName as K}from"./persist-writer.js";import{ROW as J}from"./data.js";import{TableView as Q}from"./view.js";import{TableSheet as Z}from"./table-sheet.js";import{GanttSheet as z,WorkCalendar as j}from"./gantt.js";import{ReportTemplate as ee}from"./report.js";import{TableBinding as te}from"./bind.js";import{CellPathBinding as ne,RowsBinding as oe}from"./path-binding.js";import{t as se}from"../i18n/index.js";const M=2,U=new TextEncoder,O=1<<18,A=()=>new Promise(e=>setTimeout(e,0)),$=e=>e!==null&&!e.lookup&&!e.rollup&&!e.window&&!e.name.startsWith("__formula:")&&!e.name.startsWith("__cross:");function F(e){const i={name:e.name,type:e.type};return e.caption!==e.name&&(i.caption=e.caption),e.format!=="General"&&!(e.type==="date"&&e.format==="yyyy-mm-dd")&&(i.format=e.format),e.readOnly&&(i.readOnly=!0),e.width!==null&&(i.width=e.width),e.hidden&&(i.hidden=!0),e.formula!==null&&(i.formula=e.formula),e.defaultValue!==null&&(i.defaultValue=e.defaultValue),e.required&&(i.required=!0),e.showNullAs!==null&&(i.showNullAs=e.showNullAs),e.validator!==null&&!e.validator.fn&&(i.validator=e.validator),e.trigger&&(i.trigger=e.trigger),i}function ie(e){const i=e.rowCount,{state:t,alive:r}=e;let o=!1;for(let l=0;l<i;l++)if(t[l]===J.PURGED&&r[l]===0){o=!0;break}if(!o)return null;const a=new Int32Array(i);let n=0;for(let l=0;l<i;l++)a[l]=t[l]===J.PURGED&&r[l]===0?-1:n++;return{map:a,count:n}}function C(e,i,t){if(t===null)return e.subarray(0,i);const r=new e.constructor(t.count);for(let o=0;o<i;o++)t.map[o]>=0&&(r[t.map[o]]=e[o]);return r}async function ae(e,i,t){const r=e.rowCount,o=ie(e),a=o?o.count:r,{strings:n}=e.manager,l=`t${i}/`,s=(d,h)=>(t.push({name:`${l}${d}`,blob:new Blob([h]),bytes:h.byteLength}),d),c=new Map,f=[],u=d=>{let h=c.get(d);return h===void 0&&(h=f.length,c.set(d,h),f.push(n.get(d))),h},m=[],g=[];let p=0;for(const d of e.columns){if(!$(d)||(m.push(F(d)),d.computed))continue;const h={field:d.name};if(d.isString){const b=C(d.data,r,o),y=new Int32Array(b.length);for(let w=0;w<b.length;w++){const D=b[w];y[w]=D<0?-1:u(D),++p%O===0&&await A()}h.encoding="i32",h.part=s(`c${d.index}.bin`,y)}else if(d.kinds!==null){const b=C(d.kinds,r,o),y=Float64Array.from(C(d.data,r,o));for(let w=0;w<y.length;w++)b[w]===2&&(y[w]=u(y[w])),++p%O===0&&await A();h.encoding="mixed",h.part=s(`c${d.index}.bin`,y),h.kinds=s(`c${d.index}.kinds`,b)}else h.encoding="f64",h.part=s(`c${d.index}.bin`,C(d.data,r,o));d.styles!==null&&(h.styles=s(`c${d.index}.styles`,C(d.styles,r,o))),g.push(h)}const S=[],k=new Float64Array(f.length+1);let x=0,v=[],N=0;const R=()=>{N!==0&&(S.push(U.encode(v.join(""))),v=[],N=0)};for(let d=0;d<f.length;d++){const h=re(f[d]);k[d]=x,x+=h,v.push(f[d]),N+=f[d].length,N>1<<20&&(R(),await A())}R(),k[f.length]=x,t.push({name:`${l}strings.bin`,blob:new Blob(S),bytes:x}),s("strings.idx",k);const G=C(e.alive,r,o),I=C(e.state,r,o);s("alive.bin",G),s("state.bin",I);const B=[];for(const[d,h]of e.originals){const b=o?o.map[d]:d;b<0||B.push([b,[...h].map(([y,w])=>[e.columns[y].name,_(w)])])}return{name:e.name,key:e.key,tracking:e.tracking,rowCount:a,dir:l,indexes:e.getIndexes(),windows:e.windowDefs,schema:e.schema,remote:E(e.remote),autoSync:e.autoSync,batch:e.batchSync,stringCount:f.length,fields:m,columns:g,originals:B,map:o}}function E(e){if(!e||typeof e!="object")return null;const i={};for(const[t,r]of Object.entries(e))typeof r!="function"&&(i[t]=r);return Object.keys(i).length>0?i:null}const _=e=>e!==null&&typeof e=="object"?{error:e.code}:e;function re(e){let i=e.length;for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=128)if(r<2048)i++;else if(r>=55296&&r<=56319){const o=e.charCodeAt(t+1);o>=56320&&o<=57343?(i+=2,t++):i+=2}else i+=2}return i}function T(e,i){const t=e.toJSON(),r=i.map;return r&&(t.pinnedRows=t.pinnedRows.map(o=>r.map[o]).filter(o=>o>=0),t.treeCollapsed=t.treeCollapsed.map(o=>r.map[o]).filter(o=>o>=0)),t}function le(e){return e.toJSON()}function W(e,i){let t=0;const r=new Map,{columns:o}=e;for(let a=0;a<o.length;a++){const n=o[a];if(n===void 0)continue;const l=n.length;for(let s=0;s<l;s++){const c=n[s];if(c===void 0)continue;const{kinds:f,values:u}=c;for(let m=0;m<f.length;m++){const g=f[m]&7;if(g===0)continue;let p;if(g===2){const k=u[m];if(p=r.get(k),p===void 0){p=7;const x=i.get(k);for(let v=0;v<x.length;v++)p=Math.imul(p,31)+x.charCodeAt(v)|0;r.set(k,p)}}else p=Math.round(u[m]*1e3)|0;const S=Math.imul((s<<10)+m+1,2654435761)^Math.imul(a+1,2246822507);t=t+Math.imul(p^S,625341585)|0}}}return t}function ce(e,i,t){return{sheet:e.name,kind:e.kindName,table:e.table.name,view:T(e.view,i(e.table)),options:e.options,gantt:e.kindName==="gantt"?e.toJSON():void 0,cells:W(e,t)}}function V(e,i){const{manager:t,sheets:r,bindings:o,reports:a,book:n}=e,l=s=>i.find(c=>c.name===s.name);return{format:"8sheets-datasheets",version:M,tables:i.map(({map:s,...c})=>c),relationships:t.relationships.map(s=>({from:s.from.name,fromField:s.fromField,to:s.to.name,toField:s.toField,name:s.name,inverse:s.inverse})),views:[...t.tables.values()].flatMap(s=>[...s.views.values()].map(c=>({table:s.name,name:c.name,view:T(c,l(s))}))),sheets:r.map(s=>ce(s,l,n.strings)),bindings:o.map(s=>s.toJSON?s.toJSON():{kind:"view",sheet:s.sheet.name,range:s.range,table:s.table.name,view:T(s.view,l(s.table)),options:{header:s.options.header,grow:s.options.grow,editable:s.options.editable,sticky:s.options.sticky}}),reports:a.map(le)}}async function Se(e){const{manager:i,sheets:t,bindings:r,reports:o}=e,a=e.sourceParts??[];if(!(i.tables.size>0||t.length>0||o.length>0||r.length>0))return{parts:[],replaced:a};const l=[],s=[];let c=0;for(const u of i.tables.values())s.push(await ae(u,c++,l));const f=U.encode(JSON.stringify(V(e,s)));return l.push({name:L,blob:new Blob([f]),bytes:f.length}),l.forEach((u,m)=>{u.file=K(m)}),{parts:l,replaced:a}}const fe=(()=>{const e=new Int8Array(256).fill(-1),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t<64;t++)e[i.charCodeAt(t)]=t;return e})();async function ue(e,i){const t=(await e.stream(i)).getReader(),{value:r}=await t.read();if(t.cancel().catch(()=>{}),!r)return null;const o=new TextDecoder().decode(r.subarray(0,400));if(!o.includes(q))return null;const a=/\bn="([^"]*)"/.exec(o)?.[1],n=Number(/\bb="(\d+)"/.exec(o)?.[1]??0);return a===void 0?null:{name:a,bytes:n,file:i}}async function H(e,i,t){const r=(await e.stream(i)).getReader(),o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let a=0,n=!1,l=0,s=0;for(;;){const{done:c,value:f}=await r.read();if(c)break;let u=0;if(!n){let m=0;for(;u<f.length;u++)if(f[u]===62&&(m++,m===2)){u++,n=!0;break}if(!n)continue}for(;u<f.length;u++){const m=fe[f[u]];m<0||(l=l<<6|m,s++,s===4&&(a+3<=o.length?(o[a]=l>>16,o[a+1]=l>>8&255,o[a+2]=l&255):(a<o.length&&(o[a]=l>>16),a+1<o.length&&(o[a+1]=l>>8&255)),a+=3,l=0,s=0))}}s===2&&a<o.length&&(o[a]=l>>4),s===3&&(a<o.length&&(o[a]=l>>10),a+1<o.length&&(o[a+1]=l>>2&255))}async function de(e,i,t){const r=i.addTable(t.name,{key:t.key,tracking:t.tracking,capacity:t.rowCount,fields:t.fields,windows:t.windows,schema:t.schema,remote:t.remote,autoSync:t.autoSync,batch:t.batch,indexes:t.indexes}),{dir:o}=t,a=new Float64Array(t.stringCount+1);await e(`${o}strings.idx`,a);const n=new Uint8Array(a[t.stringCount]);await e(`${o}strings.bin`,n);const l=new Int32Array(t.stringCount);for(let c=0;c<t.stringCount;c++)l[c]=i.strings.add(Y(n,a[c],a[c+1])),(c+1)%O===0&&await A();r.rowCount=t.rowCount;for(const c of t.columns){const f=r.byName.get(c.field);if(f){if(c.encoding==="i32"){const u=new Int32Array(t.rowCount);await e(`${o}${c.part}`,u);const{data:m}=f;for(let g=0;g<t.rowCount;g++){const p=u[g];m[g]=p<0?-1:l[p]}}else if(c.encoding==="mixed"){await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount)),f.kinds=new Uint8Array(r.capacity),await e(`${o}${c.kinds}`,new Uint8Array(f.kinds.buffer,0,t.rowCount));for(let u=0;u<t.rowCount;u++)f.kinds[u]===2&&(f.data[u]=l[f.data[u]])}else await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount));c.styles&&(f.styles=new Uint16Array(r.capacity),await e(`${o}${c.styles}`,new Uint16Array(f.styles.buffer,0,t.rowCount))),await A()}}await e(`${o}alive.bin`,new Uint8Array(r.alive.buffer,0,t.rowCount)),await e(`${o}state.bin`,new Uint8Array(r.state.buffer,0,t.rowCount));let s=0;for(let c=0;c<t.rowCount;c++)r.alive[c]===0&&s++;r.deletedCount=s;for(const[c,f]of t.originals)r.originals.set(c,new Map(f.map(([u,m])=>[r.byName.get(u)?.index,m]).filter(([u])=>u!==void 0)));return r.revision++,r.structureRevision++,r._markAllComputedStale(),r}function P(e,i){const t=new Q(e,i);return t.applySavedState(i),t}async function Ne(e,i){const t=new Map,r=[];for(const c of e.entries.keys()){if(!c.startsWith("customXml/")||c.includes("/_rels/")||!c.endsWith(".xml")||/itemProps/i.test(c))continue;const f=await ue(e,c);f&&(t.set(f.name,f),r.push(c))}const o=t.get(L);if(!o)return!1;const a=new Uint8Array(o.bytes);await H(e,o.file,a);const n=JSON.parse(new TextDecoder().decode(a));if(n.format!=="8sheets-datasheets"||n.version>M)return!1;i.sourceParts=me(e,r);const l=async(c,f)=>{const u=t.get(c);u&&await H(e,u.file,f)},{manager:s}=i;for(const c of n.tables)await de(l,s,c);return X(n,i),i.loaded=!0,!0}function me(e,i){const t=[];for(const r of i){t.push(r);const o=r.slice(10),a=`customXml/_rels/${o}.rels`;if(e.has(a)){t.push(a);const n=/(\d+)\.xml$/.exec(o)?.[1];n&&e.has(`customXml/itemProps${n}.xml`)&&t.push(`customXml/itemProps${n}.xml`)}}return t}function he(e,i,t){return{view:i,fields:e.fields,calendar:new j(e.calendar),calendars:e.calendars,durationUnit:e.durationUnit,scaleLevel:e.scaleLevel,scale:e.scale,showCritical:e.showCritical,showBaseline:e.showBaseline,showLinks:e.showLinks,showLabels:e.showLabels,showToday:e.showToday,statusDate:e.statusDate,taskbarRules:e.taskbarRules,taskbarStyles:e.taskbarStyles,layout:e.layout,gridlines:e.gridlines,nonWorking:e.nonWorking,progressLine:e.progressLine,frozenLimit:e.frozenLimit,sheet:t}}function X(e,i){const{book:t,manager:r}=i;for(const n of e.relationships)r.addRelationship(n);for(const n of e.views??[]){const l=r.table(n.table);l.views.set(n.name,P(l,n.view))}const o=n=>t.sheets.find(l=>l.name===n),a=[];for(const n of e.sheets){const l=o(n.sheet);if(!l)continue;if(n.cells!==void 0&&!l.isVirtual&&W(l,t.strings)!==n.cells){a.push(n.sheet);continue}const s=r.table(n.table),c=P(s,n.view);let f;n.kind==="gantt"?(f=new z(t,n.sheet,s,he(n.gantt,c,n.options)),n.gantt.resourceTable&&(f.resourceTable=r.tables.get(n.gantt.resourceTable)??null,f.assignmentTable=r.tables.get(n.gantt.assignmentTable)??null,f.resourceNamesChanged())):f=new Z(t,n.sheet,c,n.options),f.adoptFrom(l),t.sheets[t.sheets.indexOf(l)]=f,i._registerSheet(f)}a.length>0&&i.loadNotes.push(se("{sheets} changed outside this app, so they stay plain sheets. The data tables are still there.",{sheets:a.join(", "),count:a.length}));for(const n of e.bindings){const l=o(n.sheet);if(l)if(n.kind==="paths"){const s=new ne(t,l,n.source?.table?n.source:n.source?.data??null);s.paths=new Map(n.paths),s.fieldOptions=new Map(n.fieldOptions??[]),s.refresh(),i._registerBinding(s)}else if(n.kind==="rows")i._registerBinding(new oe(t,l,n.anchor,n.data,{columns:n.columns,...n.options,table:n.table?t.engine?.tables.get(n.table.toUpperCase())??null:null}));else{const s=P(r.table(n.table),n.view);i._registerBinding(new te(t,l,n.range,s,n.options))}}for(const n of e.reports){const l=o(n.sheet);if(!l)continue;const s=new ee(r,l,{table:n.table,name:n.name,titleRows:n.titleRows,pageSetup:n.pageSetup,mode:n.mode,pagination:n.pagination,layout:n.layout,dataEntry:n.dataEntry,charts:n.charts,pictures:n.pictures,states:n.states,showHiddenRows:n.showHiddenRows,showHiddenCols:n.showHiddenCols});for(const c of n.bindings)s.setBinding(c.row,c.col,c);for(const c of n.params)s.addParam(c.name,c);s.filters=n.filters,s.output=n.output?o(n.output)??null:null,i.reports.push(s)}t.engine?.sheetsChanged(),t.engine?.rebuild()}function Oe(e){const{manager:i,book:t}=e,r=[...i.tables.values()].map(a=>{const n=[],l=a.columns.filter(s=>$(s)&&!s.computed);for(let s=0;s<a.rowCount;s++){if(a.alive[s]===0)continue;const c={};for(const f of l){const u=f.get(s);u!==null&&(c[f.name]=_(u))}n.push(c)}return{name:a.name,key:a.key,tracking:a.tracking,windows:a.windowDefs,schema:a.schema,remote:E(a.remote),autoSync:a.autoSync,batch:a.batchSync,indexes:a.getIndexes(),fields:a.columns.filter($).map(F),rows:n}}),o=V(e,r.map(a=>({name:a.name,map:null})));o.tables=r;for(const a of o.sheets)delete a.cells;return o}function $e(e,i){const{book:t,manager:r}=i;for(const o of e.tables){const{rows:a,...n}=o;r.addTable(o.name,n).load(a)}for(const o of e.sheets)t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);for(const o of e.reports??[])t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);X(e,i)}export{Se as buildDataSheetPackage,$e as dataSheetsFromJSON,Oe as dataSheetsToJSON,he as ganttOptions,W as hashSheetCells,Ne as readDataSheetPackage};
|
|
1
|
+
import{decodeBytes as Y}from"../core/strings.js";import{MANIFEST_NAME as L,NS as q,partFileName as K}from"./persist-writer.js";import{ROW as J}from"./data.js";import{TableView as Q}from"./view.js";import{TableSheet as Z}from"./table-sheet.js";import{GanttSheet as z,WorkCalendar as j}from"./gantt.js";import{ReportTemplate as ee}from"./report.js";import{TableBinding as te}from"./bind.js";import{CellPathBinding as ne,RowsBinding as oe}from"./path-binding.js";import{t as se}from"../i18n/index.js";const M=2,U=new TextEncoder,N=1<<18,A=()=>new Promise(e=>setTimeout(e,0)),$=e=>e!==null&&!e.lookup&&!e.rollup&&!e.window&&!e.name.startsWith("__formula:")&&!e.name.startsWith("__cross:");function F(e){const s={name:e.name,type:e.type};return e.caption!==e.name&&(s.caption=e.caption),e.format!=="General"&&!(e.type==="date"&&e.format==="yyyy-mm-dd")&&(s.format=e.format),e.readOnly&&(s.readOnly=!0),e.width!==null&&(s.width=e.width),e.hidden&&(s.hidden=!0),e.formula!==null&&(s.formula=e.formula),e.defaultValue!==null&&(s.defaultValue=e.defaultValue),e.required&&(s.required=!0),e.showNullAs!==null&&(s.showNullAs=e.showNullAs),e.validator!==null&&!e.validator.fn&&(s.validator=e.validator),e.trigger&&(s.trigger=e.trigger),s}function ie(e){const s=e.rowCount,{state:t,alive:i}=e;let o=!1;for(let r=0;r<s;r++)if(t[r]===J.PURGED&&i[r]===0){o=!0;break}if(!o)return null;const l=new Int32Array(s);let n=0;for(let r=0;r<s;r++)l[r]=t[r]===J.PURGED&&i[r]===0?-1:n++;return{map:l,count:n}}function C(e,s,t){if(t===null)return e.subarray(0,s);const i=new e.constructor(t.count);for(let o=0;o<s;o++)t.map[o]>=0&&(i[t.map[o]]=e[o]);return i}async function ae(e,s,t){const i=e.rowCount,o=ie(e),l=o?o.count:i,{strings:n}=e.manager,r=`t${s}/`,a=(u,h)=>(t.push({name:`${r}${u}`,blob:new Blob([h]),bytes:h.byteLength}),u),c=new Map,f=[],d=u=>{let h=c.get(u);return h===void 0&&(h=f.length,c.set(u,h),f.push(n.get(u))),h},m=[],g=[];let p=0;for(const u of e.columns){if(!$(u)||(m.push(F(u)),u.computed))continue;const h={field:u.name};if(u.isString){const b=C(u.data,i,o),y=new Int32Array(b.length);for(let w=0;w<b.length;w++){const D=b[w];y[w]=D<0?-1:d(D),++p%N===0&&await A()}h.encoding="i32",h.part=a(`c${u.index}.bin`,y)}else if(u.kinds!==null){const b=C(u.kinds,i,o),y=Float64Array.from(C(u.data,i,o));for(let w=0;w<y.length;w++)b[w]===2&&(y[w]=d(y[w])),++p%N===0&&await A();h.encoding="mixed",h.part=a(`c${u.index}.bin`,y),h.kinds=a(`c${u.index}.kinds`,b)}else h.encoding="f64",h.part=a(`c${u.index}.bin`,C(u.data,i,o));u.styles!==null&&(h.styles=a(`c${u.index}.styles`,C(u.styles,i,o))),g.push(h)}const O=[],k=new Float64Array(f.length+1);let x=0,v=[],S=0;const R=()=>{S!==0&&(O.push(U.encode(v.join(""))),v=[],S=0)};for(let u=0;u<f.length;u++){const h=re(f[u]);k[u]=x,x+=h,v.push(f[u]),S+=f[u].length,S>1<<20&&(R(),await A())}R(),k[f.length]=x,t.push({name:`${r}strings.bin`,blob:new Blob(O),bytes:x}),a("strings.idx",k);const G=C(e.alive,i,o),I=C(e.state,i,o);a("alive.bin",G),a("state.bin",I);const B=[];for(const[u,h]of e.originals){const b=o?o.map[u]:u;b<0||B.push([b,[...h].map(([y,w])=>[e.columns[y].name,E(w)])])}return{name:e.name,key:e.key,tracking:e.tracking,rowCount:l,dir:r,indexes:e.getIndexes(),windows:e.windowDefs,schema:e.schema,remote:_(e.remote),autoSync:e.autoSync,batch:e.batchSync,stringCount:f.length,fields:m,columns:g,originals:B,map:o}}function _(e){if(!e||typeof e!="object")return null;const s={};for(const[t,i]of Object.entries(e))typeof i!="function"&&(s[t]=i);return Object.keys(s).length>0?s:null}const E=e=>e!==null&&typeof e=="object"?{error:e.code}:e;function re(e){let s=e.length;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);if(i>=128)if(i<2048)s++;else if(i>=55296&&i<=56319){const o=e.charCodeAt(t+1);o>=56320&&o<=57343?(s+=2,t++):s+=2}else s+=2}return s}function T(e,s){const t=e.toJSON(),i=s.map;return i&&(t.pinnedRows=t.pinnedRows.map(o=>i.map[o]).filter(o=>o>=0),t.treeCollapsed=t.treeCollapsed.map(o=>i.map[o]).filter(o=>o>=0)),t}function le(e){return e.toJSON()}function W(e,s){let t=0;const i=new Map,{columns:o}=e;for(let l=0;l<o.length;l++){const n=o[l];if(n===void 0)continue;const r=n.length;for(let a=0;a<r;a++){const c=n[a];if(c===void 0)continue;const{kinds:f,values:d}=c;for(let m=0;m<f.length;m++){const g=f[m]&7;if(g===0)continue;let p;if(g===2){const k=d[m];if(p=i.get(k),p===void 0){p=7;const x=s.get(k);for(let v=0;v<x.length;v++)p=Math.imul(p,31)+x.charCodeAt(v)|0;i.set(k,p)}}else p=Math.round(d[m]*1e3)|0;const O=Math.imul((a<<10)+m+1,2654435761)^Math.imul(l+1,2246822507);t=t+Math.imul(p^O,625341585)|0}}}return t}function ce(e,s,t){return{sheet:e.name,kind:e.kindName,table:e.table.name,view:T(e.view,s(e.table)),options:e.options,gantt:e.kindName==="gantt"?e.toJSON():void 0,cells:W(e,t)}}function V(e,s){const{manager:t,sheets:i,bindings:o,reports:l,book:n}=e,r=a=>s.find(c=>c.name===a.name);return{format:"8sheets-datasheets",version:M,tables:s.map(({map:a,...c})=>c),relationships:t.relationships.map(a=>({from:a.from.name,fromField:a.fromField,to:a.to.name,toField:a.toField,name:a.name,inverse:a.inverse})),views:[...t.tables.values()].flatMap(a=>[...a.views.values()].map(c=>({table:a.name,name:c.name,view:T(c,r(a))}))),sheets:i.map(a=>ce(a,r,n.strings)),bindings:o.map(a=>a.toJSON?a.toJSON():{kind:"view",sheet:a.sheet.name,range:a.range,table:a.table.name,view:T(a.view,r(a.table)),options:{header:a.options.header,grow:a.options.grow,editable:a.options.editable,sticky:a.options.sticky}}),reports:l.map(le)}}async function Ne(e){const{manager:s,sheets:t,bindings:i,reports:o}=e,l=e.sourceParts??[];if(!(s.tables.size>0||t.length>0||o.length>0||i.length>0))return{parts:[],replaced:l};const r=[],a=[];let c=0;for(const d of s.tables.values())a.push(await ae(d,c++,r));const f=U.encode(JSON.stringify(V(e,a)));return r.push({name:L,blob:new Blob([f]),bytes:f.length}),r.forEach((d,m)=>{d.file=K(m)}),{parts:r,replaced:l}}const fe=(()=>{const e=new Int8Array(256).fill(-1),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t<64;t++)e[s.charCodeAt(t)]=t;return e})();async function ue(e,s){const t=(await e.stream(s)).getReader(),{value:i}=await t.read();if(t.cancel().catch(()=>{}),!i)return null;const o=new TextDecoder().decode(i.subarray(0,400));if(!o.includes(q))return null;const l=/\bn="([^"]*)"/.exec(o)?.[1],n=Number(/\bb="(\d+)"/.exec(o)?.[1]??0);return l===void 0?null:{name:l,bytes:n,file:s}}async function H(e,s,t){const i=(await e.stream(s)).getReader(),o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let l=0,n=!1,r=0,a=0;for(;;){const{done:c,value:f}=await i.read();if(c)break;let d=0;if(!n){let m=0;for(;d<f.length;d++)if(f[d]===62&&(m++,m===2)){d++,n=!0;break}if(!n)continue}for(;d<f.length;d++){const m=fe[f[d]];m<0||(r=r<<6|m,a++,a===4&&(l+3<=o.length?(o[l]=r>>16,o[l+1]=r>>8&255,o[l+2]=r&255):(l<o.length&&(o[l]=r>>16),l+1<o.length&&(o[l+1]=r>>8&255)),l+=3,r=0,a=0))}}a===2&&l<o.length&&(o[l]=r>>4),a===3&&(l<o.length&&(o[l]=r>>10),l+1<o.length&&(o[l+1]=r>>2&255))}async function de(e,s,t){const i=s.addTable(t.name,{key:t.key,tracking:t.tracking,capacity:t.rowCount,fields:t.fields,windows:t.windows,schema:t.schema,remote:t.remote,autoSync:t.autoSync,batch:t.batch,indexes:t.indexes}),{dir:o}=t,l=new Float64Array(t.stringCount+1);await e(`${o}strings.idx`,l);const n=new Uint8Array(l[t.stringCount]);await e(`${o}strings.bin`,n);const r=new Int32Array(t.stringCount);for(let c=0;c<t.stringCount;c++)r[c]=s.strings.add(Y(n,l[c],l[c+1])),(c+1)%N===0&&await A();i.rowCount=t.rowCount;for(const c of t.columns){const f=i.byName.get(c.field);if(f){if(c.encoding==="i32"){const d=new Int32Array(t.rowCount);await e(`${o}${c.part}`,d);const{data:m}=f;for(let g=0;g<t.rowCount;g++){const p=d[g];m[g]=p<0?-1:r[p]}}else if(c.encoding==="mixed"){await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount)),f.kinds=new Uint8Array(i.capacity),await e(`${o}${c.kinds}`,new Uint8Array(f.kinds.buffer,0,t.rowCount));for(let d=0;d<t.rowCount;d++)f.kinds[d]===2&&(f.data[d]=r[f.data[d]])}else await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount));c.styles&&(f.styles=new Uint16Array(i.capacity),await e(`${o}${c.styles}`,new Uint16Array(f.styles.buffer,0,t.rowCount))),await A()}}await e(`${o}alive.bin`,new Uint8Array(i.alive.buffer,0,t.rowCount)),await e(`${o}state.bin`,new Uint8Array(i.state.buffer,0,t.rowCount));let a=0;for(let c=0;c<t.rowCount;c++)i.alive[c]===0&&a++;i.deletedCount=a;for(const[c,f]of t.originals)i.originals.set(c,new Map(f.map(([d,m])=>[i.byName.get(d)?.index,m]).filter(([d])=>d!==void 0)));return i.revision++,i.structureRevision++,i._markAllComputedStale(),i}function P(e,s){const t=new Q(e,s);return t.applySavedState(s),t}async function $e(e,s){const t=new Map,i=[];for(const c of e.entries.keys()){if(!c.startsWith("customXml/")||c.includes("/_rels/")||!c.endsWith(".xml")||/itemProps/i.test(c))continue;const f=await ue(e,c);f&&(t.set(f.name,f),i.push(c))}const o=t.get(L);if(!o)return!1;const l=new Uint8Array(o.bytes);await H(e,o.file,l);const n=JSON.parse(new TextDecoder().decode(l));if(n.format!=="8sheets-datasheets"||n.version>M)return!1;s.sourceParts=me(e,i);const r=async(c,f)=>{const d=t.get(c);d&&await H(e,d.file,f)},{manager:a}=s;for(const c of n.tables)await de(r,a,c);return X(n,s),s.loaded=!0,!0}function me(e,s){const t=[];for(const i of s){t.push(i);const o=i.slice(10),l=`customXml/_rels/${o}.rels`;if(e.has(l)){t.push(l);const n=/(\d+)\.xml$/.exec(o)?.[1];n&&e.has(`customXml/itemProps${n}.xml`)&&t.push(`customXml/itemProps${n}.xml`)}}return t}function he(e,s,t){return{view:s,fields:e.fields,calendar:new j(e.calendar),calendars:e.calendars,durationUnit:e.durationUnit,scaleLevel:e.scaleLevel,scale:e.scale,showCritical:e.showCritical,showBaseline:e.showBaseline,showLinks:e.showLinks,showLabels:e.showLabels,showToday:e.showToday,statusDate:e.statusDate,taskbarRules:e.taskbarRules,taskbarStyles:e.taskbarStyles,layout:e.layout,gridlines:e.gridlines,nonWorking:e.nonWorking,progressLine:e.progressLine,frozenLimit:e.frozenLimit,sheet:t}}function X(e,s){const{book:t,manager:i}=s;for(const n of e.relationships)i.addRelationship(n);for(const n of e.views??[]){const r=i.table(n.table);r.views.set(n.name,P(r,n.view))}const o=n=>t.sheets.find(r=>r.name===n),l=[];for(const n of e.sheets){const r=o(n.sheet);if(!r)continue;if(n.cells!==void 0&&!r.isVirtual&&W(r,t.strings)!==n.cells){l.push(n.sheet);continue}const a=i.table(n.table),c=P(a,n.view);let f;n.kind==="gantt"?(f=new z(t,n.sheet,a,he(n.gantt,c,n.options)),n.gantt.resourceTable&&(f.resourceTable=i.tables.get(n.gantt.resourceTable)??null,f.assignmentTable=i.tables.get(n.gantt.assignmentTable)??null,f.resourceNamesChanged())):f=new Z(t,n.sheet,c,n.options),f.adoptFrom(r),t.sheets[t.sheets.indexOf(r)]=f,s._registerSheet(f)}l.length>0&&s.loadNotes.push(se("{sheets} changed outside this app, so they stay plain sheets. The data tables are still there.",{sheets:l.join(", "),count:l.length}));for(const n of e.bindings){const r=o(n.sheet);if(r)if(n.kind==="paths"){const a=new ne(t,r,n.source?.table?n.source:n.source?.data??null);a.paths=new Map(n.paths),a.fieldOptions=new Map(n.fieldOptions??[]),a.refresh(),s._registerBinding(a)}else if(n.kind==="rows")s._registerBinding(new oe(t,r,n.anchor,n.data,{columns:n.columns,...n.options,table:n.table?t.engine?.tables.get(n.table.toUpperCase())??null:null}));else{const a=P(i.table(n.table),n.view);s._registerBinding(new te(t,r,n.range,a,n.options))}}for(const n of e.reports){const r=o(n.sheet);if(!r)continue;const a=new ee(i,r,{table:n.table,name:n.name,titleRows:n.titleRows,pageSetup:n.pageSetup,mode:n.mode,pagination:n.pagination,layout:n.layout,dataEntry:n.dataEntry,charts:n.charts,pictures:n.pictures,states:n.states,showHiddenRows:n.showHiddenRows,showHiddenCols:n.showHiddenCols});for(const c of n.bindings)a.setBinding(c.row,c.col,c);for(const c of n.params)a.addParam(c.name,c);a.filters=n.filters,a.output=n.output?o(n.output)??null:null,s.reports.push(a)}t.engine?.sheetsChanged(),t.engine?.rebuild()}const pe=5e3;function*we(e){const s=e.columns.filter(i=>$(i)&&!i.computed);let t=[];for(let i=0;i<e.rowCount;i++){if(e.alive[i]===0)continue;const o={};for(const l of s){const n=l.get(i);n!==null&&(o[l.name]=E(n))}t.push(o),t.length===pe&&(yield t,t=[])}t.length&&(yield t)}function Te(e,{rows:s=!0}={}){const{manager:t,book:i}=e,o=[...t.tables.values()].map(n=>{const r=s?[...we(n)].flat():[];return{name:n.name,key:n.key,tracking:n.tracking,windows:n.windowDefs,schema:n.schema,remote:_(n.remote),autoSync:n.autoSync,batch:n.batchSync,indexes:n.getIndexes(),fields:n.columns.filter($).map(F),rows:r}}),l=V(e,o.map(n=>({name:n.name,map:null})));l.tables=o;for(const n of l.sheets)delete n.cells;return l}function Pe(e,s){const{book:t,manager:i}=s;for(const o of e.tables){const{rows:l,...n}=o;i.addTable(o.name,n).load(l)}for(const o of e.sheets)t.sheets.some(l=>l.name===o.sheet)||t.addSheet(o.sheet);for(const o of e.reports??[])t.sheets.some(l=>l.name===o.sheet)||t.addSheet(o.sheet);X(e,s)}export{Ne as buildDataSheetPackage,Pe as dataSheetsFromJSON,Te as dataSheetsToJSON,he as ganttOptions,W as hashSheetCells,$e as readDataSheetPackage,we as rowBatches};
|
package/datasheets/report.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BOOL as ft,EMPTY as $,ERR as Z,FORMULA as J,KIND_MASK as ut,NUM as B,SPILL as pt,STR as E}from"../core/sheet.js";import{cellRef as N,colName as H,colIndex as wt,MAX_COLS as P,MAX_ROWS as L,parseRangeRef as Y,rangeRef as dt,sheetPrefix as gt}from"../core/address.js";import{rangesOf as mt}from"../core/cond-format.js";import{translateFormula as yt}from"../core/formula-refs.js";import{getPageSetup as _t}from"../print/page-setup.js";import{paginate as V}from"../print/paginate.js";import{getFormatter as j}from"../core/numfmt.js";import{ERR as Ct,XlError as bt}from"../calc/values.js";import{aggregate as Q,formulaHelper as q,groupKeys as tt,TableView as et}from"./view.js";import{sortByF64 as kt}from"./sort.js";import{Axis as st}from"../core/axis.js";import{t as A}from"../i18n/index.js";const Rt=["group","list","summary","param","static","chart"],M=(g,t)=>g*P+t,U=new Int32Array(0),G=-2,St=8e3;class O{constructor(t,s,e,l=null,a=void 0){this.parent=t,this.table=s,this.rows=e,this.node=l,this.value=a,this.first=-1,this.last=-1,this.resolved=null}}class T extends Error{}class ht{constructor(t,s,e={}){this.manager=t,this.sheet=s,this.bindings=new Map,this.params=new Map,this.filters=[],this.titleRows=e.titleRows??null,this.pageSetup=e.pageSetup??null,this.defaultTable=e.table??null,this.name=e.name??s.name,this.output=null,this.mode=e.mode??"design",this.pagination=e.pagination??null,this.layout=e.layout??null,this.dataEntry=e.dataEntry??null,this.charts=e.charts??[],this.pictures=e.pictures??[],this.states=e.states??null,this.measure=e.measure??null,this.showHiddenRows=e.showHiddenRows===!0,this.showHiddenCols=e.showHiddenCols===!0,this.listeners=new Map,s.report=this}setBinding(t,s,e){const l=e.type;if(!Rt.includes(l))throw new T(`Unknown binding type: ${l}`);const a={table:this.defaultTable,expand:l==="group"||l==="list"?"vertical":"none",agg:"sum",sort:l==="group"?"asc":null,...e,row:t,col:s};return this.bindings.set(M(t,s),a),a}binding(t,s){return this.bindings.get(M(t,s))??null}removeBinding(t,s){this.bindings.delete(M(t,s))}static markerText(t){switch(t.type){case"group":return`[${t.field}]`;case"list":return`=[${t.field}]`;case"summary":return`${t.agg??"sum"}[${t.field}]`;case"chart":return`chart[${t.chartType??"line"}]`;default:return`{${t.param}}`}}writeMarkers(t){t.sheet===this.sheet&&t.transact("report binding",s=>{for(const e of this.bindings.values())e.type!=="static"&&(s.saveCell(e.row,e.col),this.sheet.setFormula(e.row,e.col,null),this.sheet.setCell(e.row,e.col,E,t.strings.add(ht.markerText(e))))})}addParam(t,s={}){this.params.set(t,{name:t,caption:s.caption??t,type:s.type??"string",value:s.value??null,options:s.options??null})}setParam(t,s){const e=this.params.get(t);if(!e)throw new T(A("No parameter named {name}.",{name:t}));e.value=s}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>this.listeners.get(t).delete(s)}fire(t,s){let e=!0;for(const l of this.listeners.get(t)??[])l(s)===!1&&(e=!1);return e}addFilter(t){this.filters.push(t)}generate(t,{target:s=null,name:e=null,params:l=null,measure:a=null}={}){if(l)for(const[o,n]of Object.entries(l))this.setParam(o,n);a&&(this.measure=a),this.fire("stage",{stage:"start"});const f=new xt(this,t).run(s,e);return this.fire("stage",{stage:"done",result:f}),f}async generateAsync(t,s){return await new Promise(e=>setTimeout(e,0)),this.generate(t,s)}toJSON(){return{name:this.name,sheet:this.sheet.name,table:this.defaultTable,bindings:[...this.bindings.values()].map(t=>({...t})),params:[...this.params.values()],filters:this.filters,titleRows:this.titleRows,pageSetup:this.pageSetup,output:this.output?.name??null,mode:this.mode,pagination:this.pagination,layout:this.layout,dataEntry:this.dataEntry,charts:this.charts,pictures:this.pictures,states:this.states,showHiddenRows:this.showHiddenRows,showHiddenCols:this.showHiddenCols}}}const nt=(g,t)=>`${g.name}|${t.formula??t.field}|${t.by??""}|${t.size??""}|${t.bins?JSON.stringify(t.bins):""}`,vt=g=>{let t=0;for(let s=g.parent;s!==null;s=s.parent)t++;return t};class rt{constructor(t,s,e,l){this.binding=t,this.a=s,this.b=e,this.parent=l,this.children=[],this.members=[]}}class xt{constructor(t,s){this.t=t,this.book=s,this.manager=t.manager,this.sheet=t.sheet,this.roots=new Map,this.keyCache=new Map,this.helperViews=new Map,this.cellInfo=new Map,this.groupMerges=[],this.collapses=[],this.overlay=null,this.breaks=[],this.formulas=[],this.memberColumns=new Map,this.rowCap=1024,this.rowTpl=new Int32Array(this.rowCap),this.rowCtx=new Int32Array(this.rowCap),this.rowRec=new Int32Array(this.rowCap),this.rowCount=0,this.contexts=[],this.colOut=[]}_table(t){if(!t)throw new T(A("A binding needs a table."));return this.manager.table(t)}_templateExtent(){const{sheet:t}=this;let s=t.maxRow,e=t.maxCol;for(const l of this.t.bindings.values())l.row>s&&(s=l.row),l.col>e&&(e=l.col);for(const l of t.merges)l.r1>s&&(s=l.r1),l.c1>e&&(e=l.c1);return{maxRow:s,maxCol:e}}_buildTree(t,s){const e=t==="vertical",l=i=>e?i.row:i.col,a=i=>e?i.col:i.row,f=[...this.t.bindings.values()].filter(i=>(i.type==="group"||i.type==="list")&&i.expand===t);f.sort((i,u)=>a(i)-a(u)||l(i)-l(u));const o=new rt(null,0,e?s.maxRow:s.maxCol,null),n=new Map,c=i=>{if(i.span>1)return l(i)+i.span-1;const u=this.sheet.mergeAt(i.row,i.col);return u?e?u.r1:u.c1:l(i)},r=i=>{if(i.parent==="none")return o;if(i.parent){const p=n.get(M(i.parent.row,i.parent.col));if(p)return p}let u=o;for(const p of n.values())a(p.binding)>=a(i)||l(i)<p.a||l(i)>p.b||p.a>=u.a&&(u===o||a(p.binding)>=a(u.binding))&&(u=p);return u};for(const i of f){const u=r(i);if(i.type==="list"&&u!==o&&u.binding.type==="list"&&l(u.binding)===l(i)&&u.binding.table===i.table){u.members.push(i);continue}if(i.type==="list"){const w=u.children.find(m=>m.binding.type==="list"&&l(m.binding)===l(i)&&m.binding.table===i.table);if(w){w.members.push(i);continue}}const p=new rt(i,l(i),c(i),u);u.children.push(p),n.set(M(i.row,i.col),p)}const h=i=>{i.children.sort((u,p)=>u.a-p.a);for(const u of i.children)h(u),i!==o&&u.b>i.b&&(i.b=u.b),i!==o&&u.a<i.a&&(i.a=u.a);for(let u=1;u<i.children.length;u++)if(i.children[u].a<=i.children[u-1].b){const p=i.children[u].binding,w=i.children[u-1].binding;throw new T(A("The cells {first} and {second} expand over the same rows but neither is the other's parent.",{first:N(p.row,p.col),second:N(w.row,w.col)}))}};return h(o),o}_rootRows(t){let s=this.roots.get(t);if(s!==void 0)return s;const e=this.t.filters.filter(a=>this.manager.table(a.table??this.t.defaultTable)===t).map(a=>this._resolveFilter(a)),l=new et(t,{columns:[],filters:e});return s=l.filtered.slice(0,l.filteredCount),l.dispose(),this.roots.set(t,s),s}_resolveFilter(t){const s={...t};if(t.param&&(s.value=this._param(t.param)),t.param2&&(s.value2=this._param(t.param2)),t.valuesParam){const e=this._param(t.valuesParam);s.values=Array.isArray(e)?e:[e],s.op=s.op??"in"}return s}_param(t){const s=this.t.params.get(t);if(!s)throw new T(A("No parameter named {name}.",{name:t}));return s.value}_filterActive(t){if(t.param&&(this._param(t.param)===null||this._param(t.param)===""))return!1;if(t.valuesParam){const s=this._param(t.valuesParam);if(s===null||s===""||Array.isArray(s)&&s.length===0)return!1}return!0}_rowsIn(t,s){if(t===null)return this._rootRows(s);if(t.table===s)return t.rows;t.resolved===null&&(t.resolved=new Map);let e=t.resolved.get(s);return e!==void 0||(e=this._crossRows(t,s),t.resolved.set(s,e)),e}_crossRows(t,s){for(let e=t;e!==null;e=e.parent){if(e.table===s)return e.rows;if(e.table===null)continue;const l=e.node?.binding.link;if(l)return this._joinRows(e,s,l.from,l.to);const a=this.manager.relationshipBetween(e.table,s);if(!a)continue;const f=this._rootMask(s);if(a.to===e.table){const{starts:r,rows:h}=a.children();let i=0;for(let w=0;w<e.rows.length;w++)i+=r[e.rows[w]+1]-r[e.rows[w]];const u=new Int32Array(i);let p=0;for(let w=0;w<e.rows.length;w++){const m=e.rows[w];for(let C=r[m];C<r[m+1];C++)(f===null||f[h[C]]===1)&&(u[p++]=h[C])}return p===i?u:u.slice(0,p)}const o=a.parents(),n=new Uint8Array(s.rowCount),c=[];for(let r=0;r<e.rows.length;r++){const h=o[e.rows[r]];h>=0&&n[h]===0&&(f===null||f[h]===1)&&(n[h]=1,c.push(h))}return Int32Array.from(c)}return this._rootRows(s)}_rootMask(t){if(!this.t.filters.some(e=>this.manager.table(e.table??this.t.defaultTable)===t))return null;const s=new Uint8Array(t.rowCount);for(const e of this._rootRows(t))s[e]=1;return s}_joinRows(t,s,e,l){const a=new Set,f=t.table.column(e);for(let r=0;r<t.rows.length;r++)a.add(String(f.get(t.rows[r])));const o=s.column(l),n=this._rootRows(s),c=[];for(let r=0;r<n.length;r++)a.has(String(o.get(n[r])))&&c.push(n[r]);return Int32Array.from(c)}_helperView(t){let s=this.helperViews.get(t);return s===void 0&&(s=new et(t,{columns:[]}),this.helperViews.set(t,s)),s}_prepareRows(t,s,e,l=null){let a=t;const f=(s.filters??[]).filter(o=>this._filterActive(o)).map(o=>this._resolveFilter(o));if(f.length>0||s.filter){const o=this._helperView(e),n=new Uint8Array(e.rowCount);for(let h=0;h<a.length;h++)n[a[h]]=1;for(const h of f)o._applyCondition(h,n,e.rowCount);s.filter&&this._applyFilterTree(s.filter,n,e,o,l);const c=new Int32Array(a.length);let r=0;for(let h=0;h<a.length;h++)n[a[h]]===1&&(c[r++]=a[h]);a=c.subarray(0,r)}if(s.sortFormula)a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,q(e,s.sortFormula),s.sort==="desc");else if(s.sort||s.sortBy){const o=e.column(s.sortBy??s.field);o&&(a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,o,s.sort==="desc"))}return a}_applyFilterTree(t,s,e,l,a){const f=e.rowCount;if(t.and){for(const n of t.and)this._applyFilterTree(n,s,e,l,a);return}if(t.or){const n=new Uint8Array(f);for(const c of t.or){const r=s.slice();this._applyFilterTree(c,r,e,l,a);for(let h=0;h<f;h++)n[h]|=r[h]}s.set(n);return}if(t.param!==void 0&&!this._filterActive(t))return;const o=this._resolveFilter(t);if(t.cell){const n=this.t.binding(t.cell.row,t.cell.col);for(let c=a;c!=null;c=c.parent)if(c.node?.binding===n&&c.rows.length>0){o.value=c.table.column(n.field).get(c.rows[0]);break}}if(t.join){const n=this._table(t.join.table),c=n.column(t.join.field),r=a?this._rowsIn(a,n):this._rootRows(n),h=new Set;for(let i=0;i<r.length;i++)h.add(c.get(r[i]));o.op="in",o.values=[...h]}l._applyCondition(o,s,f)}_partition(t,s,e,l=null){const a=this._prepareRows(t,{...s,sort:null,sortBy:null,sortFormula:null},e,l),f=nt(e,s);let o=this.keyCache.get(f);if(o===void 0){if(o=tt(e,s),o===null)throw new T(A("No field {field} in {table}.",{field:s.field,table:e.name}));this.keyCache.set(f,o)}const n=a===t?t.slice():a;s.sort&&Tt(n,o,s.sort==="desc");const c=[],r=s.sort?null:new Map;let h=0;const i=n.length;if(s.sort)for(;h<i;){const u=o[n[h]];let p=h+1;if(u===u)for(;p<i&&o[n[p]]===u;)p++;else for(;p<i&&o[n[p]]!==o[n[p]];)p++;c.push(n.subarray(h,p)),h=p}else{for(;h<i;h++){const u=o[n[h]],p=u!==u?"blank":u,w=r.get(p);w?w.push(n[h]):r.set(p,[n[h]])}for(const u of r.values())c.push(Int32Array.from(u))}return this._orderGroups(c,s,e)}_orderGroups(t,s,e){if(s.sortList){const l=s.formula?q(e,s.formula):e.column(s.field),a=new Map(s.sortList.map((o,n)=>[String(o).toLowerCase(),n])),f=o=>a.get(String(l.get(o[0])).toLowerCase())??1/0;return t.map((o,n)=>[o,f(o),n]).sort((o,n)=>o[1]-n[1]||o[2]-n[2]).map(o=>o[0])}if(s.sortCell){const l=this.t.binding(s.sortCell.row,s.sortCell.col),a=l&&l.field?e.column(l.field):null;if(a){const f=s.sort==="desc"?-1:1,o=n=>Q(a,l.agg??"sum",n,0,n.length);return t.map(n=>[n,o(n)]).sort((n,c)=>f*(n[1]-c[1])).map(n=>n[0])}}return t}_paginateRows(){const{t}=this,s=t.pagination,e=new Set,l=new Set;for(const n of t.bindings.values())n.pageBefore&&e.add(n.row),n.pageAfter&&l.add(n.row);if(e.size>0||l.size>0)for(let n=0;n<this.rowCount;n++){const c=this.rowTpl[n];e.has(c)&&n>0&&this.breaks.push(n),l.has(c)&&this.breaks.push(n+1)}const a=s?.endRows??null,f=t.titleRows?t.titleRows.r1-t.titleRows.r0+1:0;let o=s?.rowsPerPage>0?s.rowsPerPage:0;if(a&&o===0){const n=V(this.book,this.sheet).box.h,c=a.r1-a.r0+1;o=Math.max(1,Math.floor(n/this.sheet.rows.defaultSize)-f-c)}if(a)this._repeatEndRows(a,o,f);else if(o>0)for(const n of this._rowPageStarts(this.rowCount,o,f,new Set(this.breaks)))this.breaks.push(n);this.pageStartSet=new Set(this.breaks)}_rowPageStarts(t,s,e,l){const a=[];for(const i of this.contexts)i.node?.binding?.keepTogether&&i.first!==void 0&&i.last>i.first&&a.push(i);a.sort((i,u)=>i.first-u.first);const f=[];let o=0,n=e+s,c=0;const r=[...l].sort((i,u)=>i-u);let h=0;for(;o+n<t;){let i=o+n;for(;h<r.length&&r[h]<=o;)h++;for(h<r.length&&r[h]<i&&(i=r[h]);c<a.length&&a[c].last<i;)c++;c<a.length&&a[c].first<i&&a[c].first>o&&a[c].last>=i&&(i=a[c].first),f.push(i),o=i,n=s}return f}_repeatEndRows(t,s,e){const l=this.rowCount,{rowTpl:a,rowCtx:f,rowRec:o}=this,n=[],c=[];for(let d=0;d<l;d++)(a[d]>=t.r0&&a[d]<=t.r1?c:n).push(d);if(c.length===0||n.length===0)return;const r=new Int32Array(l).fill(-1);n.forEach((d,_)=>{r[d]=_});const h=new Set;for(const d of this.breaks){let _=d;for(;_<l&&r[_]<0;)_++;_<l&&h.add(r[_])}const i=this.contexts.map(d=>[d.first,d.last]);for(const d of this.contexts){if(d.first===void 0||d.first<0)continue;let _=d.first;for(;_<l&&r[_]<0;)_++;let v=d.last;for(;v>0&&r[v]<0;)v--;d.first=_<l?r[_]:0,d.last=v>=0&&r[v]>=0?r[v]:d.first}const u=s>0?this._rowPageStarts(n.length,s,e,h):[...h].sort((d,_)=>d-_);i.forEach(([d,_],v)=>{this.contexts[v].first=d,this.contexts[v].last=_});const p=n.length+c.length*(u.length+1),w=new Int32Array(p),m=new Int32Array(p),C=new Int32Array(p),k=new Int32Array(l).fill(-1),R=[];let S=0,y=0;const x=()=>{c.forEach(d=>{w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]<0&&(k[d]=S),S++})};n.forEach((d,_)=>{y<u.length&&u[y]===_&&(x(),R.push(S),y++),w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]=S,S++}),x(),this.rowTpl=w,this.rowCtx=m,this.rowRec=C,this.rowCount=p,this.rowCap=p,this.breaks=R;const b=d=>d>=0&&d<l&&k[d]>=0?k[d]:d;for(const d of this.contexts)d.first!==void 0&&(d.first=b(d.first)),d.last!==void 0&&(d.last=b(d.last));for(const d of this.collapses)d.row=b(d.row),d.from=b(d.from),d.to=b(d.to);for(const d of this.groupMerges)d.r0=b(d.r0),d.r1=b(d.r1);this.overlay&&(this.overlay=new Map([...this.overlay].map(([d,_])=>[b(d),_])))}_paginateCols(){const{t}=this,s=t.pagination;this.colBreaks=[];const e=new Set,l=new Set;for(const p of t.bindings.values())p.colPageBefore&&e.add(p.col),p.colPageAfter&&l.add(p.col);const a=s?.endCols??null,f=p=>a&&p.tpl>=a.c0&&p.tpl<=a.c1,o=a?this.colOut.filter(f):[],n=a?this.colOut.filter(p=>!f(p)):this.colOut,c=s?.colsPerPage>0?s.colsPerPage:0,r=[],h=s?.titleCols?s.titleCols.c1-s.titleCols.c0+1:0;let i=0,u=h+c;n.forEach((p,w)=>{w>0&&(c>0&&i>=u||e.has(p.tpl)||l.has(n[w-1].tpl))&&(r.push(...o),this.colBreaks.push(r.length),i=0,u=c),r.push(p),i++}),r.push(...o),this.colOut=r}_pushRow(t,s,e){if(this.rowCount===this.rowCap){const a=this.rowCap*2,f=o=>{const n=new Int32Array(a);return n.set(o),n};this.rowTpl=f(this.rowTpl),this.rowCtx=f(this.rowCtx),this.rowRec=f(this.rowRec),this.rowCap=a}if(this.rowCount>=L)throw new T(A("The report needs more than {count} rows. Add a filter.",{count:L}));const l=this.rowCount++;return this.rowTpl[l]=t,this.rowCtx[l]=s,this.rowRec[l]=e,l}_newContext(t){return this.contexts.push(t),t.index=this.contexts.length-1,t}_emitBand(t,s,e,l,a){let f=e;const o=t.children;let n=0;for(;f<=l;){for(;n<o.length&&o[n].b<f;)n++;const c=n<o.length&&o[n].a===f?o[n]:null;if(c!==null){const r=this._expandNode(c,s);f=c.b+1+(r??0)}else this._pushRow(f,s.index,a),f++}}_expandNode(t,s){const e=t.binding,l=this._table(e.table),a=this._rowsIn(s,l),f=c=>e.fillTo>1?(e.fillTo-c%e.fillTo)%e.fillTo:0;if(e.type==="group"){let c=this._partition(a,e,l,s);e.spillMode==="none"&&(c=c.slice(0,1));const r=e.merge===!0||this.sheet.mergeAt(e.row,e.col)!==null,h=c.length;for(let i=0;i<h;i++){const u=this._newContext(new O(s,l,c[i],t));u.ordinal=i+1,u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,-1),u.last=this.rowCount-1,r&&u.last>u.first&&this.groupMerges.push({binding:e,r0:u.first,r1:u.last}),e.collapse&&u.last>u.first&&this.collapses.push({binding:e,row:u.first,from:u.first+1,to:u.last,depth:vt(u),collapsed:e.initial==="collapsed"}),e.pageBreak&&i<h-1&&this.breaks.push(this.rowCount)}for(let i=f(h);i>0;i--){const u=this._newContext(new O(s,l,U,t));u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,G),u.last=this.rowCount-1}return 0}let o=this._prepareRows(a,e,l,s);e.spillMode==="none"&&(o=o.subarray(0,1));const n=e.pageEvery??0;if(t.a===t.b&&t.children.length===0){const c=this._newContext(new O(s,l,o,t));if(c.first=this.rowCount,e.spillMode==="overwrite"){const r=o.length;for(let h=0;h<r;h++){const i=this._pushRow(t.a+h,c.index,o[h]);this.overlay===null&&(this.overlay=new Map),this.overlay.set(i,t.a)}return c.last=this.rowCount-1,Math.max(0,r-1)}for(let r=0;r<o.length;r++)this._pushRow(t.a,c.index,o[r]),n>0&&(r+1)%n===0&&r+1<o.length&&this.breaks.push(this.rowCount);for(let r=f(o.length);r>0;r--)this._pushRow(t.a,c.index,G);return c.last=this.rowCount-1,0}for(let c=0;c<o.length;c++){const r=o.subarray(c,c+1),h=this._newContext(new O(s,l,r,t));h.ordinal=c+1,h.first=this.rowCount,this._emitBand(t,h,t.a,t.b,o[c]),h.last=this.rowCount-1,n>0&&(c+1)%n===0&&c+1<o.length&&this.breaks.push(this.rowCount)}return 0}_expandColumns(t,s,e,l){let a=e,f=0;const o=t.children;for(;a<=l;){for(;f<o.length&&o[f].b<a;)f++;const n=f<o.length&&o[f].a===a?o[f]:null;if(n!==null)this._expandColumnNode(n,s),a=n.b+1;else{if(this.colOut.length>=P)throw new T(A("The report needs more than {count} columns. Add a filter.",{count:P}));this.colOut.push({tpl:a,ctx:s}),a++}}}_expandColumnNode(t,s){const e=t.binding,l=this._table(e.table),a=this._colRows(s,l);let f=e.type==="group"?this._partition(a,e,l):Array.from(this._prepareRows(a,e,l),n=>Int32Array.of(n));e.spillMode==="none"&&(f=f.slice(0,1));const o=e.fillTo>1?(e.fillTo-f.length%e.fillTo)%e.fillTo:0;for(let n=0;n<o;n++)f.push(U);for(const n of f){const c=new O(s,l,n,t);c.first=this.colOut.length,this._expandColumns(t,c,t.a,t.b),c.last=this.colOut.length-1}}_colRows(t,s){return t===null||t.table===null?this._rootRows(s):this._rowsIn(t,s)}run(t,s){const{book:e,t:l}=this,a=this._templateExtent();this.extent=a;const f=this._buildTree("vertical",a),o=this._buildTree("horizontal",a),n=this._newContext(new O(null,null,U,null));n.first=0,this._emitBand(f,n,0,a.maxRow,-1),n.last=this.rowCount-1;const c=new O(null,null,U,null);this._expandColumns(o,c,0,a.maxCol),this._paginateRows(),this._paginateCols();const r=t??e.addSheet(s??`${l.name} Report`);this.outSheet=r,r.reportWriting=!0;const h=r.formulas.size>0;this._clear(r),this._writeGeometry(r),this._writeCells(r),this._writeMerges(r),this._writeSheetRules(r),this._writePageSetup(r),this._writeFormulas(r),this._applyAutoFit(r),l.layout&&this._applyLayoutSetting(r),this._saveMap(r),h&&e.engine?.rebuild(),r.reportWriting=!1,r.revision++,l.output=r;for(const i of this.helperViews.values())i.dispose();return{sheet:r,rows:this.rowCount,cols:this.colOut.length,pages:Et(e,r)}}_clear(t){t.columns=[],t.formulas=new Map,t.maxRow=-1,t.maxCol=-1,t.merges=[],t.mergeIndex=null,t.spills=null,t.rowStyles=null,t.colStyles=null,t.pageSetup=void 0,t.cf=void 0,t.cfEval=void 0,t.validations=void 0,t.sparklines=void 0,t.rows=new st(L,this.sheet.rows.defaultSize),t.cols=new st(P,this.sheet.cols.defaultSize),t.colsChanged=!0,t.viewChanged=!0}_writeGeometry(t){const{sheet:s}=this,{colOut:e,rowTpl:l,rowCount:a}=this;if(s.cols.sizes!==null)for(let o=0;o<e.length;o++){const n=s.cols.sizeOf(e[o].tpl);s.cols.isHidden(e[o].tpl)||(n!==t.cols.defaultSize||t.cols.isCustom(o))&&t.cols.setSize(o,n)}if(s.rows.sizes!==null)for(let o=0;o<a;o++){const n=l[o];s.rows.isCustom(n)&&!s.rows.isHidden(n)&&t.rows.setSize(o,s.rows.sizeOf(n))}if(!this.t.showHiddenRows&&s.rows.hiddenSizes?.size>0)for(let o=0;o<a;o++)s.rows.isHidden(l[o])&&t.rows.setHidden(o,!0);!this.t.showHiddenCols&&s.cols.hiddenSizes?.size>0&&e.forEach((o,n)=>{s.cols.isHidden(o.tpl)&&t.cols.setHidden(n,!0)}),s.colStyles&&(t.colStyles=new Map,e.forEach((o,n)=>{const c=s.colStyles.get(o.tpl);c!==void 0&&t.colStyles.set(n,c)}))}_writeCells(t){const{colOut:s,rowCount:e,rowTpl:l,rowCtx:a,rowRec:f,sheet:o,contexts:n}=this,{strings:c}=this.book,{bindings:r}=this.t,{overlay:h}=this,i=o.formulas.size>0,u=new Map;s.forEach((w,m)=>{u.has(w.tpl)||u.set(w.tpl,m)});const p=(w,m)=>{const C=M(w,m),k=r.get(C)??null,R=k!==null&&k.type==="static"?null:k,S=o.kind(w,m),y={binding:R,options:k!==null&&k.type==="static"?k:null,kind:S&~pt,value:o.value(w,m),style:o.cellStyle(w,m),table:R&&R.table?this._table(R.table):null,col:null,formula:S&J?o.formula(w,m):null,merged:o.mergeAt(w,m)};if(R&&R.type!=="param"&&R.type!=="chart"){if(y.col=R.formula?q(y.table,R.formula):y.table?.column(R.field)??null,!y.col&&!(R.type==="summary"&&R.agg==="countAll"))throw new T(A("No field {field} in {table}.",{field:R.field,table:R.table}));y.col&&y.table.ensure(y.col),R.collapse&&(y.style=this.book.styles.derive(y.style,{indent:1,hAlign:"left"})),R.format?y.style=this.book.styles.derive(y.style,{numFmt:R.format}):y.col&&y.col.format!=="General"&&(y.style===0||this.book.styles.get(y.style).numFmt==="General")&&(y.style=this.book.styles.derive(y.style,{numFmt:y.col.format}))}return y};for(let w=0;w<s.length;w++){const{tpl:m,ctx:C}=s[w];let k=-1;const R=[],S=u.get(m)===w;for(let y=0;y<e;y++){let x=l[y];if(h!==null){const _=h.get(y);_!==void 0&&r.get(M(_,m))?.type==="list"&&(x=_)}let b=R[x];b===void 0&&(b=p(x,m),R[x]=b);const d=b.binding;if(d===null){const _=b.options;if(_!==null){if(_.pin)continue;const v=_.autoExpand??"both";if((v==="none"||v==="horizontal")&&b.seen||(v==="none"||v==="vertical")&&!S)continue;b.seen=!0}if(b.formula){i&&this.formulas.push({or:y,oc:w,tr:x,tc:m,info:b.formula,ctx:n[a[y]],colCtx:C,style:b.style});continue}b.kind!==$&&t.setCell(y,w,b.kind,b.value),b.style!==0&&t.setStyle(y,w,b.style);continue}switch(b.style!==0&&t.setStyle(y,w,b.style),d.type){case"param":lt(t,y,w,this._param(d.param),c);break;case"list":{const _=d.expand==="horizontal"?this._recordAcross(C,b.table):this._recordFor(n[a[y]],f[y],b.table);_>=0&&it(t,y,w,b.col,_);break}case"group":{const _=this._groupContext(n[a[y]],C,d);if(_===null)break;if(_.index!==void 0&&!d.repeat){if(_.index===k&&!(d.repeatOnPage&&this.pageStartSet.has(y)))break;k=_.index}this._writeGroupValue(t,y,w,d,b,_);break}case"chart":this._writeChartCell(t,y,w,d,n[a[y]]);break;default:{if(f[y]===G)break;const _=this._summaryRows(n[a[y]],C,b.table,d,f[y]),v=b.col?Q(b.col,d.agg??"sum",_,0,_.length):d.agg==="countAll"?_.length:NaN;v===v&&t.setCell(y,w,B,v)}}}}}_writeChartCell(t,s,e,l,a){if(!l.source)return;const o=(this.tplRows??(this.tplRows=this._rowsByTemplate())).get(l.source.row),n=this.colOut.findIndex(u=>u.tpl===l.source.col);if(!o||n<0)return;const c=ot(o,a.first,a.last);if(c.length===0)return;const r=c[0][0],h=c[c.length-1][1];t.sparklines||(t.sparklines=[],t.sparklinesChanged=!0),this.sparkGroups||(this.sparkGroups=new Map);let i=this.sparkGroups.get(l);i||(i={type:l.chartType??"line",markers:!1,high:!1,low:!1,first:!1,last:!1,negative:l.chartType==="winloss",lineWeight:1,seriesColor:l.color??"#2f6fb3",negativeColor:"#c42b1c",markerColor:"#107c41",items:[]},this.sparkGroups.set(l,i),t.sparklines.push(i)),i.items.push({source:`${gt(t.name)}${H(n)}${r+1}:${H(n)}${h+1}`,cell:N(s,e)})}_rowsByTemplate(){const t=new Map;for(let s=0;s<this.rowCount;s++){const e=this.rowTpl[s];let l=t.get(e);l===void 0&&(l=[],t.set(e,l)),l.push(s)}return t}_writeSheetRules(t){const{sheet:s,colOut:e}=this,l=this.tplRows??(this.tplRows=this._rowsByTemplate()),a=new Map;e.forEach((o,n)=>{a.has(o.tpl)||a.set(o.tpl,[]),a.get(o.tpl).push(n)});const f=o=>{const n=[];for(const c of mt(o)){const r=[];for(let i=c.r0;i<=c.r1&&i<=this.extent.maxRow;i++)for(const u of l.get(i)??[])r.push(u);r.sort((i,u)=>i-u);const h=[];for(let i=c.c0;i<=c.c1&&i<=this.extent.maxCol;i++)for(const u of a.get(i)??[])h.push(u);h.sort((i,u)=>i-u);for(const[i,u]of at(r))for(const[p,w]of at(h))n.push(dt({r0:i,c0:p,r1:u,c1:w}))}return n.join(" ")};s.cf&&s.cf.length>0&&(t.cf=s.cf.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.cfChanged=!0),s.validations&&s.validations.length>0&&(t.validations=s.validations.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.validationsChanged=!0);for(const o of this.t.bindings.values()){if(o.type!=="static"||!o.pin)continue;const n=s.kind(o.row,o.col),c=o.pin==="column"?l.get(o.row)?.[0]??o.row:o.row,r=o.pin==="row"?a.get(o.col)?.[0]??o.col:o.col;(n&7)!==$&&t.setCell(c,r,n&7,s.value(o.row,o.col));const h=s.cellStyle(o.row,o.col);h&&t.setStyle(c,r,h)}}_applyAutoFit(t){const s=[...this.t.bindings.values()].filter(i=>i.autoFit);if(s.length===0)return;const e=this.t.measure??(i=>i.length*6.4),{colOut:l,rowTpl:a,rowCount:f,sheet:o}=this,{strings:n,styles:c}=this.book,r=(i,u)=>{const p=t.kind(i,u)&7;if(p===0)return"";if(p===E)return n.get(t.value(i,u));if(p===B){const w=c.get(t.style(i,u)).numFmt;return w&&w!=="General"?j(w).number(t.value(i,u)):String(t.value(i,u))}return"TRUE"},h=Math.min(f,1e5);for(const i of s)if(i.autoFit==="column")l.forEach((u,p)=>{if(u.tpl!==i.col)return;let w=o.cols.sizeOf(i.col);for(let m=0;m<h;m++)a[m]===i.row&&(w=Math.max(w,e(r(m,p))+8));w!==t.cols.sizeOf(p)&&t.cols.setSize(p,Math.ceil(w))});else{const u=l.findIndex(m=>m.tpl===i.col);if(u<0)continue;const p=Math.max(10,t.cols.sizeOf(u)-6),w=t.rows.defaultSize;for(let m=0;m<h;m++){if(a[m]!==i.row)continue;const C=Math.ceil(e(r(m,u))/p),k=Math.max(o.rows.sizeOf(i.row),C*w);k!==t.rows.sizeOf(m)&&t.rows.setSize(m,k)}}}_applyLayoutSetting(t){const{type:s,count:e,repeat:l=0}=this.t.layout;if(!(e>l))return;const a=[],f=t.maxRow,o=t.maxCol;for(let c=0;c<=f;c++)for(let r=0;r<=o;r++){const h=t.kind(c,r)&15,i=t.cellStyle(c,r);(h!==0||i!==0)&&a.push(c,r,h,t.value(c,r),i)}const n=e-l;t.columns=[],t.maxRow=-1,t.maxCol=-1;for(let c=0;c<a.length;c+=5){const[r,h,i,u,p]=[a[c],a[c+1],a[c+2],a[c+3],a[c+4]],w=(m,C)=>{i!==0&&t.setCell(m,C,i,u),p!==0&&t.setStyle(m,C,p)};if(s==="row"){const m=o+1;if(r<l){const C=Math.max(1,Math.ceil((f+1-l)/n));for(let k=0;k<C;k++)w(r,h+k*m)}else{const C=Math.floor((r-l)/n);w(l+(r-l)%n,h+C*m)}}else{const m=f+1;if(h<l){const C=Math.max(1,Math.ceil((o+1-l)/n));for(let k=0;k<C;k++)w(r+k*m,h)}else{const C=Math.floor((h-l)/n);w(r+C*m,l+(h-l)%n)}}}}_saveMap(t){const{rowTpl:s,rowRec:e,rowCtx:l,rowCount:a,colOut:f,contexts:o,collapses:n}=this,c=new Map;f.forEach((h,i)=>{c.has(h.tpl)||c.set(h.tpl,i)});const r=n.map(h=>({...h,col:c.get(h.binding.col)??0}));t.reportMap={template:this.t,rowTpl:s.subarray(0,a),rowRec:e.subarray(0,a),rowCtx:l.subarray(0,a),contexts:o,colTpl:f.map(h=>h.tpl),collapses:r,overlay:this.overlay,book:this.book,layout:this.t.layout??null},r.some(h=>h.collapsed)&&ct(t)}_groupContext(t,s,e){for(let l=t;l!==null;l=l.parent)if(l.node?.binding===e)return l;for(let l=s;l!==null;l=l.parent)if(l.node?.binding===e)return l;return null}_writeGroupValue(t,s,e,l,a,f){const o=f.rows.length>0?f.rows[0]:-1;if(o<0)return;const n=a.col.get(o);if(l.bins){const c=l.bins.find(r=>typeof n=="number"&&(r.min===void 0||n>=r.min)&&(r.max===void 0||n<r.max));t.setCell(s,e,E,this.book.strings.add(c?.name??"(other)"))}else if(typeof n=="number"&&l.by&&l.by!=="value")t.setCell(s,e,E,this.book.strings.add(Ot(n,l.by)));else if(typeof n=="number"&&l.size>0){const c=Math.floor(n/l.size)*l.size;t.setCell(s,e,E,this.book.strings.add(`${c} to ${c+l.size}`))}else it(t,s,e,a.col,o)}_recordAcross(t,s){for(let e=t;e!==null&&e.node!==null;e=e.parent)if(e.table===s)return e.rows.length>0?e.rows[0]:-1;return-1}_recordFor(t,s,e){if(s===G)return-1;if(s>=0&&(t.table===e||t.table===null))return s;for(let a=t;a!==null;a=a.parent)if(a.table===e&&a.rows.length>0)return s>=0&&a===t?s:a.rows[0];const l=this._rowsIn(t,e);return l.length>0?l[0]:-1}_summaryRows(t,s,e,l,a){let f=t.table===e&&a>=0?Int32Array.of(a):this._rowsIn(t.table===null?null:t,e);for(let o=s;o!==null&&o.node!==null;o=o.parent){const n=o.node.binding;if(o.table!==e)continue;const c=nt(e,n);let r=this.keyCache.get(c);r===void 0&&(r=tt(e,n),this.keyCache.set(c,r));const h=r[o.rows[0]],i=new Int32Array(f.length);let u=0;for(let p=0;p<f.length;p++){const w=r[f[p]];(w===h||w!==w&&h!==h)&&(i[u++]=f[p])}f=i.subarray(0,u)}return l.filters?.length&&(f=this._prepareRows(f,{...l,sort:null,sortBy:null},e)),f}_writeMerges(t){const{sheet:s,rowTpl:e,rowCtx:l,rowCount:a,colOut:f,groupMerges:o}=this,n=new Map;f.forEach((r,h)=>{n.has(r.tpl)||n.set(r.tpl,[]),n.get(r.tpl).push(h)});const c=new Set;for(const r of o){const{binding:h,r0:i,r1:u}=r,p=s.mergeAt(h.row,h.col),w=p?p.c0:h.col,m=p?p.c1:h.col;p&&c.add(p);const C=[];let k=i;if(h.repeatOnPage)for(let R=i+1;R<=u;R++)this.pageStartSet.has(R)&&(C.push([k,R-1]),k=R);C.push([k,u]);for(const R of n.get(w)??[]){const S=R+(m-w);for(const[y,x]of C)(x>y||S>R)&&t.addMerge({r0:y,c0:R,r1:x,c1:S})}}for(const r of s.merges){if(c.has(r)||this.t.bindings.has(M(r.r0,r.c0))){const i=this.t.bindings.get(M(r.r0,r.c0));if(i&&(i.type==="group"||i.type==="list")&&i.expand==="vertical")continue}if(c.has(r))continue;const h=r.r1-r.r0;for(let i=0;i<a;i++){if(e[i]!==r.r0||i+h>=a)continue;let u=!0;for(let p=1;p<=h;p++)(e[i+p]!==r.r0+p||l[i+p]!==l[i])&&(u=!1);if(u)for(const p of n.get(r.c0)??[]){const w=p+(r.c1-r.c0);w<f.length&&t.addMerge({r0:i,c0:p,r1:i+h,c1:w})}}}}_writePageSetup(t){const{t:s,rowTpl:e,rowCount:l}=this,a=_t(t),f=this.sheet.pageSetup;if(f)for(const n of["orientation","paperSize","paperWidth","paperHeight","scale","fitToPage","fitToWidth","fitToHeight","horizontalCentered","verticalCentered","header","footer","headings","gridLines","margins"])f[n]!==void 0&&(a[n]=f[n]);s.pageSetup&&Object.assign(a,s.pageSetup);const o=s.pagination;if(o?.order&&(a.pageOrder=o.order),a.rowBreaks=[...new Set(this.breaks)].filter(n=>n>0&&n<l).sort((n,c)=>n-c),a.colBreaks=[...new Set(this.colBreaks)].filter(n=>n>0&&n<this.colOut.length).sort((n,c)=>n-c),o?.titleCols){let n=-1,c=-1;this.colOut.forEach((r,h)=>{r.tpl>=o.titleCols.c0&&r.tpl<=o.titleCols.c1&&(n<0||h===c+1)&&(n<0&&(n=h),c=h)}),n>=0&&(a.titleCols={c0:n,c1:c})}if(s.titleRows){let n=-1,c=-1;for(let r=0;r<l;r++){const h=e[r];if(h>=s.titleRows.r0&&h<=s.titleRows.r1)n<0&&(n=r),c=r;else if(n>=0)break}n>=0&&(a.titleRows={r0:n,r1:c})}t.pageSetupChanged=!0}_writeFormulas(t){if(this.formulas.length===0)return;const{rowTpl:s,rowCount:e,colOut:l}=this,a=new Map;for(let r=0;r<e;r++){const h=s[r];let i=a.get(h);i===void 0&&(i=[],a.set(h,i)),i.push(r)}const f=new Map;l.forEach((r,h)=>{f.has(r.tpl)||f.set(r.tpl,[]),f.get(r.tpl).push(h)});const o=new Uint32Array(this.formulas.length),n=new Uint16Array(this.formulas.length);this.formulas.forEach((r,h)=>{const{or:i,oc:u,tr:p,tc:w,info:m,ctx:C,style:k}=r,R=m.f??yt(m.sf,p-Math.floor(m.base/P),w-m.base%P),S=this._reportFunctions(R,i,C),y=Mt(S,(x,b,d,_)=>{const v=a.get(b),z=f.get(_);if(!v||!z)return null;const W=b===p?[[i,i]]:ot(v,C.first,C.last);if(W.length===0)return"#REF!";let I,F;return _===w?(I=u,F=u):(I=z[0],F=z[z.length-1]),W.map(([D,K])=>{const X=`${d}${H(I)}${x}${D+1}`;return D===K&&I===F?X:`${X}:${d}${H(F)}${x}${K+1}`}).join(",")});if(y.length>St){t.setCell(i,u,Z,Ct.REF.index),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u;return}t.setCell(i,u,J|$,0),t.setFormula(i,u,{f:y,typed:!0}),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u}),this.book.engine?.cellsChanged(t,o,n,o.length),this.book.formulasEdited=!0;const c=this.book.engine;c&&this.formulas.forEach(r=>{if(this.t.bindings.get(M(r.tr,r.tc))?.preserveFormula!==!1)return;const i=c.read(t,r.or,r.oc);t.setFormula(r.or,r.oc,null),t.setCell(r.or,r.oc,$,0),lt(t,r.or,r.oc,i,this.book.strings)})}_reportFunctions(t,s,e){if(!/RPT_/i.test(t))return t;const l=n=>this._measureCell(f(n),s,e),a=n=>{const c=n.trim();for(const r of this.t.bindings.values())if(r.alias===c)return N(r.row,r.col);return c},f=a,o=n=>n==null?'""':String(n);return t.replace(/RPT_RANK\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(1+r.values.filter(h=>h>r.current).length):'""'}).replace(/RPT_PROPORTION\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c),h=r?r.values.reduce((i,u)=>i+u,0):0;return r&&h!==0?o(r.current/h):'""'}).replace(/RPT_CUMULATIVE\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(r.values.slice(0,r.at+1).reduce((h,i)=>h+i,0)):'""'}).replace(/RPT_(MOM|YOY)\(\s*([^()]+?)\s*\)/gi,(n,c,r)=>{const h=l(r);if(!h)return'""';const i=c.toUpperCase()==="MOM"?1:{month:12,quarter:4,year:1,week:52}[h.by]??12,u=h.values[h.at-i];return u===void 0||u===0?'""':o((h.current-u)/u)}).replace(/RPT_VALUE\(\s*([^()]+?)\s*\)/gi,(n,c)=>a(c)).replace(/RPT_PARAM\(\s*"([^"]+)"\s*\)/gi,(n,c)=>{const r=this._param(c);return typeof r=="number"?String(r):`"${String(r??"").replace(/"/g,'""')}"`}).replace(/RPT_INDEX\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=Y(a(c).replace(/\$/g,"")),h=r?this.t.binding(r.r0,r.c0):null;for(let i=e;i!==null;i=i.parent)if(i.node?.binding===h)return String(i.ordinal??1);return"1"}).replace(/RPT_PAGES\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();if(!c)return String(r.length);const h=this._topContext(e);return String(r.filter(i=>i>=h.first&&i<=h.last).length||1)}).replace(/RPT_PAGE\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();let h=0;for(let p=0;p<r.length;p++)r[p]<=s&&(h=p);if(!c)return String(h+1);const i=this._topContext(e);let u=0;for(;u<h&&r[u]<i.first;)u++;return String(h-u+1)})}_topContext(t){let s=t;for(let e=t;e!=null&&e.node;e=e.parent)s=e;return s}_measureCell(t,s,e){const l=Y(t.replace(/\$/g,""));if(!l)return null;const a=this.outSheet,f=this.colOut.findIndex(p=>p.tpl===l.c0);if(f<0)return null;let o=e;for(;o&&!o.node&&o.parent;)o=o.parent;const n=o?.node?.binding?.type==="list"?o:o?.parent??o,c=n?.first??0,r=n?.last??this.rowCount-1,h=[];let i=-1,u=1/0;for(let p=c;p<=r;p++){if(this.rowTpl[p]!==l.r0||(a.kind(p,f)&ut)!==B)continue;const m=Math.abs(p-s);(p<=s||i<0)&&m<u&&(u=m,i=h.length),h.push(a.value(p,f))}return i<0||h.length===0?null:{values:h,at:i,current:h[i],by:o?.node?.binding?.by??null}}_pageStarts(){if(this.pageStarts)return this.pageStarts;const t=V(this.book,this.outSheet),s=[];for(let e=0;e<t.pageCount;e++)s.push(t.page(e).r0);return this.pageStarts=s,s}}function ot(g,t,s){const e=[];let l=0,a=g.length;if(t>=0)for(;l<a;){const f=l+a>>>1;g[f]<t?l=f+1:a=f}for(let f=l;f<g.length;f++){const o=g[f];if(t>=0&&o>s)break;const n=e[e.length-1];n&&n[1]===o-1?n[1]=o:e.push([o,o])}return e}function Mt(g,t){let s="",e=0;const l=g.length,a=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)(?::(\$?)([A-Za-z]{1,3})(\$?)(\d+))?/y;for(;e<l;){const f=g[e];if(f==='"'){let c=e+1;for(;c<l;)if(g[c]==='"')if(g[c+1]==='"')c+=2;else break;else c++;s+=g.slice(e,c+1),e=c+1;continue}if(f==="'"){const c=g.indexOf("'!",e+1);if(c>=0){const r=/^\$?[A-Za-z]{1,3}\$?\d+(:\$?[A-Za-z]{1,3}\$?\d+)?/.exec(g.slice(c+2)),h=c+2+(r?r[0].length:0);s+=g.slice(e,h),e=h;continue}}a.lastIndex=e;const o=e>0?g[e-1]:"",n=/[A-Za-z0-9_.!$]/.test(o)?null:a.exec(g);if(n){const c=g[e+n[0].length]??"";if(!/[A-Za-z0-9_.(!]/.test(c)){const r=(i,u,p,w)=>t(p,Number(w)-1,i,wt(u.toUpperCase())),h=r(n[1],n[2],n[3],n[4]);if(n[6]===void 0)s+=h??n[0];else{const i=r(n[5],n[6],n[7],n[8]);s+=h===null||i===null?n[0]:`${h.split(/[:,]/)[0]}:${i.split(/[:,]/).pop()}`}e+=n[0].length;continue}}s+=f,e++}return s}function Tt(g,t,s){const e=new Float64Array(g.length);for(let f=0;f<g.length;f++)e[f]=t[g[f]];const l=new Int32Array(g.length);for(let f=0;f<g.length;f++)l[f]=f;kt(l,g.length,e,s);const a=new Int32Array(g.length);for(let f=0;f<g.length;f++)a[f]=g[l[f]];g.set(a)}const At=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ot(g,t){const e=j("yyyy-mm").number(Math.floor(g)),l=Number(e.slice(0,4)),a=Number(e.slice(5,7));switch(t){case"year":return String(l);case"quarter":return`Q${Math.floor((a-1)/3)+1} ${l}`;case"month":return`${At[a-1]} ${l}`;default:return j("yyyy-mm-dd").number(Math.floor(g))}}function it(g,t,s,e,l){const a=e.kind(l);a!==$&&g.setCell(t,s,a,e.raw(l))}function lt(g,t,s,e,l){e==null||e===""||(typeof e=="number"?g.setCell(t,s,B,e):typeof e=="boolean"?g.setCell(t,s,ft,e?1:0):e instanceof bt?g.setCell(t,s,Z,e.index):g.setCell(t,s,E,l.add(Array.isArray(e)?e.join(", "):String(e))))}function at(g){const t=[];for(const s of g){const e=t[t.length-1];e&&(e[1]===s||e[1]===s-1)?e[1]=s:t.push([s,s])}return t}function ct(g){const t=g.reportMap;if(t){for(const s of t.collapses)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!1);for(const s of t.collapses)if(s.collapsed)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!0);g.revision++}}function jt(g,t,s,e=void 0,l=!1){const a=g.reportMap;if(!a)return!1;const f=a.collapses.find(n=>n.row===t&&(s===void 0||n.col===s));if(!f)return!1;const o=e===void 0?!f.collapsed:e==="collapsed"||e===!0;if(f.collapsed=o,l)for(const n of a.collapses)n.from>=f.from&&n.to<=f.to&&(n.collapsed=o);return ct(g),!0}function Et(g,t,s={}){return V(g,t,s).pageCount}export{Rt as BINDING_TYPES,T as ReportError,ht as ReportTemplate,ct as applyCollapses,Et as reportPages,jt as toggleCollapse};
|
|
1
|
+
import{BOOL as ft,EMPTY as $,ERR as Z,FORMULA as J,KIND_MASK as ut,NUM as B,SPILL as pt,STR as E}from"../core/sheet.js";import{cellRef as N,colName as H,colIndex as wt,MAX_COLS as P,MAX_ROWS as L,parseRangeRef as Y,rangeRef as dt,sheetPrefix as gt}from"../core/address.js";import{rangesOf as mt}from"../core/cond-format.js";import{translateFormula as yt}from"../core/formula-refs.js";import{getPageSetup as _t}from"../print/page-setup.js";import{paginate as V}from"../print/paginate.js";import{getFormatter as j}from"../core/numfmt.js";import{ERR as Ct,XlError as bt}from"../calc/values.js";import{aggregate as Q,formulaHelper as q,groupKeys as tt,TableView as et}from"./view.js";import{sortByF64 as kt}from"./sort.js";import{Axis as st}from"../core/axis.js";import{t as A}from"../i18n/index.js";const Rt=["group","list","summary","param","static","chart"],M=(g,t)=>g*P+t,U=new Int32Array(0),G=-2,St=8e3;class O{constructor(t,s,e,l=null,a=void 0){this.parent=t,this.table=s,this.rows=e,this.node=l,this.value=a,this.first=-1,this.last=-1,this.resolved=null}}class T extends Error{}class ht{constructor(t,s,e={}){this.manager=t,this.sheet=s,this.bindings=new Map,this.params=new Map,this.filters=[],this.titleRows=e.titleRows??null,this.pageSetup=e.pageSetup??null,this.defaultTable=e.table??null,this.name=e.name??s.name,this.output=null,this.mode=e.mode??"design",this.pagination=e.pagination??null,this.layout=e.layout??null,this.dataEntry=e.dataEntry??null,this.charts=e.charts??[],this.pictures=e.pictures??[],this.states=e.states??null,this.measure=e.measure??null,this.showHiddenRows=e.showHiddenRows===!0,this.showHiddenCols=e.showHiddenCols===!0,this.listeners=new Map,s.report=this}setBinding(t,s,e){const l=e.type;if(!Rt.includes(l))throw new T(`Unknown binding type: ${l}`);const a={table:this.defaultTable,expand:l==="group"||l==="list"?"vertical":"none",agg:"sum",sort:l==="group"?"asc":null,...e,row:t,col:s};return this.bindings.set(M(t,s),a),a}binding(t,s){return this.bindings.get(M(t,s))??null}removeBinding(t,s){this.bindings.delete(M(t,s))}static markerText(t){switch(t.type){case"group":return`[${t.field}]`;case"list":return`=[${t.field}]`;case"summary":return`${t.agg??"sum"}[${t.field}]`;case"chart":return`chart[${t.chartType??"line"}]`;default:return`{${t.param}}`}}writeMarkers(t){t.sheet===this.sheet&&t.transact("report binding",s=>{for(const e of this.bindings.values())e.type!=="static"&&(s.saveCell(e.row,e.col),this.sheet.setFormula(e.row,e.col,null),this.sheet.setCell(e.row,e.col,E,t.strings.add(ht.markerText(e))))})}addParam(t,s={}){this.params.set(t,{name:t,caption:s.caption??t,type:s.type??"string",value:s.value??null,options:s.options??null})}setParam(t,s){const e=this.params.get(t);if(!e)throw new T(A("No parameter named {name}.",{name:t}));e.value=s}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>this.listeners.get(t).delete(s)}fire(t,s){let e=!0;for(const l of this.listeners.get(t)??[])l(s)===!1&&(e=!1);return e}addFilter(t){this.filters.push(t)}generate(t,{target:s=null,name:e=null,params:l=null,measure:a=null}={}){if(l)for(const[o,n]of Object.entries(l))this.setParam(o,n);a&&(this.measure=a),this.fire("stage",{stage:"start"});const f=new xt(this,t).run(s,e);return this.fire("stage",{stage:"done",result:f}),f}async generateAsync(t,s){return await new Promise(e=>setTimeout(e,0)),this.generate(t,s)}toJSON(){return{name:this.name,sheet:this.sheet.name,table:this.defaultTable,bindings:[...this.bindings.values()].map(t=>({...t})),params:[...this.params.values()],filters:this.filters,titleRows:this.titleRows,pageSetup:this.pageSetup,output:this.output?.name??null,mode:this.mode,pagination:this.pagination,layout:this.layout,dataEntry:this.dataEntry,charts:this.charts,pictures:this.pictures,states:this.states,showHiddenRows:this.showHiddenRows,showHiddenCols:this.showHiddenCols}}}const nt=(g,t)=>`${g.name}|${t.formula??t.field}|${t.by??""}|${t.size??""}|${t.bins?JSON.stringify(t.bins):""}`,vt=g=>{let t=0;for(let s=g.parent;s!==null;s=s.parent)t++;return t};class rt{constructor(t,s,e,l){this.binding=t,this.a=s,this.b=e,this.parent=l,this.children=[],this.members=[]}}class xt{constructor(t,s){this.t=t,this.book=s,this.manager=t.manager,this.sheet=t.sheet,this.roots=new Map,this.keyCache=new Map,this.helperViews=new Map,this.cellInfo=new Map,this.groupMerges=[],this.collapses=[],this.overlay=null,this.breaks=[],this.formulas=[],this.memberColumns=new Map,this.rowCap=1024,this.rowTpl=new Int32Array(this.rowCap),this.rowCtx=new Int32Array(this.rowCap),this.rowRec=new Int32Array(this.rowCap),this.rowCount=0,this.contexts=[],this.colOut=[]}_table(t){if(!t)throw new T(A("A binding needs a table."));return this.manager.table(t)}_templateExtent(){const{sheet:t}=this;let s=t.maxRow,e=t.maxCol;for(const l of this.t.bindings.values())l.row>s&&(s=l.row),l.col>e&&(e=l.col);for(const l of t.merges)l.r1>s&&(s=l.r1),l.c1>e&&(e=l.c1);return{maxRow:s,maxCol:e}}_buildTree(t,s){const e=t==="vertical",l=i=>e?i.row:i.col,a=i=>e?i.col:i.row,f=[...this.t.bindings.values()].filter(i=>(i.type==="group"||i.type==="list")&&i.expand===t);f.sort((i,u)=>a(i)-a(u)||l(i)-l(u));const o=new rt(null,0,e?s.maxRow:s.maxCol,null),n=new Map,c=i=>{if(i.span>1)return l(i)+i.span-1;const u=this.sheet.mergeAt(i.row,i.col);return u?e?u.r1:u.c1:l(i)},r=i=>{if(i.parent==="none")return o;if(i.parent){const p=n.get(M(i.parent.row,i.parent.col));if(p)return p}let u=o;for(const p of n.values())a(p.binding)>=a(i)||l(i)<p.a||l(i)>p.b||p.a>=u.a&&(u===o||a(p.binding)>=a(u.binding))&&(u=p);return u};for(const i of f){const u=r(i);if(i.type==="list"&&u!==o&&u.binding.type==="list"&&l(u.binding)===l(i)&&u.binding.table===i.table){u.members.push(i);continue}if(i.type==="list"){const w=u.children.find(m=>m.binding.type==="list"&&l(m.binding)===l(i)&&m.binding.table===i.table);if(w){w.members.push(i);continue}}const p=new rt(i,l(i),c(i),u);u.children.push(p),n.set(M(i.row,i.col),p)}const h=i=>{i.children.sort((u,p)=>u.a-p.a);for(const u of i.children)h(u),i!==o&&u.b>i.b&&(i.b=u.b),i!==o&&u.a<i.a&&(i.a=u.a);for(let u=1;u<i.children.length;u++)if(i.children[u].a<=i.children[u-1].b){const p=i.children[u].binding,w=i.children[u-1].binding;throw new T(A("The cells {first} and {second} expand over the same rows but neither is the other's parent.",{first:N(p.row,p.col),second:N(w.row,w.col)}))}};return h(o),o}_rootRows(t){let s=this.roots.get(t);if(s!==void 0)return s;const e=this.t.filters.filter(a=>this.manager.table(a.table??this.t.defaultTable)===t).map(a=>this._resolveFilter(a)),l=new et(t,{columns:[],filters:e});return s=l.filtered.slice(0,l.filteredCount),l.dispose(),this.roots.set(t,s),s}_resolveFilter(t){const s={...t};if(t.param&&(s.value=this._param(t.param)),t.param2&&(s.value2=this._param(t.param2)),t.valuesParam){const e=this._param(t.valuesParam);s.values=Array.isArray(e)?e:[e],s.op=s.op??"in"}return s}_param(t){const s=this.t.params.get(t);if(!s)throw new T(A("No parameter named {name}.",{name:t}));return s.value}_filterActive(t){if(t.param&&(this._param(t.param)===null||this._param(t.param)===""))return!1;if(t.valuesParam){const s=this._param(t.valuesParam);if(s===null||s===""||Array.isArray(s)&&s.length===0)return!1}return!0}_rowsIn(t,s){if(t===null)return this._rootRows(s);if(t.table===s)return t.rows;t.resolved===null&&(t.resolved=new Map);let e=t.resolved.get(s);return e!==void 0||(e=this._crossRows(t,s),t.resolved.set(s,e)),e}_crossRows(t,s){for(let e=t;e!==null;e=e.parent){if(e.table===s)return e.rows;if(e.table===null)continue;const l=e.node?.binding.link;if(l)return this._joinRows(e,s,l.from,l.to);const a=this.manager.relationshipBetween(e.table,s);if(!a)continue;const f=this._rootMask(s);if(a.to===e.table){const{starts:r,rows:h}=a.children();let i=0;for(let w=0;w<e.rows.length;w++)i+=r[e.rows[w]+1]-r[e.rows[w]];const u=new Int32Array(i);let p=0;for(let w=0;w<e.rows.length;w++){const m=e.rows[w];for(let C=r[m];C<r[m+1];C++)(f===null||f[h[C]]===1)&&(u[p++]=h[C])}return p===i?u:u.slice(0,p)}const o=a.parents(),n=new Uint8Array(s.rowCount),c=[];for(let r=0;r<e.rows.length;r++){const h=o[e.rows[r]];h>=0&&n[h]===0&&(f===null||f[h]===1)&&(n[h]=1,c.push(h))}return Int32Array.from(c)}return this._rootRows(s)}_rootMask(t){if(!this.t.filters.some(e=>this.manager.table(e.table??this.t.defaultTable)===t))return null;const s=new Uint8Array(t.rowCount);for(const e of this._rootRows(t))s[e]=1;return s}_joinRows(t,s,e,l){const a=new Set,f=t.table.column(e);for(let r=0;r<t.rows.length;r++)a.add(String(f.get(t.rows[r])));const o=s.column(l),n=this._rootRows(s),c=[];for(let r=0;r<n.length;r++)a.has(String(o.get(n[r])))&&c.push(n[r]);return Int32Array.from(c)}_helperView(t){let s=this.helperViews.get(t);return s===void 0&&(s=new et(t,{columns:[]}),this.helperViews.set(t,s)),s}_prepareRows(t,s,e,l=null){let a=t;const f=(s.filters??[]).filter(o=>this._filterActive(o)).map(o=>this._resolveFilter(o));if(f.length>0||s.filter){const o=this._helperView(e),n=new Uint8Array(e.rowCount);for(let h=0;h<a.length;h++)n[a[h]]=1;for(const h of f)o._applyCondition(h,n,e.rowCount);s.filter&&this._applyFilterTree(s.filter,n,e,o,l);const c=new Int32Array(a.length);let r=0;for(let h=0;h<a.length;h++)n[a[h]]===1&&(c[r++]=a[h]);a=c.subarray(0,r)}if(s.sortFormula)a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,q(e,s.sortFormula),s.sort==="desc");else if(s.sort||s.sortBy){const o=e.column(s.sortBy??s.field);o&&(a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,o,s.sort==="desc"))}return a}_applyFilterTree(t,s,e,l,a){const f=e.rowCount;if(t.and){for(const n of t.and)this._applyFilterTree(n,s,e,l,a);return}if(t.or){const n=new Uint8Array(f);for(const c of t.or){const r=s.slice();this._applyFilterTree(c,r,e,l,a);for(let h=0;h<f;h++)n[h]|=r[h]}s.set(n);return}if(t.param!==void 0&&!this._filterActive(t))return;const o=this._resolveFilter(t);if(t.cell){const n=this.t.binding(t.cell.row,t.cell.col);for(let c=a;c!=null;c=c.parent)if(c.node?.binding===n&&c.rows.length>0){o.value=c.table.column(n.field).get(c.rows[0]);break}}if(t.join){const n=this._table(t.join.table),c=n.column(t.join.field),r=a?this._rowsIn(a,n):this._rootRows(n),h=new Set;for(let i=0;i<r.length;i++)h.add(c.get(r[i]));o.op="in",o.values=[...h]}l._applyCondition(o,s,f)}_partition(t,s,e,l=null){const a=this._prepareRows(t,{...s,sort:null,sortBy:null,sortFormula:null},e,l),f=nt(e,s);let o=this.keyCache.get(f);if(o===void 0){if(o=tt(e,s),o===null)throw new T(A("No field {field} in {table}.",{field:s.field,table:e.name}));this.keyCache.set(f,o)}const n=a===t?t.slice():a;s.sort&&Tt(n,o,s.sort==="desc");const c=[],r=s.sort?null:new Map;let h=0;const i=n.length;if(s.sort)for(;h<i;){const u=o[n[h]];let p=h+1;if(u===u)for(;p<i&&o[n[p]]===u;)p++;else for(;p<i&&o[n[p]]!==o[n[p]];)p++;c.push(n.subarray(h,p)),h=p}else{for(;h<i;h++){const u=o[n[h]],p=u!==u?"blank":u,w=r.get(p);w?w.push(n[h]):r.set(p,[n[h]])}for(const u of r.values())c.push(Int32Array.from(u))}return this._orderGroups(c,s,e)}_orderGroups(t,s,e){if(s.sortList){const l=s.formula?q(e,s.formula):e.column(s.field),a=new Map(s.sortList.map((o,n)=>[String(o).toLowerCase(),n])),f=o=>a.get(String(l.get(o[0])).toLowerCase())??1/0;return t.map((o,n)=>[o,f(o),n]).sort((o,n)=>o[1]-n[1]||o[2]-n[2]).map(o=>o[0])}if(s.sortCell){const l=this.t.binding(s.sortCell.row,s.sortCell.col),a=l&&l.field?e.column(l.field):null;if(a){const f=s.sort==="desc"?-1:1,o=n=>Q(a,l.agg??"sum",n,0,n.length);return t.map(n=>[n,o(n)]).sort((n,c)=>f*(n[1]-c[1])).map(n=>n[0])}}return t}_paginateRows(){const{t}=this,s=t.pagination,e=new Set,l=new Set;for(const n of t.bindings.values())n.pageBefore&&e.add(n.row),n.pageAfter&&l.add(n.row);if(e.size>0||l.size>0)for(let n=0;n<this.rowCount;n++){const c=this.rowTpl[n];e.has(c)&&n>0&&this.breaks.push(n),l.has(c)&&this.breaks.push(n+1)}const a=s?.endRows??null,f=t.titleRows?t.titleRows.r1-t.titleRows.r0+1:0;let o=s?.rowsPerPage>0?s.rowsPerPage:0;if(a&&o===0){const n=V(this.book,this.sheet).box.h,c=a.r1-a.r0+1;o=Math.max(1,Math.floor(n/this.sheet.rows.defaultSize)-f-c)}if(a)this._repeatEndRows(a,o,f);else if(o>0)for(const n of this._rowPageStarts(this.rowCount,o,f,new Set(this.breaks)))this.breaks.push(n);this.pageStartSet=new Set(this.breaks)}_rowPageStarts(t,s,e,l){const a=[];for(const i of this.contexts)i.node?.binding?.keepTogether&&i.first!==void 0&&i.last>i.first&&a.push(i);a.sort((i,u)=>i.first-u.first);const f=[];let o=0,n=e+s,c=0;const r=[...l].sort((i,u)=>i-u);let h=0;for(;o+n<t;){let i=o+n;for(;h<r.length&&r[h]<=o;)h++;for(h<r.length&&r[h]<i&&(i=r[h]);c<a.length&&a[c].last<i;)c++;c<a.length&&a[c].first<i&&a[c].first>o&&a[c].last>=i&&(i=a[c].first),f.push(i),o=i,n=s}return f}_repeatEndRows(t,s,e){const l=this.rowCount,{rowTpl:a,rowCtx:f,rowRec:o}=this,n=[],c=[];for(let d=0;d<l;d++)(a[d]>=t.r0&&a[d]<=t.r1?c:n).push(d);if(c.length===0||n.length===0)return;const r=new Int32Array(l).fill(-1);n.forEach((d,_)=>{r[d]=_});const h=new Set;for(const d of this.breaks){let _=d;for(;_<l&&r[_]<0;)_++;_<l&&h.add(r[_])}const i=this.contexts.map(d=>[d.first,d.last]);for(const d of this.contexts){if(d.first===void 0||d.first<0)continue;let _=d.first;for(;_<l&&r[_]<0;)_++;let v=d.last;for(;v>0&&r[v]<0;)v--;d.first=_<l?r[_]:0,d.last=v>=0&&r[v]>=0?r[v]:d.first}const u=s>0?this._rowPageStarts(n.length,s,e,h):[...h].sort((d,_)=>d-_);i.forEach(([d,_],v)=>{this.contexts[v].first=d,this.contexts[v].last=_});const p=n.length+c.length*(u.length+1),w=new Int32Array(p),m=new Int32Array(p),C=new Int32Array(p),k=new Int32Array(l).fill(-1),R=[];let S=0,y=0;const x=()=>{c.forEach(d=>{w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]<0&&(k[d]=S),S++})};n.forEach((d,_)=>{y<u.length&&u[y]===_&&(x(),R.push(S),y++),w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]=S,S++}),x(),this.rowTpl=w,this.rowCtx=m,this.rowRec=C,this.rowCount=p,this.rowCap=p,this.breaks=R;const b=d=>d>=0&&d<l&&k[d]>=0?k[d]:d;for(const d of this.contexts)d.first!==void 0&&(d.first=b(d.first)),d.last!==void 0&&(d.last=b(d.last));for(const d of this.collapses)d.row=b(d.row),d.from=b(d.from),d.to=b(d.to);for(const d of this.groupMerges)d.r0=b(d.r0),d.r1=b(d.r1);this.overlay&&(this.overlay=new Map([...this.overlay].map(([d,_])=>[b(d),_])))}_paginateCols(){const{t}=this,s=t.pagination;this.colBreaks=[];const e=new Set,l=new Set;for(const p of t.bindings.values())p.colPageBefore&&e.add(p.col),p.colPageAfter&&l.add(p.col);const a=s?.endCols??null,f=p=>a&&p.tpl>=a.c0&&p.tpl<=a.c1,o=a?this.colOut.filter(f):[],n=a?this.colOut.filter(p=>!f(p)):this.colOut,c=s?.colsPerPage>0?s.colsPerPage:0,r=[],h=s?.titleCols?s.titleCols.c1-s.titleCols.c0+1:0;let i=0,u=h+c;n.forEach((p,w)=>{w>0&&(c>0&&i>=u||e.has(p.tpl)||l.has(n[w-1].tpl))&&(r.push(...o),this.colBreaks.push(r.length),i=0,u=c),r.push(p),i++}),r.push(...o),this.colOut=r}_pushRow(t,s,e){if(this.rowCount===this.rowCap){const a=this.rowCap*2,f=o=>{const n=new Int32Array(a);return n.set(o),n};this.rowTpl=f(this.rowTpl),this.rowCtx=f(this.rowCtx),this.rowRec=f(this.rowRec),this.rowCap=a}if(this.rowCount>=L)throw new T(A("The report needs more than {count} rows. Add a filter.",{count:L}));const l=this.rowCount++;return this.rowTpl[l]=t,this.rowCtx[l]=s,this.rowRec[l]=e,l}_newContext(t){return this.contexts.push(t),t.index=this.contexts.length-1,t}_emitBand(t,s,e,l,a){let f=e;const o=t.children;let n=0;for(;f<=l;){for(;n<o.length&&o[n].b<f;)n++;const c=n<o.length&&o[n].a===f?o[n]:null;if(c!==null){const r=this._expandNode(c,s);f=c.b+1+(r??0)}else this._pushRow(f,s.index,a),f++}}_expandNode(t,s){const e=t.binding,l=this._table(e.table),a=this._rowsIn(s,l),f=c=>e.fillTo>1?(e.fillTo-c%e.fillTo)%e.fillTo:0;if(e.type==="group"){let c=this._partition(a,e,l,s);e.spillMode==="none"&&(c=c.slice(0,1));const r=e.merge===!0||this.sheet.mergeAt(e.row,e.col)!==null,h=c.length;for(let i=0;i<h;i++){const u=this._newContext(new O(s,l,c[i],t));u.ordinal=i+1,u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,-1),u.last=this.rowCount-1,r&&u.last>u.first&&this.groupMerges.push({binding:e,r0:u.first,r1:u.last}),e.collapse&&u.last>u.first&&this.collapses.push({binding:e,row:u.first,from:u.first+1,to:u.last,depth:vt(u),collapsed:e.initial==="collapsed"}),e.pageBreak&&i<h-1&&this.breaks.push(this.rowCount)}for(let i=f(h);i>0;i--){const u=this._newContext(new O(s,l,U,t));u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,G),u.last=this.rowCount-1}return 0}let o=this._prepareRows(a,e,l,s);e.spillMode==="none"&&(o=o.subarray(0,1));const n=e.pageEvery??0;if(t.a===t.b&&t.children.length===0){const c=this._newContext(new O(s,l,o,t));if(c.first=this.rowCount,e.spillMode==="overwrite"){const r=o.length;for(let h=0;h<r;h++){const i=this._pushRow(t.a+h,c.index,o[h]);this.overlay===null&&(this.overlay=new Map),this.overlay.set(i,t.a)}return c.last=this.rowCount-1,Math.max(0,r-1)}for(let r=0;r<o.length;r++)this._pushRow(t.a,c.index,o[r]),n>0&&(r+1)%n===0&&r+1<o.length&&this.breaks.push(this.rowCount);for(let r=f(o.length);r>0;r--)this._pushRow(t.a,c.index,G);return c.last=this.rowCount-1,0}for(let c=0;c<o.length;c++){const r=o.subarray(c,c+1),h=this._newContext(new O(s,l,r,t));h.ordinal=c+1,h.first=this.rowCount,this._emitBand(t,h,t.a,t.b,o[c]),h.last=this.rowCount-1,n>0&&(c+1)%n===0&&c+1<o.length&&this.breaks.push(this.rowCount)}return 0}_expandColumns(t,s,e,l){let a=e,f=0;const o=t.children;for(;a<=l;){for(;f<o.length&&o[f].b<a;)f++;const n=f<o.length&&o[f].a===a?o[f]:null;if(n!==null)this._expandColumnNode(n,s),a=n.b+1;else{if(this.colOut.length>=P)throw new T(A("The report needs more than {count} columns. Add a filter.",{count:P}));this.colOut.push({tpl:a,ctx:s}),a++}}}_expandColumnNode(t,s){const e=t.binding,l=this._table(e.table),a=this._colRows(s,l);let f=e.type==="group"?this._partition(a,e,l):Array.from(this._prepareRows(a,e,l),n=>Int32Array.of(n));e.spillMode==="none"&&(f=f.slice(0,1));const o=e.fillTo>1?(e.fillTo-f.length%e.fillTo)%e.fillTo:0;for(let n=0;n<o;n++)f.push(U);for(const n of f){const c=new O(s,l,n,t);c.first=this.colOut.length,this._expandColumns(t,c,t.a,t.b),c.last=this.colOut.length-1}}_colRows(t,s){return t===null||t.table===null?this._rootRows(s):this._rowsIn(t,s)}run(t,s){const{book:e,t:l}=this,a=this._templateExtent();this.extent=a;const f=this._buildTree("vertical",a),o=this._buildTree("horizontal",a),n=this._newContext(new O(null,null,U,null));n.first=0,this._emitBand(f,n,0,a.maxRow,-1),n.last=this.rowCount-1;const c=new O(null,null,U,null);this._expandColumns(o,c,0,a.maxCol),this._paginateRows(),this._paginateCols();const r=t??e.addSheet(s??`${l.name} Report`);this.outSheet=r,r.reportWriting=!0;const h=r.formulas.size>0;this._clear(r),this._writeGeometry(r),this._writeCells(r),this._writeMerges(r),this._writeSheetRules(r),this._writePageSetup(r),this._writeFormulas(r),this._applyAutoFit(r),l.layout&&this._applyLayoutSetting(r),this._saveMap(r),h&&e.engine?.rebuild(),r.reportWriting=!1,r.revision++,l.output=r;for(const i of this.helperViews.values())i.dispose();return{sheet:r,rows:this.rowCount,cols:this.colOut.length,pages:Et(e,r)}}_clear(t){t.columns=[],t.formulas=new Map,t.maxRow=-1,t.maxCol=-1,t.merges=[],t.mergeIndex=null,t.spills=null,t.rowStyles=null,t.colStyles=null,t.pageSetup=void 0,t.cf=void 0,t.cfEval=void 0,t.validations=void 0,t.sparklines=void 0,t.rows=new st(L,this.sheet.rows.defaultSize),t.cols=new st(P,this.sheet.cols.defaultSize),t.colsChanged=!0,t.viewChanged=!0}_writeGeometry(t){const{sheet:s}=this,{colOut:e,rowTpl:l,rowCount:a}=this;if(s.cols.sizes!==null)for(let o=0;o<e.length;o++){const n=s.cols.sizeOf(e[o].tpl);s.cols.isHidden(e[o].tpl)||(n!==t.cols.defaultSize||t.cols.isCustom(o))&&t.cols.setSize(o,n)}if(s.rows.sizes!==null)for(let o=0;o<a;o++){const n=l[o];s.rows.isCustom(n)&&!s.rows.isHidden(n)&&t.rows.setSize(o,s.rows.sizeOf(n))}if(!this.t.showHiddenRows&&s.rows.hiddenSizes?.size>0)for(let o=0;o<a;o++)s.rows.isHidden(l[o])&&t.rows.setHidden(o,!0);!this.t.showHiddenCols&&s.cols.hiddenSizes?.size>0&&e.forEach((o,n)=>{s.cols.isHidden(o.tpl)&&t.cols.setHidden(n,!0)}),s.colStyles&&(t.colStyles=new Map,e.forEach((o,n)=>{const c=s.colStyles.get(o.tpl);c!==void 0&&t.colStyles.set(n,c)}))}_writeCells(t){const{colOut:s,rowCount:e,rowTpl:l,rowCtx:a,rowRec:f,sheet:o,contexts:n}=this,{strings:c}=this.book,{bindings:r}=this.t,{overlay:h}=this,i=o.formulas.size>0,u=new Map;s.forEach((w,m)=>{u.has(w.tpl)||u.set(w.tpl,m)});const p=(w,m)=>{const C=M(w,m),k=r.get(C)??null,R=k!==null&&k.type==="static"?null:k,S=o.kind(w,m),y={binding:R,options:k!==null&&k.type==="static"?k:null,kind:S&~pt,value:o.value(w,m),style:o.cellStyle(w,m),table:R&&R.table?this._table(R.table):null,col:null,formula:S&J?o.formula(w,m):null,merged:o.mergeAt(w,m)};if(R&&R.type!=="param"&&R.type!=="chart"){if(y.col=R.formula?q(y.table,R.formula):y.table?.column(R.field)??null,!y.col&&!(R.type==="summary"&&R.agg==="countAll"))throw new T(A("No field {field} in {table}.",{field:R.field,table:R.table}));y.col&&y.table.ensure(y.col),R.collapse&&(y.style=this.book.styles.derive(y.style,{indent:1,hAlign:"left"})),R.format?y.style=this.book.styles.derive(y.style,{numFmt:R.format}):y.col&&y.col.format!=="General"&&(y.style===0||this.book.styles.get(y.style).numFmt==="General")&&(y.style=this.book.styles.derive(y.style,{numFmt:y.col.format}))}return y};for(let w=0;w<s.length;w++){const{tpl:m,ctx:C}=s[w];let k=-1;const R=[],S=u.get(m)===w;for(let y=0;y<e;y++){let x=l[y];if(h!==null){const _=h.get(y);_!==void 0&&r.get(M(_,m))?.type==="list"&&(x=_)}let b=R[x];b===void 0&&(b=p(x,m),R[x]=b);const d=b.binding;if(d===null){const _=b.options;if(_!==null){if(_.pin)continue;const v=_.autoExpand??"both";if((v==="none"||v==="horizontal")&&b.seen||(v==="none"||v==="vertical")&&!S)continue;b.seen=!0}if(b.formula){i&&this.formulas.push({or:y,oc:w,tr:x,tc:m,info:b.formula,ctx:n[a[y]],colCtx:C,style:b.style});continue}b.kind!==$&&t.setCell(y,w,b.kind,b.value),b.style!==0&&t.setStyle(y,w,b.style);continue}switch(b.style!==0&&t.setStyle(y,w,b.style),d.type){case"param":lt(t,y,w,this._param(d.param),c);break;case"list":{const _=d.expand==="horizontal"?this._recordAcross(C,b.table):this._recordFor(n[a[y]],f[y],b.table);_>=0&&it(t,y,w,b.col,_);break}case"group":{const _=this._groupContext(n[a[y]],C,d);if(_===null)break;if(_.index!==void 0&&!d.repeat){if(_.index===k&&!(d.repeatOnPage&&this.pageStartSet.has(y)))break;k=_.index}this._writeGroupValue(t,y,w,d,b,_);break}case"chart":this._writeChartCell(t,y,w,d,n[a[y]]);break;default:{if(f[y]===G)break;const _=this._summaryRows(n[a[y]],C,b.table,d,f[y]),v=b.col?Q(b.col,d.agg??"sum",_,0,_.length):d.agg==="countAll"?_.length:NaN;v===v&&t.setCell(y,w,B,v)}}}}}_writeChartCell(t,s,e,l,a){if(!l.source)return;const o=(this.tplRows??(this.tplRows=this._rowsByTemplate())).get(l.source.row),n=this.colOut.findIndex(u=>u.tpl===l.source.col);if(!o||n<0)return;const c=ot(o,a.first,a.last);if(c.length===0)return;const r=c[0][0],h=c[c.length-1][1];t.sparklines||(t.sparklines=[],t.sparklinesChanged=!0),this.sparkGroups||(this.sparkGroups=new Map);let i=this.sparkGroups.get(l);i||(i={type:l.chartType??"line",markers:!1,high:!1,low:!1,first:!1,last:!1,negative:l.chartType==="winloss",lineWeight:1,seriesColor:l.color??"#2f6fb3",negativeColor:"#c42b1c",markerColor:"#107c41",items:[]},this.sparkGroups.set(l,i),t.sparklines.push(i)),i.items.push({source:`${gt(t.name)}${H(n)}${r+1}:${H(n)}${h+1}`,cell:N(s,e)})}_rowsByTemplate(){const t=new Map;for(let s=0;s<this.rowCount;s++){const e=this.rowTpl[s];let l=t.get(e);l===void 0&&(l=[],t.set(e,l)),l.push(s)}return t}_writeSheetRules(t){const{sheet:s,colOut:e}=this,l=this.tplRows??(this.tplRows=this._rowsByTemplate()),a=new Map;e.forEach((o,n)=>{a.has(o.tpl)||a.set(o.tpl,[]),a.get(o.tpl).push(n)});const f=o=>{const n=[];for(const c of mt(o)){const r=[];for(let i=c.r0;i<=c.r1&&i<=this.extent.maxRow;i++)for(const u of l.get(i)??[])r.push(u);r.sort((i,u)=>i-u);const h=[];for(let i=c.c0;i<=c.c1&&i<=this.extent.maxCol;i++)for(const u of a.get(i)??[])h.push(u);h.sort((i,u)=>i-u);for(const[i,u]of at(r))for(const[p,w]of at(h))n.push(dt({r0:i,c0:p,r1:u,c1:w}))}return n.join(" ")};s.cf&&s.cf.length>0&&(t.cf=s.cf.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.cfChanged=!0),s.validations&&s.validations.length>0&&(t.validations=s.validations.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.validationsChanged=!0);for(const o of this.t.bindings.values()){if(o.type!=="static"||!o.pin)continue;const n=s.kind(o.row,o.col),c=o.pin==="column"?l.get(o.row)?.[0]??o.row:o.row,r=o.pin==="row"?a.get(o.col)?.[0]??o.col:o.col;(n&7)!==$&&t.setCell(c,r,n&7,s.value(o.row,o.col));const h=s.cellStyle(o.row,o.col);h&&t.setStyle(c,r,h)}}_applyAutoFit(t){const s=[...this.t.bindings.values()].filter(i=>i.autoFit);if(s.length===0)return;const e=this.t.measure??(i=>i.length*6.4),{colOut:l,rowTpl:a,rowCount:f,sheet:o}=this,{strings:n,styles:c}=this.book,r=(i,u)=>{const p=t.kind(i,u)&7;if(p===0)return"";if(p===E)return n.get(t.value(i,u));if(p===B){const w=c.get(t.style(i,u)).numFmt;return w&&w!=="General"?j(w).number(t.value(i,u)):String(t.value(i,u))}return"TRUE"},h=Math.min(f,1e5);for(const i of s)if(i.autoFit==="column")l.forEach((u,p)=>{if(u.tpl!==i.col)return;let w=o.cols.sizeOf(i.col);for(let m=0;m<h;m++)a[m]===i.row&&(w=Math.max(w,e(r(m,p))+8));w!==t.cols.sizeOf(p)&&t.cols.setSize(p,Math.ceil(w))});else{const u=l.findIndex(m=>m.tpl===i.col);if(u<0)continue;const p=Math.max(10,t.cols.sizeOf(u)-6),w=t.rows.defaultSize;for(let m=0;m<h;m++){if(a[m]!==i.row)continue;const C=Math.ceil(e(r(m,u))/p),k=Math.max(o.rows.sizeOf(i.row),C*w);k!==t.rows.sizeOf(m)&&t.rows.setSize(m,k)}}}_applyLayoutSetting(t){const{type:s,count:e,repeat:l=0}=this.t.layout;if(!(e>l))return;const a=[],f=t.maxRow,o=t.maxCol;for(let c=0;c<=f;c++)for(let r=0;r<=o;r++){const h=t.kind(c,r)&15,i=t.cellStyle(c,r);(h!==0||i!==0)&&a.push(c,r,h,t.value(c,r),i)}const n=e-l;t.columns=[],t.maxRow=-1,t.maxCol=-1;for(let c=0;c<a.length;c+=5){const[r,h,i,u,p]=[a[c],a[c+1],a[c+2],a[c+3],a[c+4]],w=(m,C)=>{i!==0&&t.setCell(m,C,i,u),p!==0&&t.setStyle(m,C,p)};if(s==="row"){const m=o+1;if(r<l){const C=Math.max(1,Math.ceil((f+1-l)/n));for(let k=0;k<C;k++)w(r,h+k*m)}else{const C=Math.floor((r-l)/n);w(l+(r-l)%n,h+C*m)}}else{const m=f+1;if(h<l){const C=Math.max(1,Math.ceil((o+1-l)/n));for(let k=0;k<C;k++)w(r+k*m,h)}else{const C=Math.floor((h-l)/n);w(r+C*m,l+(h-l)%n)}}}}_saveMap(t){const{rowTpl:s,rowRec:e,rowCtx:l,rowCount:a,colOut:f,contexts:o,collapses:n}=this,c=new Map;f.forEach((h,i)=>{c.has(h.tpl)||c.set(h.tpl,i)});const r=n.map(h=>({...h,col:c.get(h.binding.col)??0}));t.reportMap={template:this.t,rowTpl:s.subarray(0,a),rowRec:e.subarray(0,a),rowCtx:l.subarray(0,a),contexts:o,colTpl:f.map(h=>h.tpl),collapses:r,overlay:this.overlay,book:this.book,layout:this.t.layout??null},r.some(h=>h.collapsed)&&ct(t)}_groupContext(t,s,e){for(let l=t;l!==null;l=l.parent)if(l.node?.binding===e)return l;for(let l=s;l!==null;l=l.parent)if(l.node?.binding===e)return l;return null}_writeGroupValue(t,s,e,l,a,f){const o=f.rows.length>0?f.rows[0]:-1;if(o<0)return;const n=a.col.get(o);if(l.bins){const c=l.bins.find(r=>typeof n=="number"&&(r.min===void 0||n>=r.min)&&(r.max===void 0||n<r.max));t.setCell(s,e,E,this.book.strings.add(c?.name??"(other)"))}else if(typeof n=="number"&&l.by&&l.by!=="value")t.setCell(s,e,E,this.book.strings.add(Ot(n,l.by)));else if(typeof n=="number"&&l.size>0){const c=Math.floor(n/l.size)*l.size;t.setCell(s,e,E,this.book.strings.add(`${c} to ${c+l.size}`))}else it(t,s,e,a.col,o)}_recordAcross(t,s){for(let e=t;e!==null&&e.node!==null;e=e.parent)if(e.table===s)return e.rows.length>0?e.rows[0]:-1;return-1}_recordFor(t,s,e){if(s===G)return-1;if(s>=0&&(t.table===e||t.table===null))return s;for(let a=t;a!==null;a=a.parent)if(a.table===e&&a.rows.length>0)return s>=0&&a===t?s:a.rows[0];const l=this._rowsIn(t,e);return l.length>0?l[0]:-1}_summaryRows(t,s,e,l,a){let f=t.table===e&&a>=0?Int32Array.of(a):this._rowsIn(t.table===null?null:t,e);for(let o=s;o!==null&&o.node!==null;o=o.parent){const n=o.node.binding;if(o.table!==e)continue;const c=nt(e,n);let r=this.keyCache.get(c);r===void 0&&(r=tt(e,n),this.keyCache.set(c,r));const h=r[o.rows[0]],i=new Int32Array(f.length);let u=0;for(let p=0;p<f.length;p++){const w=r[f[p]];(w===h||w!==w&&h!==h)&&(i[u++]=f[p])}f=i.subarray(0,u)}return l.filters?.length&&(f=this._prepareRows(f,{...l,sort:null,sortBy:null},e)),f}_writeMerges(t){const{sheet:s,rowTpl:e,rowCtx:l,rowCount:a,colOut:f,groupMerges:o}=this,n=new Map;f.forEach((r,h)=>{n.has(r.tpl)||n.set(r.tpl,[]),n.get(r.tpl).push(h)});const c=new Set;for(const r of o){const{binding:h,r0:i,r1:u}=r,p=s.mergeAt(h.row,h.col),w=p?p.c0:h.col,m=p?p.c1:h.col;p&&c.add(p);const C=[];let k=i;if(h.repeatOnPage)for(let R=i+1;R<=u;R++)this.pageStartSet.has(R)&&(C.push([k,R-1]),k=R);C.push([k,u]);for(const R of n.get(w)??[]){const S=R+(m-w);for(const[y,x]of C)(x>y||S>R)&&t.addMerge({r0:y,c0:R,r1:x,c1:S})}}for(const r of s.merges){if(c.has(r)||this.t.bindings.has(M(r.r0,r.c0))){const i=this.t.bindings.get(M(r.r0,r.c0));if(i&&(i.type==="group"||i.type==="list")&&i.expand==="vertical")continue}if(c.has(r))continue;const h=r.r1-r.r0;for(let i=0;i<a;i++){if(e[i]!==r.r0||i+h>=a)continue;let u=!0;for(let p=1;p<=h;p++)(e[i+p]!==r.r0+p||l[i+p]!==l[i])&&(u=!1);if(u)for(const p of n.get(r.c0)??[]){const w=p+(r.c1-r.c0);w<f.length&&t.addMerge({r0:i,c0:p,r1:i+h,c1:w})}}}}_writePageSetup(t){const{t:s,rowTpl:e,rowCount:l}=this,a=_t(t),f=this.sheet.pageSetup;if(f)for(const n of["orientation","paperSize","paperWidth","paperHeight","scale","fitToPage","fitToWidth","fitToHeight","horizontalCentered","verticalCentered","header","footer","headings","gridLines","margins"])f[n]!==void 0&&(a[n]=f[n]);s.pageSetup&&Object.assign(a,s.pageSetup);const o=s.pagination;if(o?.order&&(a.pageOrder=o.order),a.rowBreaks=[...new Set(this.breaks)].filter(n=>n>0&&n<l).sort((n,c)=>n-c),a.colBreaks=[...new Set(this.colBreaks)].filter(n=>n>0&&n<this.colOut.length).sort((n,c)=>n-c),o?.titleCols){let n=-1,c=-1;this.colOut.forEach((r,h)=>{r.tpl>=o.titleCols.c0&&r.tpl<=o.titleCols.c1&&(n<0||h===c+1)&&(n<0&&(n=h),c=h)}),n>=0&&(a.titleCols={c0:n,c1:c})}if(s.titleRows){let n=-1,c=-1;for(let r=0;r<l;r++){const h=e[r];if(h>=s.titleRows.r0&&h<=s.titleRows.r1)n<0&&(n=r),c=r;else if(n>=0)break}n>=0&&(a.titleRows={r0:n,r1:c})}t.pageSetupChanged=!0}_writeFormulas(t){if(this.formulas.length===0)return;const{rowTpl:s,rowCount:e,colOut:l}=this,a=new Map;for(let r=0;r<e;r++){const h=s[r];let i=a.get(h);i===void 0&&(i=[],a.set(h,i)),i.push(r)}const f=new Map;l.forEach((r,h)=>{f.has(r.tpl)||f.set(r.tpl,[]),f.get(r.tpl).push(h)});const o=new Uint32Array(this.formulas.length),n=new Uint16Array(this.formulas.length);this.formulas.forEach((r,h)=>{const{or:i,oc:u,tr:p,tc:w,info:m,ctx:C,style:k}=r,R=m.f??yt(m.sf,p-Math.floor(m.base/P),w-m.base%P),S=this._reportFunctions(R,i,C),y=Mt(S,(x,b,d,_)=>{const v=a.get(b),z=f.get(_);if(!v||!z)return null;const W=b===p?[[i,i]]:ot(v,C.first,C.last);if(W.length===0)return"#REF!";let I,F;return _===w?(I=u,F=u):(I=z[0],F=z[z.length-1]),W.map(([D,K])=>{const X=`${d}${H(I)}${x}${D+1}`;return D===K&&I===F?X:`${X}:${d}${H(F)}${x}${K+1}`}).join(",")});if(y.length>St){t.setCell(i,u,Z,Ct.REF.index),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u;return}t.setCell(i,u,J|$,0),t.setFormula(i,u,{f:y,typed:!0}),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u}),this.book.engine?.cellsChanged(t,o,n,o.length),this.book.formulasEdited=!0;const c=this.book.engine;c&&this.formulas.forEach(r=>{if(this.t.bindings.get(M(r.tr,r.tc))?.preserveFormula!==!1)return;const i=c.read(t,r.or,r.oc);t.setFormula(r.or,r.oc,null),t.setCell(r.or,r.oc,$,0),lt(t,r.or,r.oc,i,this.book.strings)})}_reportFunctions(t,s,e){if(!/RPT_/i.test(t))return t;const l=n=>this._measureCell(f(n),s,e),a=n=>{const c=n.trim();for(const r of this.t.bindings.values())if(r.alias===c)return N(r.row,r.col);return c},f=a,o=n=>n==null?'""':String(typeof n=="number"?Number(n.toPrecision(15)):n);return t.replace(/RPT_RANK\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(1+r.values.filter(h=>h>r.current).length):'""'}).replace(/RPT_PROPORTION\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c),h=r?r.values.reduce((i,u)=>i+u,0):0;return r&&h!==0?o(r.current/h):'""'}).replace(/RPT_CUMULATIVE\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(r.values.slice(0,r.at+1).reduce((h,i)=>h+i,0)):'""'}).replace(/RPT_(MOM|YOY)\(\s*([^()]+?)\s*\)/gi,(n,c,r)=>{const h=l(r);if(!h)return'""';const i=c.toUpperCase()==="MOM"?1:{month:12,quarter:4,year:1,week:52}[h.by]??12,u=h.values[h.at-i];return u===void 0||u===0?'""':o((h.current-u)/u)}).replace(/RPT_VALUE\(\s*([^()]+?)\s*\)/gi,(n,c)=>a(c)).replace(/RPT_PARAM\(\s*"([^"]+)"\s*\)/gi,(n,c)=>{const r=this._param(c);return typeof r=="number"?String(r):`"${String(r??"").replace(/"/g,'""')}"`}).replace(/RPT_INDEX\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=Y(a(c).replace(/\$/g,"")),h=r?this.t.binding(r.r0,r.c0):null;for(let i=e;i!==null;i=i.parent)if(i.node?.binding===h)return String(i.ordinal??1);return"1"}).replace(/RPT_PAGES\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();if(!c)return String(r.length);const h=this._topContext(e);return String(r.filter(i=>i>=h.first&&i<=h.last).length||1)}).replace(/RPT_PAGE\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();let h=0;for(let p=0;p<r.length;p++)r[p]<=s&&(h=p);if(!c)return String(h+1);const i=this._topContext(e);let u=0;for(;u<h&&r[u]<i.first;)u++;return String(h-u+1)})}_topContext(t){let s=t;for(let e=t;e!=null&&e.node;e=e.parent)s=e;return s}_measureCell(t,s,e){const l=Y(t.replace(/\$/g,""));if(!l)return null;const a=this.outSheet,f=this.colOut.findIndex(p=>p.tpl===l.c0);if(f<0)return null;let o=e;for(;o&&!o.node&&o.parent;)o=o.parent;const n=o?.node?.binding?.type==="list"?o:o?.parent??o,c=n?.first??0,r=n?.last??this.rowCount-1,h=[];let i=-1,u=1/0;for(let p=c;p<=r;p++){if(this.rowTpl[p]!==l.r0||(a.kind(p,f)&ut)!==B)continue;const m=Math.abs(p-s);(p<=s||i<0)&&m<u&&(u=m,i=h.length),h.push(a.value(p,f))}return i<0||h.length===0?null:{values:h,at:i,current:h[i],by:o?.node?.binding?.by??null}}_pageStarts(){if(this.pageStarts)return this.pageStarts;const t=V(this.book,this.outSheet),s=[];for(let e=0;e<t.pageCount;e++)s.push(t.page(e).r0);return this.pageStarts=s,s}}function ot(g,t,s){const e=[];let l=0,a=g.length;if(t>=0)for(;l<a;){const f=l+a>>>1;g[f]<t?l=f+1:a=f}for(let f=l;f<g.length;f++){const o=g[f];if(t>=0&&o>s)break;const n=e[e.length-1];n&&n[1]===o-1?n[1]=o:e.push([o,o])}return e}function Mt(g,t){let s="",e=0;const l=g.length,a=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)(?::(\$?)([A-Za-z]{1,3})(\$?)(\d+))?/y;for(;e<l;){const f=g[e];if(f==='"'){let c=e+1;for(;c<l;)if(g[c]==='"')if(g[c+1]==='"')c+=2;else break;else c++;s+=g.slice(e,c+1),e=c+1;continue}if(f==="'"){const c=g.indexOf("'!",e+1);if(c>=0){const r=/^\$?[A-Za-z]{1,3}\$?\d+(:\$?[A-Za-z]{1,3}\$?\d+)?/.exec(g.slice(c+2)),h=c+2+(r?r[0].length:0);s+=g.slice(e,h),e=h;continue}}a.lastIndex=e;const o=e>0?g[e-1]:"",n=/[A-Za-z0-9_.!$]/.test(o)?null:a.exec(g);if(n){const c=g[e+n[0].length]??"";if(!/[A-Za-z0-9_.(!]/.test(c)){const r=(i,u,p,w)=>t(p,Number(w)-1,i,wt(u.toUpperCase())),h=r(n[1],n[2],n[3],n[4]);if(n[6]===void 0)s+=h??n[0];else{const i=r(n[5],n[6],n[7],n[8]);s+=h===null||i===null?n[0]:`${h.split(/[:,]/)[0]}:${i.split(/[:,]/).pop()}`}e+=n[0].length;continue}}s+=f,e++}return s}function Tt(g,t,s){const e=new Float64Array(g.length);for(let f=0;f<g.length;f++)e[f]=t[g[f]];const l=new Int32Array(g.length);for(let f=0;f<g.length;f++)l[f]=f;kt(l,g.length,e,s);const a=new Int32Array(g.length);for(let f=0;f<g.length;f++)a[f]=g[l[f]];g.set(a)}const At=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ot(g,t){const e=j("yyyy-mm").number(Math.floor(g)),l=Number(e.slice(0,4)),a=Number(e.slice(5,7));switch(t){case"year":return String(l);case"quarter":return`Q${Math.floor((a-1)/3)+1} ${l}`;case"month":return`${At[a-1]} ${l}`;default:return j("yyyy-mm-dd").number(Math.floor(g))}}function it(g,t,s,e,l){const a=e.kind(l);a!==$&&g.setCell(t,s,a,e.raw(l))}function lt(g,t,s,e,l){e==null||e===""||(typeof e=="number"?g.setCell(t,s,B,e):typeof e=="boolean"?g.setCell(t,s,ft,e?1:0):e instanceof bt?g.setCell(t,s,Z,e.index):g.setCell(t,s,E,l.add(Array.isArray(e)?e.join(", "):String(e))))}function at(g){const t=[];for(const s of g){const e=t[t.length-1];e&&(e[1]===s||e[1]===s-1)?e[1]=s:t.push([s,s])}return t}function ct(g){const t=g.reportMap;if(t){for(const s of t.collapses)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!1);for(const s of t.collapses)if(s.collapsed)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!0);g.revision++}}function jt(g,t,s,e=void 0,l=!1){const a=g.reportMap;if(!a)return!1;const f=a.collapses.find(n=>n.row===t&&(s===void 0||n.col===s));if(!f)return!1;const o=e===void 0?!f.collapsed:e==="collapsed"||e===!0;if(f.collapsed=o,l)for(const n of a.collapses)n.from>=f.from&&n.to<=f.to&&(n.collapsed=o);return ct(g),!0}function Et(g,t,s={}){return V(g,t,s).pageCount}export{Rt as BINDING_TYPES,T as ReportError,ht as ReportTemplate,ct as applyCollapses,Et as reportPages,jt as toggleCollapse};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CUSTOM_XML_CONTENT_TYPE as
|
|
2
|
-
<queries xmlns="${h}" version="1">${t}</queries>`}function
|
|
1
|
+
import{CUSTOM_XML_CONTENT_TYPE as T,CUSTOM_XML_REL as S,customXmlNames as b}from"../../celltypes/persist.js";import{escapeRegExp as d}from"../../core/regexp.js";import{TEXT_ENCODINGS as _}from"../../io/encoding.js";import{children as M,parseTree as N,unescapeOoxml as O}from"../../io/xml-scan.js";import{xmlText as R}from"../../io/xml-escape.js";import{cleanMoreStep as A}from"./steps-more.js";import{cleanTableStep as P}from"./steps-tables.js";import{STEP_OPS as I,COLUMN_TYPES as j,FILTER_OPS as X,MAX_DELIMITER as $}from"./steps.js";const h="urn:8sheets:getdata:1",i="customXml/",p="queries8c.xml",q="rId8cGetData",U=4*1024*1024,v=256,D=256,y=16384,L=1024,C=8192,Q=32767,k=new Set(["csv","json","xml","web","table","range","workbook"]),F=new Set(["auto","csv","json","xml","html"]),Y=new Set(Object.keys(_)),G=new Set([",",";"," ","|"]),o=(e,t=L)=>typeof e=="string"&&e.length<=t?e:null;function B(e){const t=o(e,C);if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href}function H(e){if(e===null||typeof e!="object"||!k.has(e.type))return null;const t={type:e.type},n=o(e.fileName);if(n&&(t.fileName=n),e.type==="web"){if(t.url=B(e.url),!t.url)return null;t.format=F.has(e.format)?e.format:"auto"}if(e.type==="table"&&(t.table=o(e.table),!t.table)||e.type==="range"&&(t.sheet=o(e.sheet),t.ref=o(e.ref),!t.sheet||!t.ref)||e.type==="workbook"&&(t.sheet=o(e.sheet),!t.sheet))return null;(G.has(e.delimiter)||typeof e.delimiter=="string"&&e.delimiter.length===1&&!/["\r\n]/.test(e.delimiter))&&(t.delimiter=e.delimiter),e.detectTypes===!1&&(t.detectTypes=!1),Number.isInteger(e.tableIndex)&&e.tableIndex>=0&&(t.tableIndex=e.tableIndex),Y.has(e.encoding)&&(t.encoding=e.encoding);const s=o(e.recordsPath);s&&(t.recordsPath=s);const l=o(e.recordPath);return l&&(t.recordPath=l),e.ndjson===!0&&(t.ndjson=!0),t}function J(e){if(e===null||typeof e!="object"||!I.includes(e.op))return null;const{op:t}=e;switch(t){case"promoteHeaders":return{op:t};case"chooseColumns":{if(!Array.isArray(e.names)||e.names.length>y)return null;const n=e.names.map(s=>o(s));return n.includes(null)?null:{op:t,names:n}}case"splitColumn":{const n=o(e.column),s=typeof e.delimiter=="string"&&e.delimiter.length>=1&&e.delimiter.length<=$?e.delimiter:null,l=Number.isInteger(e.parts)&&e.parts>=1&&e.parts<=100?e.parts:null;return n!==null&&s!==null&&l!==null?{op:t,column:n,delimiter:s,parts:l}:null}case"rename":{const n=o(e.from),s=o(e.to);return n!==null&&s?{op:t,from:n,to:s}:null}case"changeType":{const n=o(e.column);return n!==null&&Object.hasOwn(j,e.to)?{op:t,column:n,to:e.to}:null}case"filterRows":{const n=o(e.column);return n===null||!Object.hasOwn(X,e.test)?null:{op:t,column:n,test:e.test,value:o(e.value)??""}}case"removeDuplicates":{if(e.columns===null||e.columns===void 0)return{op:t,columns:null};if(!Array.isArray(e.columns)||e.columns.length>y)return null;const n=e.columns.map(s=>o(s));return n.includes(null)?null:{op:t,columns:n}}case"sort":{const n=o(e.column);return n!==null?{op:t,column:n,desc:e.desc===!0}:null}default:return A(e)??P(e)}}function g(e){if(e===null||typeof e!="object")return null;const t=o(e.id,64),n=o(e.name,255),s=H(e.source);if(!t||!n||!s||!Array.isArray(e.steps)||e.steps.length>D)return null;const l=e.steps.map(J);if(l.includes(null))return null;const r={id:t,name:n,source:s,steps:l},c=o(e.table);return c&&(r.table=c),e.connectionOnly===!0&&!c&&(r.connectionOnly=!0),Number.isInteger(e.refreshMinutes)&&e.refreshMinutes>=1&&e.refreshMinutes<=Q&&(r.refreshMinutes=e.refreshMinutes),r}function W(e){if(!e?.length)return null;const t=e.map(n=>{const s=g(n);return s?`<query>${R(JSON.stringify(s))}</query>`:""}).join("");return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
|
+
<queries xmlns="${h}" version="1">${t}</queries>`}function K(e){let t;try{t=N(new TextEncoder().encode(e))}catch{return{queries:[],rejected:1}}const n=[];let s=0;const l=new Set;for(const r of M(t,"query").slice(0,v)){let c=null;try{c=JSON.parse(O(r.t))}catch{}const u=g(c);u&&!l.has(u.id)?(l.add(u.id),n.push(u)):s++}return{queries:n,rejected:s}}function V(e){const t=W(e);return t===null?null:{path:`${i}${p}`,xml:t,override:{partName:`/${i}${p}`,contentType:T},relationship:{id:q,type:S,target:`/${i}${p}`}}}const le=e=>{const t=V(e.getDataQueries);return t?[t]:[]};async function x(e){const t=[];for(const n of b(e,U)){const s=await e.text(n);s.includes(h)&&t.push({name:n,text:s})}return t}async function re(e){const t=[];let n=0;for(const s of await x(e)){const l=K(s.text);t.push(...l.queries),n+=l.rejected}return{queries:t,rejected:n}}async function ue(e,t,n,s){let l=t,r=n;const c=u=>{l=l.replace(new RegExp(`<Override\\b[^>]*PartName="/${d(u)}"[^>]*/>`,"g"),"")};for(const{name:u}of await x(e)){s.add(u),c(u);const a=u.slice(i.length);r=r.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*${d(i+a)}"[^>]*/>`,"g"),"");const f=`${i}_rels/${a}.rels`;if(e.has(f)){s.add(f);for(const E of(await e.text(f)).matchAll(/Target="([^"]+)"/g)){const m=`${i}${E[1].split("/").pop()}`;e.has(m)&&(s.add(m),c(m))}}}return{types:l,rels:r}}export{Q as MAX_REFRESH_MINUTES,h as QUERIES_NS,B as cleanUrl,ue as dropQueryParts,le as getDataPackage,K as parseQueries,V as queriesPart,W as queriesXml,re as readQueries,x as readQueryParts,g as sanitizeQuery};
|
package/extras/getdata/rows.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ERRORS as
|
|
1
|
+
import{ERRORS as k,BOOL as d,EMPTY as y,ERR as f,KIND_MASK as w,NUM as R,STR as u}from"../../core/sheet.js";import{formatGeneral as x,getFormatter as v}from"../../core/numfmt.js";import{t as U}from"../../i18n/index.js";const g=4096,_=1<<21,C=16384,N=32767,F=255,L=49152;function O(r,t,s){const n=new r(U(t,s));return n.i18n={key:t,params:s},n}const M=r=>`Column${r+1}`;class z{constructor(t=[]){this.list=t,this.map=new Map(t.map((s,n)=>[s,n+1]))}id(t){if(!t||t==="General")return 0;let s=this.map.get(t);return s===void 0&&(this.list.push(t),s=this.list.length,this.map.set(t,s)),s}code(t){return t===0?"General":this.list[t-1]}}function A(r,t,s,n=[]){const i=r*t;return{rows:r,cols:t,columns:s,strings:n,kinds:new Uint8Array(i),values:new Float64Array(i),styles:new Uint16Array(i)}}const X=r=>Math.max(1,Math.min(g,Math.floor(_/Math.max(1,r))));function S(r,t){if(t===r.rows)return r;const s=t*r.cols;return{...r,rows:t,kinds:r.kinds.slice(0,s),values:r.values.slice(0,s),styles:r.styles.slice(0,s)}}function B(r,t,s){const n=r.kinds[t]&w,i=r.values[t];switch(n){case y:return"";case u:return r.strings[i];case d:return i?"TRUE":"FALSE";case f:return k[i]??"#N/A";default:{const e=r.styles[t];if(e===0||!s)return x(i);try{return v(s.code(e)).number(i).replace(/\u0001.?\u0001/g," ")}catch{return x(i)}}}}function G(r){const t=new Set;return r.map((s,n)=>{const i=String(s??"").replace(/\s+/g," ").trim().slice(0,F-8)||M(n);let e=i;for(let o=1;t.has(e.toLowerCase());o++)e=`${i}_${o}`;return t.add(e.toLowerCase()),e})}class ${constructor(){this.names=[],this.columns=[],this.nextRow=-1,this.cur=null,this.capacity=0,this.used=0,this.incoming=[],this.remap=new Int32Array(0)}_ensureColumns(t){const s=Math.max(t,this.names.length);if(this.columns.length>=s&&this.columnsFrom===this.names)return;const n=Math.max(s,this.columns.length),i=new Array(n);for(let e=0;e<n;e++)i[e]=this.names[e]??this.columns[e]??M(e);this.columns=i,this.columnsFrom=this.names}_capacityFor(t){return Math.max(16,Math.min(g,Math.floor(_/t)))}_open(t){this._ensureColumns(t);const s=Math.max(this.columns.length,1);this.capacity=this._capacityFor(s),this.cur=A(this.capacity,s,this.columns),this.used=0,this.remap.fill(-1)}_widen(t){this._ensureColumns(t);const s=this.cur,n=Math.max(this.columns.length,1),i=Math.max(this._capacityFor(n),this.used+1),e=A(i,n,this.columns,s.strings);for(let o=0;o<this.used;o++){const h=o*s.cols,l=o*n;e.kinds.set(s.kinds.subarray(h,h+s.cols),l),e.values.set(s.values.subarray(h,h+s.cols),l),e.styles.set(s.styles.subarray(h,h+s.cols),l)}this.cur=e,this.capacity=i}_take(t){const s=S(this.cur,t);return s.columns=this.columns,this.nextRow+=t,this.cur=null,this.used=0,s}*push(t,s,n){n&&(this.names=n),this.incoming=s,this.remap=this.remap.length>=s.length?this.remap.fill(-1):new Int32Array(s.length).fill(-1),this.cur!==null&&(this.names.length>this.cur.cols?this._widen(this.names.length):this._ensureColumns(this.cur.cols));for(let i=0;i<t.count;i++){const e=t.cols[i];if(e>=C)continue;const o=t.rows[i];this.nextRow<0&&(this.nextRow=o),this.cur===null&&this._open(e+1);let h=o-this.nextRow;for(;h>=this.capacity;)yield this._take(this.capacity),this._open(e+1),h=o-this.nextRow;e>=this.cur.cols&&this._widen(e+1);const l=this.cur,c=h*l.cols+e,p=t.kinds[i]&w;if(l.kinds[c]=p,l.styles[c]=t.styles[i],p===u){const m=t.values[i];let a=this.remap[m];a===-1&&(a=l.strings.length,l.strings.push(s[m]),this.remap[m]=a),l.values[c]=a}else l.values[c]=t.values[i];h>=this.used&&(this.used=h+1)}}*end(){this.cur!==null&&this.used>0&&(yield this._take(this.used)),this.cur=null}}class K{constructor(t=65536){this.capacity=t,this.rows=new Uint32Array(t),this.cols=new Uint16Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.styles=new Uint16Array(t),this.count=0,this.strings=[],this.index=new Map}get full(){return this.count>=L}_grow(){const t=this.capacity*2,s=(n,i)=>{const e=new n(t);return e.set(i),e};this.rows=s(Uint32Array,this.rows),this.cols=s(Uint16Array,this.cols),this.kinds=s(Uint8Array,this.kinds),this.values=s(Float64Array,this.values),this.styles=s(Uint16Array,this.styles),this.capacity=t}add(t,s,n,i,e=0){this.count===this.capacity&&this._grow();const o=this.count++;this.rows[o]=t,this.cols[o]=s,this.kinds[o]=n,this.values[o]=i,this.styles[o]=e}addText(t,s,n){let i=this.index.get(n);i===void 0&&(i=this.strings.length,this.strings.push(n),this.index.set(n,i)),this.add(t,s,u,i)}reset(){this.count=0,this.strings=[],this.index=new Map}}export{d as BOOL,F as COLUMN_NAME_LIMIT,K as CellCollector,y as EMPTY,f as ERR,z as Formats,_ as MATRIX_CELLS,g as MATRIX_ROWS,C as MAX_COLUMNS,R as NUM,$ as RowAssembler,u as STR,N as TEXT_LIMIT,B as cellText,G as cleanColumnNames,M as columnName,A as newBatch,X as rowsFor,S as trimBatch,O as wordedError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseInput as m}from"../../core/input.js";import{partsToSerial as i}from"../../core/numfmt.js";import{NUM as d,wordedError as l}from"./rows.js";const N=2;class c extends Error{}const v=(n,r,t,e)=>{const{cols:s}=n,o=r*s,a=e*t.cols;for(let u=0;u<s;u++)t.kinds[a+u]=n.kinds[o+u],t.values[a+u]=n.values[o+u],t.styles[a+u]=n.styles[o+u]};class x{constructor(r){this.names=r,this.columns=null,this.at=[],this.seen=new Array(r.length).fill(!1)}resolve(r){if(r===this.columns)return this.at;this.columns=r;const t=new Map;return r.forEach((e,s)=>{t.has(e)||t.set(e,s)}),this.at=this.names.map((e,s)=>{const o=t.get(e)??-1;return o>=0&&(this.seen[s]=!0),o}),this.at}check(r){if(!r)return;const t=this.names.filter((e,s)=>!this.seen[s]);if(t.length)throw l(c,"Column not found: {names}. The source may have changed; edit the query.",{names:t.join(", ")})}}const f=/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/,h=/^(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/;function g(n){const r=n.trim();let t=h.exec(r);if(t)return{value:i(Number(t[1]),Number(t[2]),Number(t[3]))+(Number(t[4])*3600+Number(t[5])*60+Number(t[6]??0))/86400,format:"yyyy-mm-dd hh:mm"};const e=m(r);if(e.kind===d&&e.format&&/[ymd]/i.test(e.format))return{value:e.value,format:e.format};if(t=f.exec(r),t){const s=Number(t[2]),o=Number(t[1]);if(s>=1&&s<=12&&o>=1&&o<=31){const a=i(Number(t[3]),s,o);return t[4]!==void 0?{value:a+(Number(t[4])*3600+Number(t[5])*60+Number(t[6]??0))/86400,format:"yyyy-mm-dd hh:mm"}:{value:a,format:"yyyy-mm-dd"}}}return null}function E(n){const r=n.trim(),t=m(r);if(t.kind===d)return{value:t.value,format:t.format??null};const e=r.replace(/[\s ]/g,"");return/^[+-]?\d+,\d+$/.test(e)?{value:Number(e.replace(",",".")),format:null}:/^[+-]?\d+$/.test(e)?{value:Number(e),format:null}:null}class T{constructor(){this.keys=[],this.at=new Map}of(r){return r.map(t=>{let e=this.at.get(t);return e===void 0&&(e=this.keys.push(t)-1,this.at.set(t,e)),e})}}export{x as ColumnLookup,T as Places,c as StepError,N as VALUE_ERROR,v as copyRowsOf,g as textToDate,E as textToNumber};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CHUNK_BITS as N,CHUNK_MASK as T,CHUNK_SIZE as p,Sheet as S}from"../../core/sheet.js";import{colName as y}from"../../core/address.js";import{StringTable as R}from"../../core/strings.js";import{Engine as k}from"../../calc/engine.js";import{formulaEntryLimit as F,toFileFormula as b}from"../../calc/parser.js";import{Arr as I,ERR as g,Lambda as U,Ref as M,RefList as _,XlError as A}from"../../calc/values.js";import{BOOL as x,ERR as D,NUM as H,STR as v,TEXT_LIMIT as K,wordedError as h}from"./rows.js";import{StepError as d}from"./shared-steps.js";import{Rearrange as X}from"./steps-more.js";import{setFormulaStage as B}from"./steps.js";const L=()=>{const i=new k({sheets:[],strings:new R,dateOffset:0});return i.legacy=!0,i},P=/\b(?:ROW|COLUMN|OFFSET|INDIRECT|CELL|SHEET|SHEETS|FORMULATEXT|ISFORMULA|GETPIVOTDATA)\s*\(/i,O=(i,e)=>!i.invalid&&!i.external&&i.names.length===0&&i.tables.length===0&&i.refs.every(t=>!t.sheet&&t.r0===0&&t.r1===0&&!t.rAbs0&&!t.rAbs1&&t.cAbs0&&t.cAbs1&&t.c1<e),V=/\[@?\[?\s*([^[\]]+?)\s*\]?\]/g,W=(i,e)=>i.split(/("(?:[^"]|"")*"?)/).map((t,a)=>a%2?t:e(t)).join("");function ne(i,e){const t=i.trim().replace(/^=/,""),a=[],c=(f,E)=>{const w=e.find(C=>C.toLowerCase()===f.toLowerCase());if(w===void 0)throw h(d,"There is no column {name}.",{name:f});let u=a.indexOf(w);return u<0&&(u=a.push(w)-1),E(u)},s=f=>b(W(t,E=>E.replace(V,(w,u)=>c(u,f))));if(P.test(t.replace(/"(?:[^"]|"")*"?/g,'""')))throw h(d,"A custom column works out each row by itself, so it can't use ROW, OFFSET, INDIRECT and the like.");const l=s(f=>`$${y(f)}1`),o=F(l);if(o)throw h(d,o);const m=L(),n=m.template(s(()=>"1"),0,e.length),r=m.template(l,0,e.length);if(t===""||r.invalid)throw h(d,"The formula is not valid.");if(n.refs.length>0||!O(r,a.length))throw h(d,"The formula can only use the query's columns, as [Name].");return{formula:l,columns:a}}class ${constructor(e,t,a){this.count=t,this.formats=a,this.engine=L(),this.sheet=new S("__row"),this.sheet.maxCol=t-1;const c=this.engine.template(e,0,t);this.fn=O(c,t)?c.fn:()=>g.NAME,this.batch=null}start(e,t){if(this.batch===e)return;this.batch=e;const{sheet:a,engine:c}=this,s=new R;c.book.strings=s,c.book.dateOffset=this.formats.dateOffset??0,a.maxRow=e.rows-1;for(let l=0;l<this.count;l++){const o=t[l],m=[];for(let n=0;n<e.rows;n+=p)m.push({kinds:new Uint8Array(p),values:new Float64Array(p),styles:null});for(let n=0;n<e.rows&&o>=0&&o<e.cols;n++){const r=n*e.cols+o,f=m[n>>N];f.kinds[n&T]=e.kinds[r],f.values[n&T]=e.kinds[r]===v?s.add(e.strings[e.values[r]]):e.values[r]}a.columns[l]=m}}value(e){const{engine:t,sheet:a,count:c}=this;let s;try{s=this.fn(e,c,a),(s instanceof M||s instanceof _)&&(s=t.refAuto(s,e,c))}catch(l){return l instanceof A?l:g.VALUE}return s instanceof I&&(s=s.data[0]),s instanceof U?g.CALC:typeof s=="number"&&!Number.isFinite(s)?g.NUM:s??null}}function j({formula:i,columns:e,to:t},a){const c=new $(i,e.length,a);return new X(e,s=>({names:[...s,t],from:[...s.map((l,o)=>o),-1]}),(s,l,o,m,n)=>{c.start(s,m);const r=c.value(l);r===null||r===""||(typeof r=="number"?(o.kinds[n]=H,o.values[n]=r):typeof r=="boolean"?(o.kinds[n]=x,o.values[n]=Number(r)):r instanceof A?(o.kinds[n]=D,o.values[n]=r.index):(o.kinds[n]=v,o.values[n]=o.strings.push(String(r).slice(0,K))-1))})}B(j);export{ne as compileFormula};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{formatNumber as Z,partsToSerial as b,serialToParts as ut}from"../../core/numfmt.js";import{BOOL as at,cellText as L,cleanColumnNames as j,EMPTY as f,ERR as E,newBatch as T,NUM as g,rowsFor as tt,STR as m,TEXT_LIMIT as G,trimBatch as q,wordedError as D}from"./rows.js";import{ColumnLookup as N,copyRowsOf as ct,Places as et,StepError as U,textToNumber as st,VALUE_ERROR as nt}from"./shared-steps.js";import{MAX_COLS as _,MAX_ROWS as P}from"../../core/address.js";const ht={trim:"Trim",clean:"Clean",lower:"lowercase",upper:"UPPERCASE",proper:"Capitalize Each Word",length:"Length",first:"First Characters…",last:"Last Characters…",before:"Text Before Delimiter…",after:"Text After Delimiter…",prefix:"Add Prefix…",suffix:"Add Suffix…"},dt={round:"Round…",roundUp:"Round Up",roundDown:"Round Down",abs:"Absolute Value",add:"Add…",subtract:"Subtract…",multiply:"Multiply…",divide:"Divide…",percent:"Percentage…"},ft={dateOnly:"Date Only",timeOnly:"Time Only",year:"Year",quarter:"Quarter",month:"Month",monthName:"Month Name",week:"Week of Year",day:"Day",weekday:"Day of Week",weekdayName:"Name of Day",hour:"Hour",minute:"Minute",second:"Second",startOfYear:"Start of Year",startOfMonth:"Start of Month",endOfMonth:"End of Month",age:"Days to Today"},mt={first:"count",last:"count",before:"text",after:"text",prefix:"text",suffix:"text",round:"integer",add:"number",subtract:"number",multiply:"number",divide:"number",percent:"number"},ot={sum:"Sum",average:"Average",min:"Min",max:"Max",count:"Count Rows",countValues:"Count Values",distinct:"Count Distinct Values",first:"First Value",join:"All Values, Joined"},pt=["keepFirst","keepLast","removeFirst","removeLast","alternate","removeBlank","removeErrors","keepErrors"],kt=e=>e.replace(/^[\s ]+|[\s ]+$/g,""),yt=e=>e.toLowerCase().replace(/(^|[^\p{L}\p{N}'’])(\p{L})/gu,(t,s,n)=>s+n.toUpperCase()),J=e=>Array.from(e),gt={trim:kt,clean:e=>e.replace(/[\u0000-\u001f\u007f]/g,""),lower:e=>e.toLowerCase(),upper:e=>e.toUpperCase(),proper:yt,length:e=>J(e).length,first:(e,t)=>J(e).slice(0,t).join(""),last:(e,t)=>t===0?"":J(e).slice(-t).join(""),before:(e,t)=>e.includes(t)?e.slice(0,e.indexOf(t)):e,after:(e,t)=>e.includes(t)?e.slice(e.indexOf(t)+t.length):"",prefix:(e,t)=>t+e,suffix:(e,t)=>e+t},vt=(e,t)=>{const s=10**t,n=Number((Math.abs(e)*s).toPrecision(15));return Math.sign(e)*Math.round(n)/s},wt={round:vt,roundUp:e=>Math.ceil(e),roundDown:e=>Math.floor(e),abs:Math.abs,add:(e,t)=>e+t,subtract:(e,t)=>e-t,multiply:(e,t)=>e*t,divide:(e,t)=>e/t,percent:(e,t)=>e*t/100},X="yyyy-mm-dd",F=(e,t,s)=>b(e,t,s),xt={dateOnly:e=>[Math.floor(e),X],timeOnly:e=>[e-Math.floor(e),"hh:mm:ss"],year:(e,t)=>[t.year],quarter:(e,t)=>[Math.ceil(t.month/3)],month:(e,t)=>[t.month],monthName:e=>[Z("mmmm",e)],week:(e,t)=>{const s=F(t.year,1,1);return[Math.floor((Math.floor(e)-s+(s-1)%7)/7)+1]},day:(e,t)=>[t.day],weekday:e=>[(Math.floor(e)+6)%7+1],weekdayName:e=>[Z("dddd",e)],hour:(e,t)=>[t.hour],minute:(e,t)=>[t.minute],second:(e,t)=>[t.second],startOfYear:(e,t)=>[F(t.year,1,1),X],startOfMonth:(e,t)=>[F(t.year,t.month,1),X],endOfMonth:(e,t)=>[(t.month===12?F(t.year+1,1,1):F(t.year,t.month+1,1))-1,X],age:(e,t,s)=>[s-Math.floor(e)]},Mt=new Set(["dateOnly","startOfYear","startOfMonth","endOfMonth"]);class Y{constructor(t,s,n){this.lookup=new N([t]),this.formats=s,this.change=n,this.saw=!1}*push(t){this.saw=!0;const s=this.lookup.resolve(t.columns)[0];if(s<0||s>=t.cols){yield t;return}const n={...t,kinds:t.kinds.slice(),values:t.values.slice(),styles:t.styles.slice()},{formats:o}=this;let i=null;for(let r=0,l=s;r<t.rows;r++,l+=t.cols){const u=this.change(t,l);u!==void 0&&(u===null?(n.kinds[l]=f,n.styles[l]=0):typeof u.value=="string"?(i===null&&(i=t.strings.slice(),n.strings=i),n.kinds[l]=m,n.values[l]=i.push(u.value.slice(0,G))-1,n.styles[l]=0):u.error||!Number.isFinite(u.value)?(n.kinds[l]=E,n.values[l]=nt,n.styles[l]=0):(n.kinds[l]=g,n.values[l]=u.value,n.styles[l]=u.keep?t.styles[l]:o.id(u.format??null)))}yield n}*end(){this.lookup.check(this.saw)}}const lt={error:!0};function Et({column:e,find:t,replace:s,whole:n},o){const i=st(t)?.value??null,r=st(s),l=s===""?null:r?{value:r.value,keep:!0}:{value:s};return new Y(e,o,(u,h)=>{const c=u.kinds[h];if(c===f)return t===""?l??void 0:void 0;if(c===m){const a=u.strings[u.values[h]];return n||t===""?a===t?s===""?null:{value:s}:void 0:a.includes(t)?{value:a.split(t).join(s)}:void 0}if(c===g)return i!==null&&u.values[h]===i?l:void 0})}function St({column:e,fn:t,value:s},n){const o=gt[t];return new Y(e,n,(i,r)=>{const l=i.kinds[r];if(l===f||l===E)return;const u=o(L(i,r,n),s);return u===""?null:{value:u}})}function Ot({column:e,fn:t,value:s},n){const o=wt[t];return new Y(e,n,(i,r)=>{const l=i.kinds[r];if(!(l===f||l===E))return l===g?{value:o(i.values[r],s),keep:!0}:lt})}function At({column:e,fn:t},s){const n=xt[t],o=new Date,i=b(o.getFullYear(),o.getMonth()+1,o.getDate());return new Y(e,s,(r,l)=>{const u=r.kinds[l];if(u===f||u===E)return;const h=s.dateOffset??0,c=r.values[l]+h;if(u!==g||c<0||c>=2958466)return lt;const[a,d]=n(c,ut(c),i);return{value:Mt.has(t)?a-h:a,format:d}})}class Tt{constructor({column:t,up:s}){this.lookup=new N([t]),this.up=s===!0,this.last=null,this.held=[],this.total=0,this.saw=!1}*push(t){if(this.saw=!0,this.up){if(this.lookup.resolve(t.columns),this.total+=t.rows,this.total>P)throw D(U,"Filling up needs all its rows in memory, and this query passed {rows} rows there. Filter first.",{rows:P.toLocaleString("en-US")});this.held.push(t);return}yield this._fill(t)}_fill(t){const s=this.lookup.resolve(t.columns)[0];if(s<0||s>=t.cols)return t;const n={...t,kinds:t.kinds.slice(),values:t.values.slice(),styles:t.styles.slice(),strings:t.strings},o=this.up?t.rows-1:0,i=this.up?-1:1;let r=null,l=-1;for(let u=0,h=o;u<t.rows;u++,h+=i){const c=h*t.cols+s,a=t.kinds[c];if(a!==f&&!(a===m&&t.strings[t.values[c]]==="")){this.last={kind:a,value:a===m?t.strings[t.values[c]]:t.values[c],style:t.styles[c]},l=a===m?t.values[c]:-1;continue}this.last!==null&&(this.last.kind===m&&l<0&&(r??=t.strings.slice(),n.strings=r,l=r.push(this.last.value)-1),n.kinds[c]=this.last.kind,n.values[c]=this.last.kind===m?l:this.last.value,n.styles[c]=this.last.style)}return n}*end(){this.lookup.check(this.saw);const t=this.held.reverse().map(s=>this._fill(s)).reverse();this.held=[],yield*t}}class ${constructor(t,s,n=null){this.lookup=new N(t),this.plan=s,this.fill=n,this.lastIn=null,this.made=null,this.places=new et,this.names=[],this.saw=!1}_make(t,s){const{names:n,from:o}=this.plan(t,s),i=new Set,r=o.map(c=>c<0?"new":i.has(c)?`copy${c}`:(i.add(c),c)),l=this.places.of(r),u=this.places.keys.length;if(u>_)throw D(U,"This step would make more than {count} columns.",{count:_.toLocaleString("en-US")});const h=new Array(u).fill(-1);l.forEach((c,a)=>{h[c]=o[a],this.names[c]=n[a]}),this.made={names:j(this.names),from:h,added:this.places.at.get("new")??-1}}*push(t){this.saw=!0;const s=this.lookup.resolve(t.columns);t.columns!==this.lastIn&&(this.lastIn=t.columns,this._make(t.columns,s));const{names:n,from:o,added:i}=this.made,r=T(t.rows,n.length,n,this.fill?t.strings.slice():t.strings);for(let l=0;l<t.rows;l++){const u=l*t.cols,h=l*r.cols;for(let c=0;c<o.length;c++){const a=o[c];a<0||a>=t.cols||(r.kinds[h+c]=t.kinds[u+a],r.values[h+c]=t.values[u+a],r.styles[h+c]=t.styles[u+a])}this.fill?.(t,l,r,s,l*r.cols+i)}yield r}*end(){this.lookup.check(this.saw)}}const S=e=>e.map((t,s)=>s);function Nt({names:e}){return new $(e,(t,s)=>{const n=S(t).filter(o=>!s.includes(o));return{names:n.map(o=>t[o]),from:n}})}function _t({column:e,to:t}){return new $([e],(s,n)=>({names:[...s,t],from:[...S(s),n[0]]}))}function Rt({columns:e,delimiter:t,to:s},n){return new $(e,(o,i)=>{const r=i.filter(d=>d>=0),l=r.length?Math.min(...r):o.length,u=S(o).filter(d=>d===l||!r.includes(d)),h=l<o.length?u.indexOf(l):u.length,c=u.map(d=>o[d]);c[h]=s;const a=u.slice();return a[h]=-1,{names:c,from:a}},(o,i,r,l,u)=>{const h=i*o.cols,c=l.map(a=>a<0||a>=o.cols||o.kinds[h+a]===f?"":L(o,h+a,n)).join(t);c!==""&&(r.kinds[u]=m,r.values[u]=r.strings.push(c.slice(0,G))-1)})}function Ct({to:e,start:t,step:s}){let n=t;return new $([],o=>({names:[...o,e],from:[...S(o),-1]}),(o,i,r,l,u)=>{r.kinds[u]=g,r.values[u]=n,n+=s})}class Lt{constructor({what:t,count:s=0,skip:n=0}){this.what=t,this.count=s,this.skip=n,this.at=0,this.held=[],this.heldRows=0}_pick(t,s){const n=T(t.rows,t.cols,t.columns,t.strings);let o=0;for(let i=0;i<t.rows;i++)s(i)&&ct(t,i,n,o++);return q(n,o)}*push(t){const{what:s,count:n}=this,o=this.at;this.at+=t.rows;const i=l=>{for(let u=l*t.cols,h=0;h<t.cols;h++,u++)if(t.kinds[u]!==f&&!(t.kinds[u]===m&&t.strings[t.values[u]]===""))return!1;return!0},r=l=>{for(let u=l*t.cols,h=0;h<t.cols;h++,u++)if(t.kinds[u]===E)return!0;return!1};switch(s){case"keepFirst":yield this._pick(t,l=>o+l<n);break;case"removeFirst":yield this._pick(t,l=>o+l>=n);break;case"alternate":yield this._pick(t,l=>(o+l)%(n+this.skip)>=n);break;case"removeBlank":yield this._pick(t,l=>!i(l));break;case"removeErrors":yield this._pick(t,l=>!r(l));break;case"keepErrors":yield this._pick(t,r);break;default:for(this.held.push(t),this.heldRows+=t.rows;this.held.length>1&&this.heldRows-this.held[0].rows>=n;){const l=this.held.shift();this.heldRows-=l.rows,yield s==="removeLast"?l:q(l,0)}}}*end(){let t=this.heldRows;for(const s of this.held){const n=t-s.rows,o=Math.max(0,Math.min(s.rows,this.count-n));yield this._pick(s,this.what==="removeLast"?i=>i<s.rows-o:i=>i>=s.rows-o),t=n}this.held=[]}}const K=(e,t)=>e.kinds[t]===m?`s${e.strings[e.values[t]]}`:e.kinds[t]===f?"":`${e.kinds[t]}:${e.values[t]}`,B=(e,t)=>({kind:e.kinds[t],value:e.kinds[t]===m?e.strings[e.values[t]]:e.values[t],style:e.styles[t]}),R={kind:f,value:0,style:0};class it{constructor(t){this.fn=t,this.n=0,this.sum=0,this.best=null,this.style=0,this.error=null,this.set=t==="distinct"?new Set:null,this.text=null}add(t,s,n){const{fn:o}=this;if(o==="count"){this.n++;return}const i=s<0?f:t.kinds[s];if(i!==f)if(o==="distinct")this.set.add(K(t,s));else if(o==="join")this.text===null?this.text=L(t,s,n):this.text.length<G&&(this.text+=`, ${L(t,s,n)}`);else if(o==="countValues")this.n++;else if(o==="first")this.best??=B(t,s);else if(i===E)this.error??=B(t,s);else if(o==="min"||o==="max"){const r=B(t,s),l=(u,h)=>u.kind!==h.kind?u.kind<h.kind:u.value<h.value;(this.best===null||(o==="min"?l(r,this.best):l(this.best,r)))&&(this.best=r)}else i===g?(this.n++,this.sum+=t.values[s],this.style||=t.styles[s]):i!==at&&(this.error??={kind:E,value:nt,style:0})}result(){if(this.error)return this.error;switch(this.fn){case"count":case"countValues":return{kind:g,value:this.n,style:0};case"distinct":return{kind:g,value:this.set.size,style:0};case"join":return this.text!==null?{kind:m,value:this.text.slice(0,G),style:0}:R;case"sum":return this.n?{kind:g,value:this.sum,style:this.style}:R;case"average":return this.n?{kind:g,value:this.sum/this.n,style:this.style}:R;default:return this.best??R}}}function*rt(e,t,s){t.length===0&&(yield T(0,e.length,e));const n=tt(e.length);for(let o=0;o<t.length;o+=n){const i=Math.min(n,t.length-o),r=T(i,e.length,e),l=new Map;for(let u=0;u<i;u++){const h=u*e.length;s(t[o+u],(c,a)=>{if(!a||a.kind===f)return;const d=h+c;if(r.kinds[d]=a.kind,r.styles[d]=a.style,a.kind===m){let k=l.get(a.value);k===void 0&&(k=r.strings.push(a.value)-1,l.set(a.value,k)),r.values[d]=k}else r.values[d]=a.value})}yield r}}const z=P;class Dt{constructor({by:t,values:s},n){this.by=t,this.values=s,this.formats=n,this.lookup=new N([...t,...s.filter(o=>o.fn!=="count").map(o=>o.column)]),this.groups=new Map,this.saw=!1}*push(t){this.saw=!0;const s=this.lookup.resolve(t.columns),n=this.by.length,o=l=>l>=0&&l<t.cols?l:-1;let i=n;const r=this.values.map(l=>l.fn==="count"?-1:o(s[i++]));for(let l=0;l<t.rows;l++){const u=l*t.cols;let h="";for(let a=0;a<n;a++)h+=`${o(s[a])<0?"":K(t,u+s[a])}\0`;let c=this.groups.get(h);if(c===void 0){if(this.groups.size>=z)throw D(U,"Group By found more than {rows} groups.",{rows:z.toLocaleString("en-US")});c={cells:s.slice(0,n).map(a=>o(a)<0?R:B(t,u+a)),totals:this.values.map(a=>new it(a.fn))},this.groups.set(h,c)}for(let a=0;a<c.totals.length;a++)c.totals[a].add(t,r[a]<0?-1:u+r[a],this.formats)}}*end(){this.lookup.check(this.saw);const t=j([...this.by,...this.values.map(n=>n.to)]),s=[...this.groups.values()];this.groups.clear(),yield*rt(t,s,(n,o)=>{n.cells.forEach((i,r)=>o(r,i)),n.totals.forEach((i,r)=>o(n.cells.length+r,i.result()))})}}class Ut{constructor({column:t,values:s,fn:n},o){this.lookup=new N([t,s]),this.fn=n,this.formats=o,this.names=new Map,this.rows=new Map,this.rest=[],this.saw=!1}*push(t){this.saw=!0;const[s,n]=this.lookup.resolve(t.columns),o=S(t.columns).filter(i=>i!==s&&i!==n);o.length>this.rest.length&&(this.rest=o.map(i=>t.columns[i]));for(let i=0;i<t.rows;i++){const r=i*t.cols;let l="";for(const d of o)l+=`${d<t.cols?K(t,r+d):""}\0`;l=l.replace(/\u0000+$/,"");let u=this.rows.get(l);if(u===void 0){if(this.rows.size>=z)throw D(U,"Group By found more than {rows} groups.",{rows:z.toLocaleString("en-US")});u={cells:o.map(d=>d<t.cols?B(t,r+d):R),totals:new Map},this.rows.set(l,u)}const h=s>=0&&s<t.cols&&t.kinds[r+s]!==f?L(t,r+s,this.formats):"";let c=this.names.get(h);if(c===void 0){if(c=this.names.size,c+this.rest.length>=_)throw D(U,"This step would make more than {count} columns.",{count:_.toLocaleString("en-US")});this.names.set(h,c)}let a=u.totals.get(c);a===void 0&&u.totals.set(c,a=new it(this.fn)),a.add(t,n>=0&&n<t.cols?r+n:-1,this.formats)}}*end(){this.lookup.check(this.saw);const t=j([...this.rest,...this.names.keys()]),s=[...this.rows.values()];this.rows.clear();const n=this.rest.length;yield*rt(t,s,(o,i)=>{o.cells.forEach((r,l)=>i(l,r));for(const[r,l]of o.totals)i(n+r,l.result())})}}class Ft{constructor({columns:t,others:s,attribute:n,value:o}){this.names=t,this.others=s===!0,this.attribute=n,this.value=o,this.lookup=new N(t),this.places=new et,this.columnNames=[],this.saw=!1,this.lastIn=null,this.made=null}*push(t){this.saw=!0;const s=this.lookup.resolve(t.columns);if(t.columns!==this.lastIn){this.lastIn=t.columns;const x=new Set(s),M=S(t.columns).filter(y=>x.has(y)!==this.others),v=S(t.columns).filter(y=>!M.includes(y)),O=this.places.of([...v,"attribute","value"]);[...v.map(y=>t.columns[y]),this.attribute,this.value].forEach((y,V)=>{this.columnNames[O[V]]=y}),this.made={turned:M,kept:v,to:O,names:j(this.columnNames)}}const{turned:n,kept:o,to:i,names:r}=this.made,[l,u]=i.slice(o.length),h=r.length,c=t.strings.slice(),a=n.map(x=>c.push(t.columns[x])-1),d=tt(h);let k=T(d,h,r,c),I=0;for(let x=0;x<t.rows;x++){const M=x*t.cols;for(let v=0;v<n.length;v++){const O=n[v];if(O>=t.cols||t.kinds[M+O]===f)continue;const y=I*h,V=(A,C)=>{A>=t.cols||(k.kinds[y+C]=t.kinds[M+A],k.values[y+C]=t.values[M+A],k.styles[y+C]=t.styles[M+A])};o.forEach((A,C)=>V(A,i[C])),k.kinds[y+l]=m,k.values[y+l]=a[v],V(O,u),++I===d&&(yield k,k=T(d,h,r,c),I=0)}}yield q(k,I)}*end(){this.lookup.check(this.saw)}}const Yt={replaceValues:Et,changeText:St,changeNumber:Ot,changeDate:At,fill:e=>new Tt(e),removeColumns:Nt,duplicateColumn:_t,mergeColumns:Rt,addIndex:Ct,keepRows:e=>new Lt(e),groupBy:(e,t)=>new Dt(e,t),pivot:(e,t)=>new Ut(e,t),unpivot:e=>new Ft(e)},Bt=P,It=1024,p=(e,t=It)=>typeof e=="string"&&e.length<=t,w=e=>p(e)&&e!=="",H=e=>Array.isArray(e)&&e.length>0&&e.length<=_&&e.every(t=>p(t)),W=(e,t=0)=>Number.isInteger(e)&&e>=t&&e<=Bt,Q=e=>typeof e=="number"&&Number.isFinite(e);function Vt(e,t){switch(mt[e]){case"count":return W(t);case"text":return w(t);case"integer":return Number.isInteger(t)&&Math.abs(t)<=15;case"number":return Q(t)&&!(e==="divide"&&t===0);default:return t===void 0}}function $t(e){const{op:t,column:s}=e,n=o=>p(s)&&Object.hasOwn(o,e.fn)&&Vt(e.fn,e.value)?{op:t,column:s,fn:e.fn,...e.value===void 0?{}:{value:e.value}}:null;switch(t){case"replaceValues":return p(s)&&p(e.find)&&p(e.replace)?{op:t,column:s,find:e.find,replace:e.replace,whole:e.whole===!0}:null;case"changeText":return n(ht);case"changeNumber":return n(dt);case"changeDate":return n(ft);case"fill":return p(s)?{op:t,column:s,up:e.up===!0}:null;case"removeColumns":return H(e.names)?{op:t,names:[...e.names]}:null;case"duplicateColumn":return p(s)&&w(e.to)?{op:t,column:s,to:e.to}:null;case"mergeColumns":return H(e.columns)&&p(e.delimiter)&&w(e.to)?{op:t,columns:[...e.columns],delimiter:e.delimiter,to:e.to}:null;case"addFormula":return w(e.to)&&p(e.formula,8192)&&e.formula!==""&&Array.isArray(e.columns)&&e.columns.length<=_&&e.columns.every(o=>p(o))?{op:t,to:e.to,formula:e.formula,columns:[...e.columns]}:null;case"addIndex":return w(e.to)&&Q(e.start)&&Q(e.step)?{op:t,to:e.to,start:e.start,step:e.step}:null;case"keepRows":return pt.includes(e.what)?["keepFirst","keepLast","removeFirst","removeLast"].includes(e.what)?W(e.count)?{op:t,what:e.what,count:e.count}:null:e.what==="alternate"?W(e.count,1)&&W(e.skip,1)?{op:t,what:e.what,count:e.count,skip:e.skip}:null:{op:t,what:e.what}:null;case"groupBy":{const o=Array.isArray(e.values)&&e.values.length>0&&e.values.length<=256&&e.values.every(i=>i!==null&&typeof i=="object"&&Object.hasOwn(ot,i.fn)&&w(i.to)&&(i.fn==="count"||p(i.column)))?e.values.map(i=>({fn:i.fn,to:i.to,...i.fn==="count"?{}:{column:i.column}})):null;return o&&H(e.by)?{op:t,by:[...e.by],values:o}:null}case"pivot":return p(s)&&p(e.values)&&Object.hasOwn(ot,e.fn)?{op:t,column:s,values:e.values,fn:e.fn}:null;case"unpivot":return H(e.columns)&&w(e.attribute)&&w(e.value)?{op:t,columns:[...e.columns],others:e.others===!0,attribute:e.attribute,value:e.value}:null;default:return null}}export{ot as AGGREGATES,mt as CHANGE_VALUES,ft as DATE_CHANGES,Yt as MORE_STAGES,dt as NUMBER_CHANGES,pt as ROW_STEPS,$ as Rearrange,ht as TEXT_CHANGES,$t as cleanMoreStep,Vt as validChange};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{cleanColumnNames as _,EMPTY as m,newBatch as g,rowsFor as A,STR as q,trimBatch as E,wordedError as w}from"./rows.js";import{ColumnLookup as N,Places as b,StepError as y}from"./shared-steps.js";import{MAX_COLS as x}from"../../core/address.js";const L={left:"All rows of this query, matching rows of the table",inner:"Only matching rows",right:"All rows of the table, matching rows of this query",full:"All rows of both",leftAnti:"Only rows of this query without a match",rightAnti:"Only rows of the table without a match"},M=(n,t)=>[...new Map(n.filter(e=>(e.op==="append"||e.op==="join")&&e[t]).map(e=>[e[t].toUpperCase(),e[t]])).values()],B=n=>M(n,"table"),J=n=>M(n,"query"),j=n=>`query:${n}`;function T(n,{table:t,query:e}){const s=n?.get((e?j(e):t).toUpperCase());if(!s&&e)throw w(y,'This workbook no longer has a query named "{name}".',{name:e});if(!s)throw w(y,'This workbook no longer has a table named "{name}".',{name:t});return s}function k(n,t,e,s,l,h){const r=t*n.cols;for(let a=0;a<e.length;a++){const o=e[a];if(o<0||o>=n.cols)continue;const i=n.kinds[r+o];if(i===m)continue;if(s.kinds[l+a]=i,s.styles[l+a]=n.styles[r+o],i!==q){s.values[l+a]=n.values[r+o];continue}const c=n.strings[n.values[r+o]];let u=h.get(c);u===void 0&&(u=s.strings.push(c)-1,h.set(c,u)),s.values[l+a]=u}}class v{constructor(t,e){this.input=T(e,t),this.columns=null}*push(t){(this.columns===null||t.columns.length>this.columns.length)&&(this.columns=t.columns),yield t}*end(){const t=this.columns??[],e=new Map(t.map((o,i)=>[o.toLowerCase(),i])),s=this.input.columns.map(o=>e.get(o.toLowerCase())??-1),l=[...t];s.forEach((o,i)=>{o<0&&(s[i]=l.push(this.input.columns[i])-1)});const h=l.map((o,i)=>s.indexOf(i)),r=_(l),a=A(r.length);for(const o of this.input.batches)for(let i=0;i<o.rows;i+=a){const c=g(Math.min(a,o.rows-i),r.length,r),u=new Map;for(let p=0;p<c.rows;p++)k(o,i+p,h,c,p*c.cols,u);yield c}}}class ${constructor(t,e){const{kind:s,left:l,right:h,add:r}=t;this.input=T(e,t),this.kind=s,this.lookup=new N(l);const a=o=>o.map(i=>{const c=this.input.columns.findIndex(u=>u===i);if(c<0)throw w(y,"Column not found: {names}. The source may have changed; edit the query.",{names:i});return c});this.keys=a(h),this.add=s==="leftAnti"?[]:a(r),this.index=new Map,this.input.batches.forEach((o,i)=>{for(let c=0;c<o.rows;c++){const u=this._key(o,c,this.keys);if(u===null)continue;const p=this.index.get(u);p?p.push(i,c):this.index.set(u,[i,c])}}),this.used=s==="right"||s==="full"||s==="rightAnti"?this.input.batches.map(o=>new Uint8Array(o.rows)):null,this.places=new b,this.columnNames=[],this.names=null,this.lastIn=null,this.saw=!1}_key(t,e,s){let l="",h=!1;for(const r of s){const a=e*t.cols+r,o=r>=0&&r<t.cols?t.kinds[a]:m;o!==m&&(h=!0),l+=o===m?"\0":o===q?`s${t.strings[t.values[a]]}\0`:`${o}:${t.values[a]}\0`}return h?l:null}_columnsFor(t){if(t===this.lastIn)return;this.lastIn=t;const e=this.add.map(l=>this.input.columns[l]);if(t.length+e.length>x)throw w(y,"This step would make more than {count} columns.",{count:x.toLocaleString("en-US")});const s=this.places.of([...t.keys(),...this.add.map(l=>`added${l}`)]);[...t,...e].forEach((l,h)=>{this.columnNames[s[h]]=l}),this.names=_(this.columnNames),this.own=new Array(this.names.length).fill(-1),this.other=new Array(this.names.length).fill(-1),t.forEach((l,h)=>{this.own[s[h]]=h}),this.add.forEach((l,h)=>{this.other[s[t.length+h]]=l})}*push(t){this.saw=!0,this._columnsFor(t.columns);const e=this.lookup.resolve(t.columns),{kind:s,names:l,used:h}=this,r=l.length,a=A(r),o=()=>({out:g(a,r,l),known:new Map,n:0});let i=o();const c=s==="leftAnti"||s==="rightAnti";for(let u=0;u<t.rows;u++){const p=this._key(t,u,e),f=p===null?void 0:this.index.get(p);if(f&&h)for(let d=0;d<f.length;d+=2)h[f[d]][f[d+1]]=1;if(c?s==="rightAnti"||f:!f&&(s==="inner"||s==="right"))continue;const I=c||!f?1:f.length/2;for(let d=0;d<I;d++){const S=i.n*r;k(t,u,this.own,i.out,S,i.known),f&&k(this.input.batches[f[2*d]],f[2*d+1],this.other,i.out,S,i.known),++i.n===a&&(yield i.out,i=o())}}yield E(i.out,i.n)}*end(){if(this.lookup.check(this.saw),this.used===null)return;this.names===null&&this._columnsFor([]);const t=this.names.length,e=A(t);let s=g(e,t,this.names),l=new Map,h=0;for(let r=0;r<this.input.batches.length;r++){const a=this.input.batches[r];for(let o=0;o<a.rows;o++)this.used[r][o]||(k(a,o,this.other,s,h*t,l),!(++h<e)&&(yield s,s=g(e,t,this.names),l=new Map,h=0))}yield E(s,h)}}const P={append:(n,t,e)=>new v(n,e),join:(n,t,e)=>new $(n,e)},C=n=>typeof n=="string"&&n.length<=1024,O=(n,t)=>Array.isArray(n)&&n.length>=t&&n.length<=x&&n.every(C);function D(n){const t=s=>C(s)&&s!=="";if(!t(n.table)&&!t(n.query))return null;const e=t(n.query)?{query:n.query}:{table:n.table};return n.op==="append"?{op:"append",...e}:n.op!=="join"||!Object.hasOwn(L,n.kind)||!O(n.left,1)||!O(n.right,1)||n.left.length!==n.right.length||!O(n.add,0)?null:{op:"join",...e,kind:n.kind,left:[...n.left],right:[...n.right],add:[...n.add]}}export{L as JOIN_KINDS,P as TABLE_STAGES,D as cleanTableStep,J as queriesOfSteps,j as queryInput,B as tablesOfSteps};
|