@8sheets/data-grid 1.0.2 → 1.1.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/api/theme-core.js +2 -0
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/info.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/parser.js +3 -3
- package/calc/values.js +1 -1
- package/calcx/culture/custom.js +1 -0
- package/calcx/culture/format-locale.js +1 -1
- package/calcx/culture/separators.js +1 -0
- package/calcx/lang/convert.js +1 -0
- package/cells/axis-ops.js +1 -1
- package/cells/block.js +1 -0
- package/cells/book-css.js +2 -2
- package/cells/cell-defaults.js +1 -1
- package/cells/consolidate-links.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/format-panes.js +3 -3
- package/cells/format-tabs.js +2 -2
- package/cells/outline-column.js +1 -1
- package/cells/panes.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/cells/shift-check.js +1 -0
- package/cells/table-rows.js +1 -0
- package/cells/text-layout.js +9 -8
- package/cells/ui-kit.js +15 -0
- package/cells/view-options.js +1 -1
- package/celltypes/diagonal.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/autofill.js +1 -1
- package/core/axis-styles.js +1 -0
- package/core/axis.js +1 -1
- package/core/culture.js +1 -0
- package/core/formula-refs.js +1 -1
- package/core/input.js +1 -1
- package/core/merge.js +1 -0
- package/core/numfmt.js +1 -1
- package/core/region-input.js +1 -0
- package/core/row-fit.js +1 -0
- package/core/sheet.js +1 -1
- package/core/structure.js +1 -0
- package/core/styles.js +1 -1
- package/core/tables.js +2 -2
- package/core/whatif.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/data-core.js +1 -1
- package/datasheets/gantt-paint.js +1 -1
- package/datasheets/path-binding.js +2 -2
- package/datasheets/rules.js +1 -1
- package/datasheets/view.js +2 -2
- package/i18n/dom.js +1 -1
- package/i18n/en/cells.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/shell.js +2 -2
- package/i18n/pl/cells.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/shell.js +2 -2
- package/io/csv.js +8 -8
- package/io/plan.js +1 -1
- package/io/text-split.js +3 -3
- package/io/xlsx-write.js +1 -1
- package/objects/chart-model.js +1 -1
- package/package.json +1 -1
- package/pivot/engine.js +1 -1
- package/print/paginate.js +1 -1
- package/print/render-page.js +3 -3
- package/table-view/api.js +1 -1
- package/table-view/cell-editor.js +2 -1
- package/table-view/chart.js +1 -0
- package/table-view/column-drag.js +1 -1
- package/table-view/context-menu.js +1 -0
- package/table-view/editors.js +1 -0
- package/table-view/events.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/fill-handle.js +1 -0
- package/table-view/filter-builder.js +1 -0
- package/table-view/find.js +1 -0
- package/table-view/grid-keys.js +2 -2
- package/table-view/labels-de.js +1 -0
- package/table-view/labels-es.js +1 -0
- package/table-view/labels-fr.js +1 -0
- package/table-view/labels-ja.js +1 -0
- package/table-view/labels.js +1 -1
- package/table-view/model.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/panel.js +1 -1
- package/table-view/pivot-spec.js +1 -0
- package/table-view/pivot.js +1 -1
- package/table-view/public.d.ts +277 -28
- package/table-view/reader.worker.js +1 -1
- package/table-view/remote.js +1 -1
- package/table-view/row-drag.js +1 -0
- package/table-view/sparkline.js +1 -0
- package/table-view/state-check.js +1 -0
- package/table-view/table-css.js +380 -0
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/menu-base.js +1 -1
package/pivot/engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withNoDataItems as Zt}from"../slicers/pivot-file.js";import{dateOptionFlags as te}from"../slicers/date-filters.js";import{BOOL as at,CHUNK_BITS as Tt,CHUNK_MASK as Ct,EMPTY as K,ERR as ct,ERRORS as Dt,KIND_MASK as Ft,NUM as B,STR as Z}from"../core/sheet.js";import{formatGeneral as St,getFormatter as Vt,partsToSerial as ee,serialToParts as pt}from"../core/numfmt.js";import{MAX_COLS as se,MAX_ROWS as ne}from"../core/address.js";import{compareText as Ut,ERR as P,ERR_BY_INDEX as Rt,numberToText as re,XlError as $}from"../calc/values.js";import{FUNCS as oe}from"../calc/functions/registry.js";import"../calc/functions/index.js";import{t as G}from"../i18n/index.js";const x=-2,Ke=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],kt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},le={...kt,countNums:"Count"};function xt(c,t){switch(c){case"count":case"countNums":return G("pivot|Count of {field}",{field:t});case"average":return G("pivot|Average of {field}",{field:t});case"max":return G("pivot|Max of {field}",{field:t});case"min":return G("pivot|Min of {field}",{field:t});case"product":return G("pivot|Product of {field}",{field:t});case"stdDev":return G("pivot|StdDev of {field}",{field:t});case"stdDevp":return G("pivot|StdDevp of {field}",{field:t});case"var":return G("pivot|Var of {field}",{field:t});case"varp":return G("pivot|Varp of {field}",{field:t});default:return G("pivot|Sum of {field}",{field:t})}}const je=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ie=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),Ye=c=>ie.has(c),Xe=c=>c==="percent"||c==="difference"||c==="percentDiff",ae=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),Qe=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],ze=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],E={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},X=0,lt=1,st=2,mt=3,Je={ITEM:X,SUBTOTAL:lt,GRAND:st,BLANK:mt},Pt=1<<23,ce=1<<24,Lt="";class S extends Error{constructor(t,e){super(G(t,e))}}function ut(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}const Bt=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,ue=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function fe(c){let t=ue,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(o=>o.has(n)),t.length===0)return null}return e?t[0]:null}const $t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Gt=[31,29,31,30,31,30,31,31,30,31,30,31],he=["seconds","minutes","hours","days","months","quarters","years"],de={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function pe(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Gt[s];return e+t-1}function me(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return $t;case"days":{const s=[];return Gt.forEach((n,o)=>{for(let r=1;r<=n;r++)s.push(`${r}-${$t[o]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function we(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return pe(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ft{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=K,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.base>=0){const l=this.cache.fields[this.base].ensureRaw();return this.rawIds=l.rawIds,this.shared=l.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:o,strs:r}=this;if(r!==null)ye(this.cache,r,null,null,t,e,s);else if(o!==null&&n===null&&this.uniformKind===B){const l=new Map;let i=NaN,u=-1;for(let f=0;f<t;f++){const w=o[f];if(w!==i){let p=l.get(w);p===void 0&&(p=s.length,s.push(w),l.set(w,p)),i=w,u=p}e[f]=u}}else n!==null?Ae(this.cache,n,o,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.shared,this;const{map:t,labels:e}=be(this),s=this.rawIds,n=s.length,o=new Int32Array(n);for(let r=0;r<n;r++)o[r]=t[s[r]];return this.ids=o,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,o=this.shared,r=new Uint8Array(o.length),l=new Float64Array(o.length);o.forEach((i,u)=>{typeof i=="number"?(r[u]=B,l[u]=i):typeof i=="string"?r[u]=Z:typeof i=="boolean"?(r[u]=at,l[u]=i?1:0):i instanceof $&&(r[u]=ct,l[u]=i.index)});for(let i=0;i<t;i++){const u=n[i];e[i]=r[u],s[i]=l[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=ut(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return ut(this.items[t])}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Vt(this.numFmt).number(t):St(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(){if(this._rank!==null)return this._rank;this.ensure();const{items:t}=this,e=new Int32Array(t.length);if(this.group!==null&&this.group.kind!=="discrete")for(let s=0;s<e.length;s++)e[s]=s;else{const s=fe(t),n=Array.from(t.keys());n.sort((o,r)=>ge(t[o],t[r],s)),n.forEach((o,r)=>{e[o]=r})}return this._rank=e,e}}function ge(c,t,e){const s=Bt(c),n=Bt(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):Ut(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function ye(c,t,e,s,n,o,r){let l=-1;for(let f=0;f<n;f++)t[f]>l&&(l=t[f]);const i=new Int32Array(l+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const w=t[f];let p=i[w];if(p<0){const h=c.getString(w),a=h.toLowerCase();p=u.get(a),p===void 0&&(p=r.length,r.push(h),u.set(a,p)),i[w]=p}o[f]=p}}function Ae(c,t,e,s,n,o){const r=new Map,l=new Map,i=new Map,u=new Map;let f=-1;for(let w=0;w<s;w++){const p=t[w];let h;if(p===B){const a=e[w];h=r.get(a),h===void 0&&(h=o.length,o.push(a),r.set(a,h))}else if(p===Z){const a=e[w];if(h=i.get(a),h===void 0){const d=c.getString(a),m=d.toLowerCase();h=l.get(m),h===void 0&&(h=o.length,o.push(d),l.set(m,h)),i.set(a,h)}}else if(p===K)f<0&&(f=o.length,o.push(null)),h=f;else{const a=p*100+e[w];h=u.get(a),h===void 0&&(h=o.length,o.push(p===at?e[w]!==0:Rt[e[w]]??P.NA),u.set(a,h))}n[w]=h}}function be(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const l=pt(t.start),i=pt(t.end),u=`<${Wt(t.start)}`,f=`>${Wt(t.end+1)}`,w=me(t.part,l.year,i.year);let p=[u,...w,f];t.labels&&t.labels.length===p.length&&(p=t.labels);for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<t.start?s[h]=0:a>=t.end+1?s[h]=p.length-1:s[h]=1+we(t.part,pt(a),l.year)}return{map:s,labels:p}}if(t.kind==="bins"){const{start:l,end:i,interval:u}=t,f=Math.max(1,Math.ceil((i-l)/u-1e-9)),w=[`<${bt(l)}`];for(let h=0;h<f;h++){const a=l+h*u,d=t.integer?Math.max(a+u-1,h===f-1?i:0):a+u;w.push(`${bt(a)}-${bt(d)}`)}w.push(`>${bt(i)}`);const p=t.labels&&t.labels.length===w.length?t.labels:w;for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<l?s[h]=0:a>i?s[h]=f+1:s[h]=1+Math.min(f-1,Math.floor((a-l)/u+1e-9))}return{map:s,labels:p}}const n=t.groups.map(l=>l.name),o=new Map;t.groups.forEach((l,i)=>{for(const u of l.keys)o.set(u,i)});const r=new Map;for(let l=0;l<e.length;l++){const i=ut(e[l]);let u=o.get(i);u===void 0&&(u=r.get(i),u===void 0&&(u=n.length,n.push(e[l]),r.set(i,u))),s[l]=u}return{map:s,labels:n}}const bt=c=>re(Number(c.toPrecision(12)));function Wt(c){const t=pt(c);return`${t.month}/${t.day}/${t.year}`}class ve{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function _e(c,t,e,s,n,o){const r=c.columns[t];if(r===void 0)return;const l=e+s;for(let i=e>>>Tt;i<=l-1>>>Tt;i++){const u=r[i];if(u===void 0)continue;const f=i<<Tt,w=Math.max(e,f)&Ct,p=Math.min(l-1,f+Ct)&Ct,h=f-e,a=u.kinds,d=u.values;for(let m=w;m<=p;m++)n[h+m]=a[m]&Ft,o[h+m]=d[m]}}class gt{constructor(){this.fields=[],this.recordCount=0,this.strings=new ve,this.source=null,this.generation=0,this.xml=null,this.id=0,this.needsRefresh=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new S("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new gt;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new gt;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new gt,n=e.length;return s.recordCount=n,t.forEach((o,r)=>{const l=new Uint8Array(n),i=new Float64Array(n);for(let f=0;f<n;f++){const w=e[f][r];typeof w=="number"?(l[f]=B,i[f]=w):typeof w=="string"?(l[f]=Z,i[f]=s.strings.add(w)):typeof w=="boolean"?(l[f]=at,i[f]=w?1:0):w instanceof $&&(l[f]=ct,i[f]=w.index)}const u=new ft(s,r,o);Ht(u,l,i,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new gt;return s&&(n.strings=s),n.recordCount=e,t.forEach((o,r)=>{const l=new ft(n,r,o.name);l.kinds=o.kinds??null,l.nums=o.nums??null,l.strs=o.strs??null,l.uniformKind=o.strs?Z:o.kinds?K:B,o.numFmt&&qt(l,o.numFmt),n.fields.push(l)}),n}refresh(){const t=this.source;if(t===null){for(const p of this.fields)p.invalidate();return this.generation++,!1}const{book:e}=t;this.strings=e.strings;let s,n,o,r,l;if(t.type==="table"){const p=t.table;s=p.sheet??e.sheets[p.sheetIndex],n=p.r0,o=p.c0,r=p.r1-(p.totalsRows??0),l=p.c1}else{if({sheet:s}=t,typeof s=="string"&&(s=e.sheets.find(p=>p.name===t.sheet)),!s)throw new S("The PivotTable source sheet no longer exists.");({r0:n,c0:o,r1:r,c1:l}=t.range),r=Math.min(r,s.maxRow),l=Math.min(l,s.maxCol)}if(r<=n)throw new S("The PivotTable source needs a header row and at least one row of data.");const i=r-n,u=new Map,f=[];for(let p=o;p<=l;p++){const h=Te(e,s,n,p);if(h==="")throw new S("The PivotTable field name is not valid: every source column needs a header.");const a=h.toLowerCase(),d=(u.get(a)??0)+1;u.set(a,d),f.push(d>1?`${h}${d}`:h)}const w=new Map(this.fields.filter(p=>!p.isVirtual).map(p=>[p.name.toLowerCase(),p]));this.recordCount=i,f.forEach((p,h)=>{let a=w.get(p.toLowerCase());a?w.delete(p.toLowerCase()):(a=new ft(this,this.fields.length,p),this.fields.push(a));const d=o+h,m=new Uint8Array(i),A=new Float64Array(i);_e(s,d,n+1,i,m,A),Ht(a,m,A,i),a.removed=!1,a.reset();for(let g=0;g<i;g++)if(m[g]!==K){qt(a,e.styles.get(s.style(n+1+g,d)).numFmt);break}});for(const p of w.values())p.removed=!0,p.kinds=null,p.nums=null,p.strs=null,p.uniformKind=K,p.reset();for(const p of this.fields)p.isVirtual&&p.reset();return this._rescaleGroups(),this.generation++,this.needsRefresh=!1,!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const o=n.group;o.autoStart&&(o.start=e.kind==="date"?Math.floor(s.min):s.min),o.autoEnd&&(o.end=e.kind==="date"?Math.floor(s.max):s.max),o.labels=void 0}}}addCalculatedField(t,e){const s=new ft(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Nt(s.formula,this),this.fields.push(s),s.index}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Nt(n,this),s.formula=n,this.generation++}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t){t.ensureRaw();let e=1/0,s=-1/0,n=!0;for(const o of t.shared){if(typeof o!="number")throw new S("Cannot group that selection.");o<e&&(e=o),o>s&&(s=o),Number.isInteger(o)||(n=!1)}if(e===1/0)throw new S("Cannot group that selection.");return{min:e,max:s,integer:n}}groupDates(t,e,{start:s,end:n}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");const{min:r,max:l}=this._numericRange(o),i=he.filter(p=>e.includes(p));if(i.length===0)throw new S("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(r),end:n??Math.floor(l)};o.group={kind:"date",part:i[0],...u,autoStart:s===void 0,autoEnd:n===void 0},o.invalidate();const f=[t];let w=o;for(const p of i.slice(1)){const h=new ft(this,this.fields.length,this._uniqueName(de[p]));h.base=t,h.group={kind:"date",part:p,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(h),w.par=h.index,w=h,f.unshift(h.index)}return f}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");if(!(n>0))throw new S("The grouping interval must be greater than zero.");const{min:r,max:l,integer:i}=this._numericRange(o);this.ungroup(t);const u=e??r,f=s??l;if(f<=u)throw new S("The ending value must be greater than the starting value.");return o.group={kind:"bins",start:u,end:f,interval:n,integer:i&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},o.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated)throw new S("Cannot group that selection.");n.ensureRaw();let o=n.par>=0?this.fields[n.par]:null;if(o&&o.group?.kind!=="discrete")throw new S("Cannot group that selection.");return o?(o.group.groups.push(...e),o.invalidate(),o.index):(o=new ft(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),o.base=t,o.group={kind:"discrete",groups:e.map(r=>({name:r.name,keys:[...r.keys]}))},this.fields.push(o),n.par=o.index,o.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function qt(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Vt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Te(c,t,e,s){const n=t.kind(e,s)&Ft,o=t.value(e,s);return n===Z?c.strings.get(o).trim():n===B?St(o):n===at?o?"TRUE":"FALSE":n===ct?Dt[o]??"":""}function Ht(c,t,e,s){let n=0,o=0;for(let r=0;r<s;r++){const l=t[r];l===B?n++:l===Z&&o++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=B,c.nums=e;else if(o===s&&s>0){c.uniformKind=Z;const r=new Int32Array(s);for(let l=0;l<s;l++)r[l]=e[l];c.strs=r}else c.uniformKind=K,c.kinds=t,c.nums=e}const Ce=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Re(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,o="";for(;;){if(n>=c.length)throw new S("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}o+=c[n++]}t.push({t:s==="'"?"name":"str",v:o}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0}),e+=n[0].length}else{const n=Ce.find(o=>c.startsWith(o,e));if(!n)throw new S("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const Kt=c=>c instanceof $?c:null,F=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw P.VALUE},jt={IF:c=>{const t=c[0]();if(Kt(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return Kt(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>F(t())!==0),OR:c=>c.some(t=>F(t())!==0),NOT:c=>F(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+F(e()),0),MIN:c=>Math.min(...c.map(t=>F(t()))),MAX:c=>Math.max(...c.map(t=>F(t()))),AVERAGE:c=>c.reduce((t,e)=>t+F(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1};function Nt(c,t){const e=Re(c);let s=0;const n=new Set,o=g=>e[s]?.t==="op"&&e[s].v===g,r=()=>new S("The formula is not valid."),l=g=>{const y=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&!b.isCalculated),v=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&b.isCalculated);if(v){for(const b of v.calc.refs)n.add(b);return b=>v.calc.fn(b)}if(!y)throw new S("The formula refers to an unknown field: {name}",{name:g.v});n.add(y.index);const _=y.index;return b=>b(_)},i=()=>{const g=e[s];if(!g)throw r();if(g.t==="num"){s++;const y=g.v;return()=>y}if(g.t==="str"){s++;const y=g.v;return()=>y}if(g.t==="name"){if(s++,g.bare&&o("(")){s++;const y=[];if(!o(")"))for(y.push(a());o(",");)s++,y.push(a());if(!o(")"))throw r();return s++,d(g.v.toUpperCase(),y)}if(g.bare&&m.has(g.v.toUpperCase())&&!t.field(g.v)){const y=jt[g.v.toUpperCase()];return()=>y([])}return l(g)}if(o("(")){s++;const y=a();if(!o(")"))throw r();return s++,y}throw r()},u=()=>{let g=i();for(;o("%");){s++;const y=g;g=v=>F(y(v))/100}return g},f=()=>{if(o("-")){s++;const g=f();return y=>-F(g(y))}return o("+")?(s++,f()):u()},w=()=>{let g=f();for(;o("^");){s++;const y=g,v=f();g=_=>{const b=F(y(_))**F(v(_));if(!Number.isFinite(b))throw P.NUM;return b}}return g},p=()=>{let g=w();for(;o("*")||o("/");){const y=e[s++].v,v=g,_=w();g=y==="*"?b=>F(v(b))*F(_(b)):b=>{const L=F(_(b));if(L===0)throw P.DIV0;return F(v(b))/L}}return g},h=()=>{let g=p();for(;o("+")||o("-");){const y=e[s++].v,v=g,_=p();g=y==="+"?b=>F(v(b))+F(_(b)):b=>F(v(b))-F(_(b))}return g},a=()=>{let g=h();for(;e[s]?.t==="op"&&["=","<>","<",">","<=",">="].includes(e[s].v);){const y=e[s++].v,v=g,_=h();g=b=>{const L=F(v(b)),R=F(_(b));switch(y){case"=":return L===R;case"<>":return L!==R;case"<":return L<R;case">":return L>R;case"<=":return L<=R;default:return L>=R}}}return g},d=(g,y)=>{const v=jt[g];if(v)return b=>v(y.map(L=>()=>L(b)));const _=oe.get(g);if(!_||_.kind!=="lift")throw new S("The formula uses a function a calculated field can't call: {name}",{name:g});if(y.length<_.min||y.length>_.max)throw r();return b=>{const L=y.map(R=>R(b));for(const R of L)if(R instanceof $)throw R;return _.fn(...L)}},m=new Set(["TRUE","FALSE"]),A=a();if(s<e.length)throw r();return{fn:A,refs:[...n]}}const ke={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"};class Et{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const o=e.num[s],r=this.num[t];if(this.num[t]=r+o,e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),o!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const l=e.mean[s]-this.mean[t],i=r+o;this.m2[t]+=e.m2[s]+l*l*r*o/i,this.mean[t]+=l*o/i}}value(t,e){const s=this.cnt[t];if(s===0)return null;if(e==="count")return s;if(e==="countNums")return this.num[t];if(this.err!==null&&this.err[t]!==0)return Rt[this.err[t]-1];const n=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return n===0?P.DIV0:this.sum[t]/n;case"max":return n===0?0:this.max[t];case"min":return n===0?0:this.min[t];case"product":return n===0?0:this.prod[t];case"stdDev":return n<2?P.DIV0:Math.sqrt(this.m2[t]/(n-1));case"stdDevp":return n<1?P.DIV0:Math.sqrt(this.m2[t]/n);case"var":return n<2?P.DIV0:this.m2[t]/(n-1);case"varp":return n<1?P.DIV0:this.m2[t]/n;default:return null}}}function xe(c,t,e,s){const{cnt:n,num:o}=c;t.base<0&&t.ensureColumn();const{kinds:r,nums:l}=t;if(l===null||t.base>=0){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}return}if(r===null){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}o.set(n)}else for(let a=0;a<s;a++){const d=e[a];if(d<0)continue;const m=r[a];m!==K&&(n[d]++,m===B?o[d]++:m===ct&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[d]===0&&(c.err[d]=l[a]+1)))}const{sum:i,min:u,max:f,prod:w,mean:p,m2:h}=c;if(i!==null)if(r===null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(i[d]+=l[a])}else for(let a=0;a<s;a++){const d=e[a];d>=0&&r[a]===B&&(i[d]+=l[a])}if(u!==null)for(let a=0;a<s;a++){const d=e[a];if(d<0||r!==null&&r[a]!==B)continue;const m=l[a];m<u[d]&&(u[d]=m),m>f[d]&&(f[d]=m)}if(w!==null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(r===null||r[a]===B)&&(w[d]*=l[a])}if(p!==null){const a=new Int32Array(c.size);for(let d=0;d<s;d++){const m=e[d];if(m<0||r!==null&&r[d]!==B)continue;const A=++a[m],g=l[d]-p[m];p[m]+=g/A,h[m]+=g*(l[d]-p[m])}}}class Le{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let r=t;this.depth[r]>e;r=this.parent[r])n.push(this.item[r]);let o=s;for(let r=n.length-1;r>=0&&o>=0;r--)o=this.findChild(o,n[r]);return o}}function Yt(c,t,e,s,n,o=null){const r=new Le(c,t,e),l=t.length;if(l===0)return r;let i=null,u=1;const f=[];for(let h=0;h<l;h++){const a=c.fields[t[h]].ensure(),d=a.ids,m=a.items.length,A=u*m,g=new Int32Array(s),y=Math.min(A,Math.max(s,1)),v=new Int32Array(y),_=new Int32Array(y);let b=0;if(A<=Pt){const D=new Int32Array(A).fill(-1);if(i===null)for(let C=0;C<s;C++){if(n!==null&&n[C]===0){g[C]=-1;continue}const N=d[C];let U=D[N];U<0&&(U=b++,D[N]=U,_[U]=N),g[C]=U}else for(let C=0;C<s;C++){const N=i[C];if(N<0){g[C]=-1;continue}const U=N*m+d[C];let I=D[U];I<0&&(I=b++,D[U]=I,v[I]=N,_[I]=d[C]),g[C]=I}}else{const D=new Map;for(let C=0;C<s;C++){const N=i===null?0:i[C];if(N<0||i===null&&n!==null&&n[C]===0){g[C]=-1;continue}const U=N*m+d[C];let I=D.get(U);I===void 0&&(I=b++,D.set(U,I),v[I]=N,_[I]=d[C]),g[C]=I}}const L=o?.(t[h]),R=L?Zt({parents:v,items:_,count:b},u,m,L.hide):{parents:v,items:_,count:b};f.push(R),i=g,u=Math.max(R.count,1)}r.leaf=i,r.nLeaves=f[l-1].count;let w=1;const p=[];for(const h of f)p.push(w),w+=h.count;return r.levelBase=p,r.nNodes=w,r.parent=new Int32Array(w),r.item=new Int32Array(w),r.depth=new Uint8Array(w),r.parent[0]=-1,r.item[0]=-1,f.forEach((h,a)=>{const d=p[a],m=a===0?0:p[a-1];for(let A=0;A<h.count;A++)r.parent[d+A]=a===0?0:m+h.parents[A],r.item[d+A]=h.items[A],r.depth[d+A]=a+1}),r}class Ne{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const o=new s(t);return o.set(n),o};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,o,r=0,l=0){this.count===this.capacity&&this._grow();const i=this.count++;this.rows[i]=t,this.cols[i]=e,this.kinds[i]=s,this.values[i]=n,this.roles[i]=o,this.levels[i]=r,this.formats[i]=l}pushValue(t,e,s,n,o=0,r=0){s==null?this.push(t,e,K,0,n,o,r):typeof s=="number"?this.push(t,e,B,s,n,o,r):typeof s=="string"?this.push(t,e,Z,this.text(s),n,o,r):typeof s=="boolean"?this.push(t,e,at,s?1:0,n,o,r):this.push(t,e,ct,s.index,n,o,r)}valueAt(t){switch(this.kinds[t]){case B:return this.values[t];case Z:return this.texts[this.values[t]];case at:return this.values[t]!==0;case ct:return Dt[this.values[t]]??"#N/A";default:return null}}}function Xt(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const Qt=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function Ee(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(r=>r==="*"?".*":r==="?"?".":Qt(r)).join(""),o=(r,l,i)=>{const u=typeof l=="number"?l:Number.NaN,f=i.trim()===""?Number.NaN:Number(i);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:Ut(r,i)};switch(t){case"captionEqual":{const r=Xt(e);return l=>r.test(l)}case"captionNotEqual":{const r=Xt(e);return l=>!r.test(l)}case"captionBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>r.test(l)}case"captionNotBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>!r.test(l)}case"captionEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>r.test(l)}case"captionNotEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>!r.test(l)}case"captionContains":{const r=new RegExp(n,"is");return l=>r.test(l)}case"captionNotContains":{const r=new RegExp(n,"is");return l=>!r.test(l)}case"captionGreaterThan":return(r,l)=>o(r,l,e)>0;case"captionGreaterThanOrEqual":return(r,l)=>o(r,l,e)>=0;case"captionLessThan":return(r,l)=>o(r,l,e)<0;case"captionLessThanOrEqual":return(r,l)=>o(r,l,e)<=0;case"captionBetween":return(r,l)=>o(r,l,e)>=0&&o(r,l,s)<=0;case"captionNotBetween":return(r,l)=>o(r,l,e)<0||o(r,l,s)>0;default:return()=>!0}}function Oe(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function wt(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const o of t.hidden){const r=n.get(o);r!==void 0&&(s[r]=1)}}if(t.labelFilter){const n=Ee(t.labelFilter);c.items.forEach((o,r)=>{n(c.labelOfValue(o),o)||(s[r]=1)})}return s}function zt(c,t){return c.ensureRaw(),te(c.shared,t)}class Ie{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=ce,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Me{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(r,l)=>{let i=s.get(r);i===void 0&&(i={sum:!1,mm:!1,prod:!1,var:!1},s.set(r,i));const u=ke[l];u&&(i[u]=!0)},o=new Set;for(const r of Object.keys(e.fieldOptions)){const l=e.fieldOptions[r].subtotals;if(Array.isArray(l))for(const i of l)o.add(i)}this.data=e.values.map((r,l)=>{const i=t.fields[r.field],u={index:l,field:r.field,name:r.name,agg:r.agg,showAs:r.showAs??null,numFmt:r.numFmt??null,calc:null};if(i.isCalculated){u.calc=i.calc??(i.calc=Nt(i.formula,t));for(const f of u.calc.refs)n(f,"sum")}else{n(r.field,r.agg);for(const f of o)n(r.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const o of Object.keys(e.fieldOptions)){const r=s.fields[o];if(!r||r.removed||r.isCalculated)continue;const l=wt(r,e.fieldOptions[o]);if(l!==null){n===null&&(n=new Uint8Array(t).fill(1));const i=r.ensure().ids;for(let u=0;u<t;u++)l[i[u]]===1&&(n[u]=0)}if(e.fieldOptions[o].range||e.fieldOptions[o].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const i=zt(r,e.fieldOptions[o]),u=r.rawIds;for(let f=0;f<t;f++)i[u[f]]===1&&(n[f]=0)}}return n}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,o=y=>y.filter(v=>v!==x||n>1);let r=o(e.rows),l=o(e.cols);n>1&&!r.includes(x)&&!l.includes(x)&&(l=[...l,x]),r=r.filter(y=>y===x||!t.fields[y].removed),l=l.filter(y=>y===x||!t.fields[y].removed);const i=this._recordMask(s);this.mask=i;const u=y=>{const v=e.fieldOptions[y];return v?.showAll?{hide:wt(t.fields[y],v)}:null},f=Yt(t,r.filter(y=>y!==x),r,s,i,u),w=Yt(t,l.filter(y=>y!==x),l,s,i,u);this.rows=f,this.cols=w;let p,h,a,d;const m=f.nLeaves,A=w.nLeaves;if(f.leaf!==null&&w.leaf!==null){const y=f.leaf,v=w.leaf;p=new Int32Array(s);const _=m*A,b=Math.min(_,Math.max(s,1));if(h=new Int32Array(b),a=new Int32Array(b),d=0,_<=Pt){const L=new Int32Array(_).fill(-1);for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const C=D*A+v[R];let N=L[C];N<0&&(N=d++,L[C]=N,h[N]=D,a[N]=v[R]),p[R]=N}}else{const L=new Map;for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const C=D*A+v[R];let N=L.get(C);N===void 0&&(N=d++,L.set(C,N),h[N]=D,a[N]=v[R]),p[R]=N}}}else if(f.leaf!==null||w.leaf!==null){p=f.leaf??w.leaf,d=f.leaf!==null?m:A;const y=new Int32Array(d);for(let _=0;_<d;_++)y[_]=_;const v=new Int32Array(d);h=f.leaf!==null?y:v,a=f.leaf!==null?v:y}else{if(p=new Int32Array(s),d=1,i!==null)for(let y=0;y<s;y++)i[y]===0&&(p[y]=-1);h=new Int32Array(1),a=new Int32Array(1)}this.cellCount=d,this.cellRow=h,this.cellCol=a,this.cells=p;const g=new Map;for(const[y,v]of this.needs){const _=new Et(d,v);xe(_,t.fields[y],p,s),g.set(y,_)}this.leafAccs=g,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let o=!1;const r=l=>{const i=e.get(l);if(i.cnt[s]!==0&&(o=!0),i.err!==null&&i.err[s]!==0)throw Rt[i.err[s]-1];return i.sum[s]};try{const l=t.calc.fn(r);return o?typeof l=="number"?Number.isFinite(l)?l:P.NUM:typeof l=="boolean"?l?1:0:l instanceof $?l:P.VALUE:null}catch(l){if(l instanceof $)return l;throw l}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes);const n=(o,r,l)=>{for(let i=1;i<=o.k;i++){const u=o.fields[i-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const w=f.valueFilter??f.top,p=s[w.data??0];if(!p)continue;const h=this._nodeAccs(o,p,l),a=o.levelBase[i-1],d=i<o.k?o.levelBase[i]:o.nNodes,m=new Map;for(let A=a;A<d;A++){if(r[A]||r[o.parent[A]]){r[A]=1;continue}const g=o.parent[A];let y=m.get(g);y===void 0&&(y=[],m.set(g,y)),y.push(A)}for(const A of m.values()){const g=y=>{const v=this._slotValue(p,h,y,null);return typeof v=="number"?v:null};if(f.valueFilter){const y=Oe(f.valueFilter);for(const v of A){const _=g(v);(_===null||!y(_))&&(r[v]=1)}}if(f.top){const y=A.filter(v=>!r[v]);for(const v of Fe(y,g,f.top,!0))r[v]=1}}for(let A=d;A<o.nNodes;A++)r[o.parent[A]]&&(r[A]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],o=new Map;for(const a of n)o.set(a,new Et(t.nNodes,this.needs.get(a)));const r=[...o.entries()].map(([a,d])=>[d,this.leafAccs.get(a)]),{cellRow:l,cellCol:i,rows:u,cols:f,rowDead:w,colDead:p}=this,h=s?l:i;for(let a=0;a<this.cellCount;a++){const d=u.leafNode(l[a]),m=f.leafNode(i[a]);if(w[d]||p[m])continue;let A=t.leafNode(h[a]);for(;A>=0;){for(const[g,y]of r)g.merge(A,y,a);A=t.parent[A]}}return o}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:o,colDead:r,cellCount:l}=this,i=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new Ie(t.nNodes,e.nNodes),w=t.parent,p=e.parent,h=new Uint8Array(l);for(let g=0;g<l;g++){const y=t.leafNode(s[g]),v=e.leafNode(n[g]);if(!(o[y]||r[v])){h[g]=1;for(let _=y;_>=0;_=w[_])if(i[_]=1,!f.dense)for(let b=v;b>=0;b=p[b])f.ensure(_,b);for(let _=v;_>=0;_=p[_])u[_]=1}}t.alive=i,e.alive=u;const a=new Map,d=[];for(const[g,y]of this.needs){const v=new Et(Math.max(f.size,1),y);a.set(g,v),d.push([v,this.leafAccs.get(g)])}const m=f.dense,A=f.cols;for(let g=0;g<l;g++){if(h[g]===0)continue;const y=t.leafNode(s[g]),v=e.leafNode(n[g]);for(let _=y;_>=0;_=w[_])for(let b=v;b>=0;b=p[b]){const L=m?_*A+b:f.get(_,b);for(let R=0;R<d.length;R++)d[R][0].merge(L,d[R][1],g)}}this.slots=f,this.accs=a,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const o=this.slots.get(e,s);return o<0?null:this._slotValue(t,this.accs,o,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const o=t.showAs?.type;if(!o||o==="normal")return this.raw(t,e,s,n);const r=this.raw(t,e,s,n);if(r instanceof $)return r;const l=(m,A)=>this.raw(t,m,A,n),i=m=>m instanceof $?m:r===null?m===null?null:0:m===null||m===0?P.DIV0:r/m;switch(o){case"percentOfTotal":return i(l(0,0));case"percentOfCol":return i(l(0,s));case"percentOfRow":return i(l(e,0));case"percentOfParentRow":return i(e===0?r:l(this.rows.parent[e],s));case"percentOfParentCol":return i(s===0?r:l(e,this.cols.parent[s]));case"index":{const m=l(0,0),A=l(e,0),g=l(0,s);return[m,A,g].some(y=>y instanceof $)?P.VALUE:!A||!g?P.DIV0:(r??0)*m/(A*g)}default:}const u=this._baseLoc(t);if(u===null)return P.NA;const{tree:f,isRow:w,depth:p}=u,h=w?e:s;if(f.depth[h]<p)return null;const a=m=>w?l(m,s):l(e,m),d=f.ancestorAt(h,p);switch(o){case"percentOfParent":return i(a(d));case"percent":case"difference":case"percentDiff":{const m=this._baseSibling(t,f,d,p);if(m==="missing")return P.NA;if(m===-1)return o==="percent"?r===null?null:1:null;const A=a(f.peer(h,p,m));return m===d?o==="percent"?r===null?null:1:null:A instanceof $?A:o==="difference"?r===null&&A===null?null:(r??0)-(A??0):r===null||A===null?null:A===0?P.DIV0:o==="percent"?r/A:(r-A)/A}case"runTotal":case"percentOfRunningTotal":{const m=this._running(t,f,w,p,h,w?s:e,d,n);if(m instanceof $||o==="runTotal")return m;const A=f.children(f.parent[d]),g=this._running(t,f,w,p,h,w?s:e,A[A.length-1],n);return g instanceof $?g:g===0?P.DIV0:m/g}case"rankAscending":case"rankDescending":return r===null?null:this._rank(t,f,w,p,h,w?s:e,r,o==="rankAscending",n);default:return r}}_baseSibling(t,e,s,n){const o=t.showAs.baseItem,r=e.parent[s];if(o==="prev"||o==="next"){const f=e.children(r),w=e.pos[s]+(o==="prev"?-1:1);return w>=0&&w<f.length?f[w]:-1}const i=e.fieldAt(n).keyIndex.get(o);if(i===void 0)return"missing";const u=e.findChild(r,i);return u<0?"missing":u}_running(t,e,s,n,o,r,l,i){t._run===void 0&&(t._run=new Map);let u=t._run.get(i);u===void 0&&(u=new Map,t._run.set(i,u));const f=e.children(e.parent[l]),w=e.pos[l],p=s?this.cols.nNodes:this.rows.nNodes;let h=w,a=0;for(;h>=0;){const d=e.peer(o,n,f[h]),m=d>=0?u.get(d*p+r):void 0;if(m!==void 0){a=m;break}h--}for(let d=h+1;d<=w;d++){const m=e.peer(o,n,f[d]);if(m<0)continue;const A=s?this.raw(t,m,r,i):this.raw(t,r,m,i);if(A instanceof $)return A;typeof A=="number"&&(a+=A),u.set(m*p+r,a)}return a}_rank(t,e,s,n,o,r,l,i,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(o,n),w=e.pathKeys(o).slice(n).join(Lt),p=`${e.parent[f]}|${r}|${w}`;let h=t._ranks.get(p);if(h===void 0){const m=[];for(const A of e.children(e.parent[f])){const g=e.peer(o,n,A);if(g<0)continue;const y=s?this.raw(t,g,r,u):this.raw(t,r,g,u);typeof y=="number"&&m.push(y)}h=Float64Array.from(m).sort(),t._ranks.set(p,h)}let a=0,d=h.length;if(i){for(;a<d;){const m=a+d>>1;h[m]<l?a=m+1:d=m}return a+1}for(;a<d;){const m=a+d>>1;h[m]<=l?a=m+1:d=m}return h.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:o}=t,r=new Int32Array(s+1);for(let u=1;u<s;u++)o[u]&&r[n[u]+1]++;for(let u=0;u<s;u++)r[u+1]+=r[u];const l=new Int32Array(r[s]),i=r.slice();for(let u=1;u<s;u++)o[u]&&(l[i[n[u]]++]=u);t.childStart=r,t.childList=l,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),w=u===0?0:t.levelBase[u-1],p=u===0?1:t.levelBase[u];for(let h=w;h<p;h++){const a=r[h],d=r[h+1];if(d-a>1){const m=Array.from(l.subarray(a,d));m.sort(f),l.set(m,a)}for(let m=a;m<d;m++)t.pos[l[m]]=m-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],o=this.cache.fields[n].ensure(),r=o.rank(),{item:l}=t,i=this.opts(n)?.sort;if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(d,m)=>r[l[d]]-r[l[m]];if(i.order==="manual"){const d=i.keys??[],m=new Map(d.map((g,y)=>[g,y])),A=new Float64Array(o.items.length);return o.items.forEach((g,y)=>{const v=m.get(ut(g));A[y]=v===void 0?d.length+r[y]:v}),(g,y)=>A[l[g]]-A[l[y]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(d,m)=>u*(r[l[d]]-r[l[m]]);const f=this.data[i.data];if(!f)return(d,m)=>r[l[d]]-r[l[m]];let w=0;if(i.path){const d=s?this.cols:this.rows;this._ensureItems(d);for(let m=0;m<i.path.length&&w>=0;m++){const g=d.fieldAt(m+1).keyIndex.get(i.path[m]);w=g===void 0?-1:d.findChild(w,g)}}const p=d=>{const m=s?this.raw(f,d,w):this.raw(f,w,d);return typeof m=="number"?m:null},h=new Map,a=d=>{let m=h.get(d);return m===void 0&&(m=p(d),h.set(d,m)),m};return(d,m)=>{const A=a(d),g=a(m);return A===null||g===null?A===g?r[l[d]]-r[l[m]]:A===null?1:-1:A===g?r[l[d]]-r[l[m]]:u*(A-g)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],o=s[n];return o===null?!1:!!(o.items!==null&&o.items.has(t.fieldAt(n).keyOf(t.item[e]))||o.paths!==null&&o.paths.has(t.pathKeys(e).join(Lt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,o={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},r=(h,a,d,m,A,g,y,v)=>{o.node.push(h),o.data.push(a),o.type.push(d),o.level.push(m),o.first.push(A),o.func.push(g),o.top.push(y?1:0),o.parentLine.push(v?1:0)},l=s.length-1,i=h=>e?s[h]===x?this.spec.layout:this._form(s[h]):"tabular",u=[null];for(let h=1;h<=t.k;h++){const a=this.opts(t.fields[h-1]),d=a?.collapsedItems?.length?new Set(a.collapsedItems):null,m=a?.collapsed?.length?new Set(a.collapsed):null;u.push(d||m?{items:d,paths:m}:null)}const f=h=>this.opts(h)?.subtotalTop??this.spec.subtotalTop,w=(h,a,d,m)=>{const A=s[a];if(A===x){for(let _=0;_<n;_++){const b=_===0&&m!==-1?m:a;a===l?r(h,_,X,a,b,null,!1,!1):i(a)==="tabular"?w(h,a+1,_,b):(r(h,_,X,a,b,null,!1,!0),o.noValues??=new Set,o.noValues.add(o.node.length-1),w(h,a+1,_,-1))}return}const g=t.children(h),y=this.opts(A),v=y?.blankLine===!0&&e;for(let _=0;_<g.length;_++){const b=g[_],L=_===0&&m!==-1?m:a;if(a===l){r(b,d,X,a,L,null,!1,!1);continue}const R=i(a),D=d<0&&s.indexOf(x,a+1)>=0;if(this._isCollapsed(t,b,u)){if(D)for(let z=0;z<n;z++)r(b,z,X,a,z===0?L:a,null,!1,R!=="tabular");else r(b,d,X,a,L,null,!1,R!=="tabular");o.collapsed??=new Set,o.collapsed.add(b),v&&r(b,d,mt,a,a,null,!1,!1);continue}const C=y?.subtotals??"auto",N=Array.isArray(C),U=C!=="none"&&!(N&&C.length===0),I=R!=="tabular"&&!D&&!N&&U&&f(A);if(R==="tabular"?w(b,a+1,d,L):(r(b,d,X,a,L,null,I,!0),I||(o.noValues??=new Set,o.noValues.add(o.node.length-1)),w(b,a+1,d,-1)),!I&&U&&!(a+1===l&&s[a+1]===x&&!N)){const yt=N?C:[null];if(D)for(let tt=0;tt<n;tt++)for(const vt of yt)r(b,tt,lt,a,a,vt,!1,!1);else for(const tt of yt)r(b,d,lt,a,a,tt,!1,!1)}v&&r(b,d,mt,a,a,null,!1,!1)}};if(s.length===0)return r(0,-1,X,-1,0,null,!1,!1),o;if(w(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(x))for(let h=0;h<n;h++)r(0,h,st,0,0,null,!1,!1);else r(0,-1,st,0,0,null,!1,!1);return o}fieldCaption(t){return t===x?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],o=this.opts(s.index)?.itemCaptions;if(o){const r=o[s.keyOf(n)];if(r!==void 0)return r}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s;const n=t.fieldAt(t.depth[e]).items[t.item[e]];return n??"(blank)"}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),o=e.data[s],r=e.func[s];return r!==null&&o>=0?`${n} ${kt[r]} of ${this.data[o].name}`:r!==null?`${n} ${kt[r]}`:o>=0?`${n} ${this.data[o].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=wt(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,o=-1;for(let r=0;r<s.length;r++)s[r]===0&&(n++,o=r);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(o),value:e.items[o]??"(blank)"}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,o=new Ne;this.buffer=o;const r=n.length,l=t.filters.filter(T=>!this.cache.fields[T].removed),i=l.length>0?l.length+1:0,u=e.slots.length===0&&s.slots.length===0&&r===0;l.forEach((T,k)=>{o.pushValue(k,0,this.fieldCaption(T),E.PAGE_LABEL);const O=this.cache.fields[T],W=this._pageValue(T);o.pushValue(k,1,W.value,E.PAGE_VALUE,0,typeof W.value=="number"?o.format(O.numFmt):0)});const f=[],w=[];let p=0;if(e.slots.length>0){let T=0,k=0;for(let W=0;W<e.slots.length;W++)f.push(T),w.push(k),(e.slots[W]===x?t.layout:this._form(e.slots[W]))==="compact"?k++:(T++,k=0);p=(e.slots[e.slots.length-1]===x?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?T+1:T}else r<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===x)&&(p=1);const h=e.lines,a=s.lines,d=a.node.length,m=h.node.length,A=s.slots.length===1&&s.slots[0]===x,g=A&&!t.hideValuesRow&&e.slots.length>0,y=s.slots.length>0&&(!A||g),v=u?0:y?1+s.slots.length:1,_=y?t.layout==="compact"?1:s.slots.length:0,b=p+Math.max(r>0||y?d:0,_),L=r>0||e.slots.length>0?m:0,R=i,D=new Uint8Array(v*Math.max(b,1)),C=(T,k,O,W,H=0,V=0)=>{o.pushValue(R+T,k,O,W,V,H),D[T*b+k]=1},N=T=>t.layout==="compact"?null:T.map(k=>this.fieldCaption(k));u&&o.pushValue(R,0,t.name,E.PLACEHOLDER);const U=v-1;if(e.slots.length>0){const T=N(e.slots);T===null?C(U,0,t.rowCaption??G("Row Labels"),E.ROW_CAPTION):e.slots.forEach((k,O)=>{(k===x?t.layout:this._form(k))==="compact"&&O>0&&f[O]===f[O-1]||D[U*b+f[O]]||C(U,f[O],T[O],E.ROW_CAPTION)})}if(y){r===1&&e.slots.length>0&&C(0,0,n[0].name,E.CORNER);const T=N(s.slots);g?C(0,p,t.dataCaption,E.COL_CAPTION):T===null?C(0,p,t.colCaption??G("Column Labels"),E.COL_CAPTION):T.forEach((k,O)=>C(0,p+O,k,E.COL_CAPTION))}else r===1&&!A&&!e.slots.includes(x)&&C(0,p,n[0].name,E.DATA_HEADER);const I=y?1:0;if(r>0||y)for(let T=0;T<d;T++){const k=a.type[T],O=p+T,W=a.node[T];if(k===st){const V=a.data[T],ht=V>=0?`Total ${n[V].name}`:t.grandCaption??G("Grand Total");C(I,O,ht,E.COL_GRAND);continue}if(k===lt){C(I+a.level[T],O,this._subtotalLabel(s,a,T),E.COL_SUBTOTAL);continue}const H=a.level[T];for(let V=a.first[T];V<=H;V++){if(V<0||V>=s.slots.length)continue;if(s.slots[V]===x){const j=a.data[T];j>=0&&C(I+V,O,n[j].name,E.DATA_HEADER)}else{const j=Ot(s.slots,V),J=s.ancestorAt(W,j);if(V===H&&a.collapsed?.has(J))C(I+V,O,`${this._labelText(s,J)} Total`,E.COL_ITEM);else{const At=this._labelValue(s,J);C(I+V,O,At,E.COL_ITEM,typeof At=="number"?o.format(s.fieldAt(j).numFmt):0,t.showExpandButtons&&j<s.k?1:0)}}}}for(let T=0;T<v;T++)for(let k=0;k<b;k++)D[T*b+k]===0&&o.push(R+T,k,K,0,E.HEADER_BLANK);const z=R+v,yt=n.map(T=>{const k=T.numFmt??De(T);return o.format(k)}),tt=h.noValues??null,vt=T=>e.slots[T];for(let T=0;T<L;T++){const k=z+T,O=h.type[T];if(O===mt)continue;const W=h.node[T],H=h.level[T],V=h.parentLine[T]===1;let ht=E.ROW_ITEM,j=E.DATA;O===lt?(ht=E.ROW_SUBTOTAL,j=E.DATA_SUBTOTAL):O===st?(ht=E.ROW_GRAND,j=E.DATA_GRAND_ROW):V&&(j=E.DATA_PARENT);const J=Math.max(H,0);if(p>0)if(e.slots.length===0)r===1&&o.pushValue(k,0,n[0].name,E.ROW_ITEM);else if(O===st){const q=h.data[T];o.pushValue(k,0,q>=0?`Total ${n[q].name}`:t.grandCaption??G("Grand Total"),E.ROW_GRAND);for(let M=1;M<p;M++)o.push(k,M,K,0,E.ROW_GRAND)}else if(O===lt){const q=f[H];for(let M=0;M<p;M++)M===q?o.pushValue(k,M,this._subtotalLabel(e,h,T),E.ROW_SUBTOTAL,w[H]):o.push(k,M,K,0,E.ROW_SUBTOTAL)}else{const q=this._labelStart(h,T,e);for(let M=q;M<=H;M++){const dt=vt(M),nt=f[M],rt=M===H&&V?E.ROW_PARENT:E.ROW_ITEM;if(dt===x){const Q=h.data[T];Q>=0&&o.pushValue(k,nt,n[Q].name,rt,w[M])}else{const Q=Ot(e.slots,M),ot=e.ancestorAt(W,Q),Y=t.showExpandButtons&&Q<e.k?1:0;if(M===H&&h.collapsed?.has(ot)&&this._form(dt)==="tabular")o.pushValue(k,nt,`${this._labelText(e,ot)} Total`,rt,w[M]+Y);else{const et=this._labelValue(e,ot),Jt=typeof et=="number"?o.format(e.fieldAt(Q).numFmt):0;o.pushValue(k,nt,et,rt,w[M]+Y,Jt)}}}}if(r===0||tt!==null&&tt.has(T))continue;const _t=h.data[T],At=h.func[T];for(let q=0;q<d;q++){const M=a.type[q];if(M===mt)continue;const dt=a.data[q],nt=_t>=0?_t:dt>=0?dt:r===1?0:-1;if(nt<0)continue;const rt=n[nt],Q=At??a.func[q],ot=this.show(rt,W,a.node[q],Q);let Y=j;O!==st&&M===st?Y=E.DATA_GRAND_COL:O===X&&!V&&M===lt&&(Y=E.DATA);const it=p+q,et=Q&&Q!==rt.agg&&!rt.numFmt?0:yt[nt];ot===null?t.showMissing===!1?o.pushValue(k,it,0,Y,J,et):t.emptyText!==""?o.pushValue(k,it,t.emptyText,Y,J,et):Y!==E.DATA&&o.push(k,it,K,0,Y,J,et):ot instanceof $&&t.errorText!==null?o.pushValue(k,it,t.errorText,Y,J,et):o.pushValue(k,it,ot,Y,J,et)}}const It=u?R+1:z+L,Mt=Math.max(b,l.length>0?2:0,u?1:0);if(It>ne||Mt>se)throw new S("The PivotTable is too large for a worksheet.");this.layout={cells:o,rows:It,cols:Mt,bodyCols:b,pageRows:i,pageFields:l,headerRows:v,labelCols:p,bodyTop:z,dataRows:L,colForLevel:f,indentForLevel:w,colRowBase:I,firstHeaderRow:u||y?1:r>1?0:1,firstDataRow:u?1:v,firstDataCol:p}}_labelStart(t,e,s){const n=t.level[e],o=t.first[e];if(o===0)return 0;for(let r=0;r<o;r++){const l=s.slots[r];if(l!==x&&this.opts(l)?.repeatLabels||l!==x&&this.spec.repeatLabels&&this._form(l)!=="compact")return r}return Math.min(o,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let o=0;o<e;o++)n.push(new Array(s).fill(null));for(let o=0;o<t.count;o++)n[t.rows[o]][t.cols[o]]=t.valueAt(o);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:o,cols:r}=this;if(t<s.pageRows-1){const i=s.pageFields[t];return i!==void 0&&e===1?{kind:"pageFilter",field:i}:null}const l=t-s.pageRows;if(l<0||t>=s.rows)return null;if(l===s.headerRows-1&&e<s.labelCols&&o.fields.length>0){const i=n.layout==="compact"?o.fields:o.slots.filter((u,f)=>u!==x&&s.colForLevel[f]===e);if(i.length>0)return{kind:"filter",axis:"row",fields:i}}if(l===0&&e>=s.labelCols&&r.fields.length>0&&s.colRowBase===1){const i=n.layout==="compact"?e===s.labelCols?r.fields:[]:r.slots.filter((u,f)=>u!==x&&f===e-s.labelCols);if(i.length>0)return{kind:"filter",axis:"col",fields:i}}if(l>=s.headerRows&&e<s.labelCols){const i=this._rowLabelAt(l-s.headerRows,e);if(i!==null)return i}if(l>=s.colRowBase&&l<s.headerRows&&e>=s.labelCols){const i=this._colLabelAt(e-s.labelCols,l-s.colRowBase);if(i!==null)return i}return l>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:l-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==X)return null;const o=this.layout.colForLevel;for(let r=n.level[t];r>=this._labelStart(n,t,s);r--)if(o[r]===e)return this._labelHit(s,n,t,r,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==X||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,o){const r=t.slots[n];if(r===x||r===void 0)return null;const l=Ot(t.slots,n),i=t.ancestorAt(e.node[s],l),u=l<t.k;return{kind:"label",axis:o,node:i,field:r,path:t.pathKeys(i),expandable:u,collapsed:u&&e.collapsed?.has(i)===!0}}togglesIn(t,e,s,n){const o=[],r=this.layout,{rows:l,cols:i}=this;if(this.spec.showExpandButtons===!1)return o;if(l.k>1)for(let u=Math.max(t,r.bodyTop);u<=Math.min(s,r.rows-1);u++)for(let f=e;f<=Math.min(n,r.labelCols-1);f++){const w=this._rowLabelAt(u-r.bodyTop,f);w!==null&&w.expandable&&o.push({row:u,col:f,collapsed:w.collapsed,indent:this._levelIndent(w)})}if(i.k>1){const u=r.pageRows+r.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,r.pageRows+r.headerRows-1);f++)for(let w=Math.max(e,r.labelCols);w<=Math.min(n,r.cols-1);w++){const p=this._colLabelAt(w-r.labelCols,f-u);p!==null&&p.expandable&&o.push({row:f,col:w,collapsed:p.collapsed,indent:0})}}return o}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,o=[];if(t.pageFields.forEach((r,l)=>o.push({row:l,col:1,axis:"page",fields:[r]})),e.fields.length>0&&n.showFieldHeaders!==!1){const r=t.pageRows+t.headerRows-1;n.layout==="compact"?o.push({row:r,col:0,axis:"row",fields:e.fields}):e.slots.forEach((l,i)=>{l!==x&&(i===0||t.colForLevel[i]!==t.colForLevel[i-1])&&o.push({row:r,col:t.colForLevel[i],axis:"row",fields:[l]})})}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const r=t.pageRows;n.layout==="compact"?o.push({row:r,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((l,i)=>{l!==x&&o.push({row:r,col:t.labelCols+i,axis:"col",fields:[l]})})}return o}}function Ot(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==x&&e++;return e}function De(c){const t=c.showAs?.type;return ae.has(t)?"0.00%":t==="index"?"0.00":"General"}function Fe(c,t,e,s){const n=e.count??10,o=e.by??"items",r=e.bottom===!0,l=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);l.sort((u,f)=>r?u[1]-f[1]:f[1]-u[1]);const i=new Set;if(o==="items"){if(l.length>0&&n>0){const u=l[Math.min(n,l.length)-1][1];for(const[f,w]of l)(r?w<=u:w>=u)&&i.add(f)}}else{const u=l.reduce((p,h)=>p+h[1],0),f=o==="percent"?u*n/100:n;let w=0;for(const[p,h]of l)if(i.add(p),w+=h,w>=f)break}return s?c.filter(u=>!i.has(u)):c.filter(u=>i.has(u))}function Se(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:G("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class Ze{constructor(t,e={}){this.cache=t,this.spec=Se(e),this.result=null,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new S("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this.result=new Me(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===x||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values=t.values.filter(n=>s(n.field))}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===B)}uniqueDataName(t,e=-1){let s=t,n=2;const o=r=>this.spec.values.some((l,i)=>i!==e&&l.name.toLowerCase()===r.toLowerCase());for(;o(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t],o=xt(n.isCalculated?"sum":e,n.name);return this.spec.values.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(o)}),this.spec.values.length>1&&!this.spec.rows.includes(x)&&!this.spec.cols.includes(x)&&this.spec.cols.push(x),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field],o=[xt(s.agg,n.name),`${le[s.agg]} of ${n.name}`].some(r=>new RegExp(`^${Qt(r)}\\d*$`).test(s.name));s.agg=e,o&&(s.name=this.uniqueDataName(xt(e,n.name),t))}place(t,e,s){const{spec:n}=this;for(const r of["rows","cols","filters"])n[r]=n[r].filter(l=>l!==t);if(t===x&&e==="filters")return;const o=n[e];s===void 0||s>o.length?o.push(t):o.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);e.values=e.values.filter(s=>s.field!==t),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}removeValue(t){const{spec:e}=this;e.values.splice(t,1),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==x),e.cols=e.cols.filter(s=>s!==x))}moveValue(t,e){const s=this.spec.values,[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n)}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){const e=this.cache.fields[t].ensure(),s=e.rank(),n=wt(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),o=new Array(e.items.length);for(let r=0;r<o.length;r++)o[s[r]]={id:r,key:ut(e.items[r]),label:e.labelOf(r),value:e.items[r],hidden:n[r]===1};return o}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,o=[];for(const l of Object.keys(this.spec.fieldOptions)){if(Number(l)===t)continue;const i=this.cache.fields[l];if(!i||i.removed||i.isCalculated)continue;const u=wt(i,this.spec.fieldOptions[l]);if(u!==null&&o.push([i.ensure().ids,u]),this.spec.fieldOptions[l].range||this.spec.fieldOptions[l].dateFilter){const f=zt(i,this.spec.fieldOptions[l]);o.push([i.rawIds,f])}}const{ids:r}=e;t:for(let l=0;l<n;l++){for(let i=0;i<o.length;i++)if(o[i][1][o[i][0][l]]===1)continue t;s[r[l]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(Lt),n=new Set(e.collapsed??[]),o=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(r=>r!==o))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(o=>ut(o)):[],this.rearrange()}}export{Ke as AGGS,kt as AGG_LABEL,Ne as CellBuffer,Qe as LABEL_FILTERS,Je as LINE,gt as PivotCache,S as PivotError,ft as PivotField,Me as PivotResult,Ze as PivotTable,E as ROLE,je as SHOW_AS,x as VALUES,ze as VALUE_FILTERS,qt as applyNumFmt,Nt as compileCalc,wt as hiddenItemFlags,ut as itemKey,ee as partsToSerial,pt as serialToParts,Ye as showAsNeedsBaseField,Xe as showAsNeedsBaseItem,Ht as storeColumn,xt as valueFieldName};
|
|
1
|
+
import{withNoDataItems as Zt}from"../slicers/pivot-file.js";import{dateOptionFlags as te}from"../slicers/date-filters.js";import{BOOL as at,CHUNK_BITS as Ct,CHUNK_MASK as Tt,EMPTY as K,ERR as ct,ERRORS as Dt,KIND_MASK as Ft,NUM as B,STR as Z}from"../core/sheet.js";import{formatGeneral as St,getFormatter as Vt,partsToSerial as ee,serialToParts as pt}from"../core/numfmt.js";import{MAX_COLS as se,MAX_ROWS as ne}from"../core/address.js";import{compareText as Ut,ERR as P,ERR_BY_INDEX as Rt,numberToText as re,XlError as $}from"../calc/values.js";import{FUNCS as oe}from"../calc/functions/registry.js";import"../calc/functions/index.js";import{t as G}from"../i18n/index.js";const L=-2,Ke=["sum","count","average","max","min","product","countNums","stdDev","stdDevp","var","varp"],kt={sum:"Sum",count:"Count",average:"Average",max:"Max",min:"Min",product:"Product",countNums:"Count Numbers",stdDev:"StdDev",stdDevp:"StdDevp",var:"Var",varp:"Varp"},le={...kt,countNums:"Count"};function Lt(c,t){switch(c){case"count":case"countNums":return G("pivot|Count of {field}",{field:t});case"average":return G("pivot|Average of {field}",{field:t});case"max":return G("pivot|Max of {field}",{field:t});case"min":return G("pivot|Min of {field}",{field:t});case"product":return G("pivot|Product of {field}",{field:t});case"stdDev":return G("pivot|StdDev of {field}",{field:t});case"stdDevp":return G("pivot|StdDevp of {field}",{field:t});case"var":return G("pivot|Var of {field}",{field:t});case"varp":return G("pivot|Varp of {field}",{field:t});default:return G("pivot|Sum of {field}",{field:t})}}const je=[["normal","No Calculation"],["percentOfTotal","% of Grand Total"],["percentOfCol","% of Column Total"],["percentOfRow","% of Row Total"],["percent","% Of"],["percentOfParentRow","% of Parent Row Total"],["percentOfParentCol","% of Parent Column Total"],["percentOfParent","% of Parent Total"],["difference","Difference From"],["percentDiff","% Difference From"],["runTotal","Running Total In"],["percentOfRunningTotal","% Running Total In"],["rankAscending","Rank Smallest to Largest"],["rankDescending","Rank Largest to Smallest"],["index","Index"]],ie=new Set(["percent","percentOfParent","difference","percentDiff","runTotal","percentOfRunningTotal","rankAscending","rankDescending"]),Ye=c=>ie.has(c),Xe=c=>c==="percent"||c==="difference"||c==="percentDiff",ae=new Set(["percentOfTotal","percentOfCol","percentOfRow","percent","percentOfParentRow","percentOfParentCol","percentOfParent","percentDiff","percentOfRunningTotal"]),Qe=["captionEqual","captionNotEqual","captionBeginsWith","captionNotBeginsWith","captionEndsWith","captionNotEndsWith","captionContains","captionNotContains","captionGreaterThan","captionGreaterThanOrEqual","captionLessThan","captionLessThanOrEqual","captionBetween","captionNotBetween"],ze=["valueEqual","valueNotEqual","valueGreaterThan","valueGreaterThanOrEqual","valueLessThan","valueLessThanOrEqual","valueBetween","valueNotBetween"],E={NONE:0,PAGE_LABEL:1,PAGE_VALUE:2,CORNER:3,HEADER_BLANK:4,COL_CAPTION:5,ROW_CAPTION:6,COL_ITEM:7,COL_SUBTOTAL:8,COL_GRAND:9,DATA_HEADER:10,ROW_ITEM:11,ROW_PARENT:12,ROW_SUBTOTAL:13,ROW_GRAND:14,DATA:15,DATA_PARENT:16,DATA_SUBTOTAL:17,DATA_GRAND_ROW:18,DATA_GRAND_COL:19,PLACEHOLDER:20},X=0,lt=1,st=2,mt=3,Je={ITEM:X,SUBTOTAL:lt,GRAND:st,BLANK:mt},Pt=1<<23,ce=1<<24,xt="";class S extends Error{constructor(t,e){super(G(t,e))}}function ut(c){if(c==null)return"blank";switch(typeof c){case"number":return`n${c}`;case"string":return`s${c.toLowerCase()}`;case"boolean":return c?"b1":"b0";default:return`e${c.code}`}}const Bt=c=>c===null?4:typeof c=="number"?0:typeof c=="string"?1:typeof c=="boolean"?2:3,ue=[["sun","mon","tue","wed","thu","fri","sat"],["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["january","february","march","april","may","june","july","august","september","october","november","december"]].map(c=>new Map(c.map((t,e)=>[t,e])));function fe(c){let t=ue,e=!1;for(const s of c){if(typeof s!="string")continue;e=!0;const n=s.toLowerCase();if(t=t.filter(o=>o.has(n)),t.length===0)return null}return e?t[0]:null}const $t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Gt=[31,29,31,30,31,30,31,31,30,31,30,31],he=["seconds","minutes","hours","days","months","quarters","years"],de={seconds:"Seconds",minutes:"Minutes",hours:"Hours",days:"Days",months:"Months",quarters:"Quarters",years:"Years"};function pe(c,t){let e=0;for(let s=0;s<c-1;s++)e+=Gt[s];return e+t-1}function me(c,t,e){switch(c){case"years":{const s=[];for(let n=t;n<=e;n++)s.push(String(n));return s}case"quarters":return["Qtr1","Qtr2","Qtr3","Qtr4"];case"months":return $t;case"days":{const s=[];return Gt.forEach((n,o)=>{for(let r=1;r<=n;r++)s.push(`${r}-${$t[o]}`)}),s}case"hours":{const s=[];for(let n=0;n<24;n++)s.push(`${n%12===0?12:n%12} ${n<12?"AM":"PM"}`);return s}default:{const s=[];for(let n=0;n<60;n++)s.push(`:${n<10?"0":""}${n}`);return s}}}function we(c,t,e){switch(c){case"years":return t.year-e;case"quarters":return Math.floor((t.month-1)/3);case"months":return t.month-1;case"days":return pe(t.month,t.day);case"hours":return Math.floor(t.ms/36e5);case"minutes":return Math.floor(t.ms/6e4)%60;default:return Math.floor(t.ms/1e3)%60}}class ft{constructor(t,e,s){this.cache=t,this.index=e,this.name=s,this.numFmt="General",this.isDate=!1,this.kinds=null,this.uniformKind=K,this.nums=null,this.strs=null,this.shared=null,this.rawIds=null,this.ids=null,this.items=null,this.group=null,this.base=-1,this.par=-1,this.formula=null,this.calc=null,this.removed=!1,this.xml=null,this._keys=null,this._rank=null}get isVirtual(){return this.base>=0||this.formula!==null}get isCalculated(){return this.formula!==null}reset(){this.shared=null,this.rawIds=null,this.invalidate()}invalidate(){this.ids=null,this.items=null,this._keys=null,this._rank=null}ensureRaw(){if(this.rawIds!==null)return this;if(this.base>=0){const l=this.cache.fields[this.base].ensureRaw();return this.rawIds=l.rawIds,this.shared=l.shared,this}const t=this.cache.recordCount,e=new Int32Array(t),s=[],{kinds:n,nums:o,strs:r}=this;if(r!==null)ye(this.cache,r,null,null,t,e,s);else if(o!==null&&n===null&&this.uniformKind===B){const l=new Map;let i=NaN,u=-1;for(let f=0;f<t;f++){const w=o[f];if(w!==i){let p=l.get(w);p===void 0&&(p=s.length,s.push(w),l.set(w,p)),i=w,u=p}e[f]=u}}else n!==null?Ae(this.cache,n,o,t,e,s):t>0&&s.push(null);return this.rawIds=e,this.shared=s,this}ensure(){if(this.ids!==null)return this;if(this.ensureRaw(),this.group===null)return this.ids=this.rawIds,this.items=this.shared,this;const{map:t,labels:e}=be(this),s=this.rawIds,n=s.length,o=new Int32Array(n);for(let r=0;r<n;r++)o[r]=t[s[r]];return this.ids=o,this.items=e,this.groupMap=t,this}ensureColumn(){if(this.nums!==null||this.strs!==null||this.rawIds===null)return this;if(this.base>=0)return this;const t=this.rawIds.length,e=new Uint8Array(t),s=new Float64Array(t),n=this.rawIds,o=this.shared,r=new Uint8Array(o.length),l=new Float64Array(o.length);o.forEach((i,u)=>{typeof i=="number"?(r[u]=B,l[u]=i):typeof i=="string"?r[u]=Z:typeof i=="boolean"?(r[u]=at,l[u]=i?1:0):i instanceof $&&(r[u]=ct,l[u]=i.index)});for(let i=0;i<t;i++){const u=n[i];e[i]=r[u],s[i]=l[u]}return this.kinds=e,this.nums=s,this}get keyIndex(){if(this._keys===null){this.ensure();const t=new Map;this.items.forEach((e,s)=>{const n=ut(e);t.has(n)||t.set(n,s)}),this._keys=t}return this._keys}keyOf(t){return ut(this.items[t])}labelOf(t){return this.labelOfValue(this.items[t])}labelOfValue(t){return t==null?"(blank)":typeof t=="string"?t:typeof t=="number"?this.numFmt!=="General"?Vt(this.numFmt).number(t):St(t):typeof t=="boolean"?t?"TRUE":"FALSE":t.code}rank(){if(this._rank!==null)return this._rank;this.ensure();const{items:t}=this,e=new Int32Array(t.length);if(this.group!==null&&this.group.kind!=="discrete")for(let s=0;s<e.length;s++)e[s]=s;else{const s=fe(t),n=Array.from(t.keys());n.sort((o,r)=>ge(t[o],t[r],s)),n.forEach((o,r)=>{e[o]=r})}return this._rank=e,e}}function ge(c,t,e){const s=Bt(c),n=Bt(t);return s!==n?s-n:s===0?c-t:s===1?e!==null?e.get(c.toLowerCase())-e.get(t.toLowerCase()):Ut(c,t):s===2?c===t?0:c?1:-1:s===3?c.index-t.index:0}function ye(c,t,e,s,n,o,r){let l=-1;for(let f=0;f<n;f++)t[f]>l&&(l=t[f]);const i=new Int32Array(l+1).fill(-1),u=new Map;for(let f=0;f<n;f++){const w=t[f];let p=i[w];if(p<0){const h=c.getString(w),a=h.toLowerCase();p=u.get(a),p===void 0&&(p=r.length,r.push(h),u.set(a,p)),i[w]=p}o[f]=p}}function Ae(c,t,e,s,n,o){const r=new Map,l=new Map,i=new Map,u=new Map;let f=-1;for(let w=0;w<s;w++){const p=t[w];let h;if(p===B){const a=e[w];h=r.get(a),h===void 0&&(h=o.length,o.push(a),r.set(a,h))}else if(p===Z){const a=e[w];if(h=i.get(a),h===void 0){const d=c.getString(a),m=d.toLowerCase();h=l.get(m),h===void 0&&(h=o.length,o.push(d),l.set(m,h)),i.set(a,h)}}else if(p===K)f<0&&(f=o.length,o.push(null)),h=f;else{const a=p*100+e[w];h=u.get(a),h===void 0&&(h=o.length,o.push(p===at?e[w]!==0:Rt[e[w]]??P.NA),u.set(a,h))}n[w]=h}}function be(c){const t=c.group,e=c.shared,s=new Int32Array(e.length);if(t.kind==="date"){const l=pt(t.start),i=pt(t.end),u=`<${Wt(t.start)}`,f=`>${Wt(t.end+1)}`,w=me(t.part,l.year,i.year);let p=[u,...w,f];t.labels&&t.labels.length===p.length&&(p=t.labels);for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<t.start?s[h]=0:a>=t.end+1?s[h]=p.length-1:s[h]=1+we(t.part,pt(a),l.year)}return{map:s,labels:p}}if(t.kind==="bins"){const{start:l,end:i,interval:u}=t,f=Math.max(1,Math.ceil((i-l)/u-1e-9)),w=[`<${bt(l)}`];for(let h=0;h<f;h++){const a=l+h*u,d=t.integer?Math.max(a+u-1,h===f-1?i:0):a+u;w.push(`${bt(a)}-${bt(d)}`)}w.push(`>${bt(i)}`);const p=t.labels&&t.labels.length===w.length?t.labels:w;for(let h=0;h<e.length;h++){const a=e[h];typeof a!="number"||a<l?s[h]=0:a>i?s[h]=f+1:s[h]=1+Math.min(f-1,Math.floor((a-l)/u+1e-9))}return{map:s,labels:p}}const n=t.groups.map(l=>l.name),o=new Map;t.groups.forEach((l,i)=>{for(const u of l.keys)o.set(u,i)});const r=new Map;for(let l=0;l<e.length;l++){const i=ut(e[l]);let u=o.get(i);u===void 0&&(u=r.get(i),u===void 0&&(u=n.length,n.push(e[l]),r.set(i,u))),s[l]=u}return{map:s,labels:n}}const bt=c=>re(Number(c.toPrecision(12)));function Wt(c){const t=pt(c);return`${t.month}/${t.day}/${t.year}`}class ve{constructor(){this.list=[],this.index=new Map}get size(){return this.list.length}get(t){return this.list[t]??""}add(t){let e=this.index.get(t);return e===void 0&&(e=this.list.length,this.list.push(t),this.index.set(t,e)),e}}function _e(c,t,e,s,n,o){const r=c.columns[t];if(r===void 0)return;const l=e+s;for(let i=e>>>Ct;i<=l-1>>>Ct;i++){const u=r[i];if(u===void 0)continue;const f=i<<Ct,w=Math.max(e,f)&Tt,p=Math.min(l-1,f+Tt)&Tt,h=f-e,a=u.kinds,d=u.values;for(let m=w;m<=p;m++)n[h+m]=a[m]&Ft,o[h+m]=d[m]}}class gt{constructor(){this.fields=[],this.recordCount=0,this.strings=new ve,this.source=null,this.generation=0,this.xml=null,this.id=0,this.needsRefresh=!1}getString(t){return this.strings.get(t)}field(t){if(typeof t=="number")return this.fields[t];const e=String(t).toLowerCase();return this.fields.find(s=>s.name.toLowerCase()===e&&!s.removed)}fieldIndex(t){if(typeof t=="number")return t;const e=this.field(t);if(!e)throw new S("Unknown field: {name}",{name:t});return e.index}static fromSheet(t,e,s){const n=new gt;return n.strings=t.strings,n.source={type:"range",book:t,sheet:e,range:s},n.refresh(),n}static fromTable(t,e){const s=new gt;return s.strings=t.strings,s.source={type:"table",book:t,table:e},s.refresh(),s}static fromRows(t,e){const s=new gt,n=e.length;return s.recordCount=n,t.forEach((o,r)=>{const l=new Uint8Array(n),i=new Float64Array(n);for(let f=0;f<n;f++){const w=e[f][r];typeof w=="number"?(l[f]=B,i[f]=w):typeof w=="string"?(l[f]=Z,i[f]=s.strings.add(w)):typeof w=="boolean"?(l[f]=at,i[f]=w?1:0):w instanceof $&&(l[f]=ct,i[f]=w.index)}const u=new ft(s,r,o);Ht(u,l,i,n),s.fields.push(u)}),s}static fromColumns(t,e,s){const n=new gt;return s&&(n.strings=s),n.recordCount=e,t.forEach((o,r)=>{const l=new ft(n,r,o.name);l.kinds=o.kinds??null,l.nums=o.nums??null,l.strs=o.strs??null,l.uniformKind=o.strs?Z:o.kinds?K:B,o.numFmt&&qt(l,o.numFmt),n.fields.push(l)}),n}refresh(){const t=this.source;if(t===null){for(const p of this.fields)p.invalidate();return this.generation++,!1}const{book:e}=t;this.strings=e.strings;let s,n,o,r,l;if(t.type==="table"){const p=t.table;s=p.sheet??e.sheets[p.sheetIndex],n=p.r0,o=p.c0,r=p.r1-(p.totalsRows??0),l=p.c1}else{if({sheet:s}=t,typeof s=="string"&&(s=e.sheets.find(p=>p.name===t.sheet)),!s)throw new S("The PivotTable source sheet no longer exists.");({r0:n,c0:o,r1:r,c1:l}=t.range),r=Math.min(r,s.maxRow),l=Math.min(l,s.maxCol)}if(r<=n)throw new S("The PivotTable source needs a header row and at least one row of data.");const i=r-n,u=new Map,f=[];for(let p=o;p<=l;p++){const h=Ce(e,s,n,p);if(h==="")throw new S("The PivotTable field name is not valid: every source column needs a header.");const a=h.toLowerCase(),d=(u.get(a)??0)+1;u.set(a,d),f.push(d>1?`${h}${d}`:h)}const w=new Map(this.fields.filter(p=>!p.isVirtual).map(p=>[p.name.toLowerCase(),p]));this.recordCount=i,f.forEach((p,h)=>{let a=w.get(p.toLowerCase());a?w.delete(p.toLowerCase()):(a=new ft(this,this.fields.length,p),this.fields.push(a));const d=o+h,m=new Uint8Array(i),A=new Float64Array(i);_e(s,d,n+1,i,m,A),Ht(a,m,A,i),a.removed=!1,a.reset();for(let g=0;g<i;g++)if(m[g]!==K){qt(a,e.styles.get(s.style(n+1+g,d)).numFmt);break}});for(const p of w.values())p.removed=!0,p.kinds=null,p.nums=null,p.strs=null,p.uniformKind=K,p.reset();for(const p of this.fields)p.isVirtual&&p.reset();return this._rescaleGroups(),this.generation++,this.needsRefresh=!1,!0}_rescaleGroups(){for(const t of this.fields){const e=t.group;if(t.base>=0||t.removed||e===null||e.kind==="discrete"||!(e.autoStart||e.autoEnd))continue;let s;try{s=this._numericRange(t)}catch{continue}for(let n=t;n;n=n.par>=0?this.fields[n.par]:null){const o=n.group;o.autoStart&&(o.start=e.kind==="date"?Math.floor(s.min):s.min),o.autoEnd&&(o.end=e.kind==="date"?Math.floor(s.max):s.max),o.labels=void 0}}}addCalculatedField(t,e){const s=new ft(this,this.fields.length,this._uniqueName(t));return s.formula=e.replace(/^\s*=\s*/,""),s.calc=Nt(s.formula,this),this.fields.push(s),s.index}updateCalculatedField(t,e){const s=this.fields[t],n=e.replace(/^\s*=\s*/,"");s.calc=Nt(n,this),s.formula=n,this.generation++}_uniqueName(t){let e=t,s=2;for(;this.fields.some(n=>n.name.toLowerCase()===e.toLowerCase());)e=`${t}${s++}`;return e}_numericRange(t){t.ensureRaw();let e=1/0,s=-1/0,n=!0;for(const o of t.shared){if(typeof o!="number")throw new S("Cannot group that selection.");o<e&&(e=o),o>s&&(s=o),Number.isInteger(o)||(n=!1)}if(e===1/0)throw new S("Cannot group that selection.");return{min:e,max:s,integer:n}}groupDates(t,e,{start:s,end:n}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");const{min:r,max:l}=this._numericRange(o),i=he.filter(p=>e.includes(p));if(i.length===0)throw new S("Choose at least one grouping unit.");this.ungroup(t);const u={start:s??Math.floor(r),end:n??Math.floor(l)};o.group={kind:"date",part:i[0],...u,autoStart:s===void 0,autoEnd:n===void 0},o.invalidate();const f=[t];let w=o;for(const p of i.slice(1)){const h=new ft(this,this.fields.length,this._uniqueName(de[p]));h.base=t,h.group={kind:"date",part:p,...u,autoStart:s===void 0,autoEnd:n===void 0},this.fields.push(h),w.par=h.index,w=h,f.unshift(h.index)}return f}groupNumbers(t,{start:e,end:s,interval:n=10}={}){const o=this.fields[t];if(o.isCalculated||o.base>=0)throw new S("Cannot group that selection.");if(!(n>0))throw new S("The grouping interval must be greater than zero.");const{min:r,max:l,integer:i}=this._numericRange(o);this.ungroup(t);const u=e??r,f=s??l;if(f<=u)throw new S("The ending value must be greater than the starting value.");return o.group={kind:"bins",start:u,end:f,interval:n,integer:i&&Number.isInteger(u)&&Number.isInteger(n),autoStart:e===void 0,autoEnd:s===void 0},o.invalidate(),t}groupText(t,e,s){const n=this.fields[t];if(n.isCalculated)throw new S("Cannot group that selection.");n.ensureRaw();let o=n.par>=0?this.fields[n.par]:null;if(o&&o.group?.kind!=="discrete")throw new S("Cannot group that selection.");return o?(o.group.groups.push(...e),o.invalidate(),o.index):(o=new ft(this,this.fields.length,this._uniqueName(s??`${n.name}2`)),o.base=t,o.group={kind:"discrete",groups:e.map(r=>({name:r.name,keys:[...r.keys]}))},this.fields.push(o),n.par=o.index,o.index)}ungroup(t){const e=this.fields[t];if(e.base>=0&&e.group?.kind==="discrete"){this.fields[e.base].par=-1,e.removed=!0,e.group={kind:"discrete",groups:[]},e.invalidate();return}e.group=null,e.invalidate();let s=e.par;for(e.par=-1;s>=0;){const n=this.fields[s];n.removed=!0,s=n.par,n.par=-1}}}function qt(c,t){c.numFmt=t??"General";try{c.isDate=c.numFmt!=="General"&&Vt(c.numFmt).isDate===!0}catch{c.isDate=!1}}function Ce(c,t,e,s){const n=t.kind(e,s)&Ft,o=t.value(e,s);return n===Z?c.strings.get(o).trim():n===B?St(o):n===at?o?"TRUE":"FALSE":n===ct?Dt[o]??"":""}function Ht(c,t,e,s){let n=0,o=0;for(let r=0;r<s;r++){const l=t[r];l===B?n++:l===Z&&o++}if(c.strs=null,c.kinds=null,c.nums=null,n===s&&s>0)c.uniformKind=B,c.nums=e;else if(o===s&&s>0){c.uniformKind=Z;const r=new Int32Array(s);for(let l=0;l<s;l++)r[l]=e[l];c.strs=r}else c.uniformKind=K,c.kinds=t,c.nums=e}const Te=["<=",">=","<>","+","-","*","/","^","%","(",")",",","=","<",">","&"];function Re(c){const t=[];let e=0;for(;e<c.length;){const s=c[e];if(s<=" ")e++;else if(s>="0"&&s<="9"||s==="."&&c[e+1]>="0"&&c[e+1]<="9"){const n=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(c.slice(e));t.push({t:"num",v:Number(n[0])}),e+=n[0].length}else if(s==="'"||s==='"'){let n=e+1,o="";for(;;){if(n>=c.length)throw new S("The formula has an unmatched quote.");if(c[n]===s){if(c[n+1]!==s)break;n++}o+=c[n++]}t.push({t:s==="'"?"name":"str",v:o}),e=n+1}else if(/[\p{L}_\\]/u.test(s)){const n=/^[\p{L}\p{N}_.\\]+/u.exec(c.slice(e));t.push({t:"name",v:n[0],bare:!0}),e+=n[0].length}else{const n=Te.find(o=>c.startsWith(o,e));if(!n)throw new S("The formula has an unexpected character: {char}",{char:s});t.push({t:"op",v:n}),e+=n.length}}return t}const Kt=c=>c instanceof $?c:null,F=c=>{if(typeof c=="number")return c;if(typeof c=="boolean")return c?1:0;if(c===null)return 0;if(c instanceof $)throw c;const t=Number(c);if(typeof c=="string"&&c.trim()!==""&&!Number.isNaN(t))return t;throw P.VALUE},jt={IF:c=>{const t=c[0]();if(Kt(t))throw t;return(typeof t=="number"?t!==0:t===!0)?c[1]?c[1]():!0:c[2]?c[2]():!1},IFERROR:c=>{try{const t=c[0]();return Kt(t)?c[1]():t}catch(t){if(t instanceof $)return c[1]();throw t}},AND:c=>c.every(t=>F(t())!==0),OR:c=>c.some(t=>F(t())!==0),NOT:c=>F(c[0]())===0,SUM:c=>c.reduce((t,e)=>t+F(e()),0),MIN:c=>Math.min(...c.map(t=>F(t()))),MAX:c=>Math.max(...c.map(t=>F(t()))),AVERAGE:c=>c.reduce((t,e)=>t+F(e()),0)/c.length,COUNT:c=>c.length,TRUE:()=>!0,FALSE:()=>!1};function Nt(c,t){const e=Re(c);let s=0;const n=new Set,o=g=>e[s]?.t==="op"&&e[s].v===g,r=()=>new S("The formula is not valid."),l=g=>{const y=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&!b.isCalculated),v=t.fields.find(b=>b.name.toLowerCase()===g.v.toLowerCase()&&b.isCalculated);if(v){for(const b of v.calc.refs)n.add(b);return b=>v.calc.fn(b)}if(!y)throw new S("The formula refers to an unknown field: {name}",{name:g.v});n.add(y.index);const _=y.index;return b=>b(_)},i=()=>{const g=e[s];if(!g)throw r();if(g.t==="num"){s++;const y=g.v;return()=>y}if(g.t==="str"){s++;const y=g.v;return()=>y}if(g.t==="name"){if(s++,g.bare&&o("(")){s++;const y=[];if(!o(")"))for(y.push(a());o(",");)s++,y.push(a());if(!o(")"))throw r();return s++,d(g.v.toUpperCase(),y)}if(g.bare&&m.has(g.v.toUpperCase())&&!t.field(g.v)){const y=jt[g.v.toUpperCase()];return()=>y([])}return l(g)}if(o("(")){s++;const y=a();if(!o(")"))throw r();return s++,y}throw r()},u=()=>{let g=i();for(;o("%");){s++;const y=g;g=v=>F(y(v))/100}return g},f=()=>{if(o("-")){s++;const g=f();return y=>-F(g(y))}return o("+")?(s++,f()):u()},w=()=>{let g=f();for(;o("^");){s++;const y=g,v=f();g=_=>{const b=F(y(_))**F(v(_));if(!Number.isFinite(b))throw P.NUM;return b}}return g},p=()=>{let g=w();for(;o("*")||o("/");){const y=e[s++].v,v=g,_=w();g=y==="*"?b=>F(v(b))*F(_(b)):b=>{const x=F(_(b));if(x===0)throw P.DIV0;return F(v(b))/x}}return g},h=()=>{let g=p();for(;o("+")||o("-");){const y=e[s++].v,v=g,_=p();g=y==="+"?b=>F(v(b))+F(_(b)):b=>F(v(b))-F(_(b))}return g},a=()=>{let g=h();for(;e[s]?.t==="op"&&["=","<>","<",">","<=",">="].includes(e[s].v);){const y=e[s++].v,v=g,_=h();g=b=>{const x=F(v(b)),R=F(_(b));switch(y){case"=":return x===R;case"<>":return x!==R;case"<":return x<R;case">":return x>R;case"<=":return x<=R;default:return x>=R}}}return g},d=(g,y)=>{const v=jt[g];if(v)return b=>v(y.map(x=>()=>x(b)));const _=oe.get(g);if(!_||_.kind!=="lift")throw new S("The formula uses a function a calculated field can't call: {name}",{name:g});if(y.length<_.min||y.length>_.max)throw r();return b=>{const x=y.map(R=>R(b));for(const R of x)if(R instanceof $)throw R;return _.fn(...x)}},m=new Set(["TRUE","FALSE"]),A=a();if(s<e.length)throw r();return{fn:A,refs:[...n]}}const ke={sum:"sum",average:"sum",count:"",countNums:"",max:"mm",min:"mm",product:"prod",stdDev:"var",stdDevp:"var",var:"var",varp:"var"};class Et{constructor(t,e){this.size=t,this.cnt=new Int32Array(t),this.num=new Int32Array(t),this.sum=e.sum?new Float64Array(t):null,this.min=e.mm?new Float64Array(t).fill(1/0):null,this.max=e.mm?new Float64Array(t).fill(-1/0):null,this.prod=e.prod?new Float64Array(t).fill(1):null,this.mean=e.var?new Float64Array(t):null,this.m2=e.var?new Float64Array(t):null,this.err=null}merge(t,e,s){const n=e.cnt[s];if(n===0)return;this.cnt[t]+=n;const o=e.num[s],r=this.num[t];if(this.num[t]=r+o,e.err!==null&&e.err[s]!==0&&(this.err===null&&(this.err=new Int8Array(this.size)),this.err[t]===0&&(this.err[t]=e.err[s])),o!==0&&(this.sum!==null&&(this.sum[t]+=e.sum[s]),this.min!==null&&(e.min[s]<this.min[t]&&(this.min[t]=e.min[s]),e.max[s]>this.max[t]&&(this.max[t]=e.max[s])),this.prod!==null&&(this.prod[t]*=e.prod[s]),this.mean!==null)){const l=e.mean[s]-this.mean[t],i=r+o;this.m2[t]+=e.m2[s]+l*l*r*o/i,this.mean[t]+=l*o/i}}value(t,e){const s=this.cnt[t];if(s===0)return null;if(e==="count")return s;if(e==="countNums")return this.num[t];if(this.err!==null&&this.err[t]!==0)return Rt[this.err[t]-1];const n=this.num[t];switch(e){case"sum":return this.sum[t];case"average":return n===0?P.DIV0:this.sum[t]/n;case"max":return n===0?0:this.max[t];case"min":return n===0?0:this.min[t];case"product":return n===0?0:this.prod[t];case"stdDev":return n<2?P.DIV0:Math.sqrt(this.m2[t]/(n-1));case"stdDevp":return n<1?P.DIV0:Math.sqrt(this.m2[t]/n);case"var":return n<2?P.DIV0:this.m2[t]/(n-1);case"varp":return n<1?P.DIV0:this.m2[t]/n;default:return null}}}function Le(c,t,e,s){const{cnt:n,num:o}=c;t.base<0&&t.ensureColumn();const{kinds:r,nums:l}=t;if(l===null||t.base>=0){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}return}if(r===null){for(let a=0;a<s;a++){const d=e[a];d>=0&&n[d]++}o.set(n)}else for(let a=0;a<s;a++){const d=e[a];if(d<0)continue;const m=r[a];m!==K&&(n[d]++,m===B?o[d]++:m===ct&&(c.err===null&&(c.err=new Int8Array(c.size)),c.err[d]===0&&(c.err[d]=l[a]+1)))}const{sum:i,min:u,max:f,prod:w,mean:p,m2:h}=c;if(i!==null)if(r===null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(i[d]+=l[a])}else for(let a=0;a<s;a++){const d=e[a];d>=0&&r[a]===B&&(i[d]+=l[a])}if(u!==null)for(let a=0;a<s;a++){const d=e[a];if(d<0||r!==null&&r[a]!==B)continue;const m=l[a];m<u[d]&&(u[d]=m),m>f[d]&&(f[d]=m)}if(w!==null)for(let a=0;a<s;a++){const d=e[a];d>=0&&(r===null||r[a]===B)&&(w[d]*=l[a])}if(p!==null){const a=new Int32Array(c.size);for(let d=0;d<s;d++){const m=e[d];if(m<0||r!==null&&r[d]!==B)continue;const A=++a[m],g=l[d]-p[m];p[m]+=g/A,h[m]+=g*(l[d]-p[m])}}}class xe{constructor(t,e,s){this.fields=e,this.slots=s,this.k=e.length,this.leaf=null,this.nLeaves=1,this.levelBase=[1],this.nNodes=1,this.parent=new Int32Array([-1]),this.item=new Int32Array([-1]),this.depth=new Uint8Array(1),this.cache=t,this.alive=null,this.childStart=null,this.childList=null,this.pos=null,this._childIndex=null,this.lines=null}leafNode(t){return this.k===0?0:this.levelBase[this.k-1]+t}ancestorAt(t,e){let s=t;for(;this.depth[s]>e;)s=this.parent[s];return this.depth[s]===e?s:-1}fieldAt(t){return this.cache.fields[this.fields[t-1]]}children(t){return this.childList.subarray(this.childStart[t],this.childStart[t+1])}findChild(t,e){if(this._childIndex===null){const s=new Map;this.stride=1;for(const n of this.fields)this.stride=Math.max(this.stride,this.cache.fields[n].items.length+1);for(let n=1;n<this.nNodes;n++)this.alive[n]&&s.set(this.parent[n]*this.stride+this.item[n],n);this._childIndex=s}return this._childIndex.get(t*this.stride+e)??-1}pathKeys(t){const e=[];for(let s=t;s>0;s=this.parent[s])e.push(this.fieldAt(this.depth[s]).keyOf(this.item[s]));return e.reverse()}peer(t,e,s){if(s<0)return-1;if(this.depth[t]===e)return s;const n=[];for(let r=t;this.depth[r]>e;r=this.parent[r])n.push(this.item[r]);let o=s;for(let r=n.length-1;r>=0&&o>=0;r--)o=this.findChild(o,n[r]);return o}}function Yt(c,t,e,s,n,o=null){const r=new xe(c,t,e),l=t.length;if(l===0)return r;let i=null,u=1;const f=[];for(let h=0;h<l;h++){const a=c.fields[t[h]].ensure(),d=a.ids,m=a.items.length,A=u*m,g=new Int32Array(s),y=Math.min(A,Math.max(s,1)),v=new Int32Array(y),_=new Int32Array(y);let b=0;if(A<=Pt){const D=new Int32Array(A).fill(-1);if(i===null)for(let T=0;T<s;T++){if(n!==null&&n[T]===0){g[T]=-1;continue}const N=d[T];let U=D[N];U<0&&(U=b++,D[N]=U,_[U]=N),g[T]=U}else for(let T=0;T<s;T++){const N=i[T];if(N<0){g[T]=-1;continue}const U=N*m+d[T];let I=D[U];I<0&&(I=b++,D[U]=I,v[I]=N,_[I]=d[T]),g[T]=I}}else{const D=new Map;for(let T=0;T<s;T++){const N=i===null?0:i[T];if(N<0||i===null&&n!==null&&n[T]===0){g[T]=-1;continue}const U=N*m+d[T];let I=D.get(U);I===void 0&&(I=b++,D.set(U,I),v[I]=N,_[I]=d[T]),g[T]=I}}const x=o?.(t[h]),R=x?Zt({parents:v,items:_,count:b},u,m,x.hide):{parents:v,items:_,count:b};f.push(R),i=g,u=Math.max(R.count,1)}r.leaf=i,r.nLeaves=f[l-1].count;let w=1;const p=[];for(const h of f)p.push(w),w+=h.count;return r.levelBase=p,r.nNodes=w,r.parent=new Int32Array(w),r.item=new Int32Array(w),r.depth=new Uint8Array(w),r.parent[0]=-1,r.item[0]=-1,f.forEach((h,a)=>{const d=p[a],m=a===0?0:p[a-1];for(let A=0;A<h.count;A++)r.parent[d+A]=a===0?0:m+h.parents[A],r.item[d+A]=h.items[A],r.depth[d+A]=a+1}),r}class Ne{constructor(t=1024){this.count=0,this.capacity=t,this.rows=new Int32Array(t),this.cols=new Int32Array(t),this.kinds=new Uint8Array(t),this.values=new Float64Array(t),this.roles=new Uint8Array(t),this.levels=new Uint8Array(t),this.formats=new Uint16Array(t),this.texts=[],this._textIndex=new Map,this.formatList=["General"],this._formatIndex=new Map([["General",0]])}_grow(){const t=this.capacity*2,e=(s,n)=>{const o=new s(t);return o.set(n),o};this.rows=e(Int32Array,this.rows),this.cols=e(Int32Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.values=e(Float64Array,this.values),this.roles=e(Uint8Array,this.roles),this.levels=e(Uint8Array,this.levels),this.formats=e(Uint16Array,this.formats),this.capacity=t}format(t){let e=this._formatIndex.get(t);return e===void 0&&(e=this.formatList.length,this.formatList.push(t),this._formatIndex.set(t,e)),e}text(t){let e=this._textIndex.get(t);return e===void 0&&(e=this.texts.length,this.texts.push(t),this._textIndex.set(t,e)),e}push(t,e,s,n,o,r=0,l=0){this.count===this.capacity&&this._grow();const i=this.count++;this.rows[i]=t,this.cols[i]=e,this.kinds[i]=s,this.values[i]=n,this.roles[i]=o,this.levels[i]=r,this.formats[i]=l}pushValue(t,e,s,n,o=0,r=0){s==null?this.push(t,e,K,0,n,o,r):typeof s=="number"?this.push(t,e,B,s,n,o,r):typeof s=="string"?this.push(t,e,Z,this.text(s),n,o,r):typeof s=="boolean"?this.push(t,e,at,s?1:0,n,o,r):this.push(t,e,ct,s.index,n,o,r)}valueAt(t){switch(this.kinds[t]){case B:return this.values[t];case Z:return this.texts[this.values[t]];case at:return this.values[t]!==0;case ct:return Dt[this.values[t]]??"#N/A";default:return null}}}function Xt(c){const t=c.replace(/[.+^${}()|[\]\\*?~]/g,e=>e==="*"?".*":e==="?"?".":`\\${e}`);return new RegExp(`^${t}$`,"is")}const Qt=c=>c.replace(/[.+^${}()|[\]\\]/g,"\\$&");function Ee(c){const{op:t}=c,e=String(c.value??""),s=String(c.value2??""),n=e.split(/([*?])/).map(r=>r==="*"?".*":r==="?"?".":Qt(r)).join(""),o=(r,l,i)=>{const u=typeof l=="number"?l:Number.NaN,f=i.trim()===""?Number.NaN:Number(i);return!Number.isNaN(u)&&!Number.isNaN(f)?u-f:Ut(r,i)};switch(t){case"captionEqual":{const r=Xt(e);return l=>r.test(l)}case"captionNotEqual":{const r=Xt(e);return l=>!r.test(l)}case"captionBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>r.test(l)}case"captionNotBeginsWith":{const r=new RegExp(`^${n}`,"is");return l=>!r.test(l)}case"captionEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>r.test(l)}case"captionNotEndsWith":{const r=new RegExp(`${n}$`,"is");return l=>!r.test(l)}case"captionContains":{const r=new RegExp(n,"is");return l=>r.test(l)}case"captionNotContains":{const r=new RegExp(n,"is");return l=>!r.test(l)}case"captionGreaterThan":return(r,l)=>o(r,l,e)>0;case"captionGreaterThanOrEqual":return(r,l)=>o(r,l,e)>=0;case"captionLessThan":return(r,l)=>o(r,l,e)<0;case"captionLessThanOrEqual":return(r,l)=>o(r,l,e)<=0;case"captionBetween":return(r,l)=>o(r,l,e)>=0&&o(r,l,s)<=0;case"captionNotBetween":return(r,l)=>o(r,l,e)<0||o(r,l,s)>0;default:return()=>!0}}function Oe(c){const t=Number(c.value),e=Number(c.value2);switch(c.op){case"valueEqual":return s=>s===t;case"valueNotEqual":return s=>s!==t;case"valueGreaterThan":return s=>s>t;case"valueGreaterThanOrEqual":return s=>s>=t;case"valueLessThan":return s=>s<t;case"valueLessThanOrEqual":return s=>s<=t;case"valueBetween":return s=>s>=Math.min(t,e)&&s<=Math.max(t,e);case"valueNotBetween":return s=>s<Math.min(t,e)||s>Math.max(t,e);default:return()=>!0}}function wt(c,t){if(!t)return null;const e=t.hidden&&t.hidden.length>0;if(!e&&!t.labelFilter)return null;c.ensure();const s=new Uint8Array(c.items.length);if(e){const n=c.keyIndex;for(const o of t.hidden){const r=n.get(o);r!==void 0&&(s[r]=1)}}if(t.labelFilter){const n=Ee(t.labelFilter);c.items.forEach((o,r)=>{n(c.labelOfValue(o),o)||(s[r]=1)})}return s}function zt(c,t){return c.ensureRaw(),te(c.shared,t)}class Ie{constructor(t,e){this.rows=t,this.cols=e,this.dense=t*e<=ce,this.map=this.dense?null:new Map,this.size=this.dense?t*e:0}ensure(t,e){const s=t*this.cols+e;if(this.dense)return s;let n=this.map.get(s);return n===void 0&&(n=this.size++,this.map.set(s,n)),n}get(t,e){const s=t*this.cols+e;return this.dense?s:this.map.get(s)??-1}}class Me{constructor(t){this.pivot=t,this.cache=t.cache,this.spec=t.spec,this._aggregate(),this._arrange()}opts(t){return this.spec.fieldOptions[t]??null}_resolveData(){const{cache:t,spec:e}=this,s=new Map,n=(r,l)=>{let i=s.get(r);i===void 0&&(i={sum:!1,mm:!1,prod:!1,var:!1},s.set(r,i));const u=ke[l];u&&(i[u]=!0)},o=new Set;for(const r of Object.keys(e.fieldOptions)){const l=e.fieldOptions[r].subtotals;if(Array.isArray(l))for(const i of l)o.add(i)}this.data=e.values.map((r,l)=>{const i=t.fields[r.field],u={index:l,field:r.field,name:r.name,agg:r.agg,showAs:r.showAs??null,numFmt:r.numFmt??null,calc:null};if(i.isCalculated){u.calc=i.calc??(i.calc=Nt(i.formula,t));for(const f of u.calc.refs)n(f,"sum")}else{n(r.field,r.agg);for(const f of o)n(r.field,f)}return u}),this.needs=s}_recordMask(t){const{spec:e,cache:s}=this;let n=null;for(const o of Object.keys(e.fieldOptions)){const r=s.fields[o];if(!r||r.removed||r.isCalculated)continue;const l=wt(r,e.fieldOptions[o]);if(l!==null){n===null&&(n=new Uint8Array(t).fill(1));const i=r.ensure().ids;for(let u=0;u<t;u++)l[i[u]]===1&&(n[u]=0)}if(e.fieldOptions[o].range||e.fieldOptions[o].dateFilter){n===null&&(n=new Uint8Array(t).fill(1));const i=zt(r,e.fieldOptions[o]),u=r.rawIds;for(let f=0;f<t;f++)i[u[f]]===1&&(n[f]=0)}}return n}_aggregate(){const{cache:t,spec:e}=this,s=t.recordCount;this._resolveData();const n=this.data.length,o=y=>y.filter(v=>v!==L||n>1);let r=o(e.rows),l=o(e.cols);n>1&&!r.includes(L)&&!l.includes(L)&&(l=[...l,L]),r=r.filter(y=>y===L||!t.fields[y].removed),l=l.filter(y=>y===L||!t.fields[y].removed);const i=this._recordMask(s);this.mask=i;const u=y=>{const v=e.fieldOptions[y];return v?.showAll?{hide:wt(t.fields[y],v)}:null},f=Yt(t,r.filter(y=>y!==L),r,s,i,u),w=Yt(t,l.filter(y=>y!==L),l,s,i,u);this.rows=f,this.cols=w;let p,h,a,d;const m=f.nLeaves,A=w.nLeaves;if(f.leaf!==null&&w.leaf!==null){const y=f.leaf,v=w.leaf;p=new Int32Array(s);const _=m*A,b=Math.min(_,Math.max(s,1));if(h=new Int32Array(b),a=new Int32Array(b),d=0,_<=Pt){const x=new Int32Array(_).fill(-1);for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const T=D*A+v[R];let N=x[T];N<0&&(N=d++,x[T]=N,h[N]=D,a[N]=v[R]),p[R]=N}}else{const x=new Map;for(let R=0;R<s;R++){const D=y[R];if(D<0){p[R]=-1;continue}const T=D*A+v[R];let N=x.get(T);N===void 0&&(N=d++,x.set(T,N),h[N]=D,a[N]=v[R]),p[R]=N}}}else if(f.leaf!==null||w.leaf!==null){p=f.leaf??w.leaf,d=f.leaf!==null?m:A;const y=new Int32Array(d);for(let _=0;_<d;_++)y[_]=_;const v=new Int32Array(d);h=f.leaf!==null?y:v,a=f.leaf!==null?v:y}else{if(p=new Int32Array(s),d=1,i!==null)for(let y=0;y<s;y++)i[y]===0&&(p[y]=-1);h=new Int32Array(1),a=new Int32Array(1)}this.cellCount=d,this.cellRow=h,this.cellCol=a,this.cells=p;const g=new Map;for(const[y,v]of this.needs){const _=new Et(d,v);Le(_,t.fields[y],p,s),g.set(y,_)}this.leafAccs=g,this._applyValueFilters(),this._rollUp()}_slotValue(t,e,s,n){if(t.calc!==null){let o=!1;const r=l=>{const i=e.get(l);if(i.cnt[s]!==0&&(o=!0),i.err!==null&&i.err[s]!==0)throw Rt[i.err[s]-1];return i.sum[s]};try{const l=t.calc.fn(r);return o?typeof l=="number"?Number.isFinite(l)?l:P.NUM:typeof l=="boolean"?l?1:0:l instanceof $?l:P.VALUE:null}catch(l){if(l instanceof $)return l;throw l}}return e.get(t.field).value(s,n??t.agg)}_applyValueFilters(){const{rows:t,cols:e,data:s}=this;this.rowDead=new Uint8Array(t.nNodes),this.colDead=new Uint8Array(e.nNodes);const n=(o,r,l)=>{for(let i=1;i<=o.k;i++){const u=o.fields[i-1],f=this.opts(u);if(!f||!f.valueFilter&&!f.top)continue;const w=f.valueFilter??f.top,p=s[w.data??0];if(!p)continue;const h=this._nodeAccs(o,p,l),a=o.levelBase[i-1],d=i<o.k?o.levelBase[i]:o.nNodes,m=new Map;for(let A=a;A<d;A++){if(r[A]||r[o.parent[A]]){r[A]=1;continue}const g=o.parent[A];let y=m.get(g);y===void 0&&(y=[],m.set(g,y)),y.push(A)}for(const A of m.values()){const g=y=>{const v=this._slotValue(p,h,y,null);return typeof v=="number"?v:null};if(f.valueFilter){const y=Oe(f.valueFilter);for(const v of A){const _=g(v);(_===null||!y(_))&&(r[v]=1)}}if(f.top){const y=A.filter(v=>!r[v]);for(const v of Fe(y,g,f.top,!0))r[v]=1}}for(let A=d;A<o.nNodes;A++)r[o.parent[A]]&&(r[A]=1)}};n(t,this.rowDead,!0),n(e,this.colDead,!1)}_nodeAccs(t,e,s){const n=e.calc!==null?e.calc.refs:[e.field],o=new Map;for(const a of n)o.set(a,new Et(t.nNodes,this.needs.get(a)));const r=[...o.entries()].map(([a,d])=>[d,this.leafAccs.get(a)]),{cellRow:l,cellCol:i,rows:u,cols:f,rowDead:w,colDead:p}=this,h=s?l:i;for(let a=0;a<this.cellCount;a++){const d=u.leafNode(l[a]),m=f.leafNode(i[a]);if(w[d]||p[m])continue;let A=t.leafNode(h[a]);for(;A>=0;){for(const[g,y]of r)g.merge(A,y,a);A=t.parent[A]}}return o}_rollUp(){const{rows:t,cols:e,cellRow:s,cellCol:n,rowDead:o,colDead:r,cellCount:l}=this,i=new Uint8Array(t.nNodes),u=new Uint8Array(e.nNodes),f=new Ie(t.nNodes,e.nNodes),w=t.parent,p=e.parent,h=new Uint8Array(l);for(let g=0;g<l;g++){const y=t.leafNode(s[g]),v=e.leafNode(n[g]);if(!(o[y]||r[v])){h[g]=1;for(let _=y;_>=0;_=w[_])if(i[_]=1,!f.dense)for(let b=v;b>=0;b=p[b])f.ensure(_,b);for(let _=v;_>=0;_=p[_])u[_]=1}}t.alive=i,e.alive=u;const a=new Map,d=[];for(const[g,y]of this.needs){const v=new Et(Math.max(f.size,1),y);a.set(g,v),d.push([v,this.leafAccs.get(g)])}const m=f.dense,A=f.cols;for(let g=0;g<l;g++){if(h[g]===0)continue;const y=t.leafNode(s[g]),v=e.leafNode(n[g]);for(let _=y;_>=0;_=w[_])for(let b=v;b>=0;b=p[b]){const x=m?_*A+b:f.get(_,b);for(let R=0;R<d.length;R++)d[R][0].merge(x,d[R][1],g)}}this.slots=f,this.accs=a,this.cells=null,t.leaf=null,e.leaf=null}raw(t,e,s,n=null){if(e<0||s<0)return null;const o=this.slots.get(e,s);return o<0?null:this._slotValue(t,this.accs,o,n)}_baseLoc(t){if(t._loc!==void 0)return t._loc;const e=t.showAs?.baseField;let s=null;if(e!=null&&e>=0){let n=this.rows.fields.indexOf(e);n>=0?s={tree:this.rows,isRow:!0,depth:n+1}:(n=this.cols.fields.indexOf(e),n>=0&&(s={tree:this.cols,isRow:!1,depth:n+1}))}return t._loc=s,s}show(t,e,s,n=null){const o=t.showAs?.type;if(!o||o==="normal")return this.raw(t,e,s,n);const r=this.raw(t,e,s,n);if(r instanceof $)return r;const l=(m,A)=>this.raw(t,m,A,n),i=m=>m instanceof $?m:r===null?m===null?null:0:m===null||m===0?P.DIV0:r/m;switch(o){case"percentOfTotal":return i(l(0,0));case"percentOfCol":return i(l(0,s));case"percentOfRow":return i(l(e,0));case"percentOfParentRow":return i(e===0?r:l(this.rows.parent[e],s));case"percentOfParentCol":return i(s===0?r:l(e,this.cols.parent[s]));case"index":{const m=l(0,0),A=l(e,0),g=l(0,s);return[m,A,g].some(y=>y instanceof $)?P.VALUE:!A||!g?P.DIV0:(r??0)*m/(A*g)}default:}const u=this._baseLoc(t);if(u===null)return P.NA;const{tree:f,isRow:w,depth:p}=u,h=w?e:s;if(f.depth[h]<p)return null;const a=m=>w?l(m,s):l(e,m),d=f.ancestorAt(h,p);switch(o){case"percentOfParent":return i(a(d));case"percent":case"difference":case"percentDiff":{const m=this._baseSibling(t,f,d,p);if(m==="missing")return P.NA;if(m===-1)return o==="percent"?r===null?null:1:null;const A=a(f.peer(h,p,m));return m===d?o==="percent"?r===null?null:1:null:A instanceof $?A:o==="difference"?r===null&&A===null?null:(r??0)-(A??0):r===null||A===null?null:A===0?P.DIV0:o==="percent"?r/A:(r-A)/A}case"runTotal":case"percentOfRunningTotal":{const m=this._running(t,f,w,p,h,w?s:e,d,n);if(m instanceof $||o==="runTotal")return m;const A=f.children(f.parent[d]),g=this._running(t,f,w,p,h,w?s:e,A[A.length-1],n);return g instanceof $?g:g===0?P.DIV0:m/g}case"rankAscending":case"rankDescending":return r===null?null:this._rank(t,f,w,p,h,w?s:e,r,o==="rankAscending",n);default:return r}}_baseSibling(t,e,s,n){const o=t.showAs.baseItem,r=e.parent[s];if(o==="prev"||o==="next"){const f=e.children(r),w=e.pos[s]+(o==="prev"?-1:1);return w>=0&&w<f.length?f[w]:-1}const i=e.fieldAt(n).keyIndex.get(o);if(i===void 0)return"missing";const u=e.findChild(r,i);return u<0?"missing":u}_running(t,e,s,n,o,r,l,i){t._run===void 0&&(t._run=new Map);let u=t._run.get(i);u===void 0&&(u=new Map,t._run.set(i,u));const f=e.children(e.parent[l]),w=e.pos[l],p=s?this.cols.nNodes:this.rows.nNodes;let h=w,a=0;for(;h>=0;){const d=e.peer(o,n,f[h]),m=d>=0?u.get(d*p+r):void 0;if(m!==void 0){a=m;break}h--}for(let d=h+1;d<=w;d++){const m=e.peer(o,n,f[d]);if(m<0)continue;const A=s?this.raw(t,m,r,i):this.raw(t,r,m,i);if(A instanceof $)return A;typeof A=="number"&&(a+=A),u.set(m*p+r,a)}return a}_rank(t,e,s,n,o,r,l,i,u){t._ranks===void 0&&(t._ranks=new Map);const f=e.ancestorAt(o,n),w=e.pathKeys(o).slice(n).join(xt),p=`${e.parent[f]}|${r}|${w}`;let h=t._ranks.get(p);if(h===void 0){const m=[];for(const A of e.children(e.parent[f])){const g=e.peer(o,n,A);if(g<0)continue;const y=s?this.raw(t,g,r,u):this.raw(t,r,g,u);typeof y=="number"&&m.push(y)}h=Float64Array.from(m).sort(),t._ranks.set(p,h)}let a=0,d=h.length;if(i){for(;a<d;){const m=a+d>>1;h[m]<l?a=m+1:d=m}return a+1}for(;a<d;){const m=a+d>>1;h[m]<=l?a=m+1:d=m}return h.length-a+1}_arrange(){for(const t of this.data)t._run=void 0,t._ranks=void 0;this._buildChildren(this.rows,!0),this._buildChildren(this.cols,!1),this.rows.lines=this._buildLines(this.rows,!0),this.cols.lines=this._buildLines(this.cols,!1),this._layout()}rearrange(){return this._arrange(),this}_buildChildren(t,e){const{nNodes:s,parent:n,alive:o}=t,r=new Int32Array(s+1);for(let u=1;u<s;u++)o[u]&&r[n[u]+1]++;for(let u=0;u<s;u++)r[u+1]+=r[u];const l=new Int32Array(r[s]),i=r.slice();for(let u=1;u<s;u++)o[u]&&(l[i[n[u]]++]=u);t.childStart=r,t.childList=l,t.pos=new Int32Array(s),t._childIndex=null;for(let u=0;u<t.k;u++){const f=this._sortCompare(t,u+1,e),w=u===0?0:t.levelBase[u-1],p=u===0?1:t.levelBase[u];for(let h=w;h<p;h++){const a=r[h],d=r[h+1];if(d-a>1){const m=Array.from(l.subarray(a,d));m.sort(f),l.set(m,a)}for(let m=a;m<d;m++)t.pos[l[m]]=m-a}}}_sortCompare(t,e,s){const n=t.fields[e-1],o=this.cache.fields[n].ensure(),r=o.rank(),{item:l}=t,i=this.opts(n)?.sort;if((!i||i.order==="asc"||i.order===void 0)&&(!i||i.data===void 0||i.data===null))return(d,m)=>r[l[d]]-r[l[m]];if(i.order==="manual"){const d=i.keys??[],m=new Map(d.map((g,y)=>[g,y])),A=new Float64Array(o.items.length);return o.items.forEach((g,y)=>{const v=m.get(ut(g));A[y]=v===void 0?d.length+r[y]:v}),(g,y)=>A[l[g]]-A[l[y]]}const u=i.order==="desc"?-1:1;if(i.data===void 0||i.data===null)return(d,m)=>u*(r[l[d]]-r[l[m]]);const f=this.data[i.data];if(!f)return(d,m)=>r[l[d]]-r[l[m]];let w=0;if(i.path){const d=s?this.cols:this.rows;this._ensureItems(d);for(let m=0;m<i.path.length&&w>=0;m++){const g=d.fieldAt(m+1).keyIndex.get(i.path[m]);w=g===void 0?-1:d.findChild(w,g)}}const p=d=>{const m=s?this.raw(f,d,w):this.raw(f,w,d);return typeof m=="number"?m:null},h=new Map,a=d=>{let m=h.get(d);return m===void 0&&(m=p(d),h.set(d,m)),m};return(d,m)=>{const A=a(d),g=a(m);return A===null||g===null?A===g?r[l[d]]-r[l[m]]:A===null?1:-1:A===g?r[l[d]]-r[l[m]]:u*(A-g)}}_ensureItems(t){for(const e of t.fields)this.cache.fields[e].ensure()}_form(t){return this.opts(t)?.layout??this.spec.layout}_isCollapsed(t,e,s){const n=t.depth[e],o=s[n];return o===null?!1:!!(o.items!==null&&o.items.has(t.fieldAt(n).keyOf(t.item[e]))||o.paths!==null&&o.paths.has(t.pathKeys(e).join(xt)))}_buildLines(t,e){const{slots:s}=t,n=this.data.length,o={node:[],data:[],type:[],level:[],first:[],func:[],top:[],parentLine:[]},r=(h,a,d,m,A,g,y,v)=>{o.node.push(h),o.data.push(a),o.type.push(d),o.level.push(m),o.first.push(A),o.func.push(g),o.top.push(y?1:0),o.parentLine.push(v?1:0)},l=s.length-1,i=h=>e?s[h]===L?this.spec.layout:this._form(s[h]):"tabular",u=[null];for(let h=1;h<=t.k;h++){const a=this.opts(t.fields[h-1]),d=a?.collapsedItems?.length?new Set(a.collapsedItems):null,m=a?.collapsed?.length?new Set(a.collapsed):null;u.push(d||m?{items:d,paths:m}:null)}const f=h=>this.opts(h)?.subtotalTop??this.spec.subtotalTop,w=(h,a,d,m)=>{const A=s[a];if(A===L){for(let _=0;_<n;_++){const b=_===0&&m!==-1?m:a;a===l?r(h,_,X,a,b,null,!1,!1):i(a)==="tabular"?w(h,a+1,_,b):(r(h,_,X,a,b,null,!1,!0),o.noValues??=new Set,o.noValues.add(o.node.length-1),w(h,a+1,_,-1))}return}const g=t.children(h),y=this.opts(A),v=y?.blankLine===!0&&e;for(let _=0;_<g.length;_++){const b=g[_],x=_===0&&m!==-1?m:a;if(a===l){r(b,d,X,a,x,null,!1,!1);continue}const R=i(a),D=d<0&&s.indexOf(L,a+1)>=0;if(this._isCollapsed(t,b,u)){if(D)for(let z=0;z<n;z++)r(b,z,X,a,z===0?x:a,null,!1,R!=="tabular");else r(b,d,X,a,x,null,!1,R!=="tabular");o.collapsed??=new Set,o.collapsed.add(b),v&&r(b,d,mt,a,a,null,!1,!1);continue}const T=y?.subtotals??"auto",N=Array.isArray(T),U=T!=="none"&&!(N&&T.length===0),I=R!=="tabular"&&!D&&!N&&U&&f(A);if(R==="tabular"?w(b,a+1,d,x):(r(b,d,X,a,x,null,I,!0),I||(o.noValues??=new Set,o.noValues.add(o.node.length-1)),w(b,a+1,d,-1)),!I&&U&&!(a+1===l&&s[a+1]===L&&!N)){const yt=N?T:[null];if(D)for(let tt=0;tt<n;tt++)for(const vt of yt)r(b,tt,lt,a,a,vt,!1,!1);else for(const tt of yt)r(b,d,lt,a,a,tt,!1,!1)}v&&r(b,d,mt,a,a,null,!1,!1)}};if(s.length===0)return r(0,-1,X,-1,0,null,!1,!1),o;if(w(0,0,-1,-1),t.k>0&&(e?this.spec.grandRow:this.spec.grandCol))if(s.includes(L))for(let h=0;h<n;h++)r(0,h,st,0,0,null,!1,!1);else r(0,-1,st,0,0,null,!1,!1);return o}fieldCaption(t){return t===L?this.spec.dataCaption:this.opts(t)?.caption??this.cache.fields[t].name}itemCaption(t,e){const s=t.fieldAt(t.depth[e]),n=t.item[e],o=this.opts(s.index)?.itemCaptions;if(o){const r=o[s.keyOf(n)];if(r!==void 0)return r}return null}_labelValue(t,e){const s=this.itemCaption(t,e);if(s!==null)return s;const n=t.fieldAt(t.depth[e]).items[t.item[e]];return n??"(blank)"}_labelText(t,e){const s=this.itemCaption(t,e);return s!==null?s:t.fieldAt(t.depth[e]).labelOf(t.item[e])}_subtotalLabel(t,e,s){const n=this._labelText(t,e.node[s]),o=e.data[s],r=e.func[s];return r!==null&&o>=0?`${n} ${kt[r]} of ${this.data[o].name}`:r!==null?`${n} ${kt[r]}`:o>=0?`${n} ${this.data[o].name}`:`${n} Total`}_pageValue(t){const e=this.cache.fields[t].ensure(),s=wt(e,this.opts(t));if(s===null)return{text:"(All)",value:"(All)"};let n=0,o=-1;for(let r=0;r<s.length;r++)s[r]===0&&(n++,o=r);return n===s.length?{text:"(All)",value:"(All)"}:n===1?{text:e.labelOf(o),value:e.items[o]??"(blank)"}:{text:"(Multiple Items)",value:"(Multiple Items)"}}_layout(){const{spec:t,rows:e,cols:s,data:n}=this,o=new Ne;this.buffer=o;const r=n.length,l=t.filters.filter(C=>!this.cache.fields[C].removed),i=l.length>0?l.length+1:0,u=e.slots.length===0&&s.slots.length===0&&r===0;l.forEach((C,k)=>{o.pushValue(k,0,this.fieldCaption(C),E.PAGE_LABEL);const O=this.cache.fields[C],W=this._pageValue(C);o.pushValue(k,1,W.value,E.PAGE_VALUE,0,typeof W.value=="number"?o.format(O.numFmt):0)});const f=[],w=[];let p=0;if(e.slots.length>0){let C=0,k=0;for(let W=0;W<e.slots.length;W++)f.push(C),w.push(k),(e.slots[W]===L?t.layout:this._form(e.slots[W]))==="compact"?k++:(C++,k=0);p=(e.slots[e.slots.length-1]===L?t.layout:this._form(e.slots[e.slots.length-1]))==="compact"?C+1:C}else r<=1&&s.slots.length>0&&!(s.slots.length===1&&s.slots[0]===L)&&(p=1);const h=e.lines,a=s.lines,d=a.node.length,m=h.node.length,A=s.slots.length===1&&s.slots[0]===L,g=A&&!t.hideValuesRow&&e.slots.length>0,y=s.slots.length>0&&(!A||g),v=u?0:y?1+s.slots.length:1,_=y?t.layout==="compact"?1:s.slots.length:0,b=p+Math.max(r>0||y?d:0,_),x=r>0||e.slots.length>0?m:0,R=i,D=new Uint8Array(v*Math.max(b,1)),T=(C,k,O,W,H=0,V=0)=>{o.pushValue(R+C,k,O,W,V,H),D[C*b+k]=1},N=C=>t.layout==="compact"?null:C.map(k=>this.fieldCaption(k));u&&o.pushValue(R,0,t.name,E.PLACEHOLDER);const U=v-1;if(e.slots.length>0){const C=N(e.slots);C===null?T(U,0,t.rowCaption??G("Row Labels"),E.ROW_CAPTION):e.slots.forEach((k,O)=>{(k===L?t.layout:this._form(k))==="compact"&&O>0&&f[O]===f[O-1]||D[U*b+f[O]]||T(U,f[O],C[O],E.ROW_CAPTION)})}if(y){r===1&&e.slots.length>0&&T(0,0,n[0].name,E.CORNER);const C=N(s.slots);g?T(0,p,t.dataCaption,E.COL_CAPTION):C===null?T(0,p,t.colCaption??G("Column Labels"),E.COL_CAPTION):C.forEach((k,O)=>T(0,p+O,k,E.COL_CAPTION))}else r===1&&!A&&!e.slots.includes(L)&&T(0,p,n[0].name,E.DATA_HEADER);const I=y?1:0;if(r>0||y)for(let C=0;C<d;C++){const k=a.type[C],O=p+C,W=a.node[C];if(k===st){const V=a.data[C],ht=V>=0?`Total ${n[V].name}`:t.grandCaption??G("Grand Total");T(I,O,ht,E.COL_GRAND);continue}if(k===lt){T(I+a.level[C],O,this._subtotalLabel(s,a,C),E.COL_SUBTOTAL);continue}const H=a.level[C];for(let V=a.first[C];V<=H;V++){if(V<0||V>=s.slots.length)continue;if(s.slots[V]===L){const j=a.data[C];j>=0&&T(I+V,O,n[j].name,E.DATA_HEADER)}else{const j=Ot(s.slots,V),J=s.ancestorAt(W,j);if(V===H&&a.collapsed?.has(J))T(I+V,O,`${this._labelText(s,J)} Total`,E.COL_ITEM);else{const At=this._labelValue(s,J);T(I+V,O,At,E.COL_ITEM,typeof At=="number"?o.format(s.fieldAt(j).numFmt):0,t.showExpandButtons&&j<s.k?1:0)}}}}for(let C=0;C<v;C++)for(let k=0;k<b;k++)D[C*b+k]===0&&o.push(R+C,k,K,0,E.HEADER_BLANK);const z=R+v,yt=n.map(C=>{const k=C.numFmt??De(C);return o.format(k)}),tt=h.noValues??null,vt=C=>e.slots[C];for(let C=0;C<x;C++){const k=z+C,O=h.type[C];if(O===mt)continue;const W=h.node[C],H=h.level[C],V=h.parentLine[C]===1;let ht=E.ROW_ITEM,j=E.DATA;O===lt?(ht=E.ROW_SUBTOTAL,j=E.DATA_SUBTOTAL):O===st?(ht=E.ROW_GRAND,j=E.DATA_GRAND_ROW):V&&(j=E.DATA_PARENT);const J=Math.max(H,0);if(p>0)if(e.slots.length===0)r===1&&o.pushValue(k,0,n[0].name,E.ROW_ITEM);else if(O===st){const q=h.data[C];o.pushValue(k,0,q>=0?`Total ${n[q].name}`:t.grandCaption??G("Grand Total"),E.ROW_GRAND);for(let M=1;M<p;M++)o.push(k,M,K,0,E.ROW_GRAND)}else if(O===lt){const q=f[H];for(let M=0;M<p;M++)M===q?o.pushValue(k,M,this._subtotalLabel(e,h,C),E.ROW_SUBTOTAL,w[H]):o.push(k,M,K,0,E.ROW_SUBTOTAL)}else{const q=this._labelStart(h,C,e);for(let M=q;M<=H;M++){const dt=vt(M),nt=f[M],rt=M===H&&V?E.ROW_PARENT:E.ROW_ITEM;if(dt===L){const Q=h.data[C];Q>=0&&o.pushValue(k,nt,n[Q].name,rt,w[M])}else{const Q=Ot(e.slots,M),ot=e.ancestorAt(W,Q),Y=t.showExpandButtons&&Q<e.k?1:0;if(M===H&&h.collapsed?.has(ot)&&this._form(dt)==="tabular")o.pushValue(k,nt,`${this._labelText(e,ot)} Total`,rt,w[M]+Y);else{const et=this._labelValue(e,ot),Jt=typeof et=="number"?o.format(e.fieldAt(Q).numFmt):0;o.pushValue(k,nt,et,rt,w[M]+Y,Jt)}}}}if(r===0||tt!==null&&tt.has(C))continue;const _t=h.data[C],At=h.func[C];for(let q=0;q<d;q++){const M=a.type[q];if(M===mt)continue;const dt=a.data[q],nt=_t>=0?_t:dt>=0?dt:r===1?0:-1;if(nt<0)continue;const rt=n[nt],Q=At??a.func[q],ot=this.show(rt,W,a.node[q],Q);let Y=j;O!==st&&M===st?Y=E.DATA_GRAND_COL:O===X&&!V&&M===lt&&(Y=E.DATA);const it=p+q,et=Q&&Q!==rt.agg&&!rt.numFmt?0:yt[nt];ot===null?t.showMissing===!1?o.pushValue(k,it,0,Y,J,et):t.emptyText!==""?o.pushValue(k,it,t.emptyText,Y,J,et):Y!==E.DATA&&o.push(k,it,K,0,Y,J,et):ot instanceof $&&t.errorText!==null?o.pushValue(k,it,t.errorText,Y,J,et):o.pushValue(k,it,ot,Y,J,et)}}const It=u?R+1:z+x,Mt=Math.max(b,l.length>0?2:0,u?1:0);if(It>ne||Mt>se)throw new S("The PivotTable is too large for a worksheet.");this.layout={cells:o,rows:It,cols:Mt,bodyCols:b,pageRows:i,pageFields:l,headerRows:v,labelCols:p,bodyTop:z,dataRows:x,colForLevel:f,indentForLevel:w,colRowBase:I,firstHeaderRow:u||y?1:r>1?0:1,firstDataRow:u?1:v,firstDataCol:p}}_labelStart(t,e,s){const n=t.level[e],o=t.first[e];if(o===0)return 0;for(let r=0;r<o;r++){const l=s.slots[r];if(l!==L&&this.opts(l)?.repeatLabels||l!==L&&this.spec.repeatLabels&&this._form(l)!=="compact")return r}return Math.min(o,n)}toRows(){const{cells:t,rows:e,cols:s}=this.layout,n=[];for(let o=0;o<e;o++)n.push(new Array(s).fill(null));for(let o=0;o<t.count;o++)n[t.rows[o]][t.cols[o]]=t.valueAt(o);return n}hitTest(t,e){const s=this.layout,{spec:n,rows:o,cols:r}=this;if(t<s.pageRows-1){const i=s.pageFields[t];return i!==void 0&&e===1?{kind:"pageFilter",field:i}:null}const l=t-s.pageRows;if(l<0||t>=s.rows)return null;if(l===s.headerRows-1&&e<s.labelCols&&o.fields.length>0){const i=n.layout==="compact"?o.fields:o.slots.filter((u,f)=>u!==L&&s.colForLevel[f]===e);if(i.length>0)return{kind:"filter",axis:"row",fields:i}}if(l===0&&e>=s.labelCols&&r.fields.length>0&&s.colRowBase===1){const i=n.layout==="compact"?e===s.labelCols?r.fields:[]:r.slots.filter((u,f)=>u!==L&&f===e-s.labelCols);if(i.length>0)return{kind:"filter",axis:"col",fields:i}}if(l>=s.headerRows&&e<s.labelCols){const i=this._rowLabelAt(l-s.headerRows,e);if(i!==null)return i}if(l>=s.colRowBase&&l<s.headerRows&&e>=s.labelCols){const i=this._colLabelAt(e-s.labelCols,l-s.colRowBase);if(i!==null)return i}return l>=s.headerRows&&e>=s.labelCols?{kind:"value",rowLine:l-s.headerRows,colLine:e-s.labelCols}:null}_rowLabelAt(t,e){const{rows:s}=this,n=s.lines;if(t>=n.node.length||n.type[t]!==X)return null;const o=this.layout.colForLevel;for(let r=n.level[t];r>=this._labelStart(n,t,s);r--)if(o[r]===e)return this._labelHit(s,n,t,r,"row");return null}_colLabelAt(t,e){const{cols:s}=this,n=s.lines;return t>=n.node.length||n.type[t]!==X||e<n.first[t]||e>n.level[t]?null:this._labelHit(s,n,t,e,"col")}_labelHit(t,e,s,n,o){const r=t.slots[n];if(r===L||r===void 0)return null;const l=Ot(t.slots,n),i=t.ancestorAt(e.node[s],l),u=l<t.k;return{kind:"label",axis:o,node:i,field:r,path:t.pathKeys(i),expandable:u,collapsed:u&&e.collapsed?.has(i)===!0}}togglesIn(t,e,s,n){const o=[],r=this.layout,{rows:l,cols:i}=this;if(this.spec.showExpandButtons===!1)return o;if(l.k>1)for(let u=Math.max(t,r.bodyTop);u<=Math.min(s,r.rows-1);u++)for(let f=e;f<=Math.min(n,r.labelCols-1);f++){const w=this._rowLabelAt(u-r.bodyTop,f);w!==null&&w.expandable&&o.push({row:u,col:f,collapsed:w.collapsed,indent:this._levelIndent(w)})}if(i.k>1){const u=r.pageRows+r.colRowBase;for(let f=Math.max(t,u);f<=Math.min(s,r.pageRows+r.headerRows-1);f++)for(let w=Math.max(e,r.labelCols);w<=Math.min(n,r.cols-1);w++){const p=this._colLabelAt(w-r.labelCols,f-u);p!==null&&p.expandable&&o.push({row:f,col:w,collapsed:p.collapsed,indent:0})}}return o}_levelIndent(t){const e=this.rows.slots.indexOf(t.field);return e>=0?this.layout.indentForLevel[e]:0}filterButtons(){const t=this.layout,{rows:e,cols:s,spec:n}=this,o=[];if(t.pageFields.forEach((r,l)=>o.push({row:l,col:1,axis:"page",fields:[r]})),e.fields.length>0&&n.showFieldHeaders!==!1){const r=t.pageRows+t.headerRows-1;n.layout==="compact"?o.push({row:r,col:0,axis:"row",fields:e.fields}):e.slots.forEach((l,i)=>{l!==L&&(i===0||t.colForLevel[i]!==t.colForLevel[i-1])&&o.push({row:r,col:t.colForLevel[i],axis:"row",fields:[l]})})}if(s.fields.length>0&&n.showFieldHeaders!==!1&&t.colRowBase===1){const r=t.pageRows;n.layout==="compact"?o.push({row:r,col:t.labelCols,axis:"col",fields:s.fields}):s.slots.forEach((l,i)=>{l!==L&&o.push({row:r,col:t.labelCols+i,axis:"col",fields:[l]})})}return o}}function Ot(c,t){let e=0;for(let s=0;s<=t;s++)c[s]!==L&&e++;return e}function De(c){const t=c.showAs?.type;return ae.has(t)?"0.00%":t==="index"?"0.00":"General"}function Fe(c,t,e,s){const n=e.count??10,o=e.by??"items",r=e.bottom===!0,l=c.map(u=>[u,t(u)]).filter(u=>u[1]!==null);l.sort((u,f)=>r?u[1]-f[1]:f[1]-u[1]);const i=new Set;if(o==="items"){if(l.length>0&&n>0){const u=l[Math.min(n,l.length)-1][1];for(const[f,w]of l)(r?w<=u:w>=u)&&i.add(f)}}else{const u=l.reduce((p,h)=>p+h[1],0),f=o==="percent"?u*n/100:n;let w=0;for(const[p,h]of l)if(i.add(p),w+=h,w>=f)break}return s?c.filter(u=>!i.has(u)):c.filter(u=>i.has(u))}function Se(c){return{name:"PivotTable1",rows:[],cols:[],values:[],filters:[],fieldOptions:{},layout:"compact",subtotalTop:!0,grandRow:!0,grandCol:!0,repeatLabels:!1,rowCaption:null,colCaption:null,dataCaption:G("Values"),grandCaption:null,emptyText:"",errorText:null,style:{name:"PivotStyleLight16",rowHeaders:!0,colHeaders:!0,rowStripes:!1,colStripes:!1,lastColumn:!0},showExpandButtons:!0,showFieldHeaders:!0,hideValuesRow:!0,...c}}class Ze{constructor(t,e={}){this.cache=t,this.spec=Se(e),this.rememberLayout(),this.result=null,this.listeners=new Set,this.anchor=null,this.xml=null,this.dirty=!0}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(){this.dirty=!0;for(const t of this.listeners)t(this)}rememberLayout(){this.renderedLayout={cache:this.cache,spec:structuredClone(this.spec)}}update(){if(this.cache.needsRefresh){if(this.cache.source===null)throw new S("The PivotTable report was saved without the underlying data. Its source is not available.");this.cache.refresh()}return this._dropRemoved(),this.result=new Me(this),this._emit(),this.result}rearrange(){return this.result===null?this.update():(this.result.rearrange(),this._emit(),this.result)}refresh(){return this.cache.refresh(),this.update()}_dropRemoved(){const{spec:t,cache:e}=this,s=n=>n===L||!e.fields[n]?.removed;t.rows=t.rows.filter(s),t.cols=t.cols.filter(s),t.filters=t.filters.filter(s),t.values=t.values.filter(n=>s(n.field))}options(t){const{fieldOptions:e}=this.spec;let s=e[t];return s===void 0&&(s={},e[t]=s),s}defaultAgg(t){const e=this.cache.fields[t];return e.isCalculated?"sum":e.base>=0||e.isDate?"count":this._allNumeric(e)?"sum":"count"}_allNumeric(t){return t.strs!==null?!1:t.rawIds!==null?t.shared.every(e=>typeof e=="number"):t.kinds===null?t.nums!==null:t.kinds.every(e=>e===B)}uniqueDataName(t,e=-1){let s=t,n=2;const o=r=>this.spec.values.some((l,i)=>i!==e&&l.name.toLowerCase()===r.toLowerCase());for(;o(s);)s=`${t}${n++}`;return s}addValue(t,e=this.defaultAgg(t),s=this.spec.values.length){const n=this.cache.fields[t],o=Lt(n.isCalculated?"sum":e,n.name);return this.spec.values.splice(s,0,{field:t,agg:e,name:this.uniqueDataName(o)}),this.spec.values.length>1&&!this.spec.rows.includes(L)&&!this.spec.cols.includes(L)&&this.spec.cols.push(L),this.spec.values.length-1}setValueAgg(t,e){const s=this.spec.values[t],n=this.cache.fields[s.field],o=[Lt(s.agg,n.name),`${le[s.agg]} of ${n.name}`].some(r=>new RegExp(`^${Qt(r)}\\d*$`).test(s.name));s.agg=e,o&&(s.name=this.uniqueDataName(Lt(e,n.name),t))}place(t,e,s){const{spec:n}=this;for(const r of["rows","cols","filters"])n[r]=n[r].filter(l=>l!==t);if(t===L&&e==="filters")return;const o=n[e];s===void 0||s>o.length?o.push(t):o.splice(s,0,t)}removeFromLayout(t){const{spec:e}=this;for(const s of["rows","cols","filters"])e[s]=e[s].filter(n=>n!==t);e.values=e.values.filter(s=>s.field!==t),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==L),e.cols=e.cols.filter(s=>s!==L))}removeValue(t){const{spec:e}=this;e.values.splice(t,1),e.values.length<=1&&(e.rows=e.rows.filter(s=>s!==L),e.cols=e.cols.filter(s=>s!==L))}moveValue(t,e){const s=this.spec.values,[n]=s.splice(t,1);s.splice(Math.max(0,Math.min(e,s.length)),0,n)}isUsed(t){const{spec:e}=this;return e.rows.includes(t)||e.cols.includes(t)||e.filters.includes(t)||e.values.some(s=>s.field===t)}itemsOf(t){const e=this.cache.fields[t].ensure(),s=e.rank(),n=wt(e,{hidden:this.spec.fieldOptions[t]?.hidden})??new Uint8Array(e.items.length),o=new Array(e.items.length);for(let r=0;r<o.length;r++)o[s[r]]={id:r,key:ut(e.items[r]),label:e.labelOf(r),value:e.items[r],hidden:n[r]===1};return o}itemsWithData(t){const e=this.cache.fields[t].ensure(),s=new Uint8Array(e.items.length),n=this.cache.recordCount,o=[];for(const l of Object.keys(this.spec.fieldOptions)){if(Number(l)===t)continue;const i=this.cache.fields[l];if(!i||i.removed||i.isCalculated)continue;const u=wt(i,this.spec.fieldOptions[l]);if(u!==null&&o.push([i.ensure().ids,u]),this.spec.fieldOptions[l].range||this.spec.fieldOptions[l].dateFilter){const f=zt(i,this.spec.fieldOptions[l]);o.push([i.rawIds,f])}}const{ids:r}=e;t:for(let l=0;l<n;l++){for(let i=0;i<o.length;i++)if(o[i][1][o[i][0][l]]===1)continue t;s[r[l]]=1}return s}setHidden(t,e){const s=this.options(t);s.hidden=[...e]}clearFilters(t){const e=this.options(t);delete e.hidden,delete e.labelFilter,delete e.valueFilter,delete e.top,delete e.range,delete e.dateFilter}hasFilter(t){const e=this.spec.fieldOptions[t];return!!e&&(e.hidden&&e.hidden.length>0||!!e.labelFilter||!!e.valueFilter||!!e.top||!!e.range||!!e.dateFilter)}toggleCollapse(t){const e=this.options(t.field),s=t.path.join(xt),n=new Set(e.collapsed??[]),o=t.path[t.path.length-1];return t.collapsed?(n.delete(s),e.collapsedItems&&(e.collapsedItems=e.collapsedItems.filter(r=>r!==o))):n.add(s),e.collapsed=[...n],this.rearrange()}setFieldCollapsed(t,e){const s=this.options(t);s.collapsed=[];const n=this.cache.fields[t].ensure();return s.collapsedItems=e?n.items.map(o=>ut(o)):[],this.rearrange()}}export{Ke as AGGS,kt as AGG_LABEL,Ne as CellBuffer,Qe as LABEL_FILTERS,Je as LINE,gt as PivotCache,S as PivotError,ft as PivotField,Me as PivotResult,Ze as PivotTable,E as ROLE,je as SHOW_AS,L as VALUES,ze as VALUE_FILTERS,qt as applyNumFmt,Nt as compileCalc,wt as hiddenItemFlags,ut as itemKey,ee as partsToSerial,pt as serialToParts,Ye as showAsNeedsBaseField,Xe as showAsNeedsBaseItem,Ht as storeColumn,Lt as valueFieldName};
|
package/print/paginate.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHUNK_MASK as P,CONTENT_MASK as z}from"../core/sheet.js";import{MAX_COLS as E,MAX_ROWS as X}from"../core/address.js";import{getPageSetup as D,paperDimensions as F}from"./page-setup.js";const K=16,I=10,q=100;function L(c){return Math.max(22,String(c+1).length*7+6)}function J(c,t,s=null){let n=-1,e=-1;const o=t?.list,i=r=>{if(r===0||!o)return!1;const l=o[r];return l!==void 0&&(l.fill!==null||l.borders!==null)};for(let r=c.columns.length-1;r>=0;r--){const l=c.columns[r];if(l===void 0)continue;const a=U(l,n,i);a<0||(a>n&&(n=a),r>e&&(e=r))}s&&(s.r1>n&&(n=s.r1),s.c1>e&&(e=s.c1));for(const r of c.merges??[])r.r0<=n&&r.c0<=e&&(r.r1>n&&(n=r.r1),r.c1>e&&(e=r.c1));return{maxRow:n,maxCol:e}}function U(c,t,s){for(let n=c.length-1;n>=0;n--){const e=n*(P+1);if(e+P<=t)return-1;const o=c[n];if(o===void 0)continue;const{kinds:i,styles:r}=o;for(let l=P;l>=0;l--)if((i[l]&z)!==0||r!==null&&s(r[l]))return e+l}return-1}function H(c,t,s=c.length){let n=0,e=s;for(;n<e;){const o=n+e>>>1;c[o]<t?n=o+1:e=o}return n}const W=(c,t)=>{const s=c.length-1,n=H(c,t+1)-1;return n<0||n>=s?-1:n};function Y(c,t,s,n,e,o,i,r=1/0){let l=new Int32Array(64),a=0;const h=p=>{if(a===l.length){const x=new Int32Array(l.length*2);x.set(l),l=x}l[a++]=p},w=c.offsetOf(s+1);let u=t,f=i?H(i,t+1):0;const g=i?i.length:0;for(;u<=s;){const p=c.offsetOf(u);if(w-p<=0)break;if(a>=r)return null;h(u);const x=e!==null&&u>e[1],C=Math.max(1,x?n-o:n);let d;for(w-p<=C?d=s+1:(d=c.indexAt(p+C),d<=u&&(d=u+1),d>s+1&&(d=s+1));f<g&&i[f]<=u;)f++;f<g&&i[f]<d&&(d=i[f]),u=d}return h(s+1),l.slice(0,a)}const B=(c,t,s)=>c.offsetOf(s+1)-c.offsetOf(t);function G(c,t,s={}){return new V(c,t,s)}class V{constructor(t,s,n){this.book=t,this.sheet=s,this.setup=n.setup??D(s);const{setup:e}=this;this.paper=F(s.isChartSheet&&e.orientation==="default"?{...e,orientation:"landscape"}:e,n.fallbackPaper);const o=e.margins;if(this.box={x:o.left*72,y:o.top*72,w:Math.max(1,this.paper.width-(o.left+o.right)*72),h:Math.max(1,this.paper.height-(o.top+o.bottom)*72)},s.isChartSheet){this.areas=[],this.percent=100,this.scale=1,this.headingW=0,this.headingH=0,this.layouts=[],this._firsts=[],this.pageCount=1;return}const i=n.areas??(n.ignorePrintArea?[]:e.printAreas),r=i.length===0&&!n.ignorePrintArea?s.defaultPrintAreas?.()??i:i,a=r.length===0||r.some(f=>f.r0===0&&f.r1===X-1||f.c0===0&&f.c1===E-1)?J(s,t?.styles,n.objectExtent??null):null;this.areas=Z(r,a);let h=0;for(const f of this.areas)f.r1>h&&(h=f.r1);this.headingW=e.headings?L(h):0,this.headingH=e.headings?K:0;const{rows:w,cols:u}=s;this.titleRows=e.titleRows?[e.titleRows.r0,e.titleRows.r1]:null,this.titleCols=e.titleCols?[e.titleCols.c0,e.titleCols.c1]:null,this.titleH=this.titleRows?B(w,this.titleRows[0],this.titleRows[1]):0,this.titleW=this.titleCols?B(u,this.titleCols[0],this.titleCols[1]):0,this.useManualBreaks=!e.fitToPage,this.percent=e.fitToPage?this._fitPercent():Q(e.scale),this.scale=this.percent/100,this._layout()}_roomW(t){return this.box.w/t-this.headingW}_roomH(t){return this.box.h/t-this.headingH}_colBands(t,s,n=1/0){const e=this._roomW(s),o=this.titleCols!==null&&this.titleW<e?this.titleCols:null;return{title:o,starts:Y(this.sheet.cols,t.c0,t.c1,e,o,this.titleW,this.useManualBreaks?this.setup.colBreaks:null,n)}}_rowBands(t,s,n=1/0){const e=this._roomH(s),o=this.titleRows!==null&&this.titleH<e?this.titleRows:null;return{title:o,starts:Y(this.sheet.rows,t.r0,t.r1,e,o,this.titleH,this.useManualBreaks?this.setup.rowBreaks:null,n)}}bandsOver(t,s,n){const e=t==="col"?{c0:s,c1:n}:{r0:s,r1:n};return t==="col"?this._colBands(e,this.scale):this._rowBands(e,this.scale)}_fitPercent(){const{setup:t,sheet:s}=this,n=t.fitToWidth>0?t.fitToWidth:1/0,e=t.fitToHeight>0?t.fitToHeight:1/0;if(n===1/0&&e===1/0)return q;const o=l=>this.areas.every(a=>(n===1/0||this._colBands(a,l/100,n).starts!==null)&&(e===1/0||this._rowBands(a,l/100,e).starts!==null));let i=q;for(const l of this.areas){const a=B(s.cols,l.c0,l.c1)+this.headingW,h=B(s.rows,l.r0,l.r1)+this.headingH;n!==1/0&&a>0&&(i=Math.min(i,Math.ceil(100*n*this.box.w/a))),e!==1/0&&h>0&&(i=Math.min(i,Math.ceil(100*e*this.box.h/h)))}if(i=Math.max(I,i),o(i))return i;let r=I;if(!o(r))return I;for(;i-r>1;){const l=r+i>>>1;o(l)?r=l:i=l}return r}_layout(){this.layouts=[];let t=0;for(let s=0;s<this.areas.length;s++){const n=this.areas[s],e=this._rowBands(n,this.scale),o=this._colBands(n,this.scale),i=e.starts.length-1,r=o.starts.length-1,l=i*r;l!==0&&(this.layouts.push({area:n,areaIndex:s,rows:e.starts,cols:o.starts,titleRows:e.title,titleCols:o.title,nRows:i,nCols:r,first:t,count:l}),t+=l)}this.pageCount=t,this._firsts=this.layouts.map(s=>s.first)}_layoutOf(t){return this.layouts[Math.max(0,H(this._firsts,t+1)-1)]}_seq(t,s,n){return this.setup.pageOrder==="overThenDown"?s*t.nCols+n:n*t.nRows+s}page(t){if(t<0||t>=this.pageCount)return null;if(this.sheet.isChartSheet)return this._chartPage(t);const s=this._layoutOf(t),n=t-s.first;let e,o;this.setup.pageOrder==="overThenDown"?(e=Math.floor(n/s.nCols),o=n%s.nCols):(o=Math.floor(n/s.nRows),e=n%s.nRows);const{sheet:i,setup:r,scale:l,box:a}=this,h=s.rows[e],w=s.rows[e+1]-1,u=s.cols[o],f=s.cols[o+1]-1,g=s.titleRows!==null&&h>s.titleRows[1]?{r0:s.titleRows[0],r1:s.titleRows[1]}:null,p=s.titleCols!==null&&u>s.titleCols[1]?{c0:s.titleCols[0],c1:s.titleCols[1]}:null,x=p?this.titleW:0,C=g?this.titleH:0,d=B(i.cols,u,f),M=B(i.rows,h,w),b=(this.headingW+x+d)*l,O=(this.headingH+C+M)*l,_=a.x+(r.horizontalCentered?Math.max(0,(a.w-b)/2):0),R=a.y+(r.verticalCentered?Math.max(0,(a.h-O)/2):0);return{index:t,areaIndex:s.areaIndex,area:s.area,rowBand:e,colBand:o,r0:h,r1:w,c0:u,c1:f,titleRows:g,titleCols:p,titleW:x,titleH:C,bodyW:d,bodyH:M,headingW:this.headingW,headingH:this.headingH,scale:l,paperW:this.paper.width,paperH:this.paper.height,originX:_,originY:R,contentW:b,contentH:O}}_chartPage(t){const{box:s,paper:n}=this;return{index:t,chartBox:{x:3,y:3,w:Math.max(1,s.w-7),h:Math.max(1,s.h-7)},areaIndex:0,area:{r0:0,c0:0,r1:0,c1:0},rowBand:0,colBand:0,r0:0,r1:0,c0:0,c1:0,titleRows:null,titleCols:null,titleW:0,titleH:0,bodyW:s.w,bodyH:s.h,headingW:0,headingH:0,scale:1,paperW:n.width,paperH:n.height,originX:s.x,originY:s.y,contentW:s.w,contentH:s.h}}pageAt(t,s){for(const n of this.layouts){const{area:e}=n;if(t<e.r0||t>e.r1||s<e.c0||s>e.c1)continue;const o=W(n.rows,t),i=W(n.cols,s);if(!(o<0||i<0))return n.first+this._seq(n,o,i)}return-1}cellOnPage(t,s,n){const{sheet:e}=this,o=(l,a,h,w,u,f,g)=>a>=h&&a<=w?g+f+l.offsetOf(a)-l.offsetOf(h):u&&a>=u[0]&&a<=u[1]?g+l.offsetOf(a)-l.offsetOf(u[0]):null,i=o(e.rows,s,t.r0,t.r1,t.titleRows&&[t.titleRows.r0,t.titleRows.r1],t.titleH,t.headingH),r=o(e.cols,n,t.c0,t.c1,t.titleCols&&[t.titleCols.c0,t.titleCols.c1],t.titleW,t.headingW);return r===null||i===null?null:{x:t.originX+r*t.scale,y:t.originY+i*t.scale,w:e.cols.sizeOf(n)*t.scale,h:e.rows.sizeOf(s)*t.scale}}cellAtPoint(t,s,n){const{sheet:e}=this,o=(s-t.originX)/t.scale-t.headingW,i=(n-t.originY)/t.scale-t.headingH;if(o<0||i<0||o>=t.titleW+t.bodyW||i>=t.titleH+t.bodyH)return null;const r=i<t.titleH?e.rows.indexAt(e.rows.offsetOf(t.titleRows.r0)+i):e.rows.indexAt(e.rows.offsetOf(t.r0)+i-t.titleH),l=o<t.titleW?e.cols.indexAt(e.cols.offsetOf(t.titleCols.c0)+o):e.cols.indexAt(e.cols.offsetOf(t.c0)+o-t.titleW);return{row:r,col:l}}breakPreview(t){const{sheet:s,setup:n}=this,{rows:e,cols:o}=s,i={scale:this.scale,percent:this.percent,areas:[],rowBreaks:[],colBreaks:[],pages:[]},r=this.useManualBreaks?n.rowBreaks:[],l=this.useManualBreaks?n.colBreaks:[],a=(h,w)=>{const u=H(h,w);return u<h.length&&h[u]===w};for(const h of this.layouts){const{area:w}=h,u=o.offsetOf(w.c0),f=o.offsetOf(w.c1+1),g=e.offsetOf(w.r0),p=e.offsetOf(w.r1+1);i.areas.push({...w,x:u,y:g,w:f-u,h:p-g});const x=Math.max(t.r0,w.r0),C=Math.min(t.r1,w.r1),d=Math.max(t.c0,w.c0),M=Math.min(t.c1,w.c1);if(x>C||d>M)continue;const b=Math.max(0,W(h.rows,x)),O=Math.max(b,W(h.rows,C)),_=Math.max(0,W(h.cols,d)),R=Math.max(_,W(h.cols,M));for(let m=b;m<=O;m++){const y=h.rows[m];m!==0&&i.rowBreaks.push({row:y,y:e.offsetOf(y),x0:u,x1:f,manual:a(r,y)})}for(let m=_;m<=R;m++){const y=h.cols[m];m!==0&&i.colBreaks.push({col:y,x:o.offsetOf(y),y0:g,y1:p,manual:a(l,y)})}for(let m=b;m<=O;m++)for(let y=_;y<=R;y++){const A=h.rows[m],k=h.rows[m+1]-1,v=h.cols[y],N=h.cols[y+1]-1,T=o.offsetOf(v),S=e.offsetOf(A);i.pages.push({index:h.first+this._seq(h,m,y),r0:A,r1:k,c0:v,c1:N,x:T,y:S,w:o.offsetOf(N+1)-T,h:e.offsetOf(k+1)-S})}}return i}pageLayoutView({gap:t=18}={}){const{paper:s}=this,n=s.width,e=s.height,o=n+t,i=e+t,r=[];let l=0,a=0;for(const f of this.layouts)r.push({layout:f,y:l}),l+=f.nRows*i,a=Math.max(a,f.nCols*o-t);const h=Math.max(0,l-t);return{width:a,height:h,rectOf:f=>{const g=this.page(f);if(!g)return null;const p=r[H(this._firsts,f+1)-1];return{index:f,x:g.colBand*o,y:p.y+g.rowBand*i,w:n,h:e}},visible:(f,g,p,x)=>{const C=[];for(const{layout:d,y:M}of r){const b=Math.max(0,Math.floor((g-M)/i)),O=Math.min(d.nRows-1,Math.floor((x-M)/i)),_=Math.max(0,Math.floor(f/o)),R=Math.min(d.nCols-1,Math.floor(p/o));for(let m=b;m<=O;m++)for(let y=_;y<=R;y++)C.push({index:d.first+this._seq(d,m,y),x:y*o,y:M+m*i,w:n,h:e})}return C}}}}function Q(c){const t=Math.round(Number(c)||100);return Math.min(400,Math.max(10,t))}function Z(c,t){const s=[];if(c.length===0)return t.maxRow>=0&&t.maxCol>=0&&s.push({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol}),s;for(const n of c){let{r0:e,c0:o,r1:i,c1:r}=n;e===0&&i===X-1&&(i=Math.max(t.maxRow,0)),o===0&&r===E-1&&(r=Math.max(t.maxCol,0)),i>=e&&r>=o&&s.push({r0:e,c0:o,r1:i,c1:r})}return s}function et(c,t={}){let s;Array.isArray(t.sheets)?s=t.sheets:t.sheets==="all"?s=c.sheets.map((i,r)=>i.hidden?-1:r).filter(i=>i>=0):s=[c.activeSheet];const n=[];let e=0,o=1;for(const i of s){const r=c.sheets[i],l=G(c,r,{setup:t.setups?.get(r),areas:i===c.activeSheet?t.areas:void 0,ignorePrintArea:t.ignorePrintArea,objectExtent:t.objectExtents?.get(r),fallbackPaper:t.fallbackPaper});l.setup.useFirstPageNumber&&(o=l.setup.firstPageNumber),n.push({sheet:r,sheetIndex:i,pagination:l,first:e,firstNumber:o}),e+=l.pageCount,o+=l.pageCount}return new $(c,n,e)}class ${constructor(t,s,n){this.book=t,this.entries=s,this.pageCount=n,this._firsts=s.map(e=>e.first)}entryOf(t){let s=H(this._firsts,t+1)-1;for(;s>0&&this.entries[s].pagination.pageCount===0;)s--;return this.entries[Math.max(0,s)]}at(t){if(t<0||t>=this.pageCount)return null;const s=this.entryOf(t),n=t-s.first;return{index:t,sheet:s.sheet,sheetIndex:s.sheetIndex,pagination:s.pagination,page:s.pagination.page(n),sheetPage:n,pageNumber:s.firstNumber+n,totalPages:this.pageCount}}firstPageOf(t){const s=this.entries.find(n=>n.sheetIndex===t);return s&&s.pagination.pageCount>0?s.first:-1}}export{V as Pagination,$ as PrintJob,et as createPrintJob,H as lowerBound,G as paginate,J as printedExtent};
|
|
1
|
+
import{CHUNK_MASK as P,CONTENT_MASK as z}from"../core/sheet.js";import{MAX_COLS as E,MAX_ROWS as X}from"../core/address.js";import{getPageSetup as D,paperDimensions as F}from"./page-setup.js";const K=16,I=10,q=100;function L(c){return Math.max(22,String(c+1).length*7+6)}function J(c,t,s=null){let e=-1,n=-1;const o=t?.list,i=r=>{if(r===0||!o)return!1;const l=o[r];return l!==void 0&&(l.fill!==null||l.borders!==null)};for(let r=c.columns.length-1;r>=0;r--){const l=c.columns[r];if(l===void 0)continue;const a=U(l,e,i);a<0||(a>e&&(e=a),r>n&&(n=r))}s&&(s.r1>e&&(e=s.r1),s.c1>n&&(n=s.c1));for(const r of c.merges??[])r.r0<=e&&r.c0<=n&&(r.r1>e&&(e=r.r1),r.c1>n&&(n=r.c1));return{maxRow:e,maxCol:n}}function U(c,t,s){for(let e=c.length-1;e>=0;e--){const n=e*(P+1);if(n+P<=t)return-1;const o=c[e];if(o===void 0)continue;const{kinds:i,styles:r}=o;for(let l=P;l>=0;l--)if((i[l]&z)!==0||r!==null&&s(r[l]))return n+l}return-1}function H(c,t,s=c.length){let e=0,n=s;for(;e<n;){const o=e+n>>>1;c[o]<t?e=o+1:n=o}return e}const W=(c,t)=>{const s=c.length-1,e=H(c,t+1)-1;return e<0||e>=s?-1:e};function Y(c,t,s,e,n,o,i,r=1/0){let l=new Int32Array(64),a=0;const h=x=>{if(a===l.length){const p=new Int32Array(l.length*2);p.set(l),l=p}l[a++]=x},w=c.offsetOf(s+1);let u=t,f=i?H(i,t+1):0;const g=i?i.length:0;for(;u<=s;){const x=c.offsetOf(u);if(w-x<=0)break;if(a>=r)return null;h(u);const p=n!==null&&u>n[1],C=Math.max(1,p?e-o:e);let d;for(w-x<=C?d=s+1:(d=c.indexAt(x+C),d<=u&&(d=u+1),d>s+1&&(d=s+1));f<g&&i[f]<=u;)f++;f<g&&i[f]<d&&(d=i[f]),u=d}return h(s+1),l.slice(0,a)}const B=(c,t,s)=>c.offsetOf(s+1)-c.offsetOf(t);function G(c,t,s={}){return new V(c,t,s)}class V{constructor(t,s,e){this.book=t,this.sheet=s,this.cols=e.cols??s.cols,this.setup=e.setup??D(s);const{setup:n}=this;this.paper=F(s.isChartSheet&&n.orientation==="default"?{...n,orientation:"landscape"}:n,e.fallbackPaper);const o=n.margins;if(this.box={x:o.left*72,y:o.top*72,w:Math.max(1,this.paper.width-(o.left+o.right)*72),h:Math.max(1,this.paper.height-(o.top+o.bottom)*72)},s.isChartSheet){this.areas=[],this.percent=100,this.scale=1,this.headingW=0,this.headingH=0,this.layouts=[],this._firsts=[],this.pageCount=1;return}const i=e.areas??(e.ignorePrintArea?[]:n.printAreas),r=i.length===0&&!e.ignorePrintArea?s.defaultPrintAreas?.()??i:i,a=r.length===0||r.some(f=>f.r0===0&&f.r1===X-1||f.c0===0&&f.c1===E-1)?J(s,t?.styles,e.objectExtent??null):null;this.areas=Z(r,a);let h=0;for(const f of this.areas)f.r1>h&&(h=f.r1);this.headingW=n.headings?L(h):0,this.headingH=n.headings?K:0;const{rows:w}=s,{cols:u}=this;this.titleRows=n.titleRows?[n.titleRows.r0,n.titleRows.r1]:null,this.titleCols=n.titleCols?[n.titleCols.c0,n.titleCols.c1]:null,this.titleH=this.titleRows?B(w,this.titleRows[0],this.titleRows[1]):0,this.titleW=this.titleCols?B(u,this.titleCols[0],this.titleCols[1]):0,this.useManualBreaks=!n.fitToPage,this.percent=n.fitToPage?this._fitPercent():Q(n.scale),this.scale=this.percent/100,this._layout()}_roomW(t){return this.box.w/t-this.headingW}_roomH(t){return this.box.h/t-this.headingH}_colBands(t,s,e=1/0){const n=this._roomW(s),o=this.titleCols!==null&&this.titleW<n?this.titleCols:null;return{title:o,starts:Y(this.cols,t.c0,t.c1,n,o,this.titleW,this.useManualBreaks?this.setup.colBreaks:null,e)}}_rowBands(t,s,e=1/0){const n=this._roomH(s),o=this.titleRows!==null&&this.titleH<n?this.titleRows:null;return{title:o,starts:Y(this.sheet.rows,t.r0,t.r1,n,o,this.titleH,this.useManualBreaks?this.setup.rowBreaks:null,e)}}bandsOver(t,s,e){const n=t==="col"?{c0:s,c1:e}:{r0:s,r1:e};return t==="col"?this._colBands(n,this.scale):this._rowBands(n,this.scale)}_fitPercent(){const{setup:t,sheet:s}=this,e=t.fitToWidth>0?t.fitToWidth:1/0,n=t.fitToHeight>0?t.fitToHeight:1/0;if(e===1/0&&n===1/0)return q;const o=l=>this.areas.every(a=>(e===1/0||this._colBands(a,l/100,e).starts!==null)&&(n===1/0||this._rowBands(a,l/100,n).starts!==null));let i=q;for(const l of this.areas){const a=B(this.cols,l.c0,l.c1)+this.headingW,h=B(s.rows,l.r0,l.r1)+this.headingH;e!==1/0&&a>0&&(i=Math.min(i,Math.ceil(100*e*this.box.w/a))),n!==1/0&&h>0&&(i=Math.min(i,Math.ceil(100*n*this.box.h/h)))}if(i=Math.max(I,i),o(i))return i;let r=I;if(!o(r))return I;for(;i-r>1;){const l=r+i>>>1;o(l)?r=l:i=l}return r}_layout(){this.layouts=[];let t=0;for(let s=0;s<this.areas.length;s++){const e=this.areas[s],n=this._rowBands(e,this.scale),o=this._colBands(e,this.scale),i=n.starts.length-1,r=o.starts.length-1,l=i*r;l!==0&&(this.layouts.push({area:e,areaIndex:s,rows:n.starts,cols:o.starts,titleRows:n.title,titleCols:o.title,nRows:i,nCols:r,first:t,count:l}),t+=l)}this.pageCount=t,this._firsts=this.layouts.map(s=>s.first)}_layoutOf(t){return this.layouts[Math.max(0,H(this._firsts,t+1)-1)]}_seq(t,s,e){return this.setup.pageOrder==="overThenDown"?s*t.nCols+e:e*t.nRows+s}page(t){if(t<0||t>=this.pageCount)return null;if(this.sheet.isChartSheet)return this._chartPage(t);const s=this._layoutOf(t),e=t-s.first;let n,o;this.setup.pageOrder==="overThenDown"?(n=Math.floor(e/s.nCols),o=e%s.nCols):(o=Math.floor(e/s.nRows),n=e%s.nRows);const{sheet:i,setup:r,scale:l,box:a}=this,h=s.rows[n],w=s.rows[n+1]-1,u=s.cols[o],f=s.cols[o+1]-1,g=s.titleRows!==null&&h>s.titleRows[1]?{r0:s.titleRows[0],r1:s.titleRows[1]}:null,x=s.titleCols!==null&&u>s.titleCols[1]?{c0:s.titleCols[0],c1:s.titleCols[1]}:null,p=x?this.titleW:0,C=g?this.titleH:0,d=B(this.cols,u,f),M=B(i.rows,h,w),b=(this.headingW+p+d)*l,O=(this.headingH+C+M)*l,_=a.x+(r.horizontalCentered?Math.max(0,(a.w-b)/2):0),R=a.y+(r.verticalCentered?Math.max(0,(a.h-O)/2):0);return{index:t,areaIndex:s.areaIndex,area:s.area,rowBand:n,colBand:o,r0:h,r1:w,c0:u,c1:f,titleRows:g,titleCols:x,titleW:p,titleH:C,bodyW:d,bodyH:M,headingW:this.headingW,headingH:this.headingH,scale:l,paperW:this.paper.width,paperH:this.paper.height,originX:_,originY:R,contentW:b,contentH:O}}_chartPage(t){const{box:s,paper:e}=this;return{index:t,chartBox:{x:3,y:3,w:Math.max(1,s.w-7),h:Math.max(1,s.h-7)},areaIndex:0,area:{r0:0,c0:0,r1:0,c1:0},rowBand:0,colBand:0,r0:0,r1:0,c0:0,c1:0,titleRows:null,titleCols:null,titleW:0,titleH:0,bodyW:s.w,bodyH:s.h,headingW:0,headingH:0,scale:1,paperW:e.width,paperH:e.height,originX:s.x,originY:s.y,contentW:s.w,contentH:s.h}}pageAt(t,s){for(const e of this.layouts){const{area:n}=e;if(t<n.r0||t>n.r1||s<n.c0||s>n.c1)continue;const o=W(e.rows,t),i=W(e.cols,s);if(!(o<0||i<0))return e.first+this._seq(e,o,i)}return-1}cellOnPage(t,s,e){const{sheet:n}=this,o=(l,a,h,w,u,f,g)=>a>=h&&a<=w?g+f+l.offsetOf(a)-l.offsetOf(h):u&&a>=u[0]&&a<=u[1]?g+l.offsetOf(a)-l.offsetOf(u[0]):null,i=o(n.rows,s,t.r0,t.r1,t.titleRows&&[t.titleRows.r0,t.titleRows.r1],t.titleH,t.headingH),r=o(this.cols,e,t.c0,t.c1,t.titleCols&&[t.titleCols.c0,t.titleCols.c1],t.titleW,t.headingW);return r===null||i===null?null:{x:t.originX+r*t.scale,y:t.originY+i*t.scale,w:this.cols.sizeOf(e)*t.scale,h:n.rows.sizeOf(s)*t.scale}}cellAtPoint(t,s,e){const{sheet:n}=this,o=(s-t.originX)/t.scale-t.headingW,i=(e-t.originY)/t.scale-t.headingH;if(o<0||i<0||o>=t.titleW+t.bodyW||i>=t.titleH+t.bodyH)return null;const r=i<t.titleH?n.rows.indexAt(n.rows.offsetOf(t.titleRows.r0)+i):n.rows.indexAt(n.rows.offsetOf(t.r0)+i-t.titleH),l=o<t.titleW?this.cols.indexAt(this.cols.offsetOf(t.titleCols.c0)+o):this.cols.indexAt(this.cols.offsetOf(t.c0)+o-t.titleW);return{row:r,col:l}}breakPreview(t){const{sheet:s,setup:e}=this,{rows:n}=s,{cols:o}=this,i={scale:this.scale,percent:this.percent,areas:[],rowBreaks:[],colBreaks:[],pages:[]},r=this.useManualBreaks?e.rowBreaks:[],l=this.useManualBreaks?e.colBreaks:[],a=(h,w)=>{const u=H(h,w);return u<h.length&&h[u]===w};for(const h of this.layouts){const{area:w}=h,u=o.offsetOf(w.c0),f=o.offsetOf(w.c1+1),g=n.offsetOf(w.r0),x=n.offsetOf(w.r1+1);i.areas.push({...w,x:u,y:g,w:f-u,h:x-g});const p=Math.max(t.r0,w.r0),C=Math.min(t.r1,w.r1),d=Math.max(t.c0,w.c0),M=Math.min(t.c1,w.c1);if(p>C||d>M)continue;const b=Math.max(0,W(h.rows,p)),O=Math.max(b,W(h.rows,C)),_=Math.max(0,W(h.cols,d)),R=Math.max(_,W(h.cols,M));for(let m=b;m<=O;m++){const y=h.rows[m];m!==0&&i.rowBreaks.push({row:y,y:n.offsetOf(y),x0:u,x1:f,manual:a(r,y)})}for(let m=_;m<=R;m++){const y=h.cols[m];m!==0&&i.colBreaks.push({col:y,x:o.offsetOf(y),y0:g,y1:x,manual:a(l,y)})}for(let m=b;m<=O;m++)for(let y=_;y<=R;y++){const A=h.rows[m],k=h.rows[m+1]-1,v=h.cols[y],N=h.cols[y+1]-1,T=o.offsetOf(v),S=n.offsetOf(A);i.pages.push({index:h.first+this._seq(h,m,y),r0:A,r1:k,c0:v,c1:N,x:T,y:S,w:o.offsetOf(N+1)-T,h:n.offsetOf(k+1)-S})}}return i}pageLayoutView({gap:t=18}={}){const{paper:s}=this,e=s.width,n=s.height,o=e+t,i=n+t,r=[];let l=0,a=0;for(const f of this.layouts)r.push({layout:f,y:l}),l+=f.nRows*i,a=Math.max(a,f.nCols*o-t);const h=Math.max(0,l-t);return{width:a,height:h,rectOf:f=>{const g=this.page(f);if(!g)return null;const x=r[H(this._firsts,f+1)-1];return{index:f,x:g.colBand*o,y:x.y+g.rowBand*i,w:e,h:n}},visible:(f,g,x,p)=>{const C=[];for(const{layout:d,y:M}of r){const b=Math.max(0,Math.floor((g-M)/i)),O=Math.min(d.nRows-1,Math.floor((p-M)/i)),_=Math.max(0,Math.floor(f/o)),R=Math.min(d.nCols-1,Math.floor(x/o));for(let m=b;m<=O;m++)for(let y=_;y<=R;y++)C.push({index:d.first+this._seq(d,m,y),x:y*o,y:M+m*i,w:e,h:n})}return C}}}}function Q(c){const t=Math.round(Number(c)||100);return Math.min(400,Math.max(10,t))}function Z(c,t){const s=[];if(c.length===0)return t.maxRow>=0&&t.maxCol>=0&&s.push({r0:0,c0:0,r1:t.maxRow,c1:t.maxCol}),s;for(const e of c){let{r0:n,c0:o,r1:i,c1:r}=e;n===0&&i===X-1&&(i=Math.max(t.maxRow,0)),o===0&&r===E-1&&(r=Math.max(t.maxCol,0)),i>=n&&r>=o&&s.push({r0:n,c0:o,r1:i,c1:r})}return s}function et(c,t={}){let s;Array.isArray(t.sheets)?s=t.sheets:t.sheets==="all"?s=c.sheets.map((i,r)=>i.hidden?-1:r).filter(i=>i>=0):s=[c.activeSheet];const e=[];let n=0,o=1;for(const i of s){const r=c.sheets[i],l=G(c,r,{setup:t.setups?.get(r),areas:i===c.activeSheet?t.areas:void 0,ignorePrintArea:t.ignorePrintArea,objectExtent:t.objectExtents?.get(r),fallbackPaper:t.fallbackPaper});l.setup.useFirstPageNumber&&(o=l.setup.firstPageNumber),e.push({sheet:r,sheetIndex:i,pagination:l,first:n,firstNumber:o}),n+=l.pageCount,o+=l.pageCount}return new $(c,e,n)}class ${constructor(t,s,e){this.book=t,this.entries=s,this.pageCount=e,this._firsts=s.map(n=>n.first)}entryOf(t){let s=H(this._firsts,t+1)-1;for(;s>0&&this.entries[s].pagination.pageCount===0;)s--;return this.entries[Math.max(0,s)]}at(t){if(t<0||t>=this.pageCount)return null;const s=this.entryOf(t),e=t-s.first;return{index:t,sheet:s.sheet,sheetIndex:s.sheetIndex,pagination:s.pagination,page:s.pagination.page(e),sheetPage:e,pageNumber:s.firstNumber+e,totalPages:this.pageCount}}firstPageOf(t){const s=this.entries.find(e=>e.sheetIndex===t);return s&&s.pagination.pageCount>0?s.first:-1}}export{V as Pagination,$ as PrintJob,et as createPrintJob,H as lowerBound,G as paginate,J as printedExtent};
|
package/print/render-page.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readingDirection as
|
|
2
|
-
`)){let r="";for(const h of t.split(/(?<=\s)/)){const d=r+h;for(r!==""&&this.width(d.trimEnd())>s?(o.push(r.trimEnd()),r=h):r=d;this.width(r.trimEnd())>s&&r.length>1;){let T=r.length-1;for(;T>1&&this.width(r.slice(0,T))>s;)T--;o.push(r.slice(0,T)),r=r.slice(T)}}o.push(r.trimEnd())}return this.wrapCache.size>4096&&this.wrapCache.clear(),this.wrapCache.set(p,o),o}wrapped(i,l,s,p,o,t,r,h,d){const{ctx:T}=this,a=this.wrapLines(J(l),i,t-h*2),w=Math.round(d*1.26),u=a.length*w,b=l.vAlign??"bottom";let C;b==="top"?C=o:b==="center"?C=o+(r-u)/2:C=o+r-u,T.save(),T.beginPath(),T.rect(p,o,t,r),T.clip(),T.textAlign=s==="center"?"center":s==="right"?"right":"left";const F=s==="center"?p+t/2:s==="right"?p+t-h:p+h;for(let k=0;k<a.length;k++){const P=C+k*w+Math.round(w*.8);P+w<o||P-w>o+r||T.fillText(a[k],F,P)}T.restore(),T.textAlign="left"}rotated(i,l,s,p,o,t){const{ctx:r}=this;r.save(),r.beginPath(),r.rect(s,p,o,t),r.clip(),r.translate(s+o/2,p+t/2);const h=l.rotation;if(r.textAlign="center",h===255){const d=l.fontSize*1.1,T=-((i.length-1)*d)/2;for(let a=0;a<i.length;a++)r.fillText(i[a],0,T+a*d)}else{const d=h>90?90-h:h;r.rotate(-d*Math.PI/180),r.fillText(i,0,l.fontSize*.35)}r.restore(),r.textAlign="left"}side(i,l,s,p,o){if(!i)return;const{ctx:t}=this,r=
|
|
3
|
-
`).forEach((t,r)=>{r>0&&l.push([]),t&&l[l.length-1].push({...s,text:t})});return l}function
|
|
1
|
+
import{readingDirection as ft,visualOrder as at,wrapsByAlign as ht}from"../cells/text-layout.js";import{gradientPatches as q}from"../cells/paint.js";import{paintWatermarks as dt}from"../shapes/watermark.js";import{BOOL as ut,CHUNK_BITS as Q,CHUNK_MASK as H,EMPTY as K,ERR as tt,ERRORS as mt,KIND_MASK as U,NUM as W,STR as v,FORMULA as et,SPILL as nt}from"../core/sheet.js";import{isBarcodeText as gt,paintBarcodeValue as bt}from"../celltypes/barcode.js";import{printCellType as ot,printEmptyTypedCells as pt}from"../celltypes/cell-types.js";import{FILL_MARK as it,fitGeneral as wt,formatGeneral as kt,getFormatter as V}from"../core/numfmt.js";import{colName as yt}from"../core/address.js";import{cssFont as E}from"../core/styles.js";import{CondFormats as Tt}from"../core/cond-format.js";import{drawCfIcon as xt,iconSide as St,monoContext as Dt,paintCfBar as At}from"../cells/cf-paint.js";import{sparklineIndex as Ot}from"../core/sparklines.js";import{paintSparkline as Rt}from"../sparklines/excel-paint.js";import{isSparklineText as Ft,paintSparklineValue as Pt}from"../sparklines/paint.js";import{paintSparkRulesOnPage as Ct,sparkRuleHidesValue as Mt}from"../sparklines/rule.js";import{preparePicturesForPrint as It}from"../sparklines/print.js";import{tableColors as zt,tablesOf as Nt}from"../core/tables.js";import{paintCustomTable as vt}from"../slicers/custom-styles.js";import{resolveColor as Lt}from"../io/xlsx-styles.js";import{parseHeaderFooter as Wt}from"./page-setup.js";const Ht=2,Et=6,Bt=32,Y="#000000",$=.25,j=10,_t={hair:.25,thin:.5,dotted:.5,dashed:.5,dashDot:.5,dashDotDot:.5,medium:1,mediumDashed:1,mediumDashDot:1,mediumDashDotDot:1,slantDashDot:1,thick:1.5,double:.5},Gt={hair:[.5,.75],dotted:[.5,1.5],dashed:[3,1.5],dashDot:[3,1.5,.75,1.5],dashDotDot:[3,1.5,.75,1.5,.75,1.5],mediumDashed:[4,2],mediumDashDot:[4,2,1,2],mediumDashDotDot:[4,2,1,2,1,2],slantDashDot:[4,1,1,1]},st=new WeakMap;function J(n){let i=st.get(n);return i===void 0&&(i=E(n,n.fontSize),st.set(n,i)),i}function Xt(n,i,l,s){switch(i){case W:return s.numFmt==="General"?kt(l):V(s.numFmt).number(l);case v:{const p=n.strings.get(l);return s.numFmt==="General"||s.numFmt==="@"?p:V(s.numFmt).text(p)}case ut:return l?"TRUE":"FALSE";case tt:return mt[l]??"#N/A";default:return""}}class Kt{constructor(i,l,s,p){this.ctx=i,this.book=l,this.sheet=s,this.styles=l.styles.list,this.mono=p.blackAndWhite,this.errors=p.errors,this.cfFrame=null,this.tables=null,this.font="",this.ink="",this.wrapCache=new Map,this.reachX=null}style(i,l){return this.styles[this.sheet.style(i,l)]??this.styles[0]}textStyle(i,l,s,p,o){let t=this.style(i,l);const r=this.cfFrame===null?void 0:this.cfFrame.get(i*16384+l);if(r!==void 0){if(r.icon&&this.icon(r.icon,s,p,o,t),r.hideValue)return null;(r.color||r.numFmt!==void 0||r.bold!==void 0||r.italic!==void 0||r.underline!==void 0||r.strike!==void 0)&&(t={...t,color:r.color??t.color,numFmt:r.numFmt??t.numFmt,bold:r.bold??t.bold,italic:r.italic??t.italic,underline:r.underline??t.underline,strike:r.strike??t.strike})}if(this.tables!==null)for(const h of this.tables){if(i<h.r0||i>h.r1||l<h.c0||l>h.c1||!h._colors)continue;const d=h._colors.format(h,i,l);t={...t,color:t.color??d.color,bold:t.bold||d.bold===!0,italic:t.italic||d.italic===!0},d.underline&&!t.underline&&(t.underline=d.underline),d.strike&&(t.strike=!0);break}return t}icon(i,l,s,p,o){const t=St(p,1,o.fontSize),r=o.vAlign==="top"?s+1:o.vAlign==="center"?s+(p-t)/2:s+p-t-1;xt(this.mono?Dt(this.ctx):this.ctx,i.name,i.level,l+1,r,t),this.ink=""}setFont(i){this.font!==i&&(this.ctx.font=i,this.font=i)}setInk(i){this.ink!==i&&(this.ctx.fillStyle=i,this.ink=i)}reset(){this.font="",this.ink=""}width(i){return this.ctx.measureText(i).width}richLine(i,l,s,p,o,t,r,h,d){const{ctx:T}=this,a=[];let w=0,u=0;l.forEach((k,P)=>{const x=l[P+1]?.at??i.length;if(x<=k.at)return;const D={...s,fontName:k.name??s.fontName,fontSize:k.sz??s.fontSize,bold:k.b??s.bold,italic:k.i??s.italic},I=J(D);this.setFont(I);const N=i.slice(k.at,x).replace(/\n/g," "),M=T.measureText(N).width;a.push({piece:N,font:I,ink:k.color??s.color??"#000000",pw:M}),w+=M,u=Math.max(u,D.fontSize)});const b=s.vAlign??"bottom",C=b==="top"?t+u*1.05:b==="center"?t+(h+u*.72)/2:t+h-3;let F=p==="right"?o+r-d-w:p==="center"||p==="centerContinuous"?o+(r-w)/2:o+d;T.textAlign="left";for(const k of a)this.setFont(k.font),this.setInk(k.ink),T.fillText(k.piece,F,C),F+=k.pw}text(i,l,s,p,o,t,r,h,d,T=!1){const{ctx:a,sheet:w}=this,u=this.reachX===null?this.textStyle(i,l,o,t,h):this.style(i,l);if(u===null)return;if(w.cellTypes!==null&&this.reachX===null&&ot(a,this.book,w,i,l,o,t,r,h)){this.reset();return}if(s===W&&p===0&&w.hideZeros)return;if(u.ext?.pad){const[c,y,R,z]=u.ext.pad;o+=z,t+=c,r=Math.max(0,r-z-y),h=Math.max(0,h-c-R)}let b=Xt(this.book,s,p,u);if(s===tt&&this.errors!=="displayed"&&(b=this.errors==="blank"?"":this.errors==="dash"?"--":"#N/A"),b===""||s===v&>(b)&&(w.kind(i,l)&(et|nt))!==0&&bt(a,b,o,t,r,h,1)||s===v&&Ft(b)&&(w.kind(i,l)&(et|nt))!==0&&Pt(a,b,o,t,r,h,1,{ink:u.color??"#000000",snap:!1,mono:this.mono})||w.sparkRules!==null&&Mt(w,i,l))return;const C=J(u);this.setFont(C);let F=u.color??"#000000";s===W&&u.numFmt!=="General"&&(F=V(u.numFmt).color(p)??F),this.setInk(this.mono?"#000000":F);const k=Ht,P=s===v?ft(u.readingOrder,b):null;s===v&&!("direction"in a)&&(b=at(b,P==="rtl")),P==="rtl"&&"direction"in a?(a.direction="rtl",this.pendingDirection=!0):this.pendingDirection&&(a.direction="ltr",this.pendingDirection=!1);const x=u.hAlign??(s===W||P==="rtl"?"right":s===v?"left":"center");if(x==="centerContinuous")for(let c=l+1;(w.kind(i,c)&15)===0&&w.mergeAt(i,c)===null&&this.book.styles.get(w.style(i,c)).hAlign==="centerContinuous";c++)r+=w.cols.sizeOf(c);const D=r-k*2,I=u.fontSize;if(this.reachX!==null&&(u.rotation!==0||u.wrap))return;if(u.rotation!==0){this.rotated(b,u,o,t,r,h);return}if(u.wrap||ht(u)){this.wrapped(b,u,x,o,t,r,h,k,I);return}const N=s===v?this.book.strings.rich?.get(p):void 0;if(N!==void 0&&!this.mono){this.richLine(b,N,u,x,o,t,r,h,k);return}const M=u.vAlign??"bottom";let O;if(M==="top"?O=t+I*1.05:M==="center"?O=t+(h+I*.72)/2:O=t+h-3,b.indexOf(it)>=0){if(this.reachX!==null)return;const c=b.split(it),y=c[0],R=c[1]??" ",z=c.slice(2).join("");a.textAlign="left",y&&a.fillText(y,o+k,O);const L=this.width(y),G=this.width(z);if(R!==" "){const X=this.width(R)||1,Z=Math.floor((D-L-G)/X);Z>0&&a.fillText(R.repeat(Z),o+k+L,O)}a.textAlign="right",z&&a.fillText(z,o+r-k,O),a.textAlign="left";return}let S=this.width(b);if(S>D&&s===W&&(u.numFmt==="General"&&(b=wt(p,c=>this.width(c)<=D),S=this.width(b)),S>D)){const c=this.width("#")||1;b="#".repeat(Math.max(1,Math.floor(D/c))),S=c*b.length}let A=!1;if(u.shrink&&S>D&&D>0&&(this.setFont(E(u,I*(D/S))),S=D,A=!0),u.indent>0){const c=u.indent*Et;x==="left"?(o+=c,r-=c):x==="right"&&(r-=c)}let e,f=!1,g=o,m=o+r;if(x==="center"||x==="centerContinuous")e=o+(r-S)/2;else if(x==="right")e=o+r-k-S;else if(x==="fill"){const c=Math.max(1,Math.floor(D/(S||1)));b=b.repeat(c),S*=c,e=o+k}else e=o+k;if(this.reachX!==null&&e+S<=this.reachX){A&&this.setFont(C);return}if(S>D||e<o+k)if(T)f=!0;else if(s===v){if(e+S>m){let c=l+1,y=m;for(;y<e+S&&c<=d.c1&&(w.kind(i,c)&15)===0&&w.mergeAt(i,c)===null;)y+=w.cols.sizeOf(c),c++;m=y}if(e<g){let c=l-1,y=g;for(;y>e&&c>=d.c0&&(w.kind(i,c)&15)===0&&w.mergeAt(i,c)===null;)y-=w.cols.sizeOf(c),c--;g=y}f=e+S>m||e<g}else f=!0;a.textAlign="left",f?(a.save(),a.beginPath(),a.rect(g,t,m-g,h),a.clip(),a.fillText(b,e,O),this.decorate(u,e,O,S,I),a.restore()):(a.fillText(b,e,O),(u.underline!==0||u.strike)&&this.decorate(u,e,O,S,I)),A&&this.setFont(C)}decorate(i,l,s,p,o){const{ctx:t}=this,r=Math.max(.5,o/14);if(i.underline!==0){const h=s+o*.14;t.fillRect(l,h,p,r),i.underline===2&&t.fillRect(l,h+r*2,p,r)}i.strike&&t.fillRect(l,s-o*.3,p,r)}wrapLines(i,l,s){const p=`${i}|${Math.round(s)}|${l}`;let o=this.wrapCache.get(p);if(o!==void 0)return o;o=[];for(const t of l.split(`
|
|
2
|
+
`)){let r="";for(const h of t.split(/(?<=\s)/)){const d=r+h;for(r!==""&&this.width(d.trimEnd())>s?(o.push(r.trimEnd()),r=h):r=d;this.width(r.trimEnd())>s&&r.length>1;){let T=r.length-1;for(;T>1&&this.width(r.slice(0,T))>s;)T--;o.push(r.slice(0,T)),r=r.slice(T)}}o.push(r.trimEnd())}return this.wrapCache.size>4096&&this.wrapCache.clear(),this.wrapCache.set(p,o),o}wrapped(i,l,s,p,o,t,r,h,d){const{ctx:T}=this,a=this.wrapLines(J(l),i,t-h*2),w=Math.round(d*1.26),u=a.length*w,b=l.vAlign??"bottom";let C;b==="top"?C=o:b==="center"?C=o+(r-u)/2:C=o+r-u,T.save(),T.beginPath(),T.rect(p,o,t,r),T.clip(),T.textAlign=s==="center"?"center":s==="right"?"right":"left";const F=s==="center"?p+t/2:s==="right"?p+t-h:p+h;for(let k=0;k<a.length;k++){const P=C+k*w+Math.round(w*.8);P+w<o||P-w>o+r||T.fillText(a[k],F,P)}T.restore(),T.textAlign="left"}rotated(i,l,s,p,o,t){const{ctx:r}=this;r.save(),r.beginPath(),r.rect(s,p,o,t),r.clip(),r.translate(s+o/2,p+t/2);const h=l.rotation;if(r.textAlign="center",h===255){const d=l.fontSize*1.1,T=-((i.length-1)*d)/2;for(let a=0;a<i.length;a++)r.fillText(i[a],0,T+a*d)}else{const d=h>90?90-h:h;r.rotate(-d*Math.PI/180),r.fillText(i,0,l.fontSize*.35)}r.restore(),r.textAlign="left"}side(i,l,s,p,o){if(!i)return;const{ctx:t}=this,r=_t[i.style]??.5;if(t.strokeStyle=this.mono?"#000000":i.color??"#000000",t.lineWidth=r,t.setLineDash(Gt[i.style]??[]),t.beginPath(),i.style==="double"){const h=s===o?0:.75,d=s===o?.75:0;t.moveTo(l-h,s-d),t.lineTo(p-h,o-d),t.moveTo(l+h,s+d),t.lineTo(p+h,o+d)}else t.moveTo(l,s),t.lineTo(p,o);t.stroke()}}function rt(n,i,l){const s=new Float64Array(l-i+2);let p=0;for(let o=i;o<=l;o++)s[o-i]=p,p+=n.sizeOf(o);return s[l-i+1]=p,s}function B(n,i,l,s,p){const{ctx:o,sheet:t}=n,{x:r,y:h,r0:d,r1:T,c0:a,c1:w}=i,u=rt(t.cols,a,w),b=rt(t.rows,d,T),C=w-a+1,F=T-d+1,k=u[C],P=b[F];if(k<=0||P<=0)return;if(o.save(),o.beginPath(),o.rect(r,h,k,P),o.clip(),n.reset(),l){o.strokeStyle=Y,o.lineWidth=$,o.setLineDash([]),o.beginPath();for(let e=0;e<=C;e++)e>0&&u[e]===u[e-1]||(o.moveTo(r+u[e],h),o.lineTo(r+u[e],h+P));for(let e=0;e<=F;e++)e>0&&b[e]===b[e-1]||(o.moveTo(r,h+b[e]),o.lineTo(r+k,h+b[e]));o.stroke()}const x=t.mergesInRows(d,T).filter(e=>e.c1>=a&&e.c0<=w),D=x.length>0,I=t.rowStyles!==null||t.colStyles!==null,N=n.styles[0].fill===null&&n.styles[0].borders===null;n.tables=null;const{book:M}=n;if(M.engine&&M.engine.tables.size>0){const e=Nt(M,t);e.length>0&&(n.tables=e);for(const f of e){if(f.r1<d||f.r0>T||f.c1<a||f.c0>w)continue;const g=zt(f.styleName,M.theme);g&&(f._colors=g,vt(o,f,g,{ra:d,rb:T,ca:a,cb:w,xs:u,ys:b,ox:r,oy:h,line:.5,noFill:n.mono,setInk:m=>n.setInk(n.mono?"#000000":m)}))}}let O=null;for(let e=a;e<=w;e++){const f=u[e-a+1]-u[e-a];if(f===0)continue;const g=t.columns[e];if(!(g===void 0&&!I&&N))for(let m=d;m<=T;m++){if(!I&&N){const R=g[m>>>Q];if(R===void 0||R.styles===null){m|=H;continue}if(R.styles[m&H]===0)continue}const c=b[m-d+1]-b[m-d];if(c===0)continue;const y=n.style(m,e);y.fill===null&&y.borders===null||D&&t.mergeAt(m,e)!==null||(y.fill!==null&&!n.mono&&(y.gradient?q(y.gradient,r+u[e-a],h+b[m-d],f,c,(R,z,L,G,X)=>{n.setInk(R),o.fillRect(z,L,G,X)}):(n.setInk(ct(y)),o.fillRect(r+u[e-a],h+b[m-d],f,c))),y.borders!==null&&(O??=[]).push(m,e,y.borders))}}const S=e=>{const f=r+t.cols.offsetOf(e.c0)-t.cols.offsetOf(a),g=h+t.rows.offsetOf(e.r0)-t.rows.offsetOf(d);return{x:f,y:g,w:t.cols.offsetOf(e.c1+1)-t.cols.offsetOf(e.c0),h:t.rows.offsetOf(e.r1+1)-t.rows.offsetOf(e.r0)}};for(const e of x){const f=S(e),g=n.style(e.r0,e.c0);(l||g.fill!==null&&!n.mono)&&(g.gradient&&!n.mono?q(g.gradient,f.x,f.y,f.w,f.h,(m,c,y,R,z)=>{n.setInk(m),o.fillRect(c,y,R,z)}):(n.setInk(g.fill!==null&&!n.mono?ct(g):"#ffffff"),o.fillRect(f.x,f.y,f.w,f.h))),l&&(o.strokeStyle=Y,o.lineWidth=$,o.setLineDash([]),o.strokeRect(f.x,f.y,f.w,f.h))}if(n.cfFrame=null,t.cf&&t.cf.length>0){t.cfEval||(t.cfEval=new Tt(M,t,f=>Lt(f,M.theme??[])));const e=new Map;n.cfFrame=e;for(let f=a;f<=w;f++){const g=u[f-a+1]-u[f-a];for(let m=d;m<=T;m++){const c=t.cfEval.at(m,f);if(c===null)continue;e.set(m*16384+f,c);const y=r+u[f-a],R=h+b[m-d],z=b[m-d+1]-b[m-d];c.noFill&&!n.mono&&(n.setInk("#FFFFFF"),o.fillRect(y,R,g,z)),c.fill&&!n.mono&&(n.setInk(c.fill),o.fillRect(y,R,g,z)),c.bar&&!n.mono&&(At(o,c.bar,y,R,g,z,1,!1,!0),n.ink=""),c.borders&&(O??=[]).push(m,f,c.borders)}}}if(O!==null)for(let e=0;e<O.length;e+=3){const f=O[e],g=O[e+1],m=O[e+2],c=r+u[g-a],y=r+u[g-a+1],R=h+b[f-d],z=h+b[f-d+1];n.side(m.t,c,R,y,R),n.side(m.b,c,z,y,z),n.side(m.l,c,R,c,z),n.side(m.r,y,R,y,z),m.d&&m.down&&n.side(m.d,c,R,y,z),m.d&&m.up&&n.side(m.d,c,z,y,R)}for(const e of x){const f=S(e);for(let g=e.c0;g<=e.c1;g++){const m=t.cols.sizeOf(g),c=f.x+t.cols.offsetOf(g)-t.cols.offsetOf(e.c0),y=n.style(e.r0,g).borders;y?.t&&n.side(y.t,c,f.y,c+m,f.y);const R=n.style(e.r1,g).borders;R?.b&&n.side(R.b,c,f.y+f.h,c+m,f.y+f.h)}for(let g=e.r0;g<=e.r1;g++){const m=t.rows.sizeOf(g),c=f.y+t.rows.offsetOf(g)-t.rows.offsetOf(e.r0),y=n.style(g,e.c0).borders;y?.l&&n.side(y.l,f.x,c,f.x,c+m);const R=n.style(g,e.c1).borders;R?.r&&n.side(R.r,f.x+f.w,c,f.x+f.w,c+m)}}if(t.sparklines&&t.sparklines.length>0&&M.engine)for(const[e,f]of Ot(t)){const g=Math.floor(e/16384),m=e-g*16384;g<d||g>T||m<a||m>w||Rt(o,M.engine,t,f,g,m,r+u[m-a],h+b[g-d],u[m-a+1]-u[m-a],b[g-d+1]-b[g-d],1,{snap:!1,mono:n.mono})}t.sparkRules!==null&&Ct(o,M,t,{r0:d,r1:T,c0:a,c1:w,xs:u,ys:b,ox:r,oy:h,mono:n.mono}),n.reset(),o.textBaseline="alphabetic",o.textAlign="left";const A={c0:a,c1:w};for(let e=a;e<=w;e++){const f=r+u[e-a],g=u[e-a+1]-u[e-a];if(g===0)continue;const m=t.columns[e];if(m!==void 0)for(let c=d;c<=T;c++){const y=m[c>>>Q];if(y===void 0){c|=H;continue}const R=c&H,z=y.kinds[R]&U;if(z===K||D&&t.mergeAt(c,e)!==null)continue;const L=b[c-d+1]-b[c-d];L!==0&&n.text(c,e,z,y.values[R],f,h+b[c-d],g,L,A)}}if(s<a)for(let e=d;e<=T;e++){const f=b[e-d+1]-b[e-d];if(f===0||t.kind(e,a)!==0)continue;let g=0;for(let m=a-1;m>=Math.max(s,a-Bt);m--){g+=t.cols.sizeOf(m);const c=t.kind(e,m)&U;if(c!==K){c===v&&t.mergeAt(e,m)===null&&(n.reachX=r,n.text(e,m,c,t.value(e,m),r-g,h+b[e-d],t.cols.sizeOf(m),f,A),n.reachX=null);break}}}for(const e of x){const f=t.kind(e.r0,e.c0)&U;if(f===K)continue;const g=S(e);n.text(e.r0,e.c0,f,t.value(e.r0,e.c0),g.x,g.y,g.w,g.h,A,!0)}t.cellTypes!==null&&pt(n.book,t,d,T,a,w,(e,f)=>{ot(n.ctx,n.book,t,e,f,r+u[f-a],h+b[e-d],u[f-a+1]-u[f-a],b[e-d+1]-b[e-d]),n.reset()}),p&&(n.reset(),p(i),n.reset()),o.restore(),n.reset()}function Ut(n,i,l){const{ctx:s,sheet:p}=n,{headingW:o,headingH:t,titleW:r,titleH:h}=i,d=r+i.bodyW,T=h+i.bodyH;s.strokeStyle=Y,s.lineWidth=$,s.setLineDash([]),n.reset(),s.font=l,s.textBaseline="alphabetic",s.textAlign="center",n.setInk("#000000");const a=3;s.strokeRect(0,0,o+d,t),s.strokeRect(0,0,o,t+T);const w=(b,C,F)=>{let k=F;for(let P=b;P<=C;P++){const x=p.cols.sizeOf(P);x>0&&(s.beginPath(),s.moveTo(k+x,0),s.lineTo(k+x,t),s.stroke(),s.fillText(yt(P),k+x/2,t-a)),k+=x}},u=(b,C,F)=>{let k=F;for(let P=b;P<=C;P++){const x=p.rows.sizeOf(P);x>0&&(s.beginPath(),s.moveTo(0,k+x),s.lineTo(o,k+x),s.stroke(),s.fillText(String(P+1),o/2,k+x-a)),k+=x}};i.titleCols&&w(i.titleCols.c0,i.titleCols.c1,o),w(i.c0,i.c1,o+r),i.titleRows&&u(i.titleRows.r0,i.titleRows.r1,t),u(i.r0,i.r1,t+h),s.textAlign="left"}const _=new Map;function Vt(n){let i=_.get(n);return i===void 0&&(i=Wt(n),_.size>256&&_.clear(),_.set(n,i)),i}function Yt(n,i){switch(n.field){case"page":return String(i.pageNumber+(n.offset??0));case"pages":return String(i.totalPages);case"date":return i.now.toLocaleDateString(i.locale);case"time":return i.now.toLocaleTimeString(i.locale,{hour:"2-digit",minute:"2-digit"});case"file":return i.fileName;case"sheet":return i.sheetName;case"path":return i.filePath;default:return""}}function $t(n,i){const l=[[]];for(const s of n)(s.field?Yt(s,i):s.text).split(`
|
|
3
|
+
`).forEach((t,r)=>{r>0&&l.push([]),t&&l[l.length-1].push({...s,text:t})});return l}function jt(n,i,l,s,p,o=null){const{setup:t,paper:r}=i,h=t.margins,d=s.pageNumber%2===0,T=x=>t.differentFirst&&s.sheetPage===0?x.first:t.differentOddEven&&d?x.even:x.odd,a=T(t.header),w=T(t.footer);if(!a&&!w)return;const u=s.defaultStyle,b=(t.alignWithMargins?h.left:.7)*72,C=r.width-(t.alignWithMargins?h.right:.7)*72;n.save(),n.textBaseline="alphabetic",n.textAlign="left";const F=(x,D,I,N)=>{const M=x.map(A=>{const e=(A.size??j)*p*(A.script!==0?.66:1),f=E({...u,fontName:A.font??u.fontName,bold:A.bold,italic:A.italic},e);return n.font=f,{run:A,size:e,font:f,width:n.measureText(A.text).width}});let O=0;for(const A of M)O+=A.width;let S=I==="center"?D-O/2:I==="right"?D-O:D;for(const{run:A,size:e,font:f,width:g}of M){n.font=f;const m=t.blackAndWhite?"#000000":A.color??"#000000";n.fillStyle=m;const c=N-(A.script===1?e*.5:A.script===-1?-e*.2:0);n.fillText(A.text,S,c);const y=Math.max(.4,e/14);A.underline&&(n.fillRect(S,c+e*.14,g,y),A.underline===2&&n.fillRect(S,c+e*.14+y*2,g,y)),A.strike&&n.fillRect(S,c-e*.3,g,y),S+=g}},k=x=>{let D=j;return x.length>0&&(D=Math.max(...x.map(I=>I.size??j))),D*p*1.2},P=(x,D,I,N)=>{if(x.length===0)return;const M=$t(x,s);if(N){let O=h.header*72;for(const S of M){const A=k(S);F(S,D,I,O+A*.8),O+=A}}else{let O=r.height-h.footer*72;for(let S=M.length-1;S>=0;S--){const A=k(M[S]);F(M[S],D,I,O-A*.2),O-=A}}};for(const[x,D]of[[a,!0],[w,!1]]){if(!x)continue;const I=Vt(x),N=o?.[D?"header":"footer"];N!=="L"&&P(I.left,b,"left",D),N!=="C"&&P(I.center,r.width/2,"center",D),N!=="R"&&P(I.right,C,"right",D)}n.restore()}function Jt(n,i){n.translate((i.paperW-2*i.originX)/i.scale,0),n.scale(-1,1);const l=Object.prototype.hasOwnProperty.call(n,"fillText"),s=n.fillText;return n.fillText=function(o,t,r){const h=n.measureText(o).width,d=n.textAlign,T=d==="right"||d==="end"?t-h:d==="center"?t-h/2:t;n.save(),n.scale(-1,1),n.textAlign="left",s.call(n,o,-T-h,r),n.restore()},()=>{l?n.fillText=s:delete n.fillText}}function lt(n,i,l,s={}){const{book:p,sheet:o,setup:t}=i,r=p.styles.list[0];n.save(),s.background!==!1&&(n.fillStyle="#ffffff",n.fillRect(0,0,l.paperW,l.paperH)),dt(n,o,l,s.sheetPage??l.index,t);const h={pageNumber:s.pageNumber??l.index+1,totalPages:s.totalPages??i.pageCount,sheetPage:s.sheetPage??l.index,fileName:s.fileName??p.fileName??"",filePath:s.filePath??"",sheetName:o.name,now:s.now??new Date,locale:s.locale,defaultStyle:r};jt(n,i,l,h,t.scaleWithDoc?l.scale:1),n.save(),n.translate(l.originX,l.originY),n.scale(l.scale,l.scale);const d=o.rtl===!0?Jt(n,l):null,T=new Kt(n,p,o,t),{headingW:a,headingH:w,titleW:u,titleH:b,titleRows:C,titleCols:F,r0:k,r1:P,c0:x,c1:D,area:I}=l,N=t.gridLines&&!t.draft;t.headings&&Ut(T,l,E(r,r.fontSize));const M=s.objectPainters??null,O=M&&M.length>0?e=>{const f=e.x-o.cols.offsetOf(e.c0),g=e.y-o.rows.offsetOf(e.r0),m={printing:!0,dpr:1,zoom:1,hx:e.x,hy:e.y,cssW:e.x+o.cols.offsetOf(e.c1+1)-o.cols.offsetOf(e.c0),cssH:e.y+o.rows.offsetOf(e.r1+1)-o.rows.offsetOf(e.r0),toScreen:(c,y)=>({x:f+c,y:g+y}),sheet:o};for(const c of M)c(n,m)}:null;if(l.chartBox){if(M){const e={printing:!0,dpr:1,zoom:1,hx:0,hy:0,cssW:l.bodyW,cssH:l.bodyH,toScreen:(f,g)=>({x:f,y:g}),sheet:o,chartBox:l.chartBox};for(const f of M)f(n,e)}n.restore(),n.restore();return}const S=a+u,A=w+b;B(T,{x:S,y:A,r0:k,r1:P,c0:x,c1:D},N,I.c0,O),C&&B(T,{x:S,y:w,r0:C.r0,r1:C.r1,c0:x,c1:D},N,I.c0,O),F&&B(T,{x:a,y:A,r0:k,r1:P,c0:F.c0,c1:F.c1},N,F.c0,O),C&&F&&B(T,{x:a,y:w,r0:C.r0,r1:C.r1,c0:F.c0,c1:F.c1},N,F.c0,O),d?.(),n.restore(),n.restore()}function ke(n,i,l,{pxPerPt:s=2,...p}={}){const o=i.at(l);if(o===null)return null;const{page:t,pagination:r}=o;n.width=Math.max(1,Math.round(t.paperW*s)),n.height=Math.max(1,Math.round(t.paperH*s));const h=n.getContext("2d",{alpha:!1});return h.setTransform(s,0,0,s,0,0),lt(h,r,t,{pageNumber:o.pageNumber,totalPages:o.totalPages,sheetPage:o.sheetPage,...p}),o}const Zt=()=>new Promise(n=>setTimeout(n,0)),qt={gray0625:.0625,gray125:.125,lightGray:.25,mediumGray:.5,darkGray:.75,lightHorizontal:.25,lightVertical:.25,lightDown:.25,lightUp:.25,lightGrid:.44,lightTrellis:.5,darkHorizontal:.5,darkVertical:.5,darkDown:.5,darkUp:.5,darkGrid:.5,darkTrellis:.75};function ct(n){if(!n.pattern)return n.fill;const i=qt[n.pattern.type]??.5,l=s=>{const p=parseInt(n.pattern.fg.slice(s,s+2),16),o=parseInt(n.fill.slice(s,s+2),16);return Math.round(p*i+o*(1-i)).toString(16).padStart(2,"0")};return`#${l(1)}${l(3)}${l(5)}`}async function ye(n,i,l={}){const{title:s,author:p,subject:o,fonts:t,compress:r,signal:h,onProgress:d,...T}=l,[{PdfWriter:a}]=await Promise.all([import("./pdf.js"),It(n)]),w=new a(i,{title:s,author:p,subject:o,fonts:t,compress:r}),u=T.now??new Date;let b=performance.now();for(let C=0;C<n.pageCount;C++){h?.throwIfAborted();const F=n.at(C),{page:k,pagination:P}=F,x=w.beginPage(k.paperW,k.paperH);lt(x,P,k,{...T,now:u,background:!1,pageNumber:F.pageNumber,totalPages:F.totalPages,sheetPage:F.sheetPage}),await w.endPage(),d?.(C+1,n.pageCount),performance.now()-b>12&&(await Zt(),b=performance.now())}return await w.finish(),{pages:w.pageCount,bytes:w.offset,missing:[...w.missing],fontWarnings:w.fontWarnings}}export{Xt as displayText,jt as paintHeaderFooter,ke as renderJobPageToCanvas,lt as renderPage,ye as writeJobPdf};
|