@8sheets/data-grid 1.0.2 → 1.1.1

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.
Files changed (136) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/api/theme-core.js +2 -0
  4. package/calc/adjust.js +1 -1
  5. package/calc/compile.js +1 -1
  6. package/calc/engine.js +1 -1
  7. package/calc/functions/array.js +1 -1
  8. package/calc/functions/database.js +1 -1
  9. package/calc/functions/date.js +1 -1
  10. package/calc/functions/financial.js +1 -1
  11. package/calc/functions/helpers.js +1 -1
  12. package/calc/functions/info.js +1 -1
  13. package/calc/functions/logical.js +1 -1
  14. package/calc/functions/lookup.js +1 -1
  15. package/calc/functions/math.js +1 -1
  16. package/calc/functions/stat.js +1 -1
  17. package/calc/functions/text.js +1 -1
  18. package/calc/parser.js +3 -3
  19. package/calc/values.js +1 -1
  20. package/calcx/async.js +1 -1
  21. package/calcx/culture/custom.js +1 -0
  22. package/calcx/culture/format-locale.js +1 -1
  23. package/calcx/culture/separators.js +1 -0
  24. package/calcx/functions/dynamic.js +1 -1
  25. package/calcx/functions/ets.js +1 -1
  26. package/calcx/functions/misc.js +1 -1
  27. package/calcx/lang/convert.js +1 -0
  28. package/cells/axis-ops.js +1 -1
  29. package/cells/block.js +1 -0
  30. package/cells/book-css.js +2 -2
  31. package/cells/cell-defaults.js +1 -1
  32. package/cells/cf-engine.js +1 -1
  33. package/cells/consolidate-links.js +1 -1
  34. package/cells/find-engine.js +2 -2
  35. package/cells/format-panes.js +3 -3
  36. package/cells/format-tabs.js +2 -2
  37. package/cells/outline-column.js +1 -1
  38. package/cells/panes.js +1 -1
  39. package/cells/rich-runs.js +2 -2
  40. package/cells/rich-values.js +1 -1
  41. package/cells/selection-modes.js +1 -1
  42. package/cells/shift-check.js +1 -0
  43. package/cells/table-rows.js +1 -0
  44. package/cells/text-layout.js +9 -8
  45. package/cells/ui-kit.js +15 -0
  46. package/cells/view-options.js +1 -1
  47. package/celltypes/cell-types.js +2 -2
  48. package/celltypes/diagonal.js +1 -1
  49. package/celltypes/dropdowns.js +3 -2
  50. package/celltypes/file-cell.js +2 -2
  51. package/celltypes/range-template.js +2 -2
  52. package/core/autofill.js +1 -1
  53. package/core/axis-styles.js +1 -0
  54. package/core/axis.js +1 -1
  55. package/core/cell-type-rules.js +1 -0
  56. package/core/changes.js +1 -1
  57. package/core/cond-format.js +1 -1
  58. package/core/culture.js +1 -0
  59. package/core/formula-refs.js +1 -1
  60. package/core/input.js +1 -1
  61. package/core/merge.js +1 -0
  62. package/core/numfmt.js +1 -1
  63. package/core/region-input.js +1 -0
  64. package/core/row-fit.js +1 -0
  65. package/core/sheet.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/structure.js +1 -0
  68. package/core/styles.js +1 -1
  69. package/core/tables.js +2 -2
  70. package/core/validation-ranges.js +1 -0
  71. package/core/whatif.js +1 -1
  72. package/core/workbook.js +1 -1
  73. package/datasheets/data-core.js +1 -1
  74. package/datasheets/gantt-paint.js +1 -1
  75. package/datasheets/manager.js +1 -1
  76. package/datasheets/path-binding.js +2 -2
  77. package/datasheets/rules.js +1 -1
  78. package/datasheets/view.js +2 -2
  79. package/i18n/dom.js +1 -1
  80. package/i18n/en/cells.js +1 -1
  81. package/i18n/en/format.js +1 -1
  82. package/i18n/en/misc.js +1 -1
  83. package/i18n/en/shell.js +2 -2
  84. package/i18n/pl/cells.js +1 -1
  85. package/i18n/pl/format.js +1 -1
  86. package/i18n/pl/misc.js +1 -1
  87. package/i18n/pl/shell.js +2 -2
  88. package/io/client.js +1 -1
  89. package/io/csv.js +8 -8
  90. package/io/plan.js +1 -1
  91. package/io/text-split.js +3 -3
  92. package/io/xlsx-read.js +1 -1
  93. package/io/xlsx-write.js +1 -1
  94. package/io/xml-scan.js +2 -1
  95. package/io/zip-reader.js +1 -1
  96. package/objects/chart-model.js +1 -1
  97. package/package.json +1 -1
  98. package/pivot/engine.js +1 -1
  99. package/pivot/xml.js +2 -2
  100. package/print/paginate.js +1 -1
  101. package/print/render-page.js +3 -3
  102. package/slicers/format.js +2 -2
  103. package/slicers/structured.js +1 -1
  104. package/table-view/api.js +1 -1
  105. package/table-view/cell-editor.js +2 -1
  106. package/table-view/chart.js +1 -0
  107. package/table-view/column-drag.js +1 -1
  108. package/table-view/context-menu.js +1 -0
  109. package/table-view/editors.js +1 -0
  110. package/table-view/events.js +1 -1
  111. package/table-view/files.js +1 -1
  112. package/table-view/fill-handle.js +1 -0
  113. package/table-view/filter-builder.js +1 -0
  114. package/table-view/find.js +1 -0
  115. package/table-view/grid-keys.js +2 -2
  116. package/table-view/labels-de.js +1 -0
  117. package/table-view/labels-es.js +1 -0
  118. package/table-view/labels-fr.js +1 -0
  119. package/table-view/labels-ja.js +1 -0
  120. package/table-view/labels.js +1 -1
  121. package/table-view/model.js +1 -1
  122. package/table-view/mount.js +1 -1
  123. package/table-view/panel.js +1 -1
  124. package/table-view/pivot-spec.js +1 -0
  125. package/table-view/pivot.js +1 -1
  126. package/table-view/public.d.ts +277 -28
  127. package/table-view/reader.worker.js +1 -1
  128. package/table-view/remote.js +1 -1
  129. package/table-view/row-drag.js +1 -0
  130. package/table-view/sparkline.js +1 -0
  131. package/table-view/state-check.js +1 -0
  132. package/table-view/table-css.js +380 -0
  133. package/table-view/version.js +1 -1
  134. package/ui/dialogs.js +3 -3
  135. package/ui/menu-base.js +1 -1
  136. package/ui/protection-ui.js +1 -1
package/pivot/xml.js CHANGED
@@ -1,2 +1,2 @@
1
- import{pivotCfNode as $e,pivotChartFormatsNode as _e}from"../slicers/pivot-file.js";import{dateFilterNodes as qe,isDateFilterType as He,parseDateFilter as Ve}from"../slicers/date-filters.js";import{MAX_COLS as Ge,parseRangeRef as de,rangeRef as fe}from"../core/address.js";import{BUILTIN_FORMATS as K,partsToSerial as Xe,serialToParts as je}from"../core/numfmt.js";import{BOOL as Ue,EMPTY as We,ERR as Ke,ERRORS as Ye,NUM as pe,STR as Je}from"../core/sheet.js";import{decodeRange as L,unescapeXml as Qe,unescapeXstring as he,XmlScanner as me}from"../io/xml-scan.js";import{escapeMarkup as Y,xmlAttr as ge}from"../io/xml-escape.js";import{relsPathOf as Ze,resolveTarget as ze}from"../io/package-paths.js";import{ERR_BY_CODE as we,ERR_BY_INDEX as be,XlError as et}from"../calc/values.js";import{applyNumFmt as J,itemKey as $,LINE as j,PivotCache as tt,PivotField as nt,PivotTable as st,storeColumn as at,VALUES as Q,compileCalc as ot,valueFieldName as rt}from"./engine.js";const Z="http://schemas.openxmlformats.org/spreadsheetml/2006/main",V="http://schemas.openxmlformats.org/officeDocument/2006/relationships",z="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",it="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}",lt="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}",ct="{2946ED86-A175-432a-8AC1-64E0C546D7DE}",ee={table:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",definition:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",records:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"},_={table:`${V}/pivotTable`,definition:`${V}/pivotCacheDefinition`,records:`${V}/pivotCacheRecords`},xe=1048828,ye=1048829,ve=4294967294,ut=new Set(["percentOfParent","percentOfParentRow","percentOfParentCol","percentOfRunningTotal","rankAscending","rankDescending"]),te={sum:"sumSubtotal",count:"countASubtotal",average:"avgSubtotal",max:"maxSubtotal",min:"minSubtotal",product:"productSubtotal",countNums:"countSubtotal",stdDev:"stdDevSubtotal",stdDevp:"stdDevPSubtotal",var:"varSubtotal",varp:"varPSubtotal"},Fe={sum:"sum",count:"countA",average:"avg",max:"max",min:"min",product:"product",countNums:"count",stdDev:"stdDev",stdDevp:"stdDevP",var:"var",varp:"varP"},m=(t,e={},s=[])=>({n:t,a:e,c:s,t:""}),b=(t,e)=>t?.c.find(s=>s.n===e)??null,A=(t,e)=>t?t.c.filter(s=>s.n===e):[],T=(t,e)=>t===void 0?e:t==="1"||t==="true";function Se(t,e,s){const a={};let n=e;for(;n<s;){for(;n<s&&t[n]<=32;)n++;if(n>=s)break;const l=n;for(;n<s&&t[n]!==61&&t[n]>32;)n++;const o=n;for(;n<s&&t[n]!==34&&t[n]!==39;)n++;if(n>=s)break;const c=t[n++],r=n,i=t.indexOf(c,n),u=i<0||i>s?s:i;a[L(t,l,o)]=he(L(t,r,u)),n=u+1}return a}function dt(t,e,s){let a=e;for(;a>0&&t[a-1]!==60;)a--;return L(t,a,s)}function ne(t,e=[]){e.push("<",t.n);for(const s of Object.keys(t.a)){const a=t.a[s];a!=null&&e.push(" ",s,'="',ge(a),'"')}if(t.c.length===0&&t.t==="")return e.push("/>"),e;e.push(">"),t.t&&e.push(Y(t.t));for(const s of t.c)typeof s=="string"?e.push(s):ne(s,e);return e.push("</",t.n,">"),e}const ft=new Set(["s","n","d","b","e","m"]);function Te(t,e){switch(t){case"n":return Number(e.v);case"s":return e.v??"";case"d":return U(e.v);case"b":return e.v==="1"||e.v==="true";case"e":return we.get(e.v)??be[6];default:return null}}class Ie{constructor(){this.root=m("#root"),this.stack=[this.root],this.shared=null,this.sharedDepth=0,this.scanner=new me(this)}feed(e){this.scanner.feed(e)}finish(){return this.root.c[0]??null}open(e,s,a,n,l,o){const c=this.stack[this.stack.length-1];if(this.shared!==null&&c===this.shared){const i=L(e,s,a);if(ft.has(i)){const u=Se(e,n,l);c.items.push(Te(i,u)),o||this.sharedDepth++;return}}if(this.sharedDepth>0){o||this.sharedDepth++;return}const r=m(dt(e,s,a),Se(e,n,l));r.n==="sharedItems"&&(r.items=[],this.shared=r),c.c.push(r),o?r.n==="sharedItems"&&(this.shared=null):this.stack.push(r)}close(){if(this.sharedDepth>0){this.sharedDepth--;return}this.stack.pop()===this.shared&&(this.shared=null),this.stack.length===0&&this.stack.push(this.root)}text(e,s,a){if(this.sharedDepth>0)return;let n=!0;for(let l=s;l<a;l++)if(e[l]>32){n=!1;break}n||(this.stack[this.stack.length-1].t+=Qe(L(e,s,a)))}}function Ne(t){const e=new Ie;return e.feed(typeof t=="string"?new TextEncoder().encode(t):t),e.finish()}async function Ce(t,e){if(t instanceof Uint8Array)e.feed(t);else if(t.getReader){const s=t.getReader();for(;;){const{done:a,value:n}=await s.read();if(a)break;e.feed(n)}}else for await(const s of t)e.feed(s);return e.finish()}function U(t){const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(\.\d+)?)?/.exec(t??"");if(!e)return 0;const s=Xe(Number(e[1]),Number(e[2]),Number(e[3]));return e[4]===void 0?s:s+(Number(e[4])*3600+Number(e[5])*60+Number(e[6])+Number(e[7]??0))/86400}const q=(t,e=2)=>String(t).padStart(e,"0");function H(t){const e=je(t),s=Math.floor(e.ms/1e3);return`${q(e.year,4)}-${q(e.month)}-${q(e.day)}T${q(Math.floor(s/3600))}:${q(Math.floor(s/60)%60)}:${q(s%60)}`}class pt{constructor(e){this.positions=e.fields.filter(a=>a.a.databaseField===void 0||T(a.a.databaseField,!0));const s=e.c?Number(e.a.recordCount??1024):1024;this.capacity=Math.max(s,16),this.count=0,this.columns=this.positions.map(()=>({ids:null,kinds:null,nums:null})),this.pool=new Map,this.strings=[],this.at=-1,this.scanner=new me(this),this.inRecord=!1}feed(e){this.scanner.feed(e)}_grow(){this.capacity*=2;const e=(s,a)=>{if(a===null)return null;const n=new s(this.capacity);return n.set(a),n};for(const s of this.columns)s.ids=e(Int32Array,s.ids),s.kinds=e(Uint8Array,s.kinds),s.nums=e(Float64Array,s.nums)}open(e,s,a,n,l){if(a-s!==1)return;const o=e[s];if(o===114){this.count===this.capacity&&this._grow(),this.count++,this.at=0;return}if(this.at<0)return;const c=this.at++,r=this.columns[c];if(r===void 0)return;const i=this.count-1;if(o===120){r.ids===null&&(r.ids=new Int32Array(this.capacity));let d=0,h=Ee(e,n,l);if(h>=0)for(;h<l;h++){const g=e[h]-48;if(g<0||g>9)break;d=d*10+g}r.ids[i]=d;return}if(r.kinds===null&&(r.kinds=new Uint8Array(this.capacity),r.nums=new Float64Array(this.capacity)),o===109)return;const u=Ee(e,n,l);if(u<0)return;let p=u;const f=e[u-1];for(;p<l&&e[p]!==f;)p++;switch(o){case 110:r.kinds[i]=pe,r.nums[i]=Number(L(e,u,p));break;case 115:{const d=he(L(e,u,p));let h=this.pool.get(d);h===void 0&&(h=this.strings.length,this.strings.push(d),this.pool.set(d,h)),r.kinds[i]=Je,r.nums[i]=h;break}case 100:r.kinds[i]=pe,r.nums[i]=U(L(e,u,p)),r.dates=!0;break;case 98:r.kinds[i]=Ue,r.nums[i]=e[u]===49||e[u]===116?1:0;break;case 101:{const d=we.get(L(e,u,p));r.kinds[i]=Ke,r.nums[i]=d?d.index:6;break}default:}}close(e,s,a){a-s===1&&e[s]===114&&(this.at=-1)}text(){}finish(){return this}}function Ee(t,e,s){for(let a=e;a<s-2;a++)if(t[a]===118&&t[a+1]===61&&t[a-1]<=32)return a+3;return-1}async function ht(t){const e=await Ce(t,new Ie),s=b(e,"cacheFields");return{root:e,fields:s?A(s,"cacheField"):[],a:e.a,c:e.c}}async function mt(t,e){return Ce(t,new pt(e))}function Re(t){const e=b(t,"groupItems");return e?e.c.map(s=>Te(s.n,s.a)):[]}function gt(t,e){const s=Number(t.numFmtId??0);return K[s]??e?.(s)??"General"}function wt(t,e,{numFmtOf:s}={}){const a=new tt,{fields:n}=t;a.xml={root:t.root},a.needsRefresh=e==null;const l=e?e.count:0;a.recordCount=l,e&&(a.strings.list=e.strings,a.strings.index=e.pool);let o=0;n.forEach((c,r)=>{const i=new nt(a,r,c.a.name??`Field${r+1}`);i.xml={node:c},J(i,gt(c.a,s));const u=b(c,"sharedItems"),p=u?.items??[],f=c.a.databaseField===void 0||T(c.a.databaseField,!0);if(u&&T(u.a.containsDate,!1)&&i.numFmt==="General"&&J(i,"m/d/yyyy"),c.a.formula!==void 0)i.formula=c.a.formula;else if(f&&e){const d=e.columns[o];d?.ids?(i.rawIds=d.ids.subarray(0,l),i.shared=p.slice()):d?.kinds&&(at(i,d.kinds.subarray(0,l),d.nums.subarray(0,l),l),d.dates&&i.numFmt==="General"&&J(i,"m/d/yyyy"))}else f&&(i.shared=p.slice(),i.rawIds=new Int32Array(0));f&&o++,a.fields.push(i)}),n.forEach((c,r)=>{const i=b(c,"fieldGroup");if(!i)return;const u=a.fields[r],p=i.a.base!==void 0?Number(i.a.base):r;i.a.par!==void 0&&(u.par=Number(i.a.par)),p!==r&&(u.base=p);const f=b(i,"rangePr"),d=b(i,"discretePr"),h=Re(i);if(f){const g=f.a.groupBy??"range",w=T(f.a.autoStart,!0),x=T(f.a.autoEnd,!0);if(g==="range"){const v=Number(f.a.startNum??0),y=Number(f.a.endNum??0),F=Number(f.a.groupInterval??1),S=h.length>1&&/^-?\d+--?\d+$/.test(String(h[1]))&&Number.isInteger(v)&&Number.isInteger(F)&&Number(String(h[1]).match(/^-?\d+-(-?\d+)$/)?.[1])===v+F-1;u.group={kind:"bins",start:v,end:y,interval:F,integer:S,autoStart:w,autoEnd:x,labels:h}}else u.group={kind:"date",part:g,start:Math.floor(U(f.a.startDate)),end:Math.floor(U(f.a.endDate))-1,autoStart:w,autoEnd:x,labels:h}}else if(d&&p!==r){const g=a.fields[p],w=A(d,"x").map(F=>Number(F.a.v??0)),x=h.map(()=>[]),v=b(n[p],"sharedItems")?.items??g.shared??[];w.forEach((F,S)=>{x[F]&&x[F].push($(v[S]??null))});const y=[];h.forEach((F,S)=>{x[S].length===1&&x[S][0]===$(F)||y.push({name:String(F),keys:x[S]})}),u.group={kind:"discrete",groups:y}}});for(const c of a.fields)if(c.formula!==null)try{c.calc=ot(c.formula,a)}catch{c.calc={fn:()=>{throw be[4]},refs:[]}}return a}function se(t,e){const s=t.fields[e].xml?.node,a=s?b(s,"fieldGroup"):null,n=a?Re(a):[];return n.length>0?n:(s?b(s,"sharedItems"):null)?.items??[]}function bt(t){const e=t.a.type??"",s=b(b(t,"autoFilter"),"filterColumn");if(e==="count"||e==="percent"||e==="sum"){const a=b(s,"top10");return a?{top:{count:Number(a.a.val??10),by:e==="count"?"items":e,bottom:a.a.top==="0"||a.a.top==="false",data:Number(t.a.iMeasureFld??0)}}:null}if(He(e))return{dateFilter:Ve(t)};if(e.startsWith("caption"))return{labelFilter:{op:e,value:t.a.stringValue1??"",value2:t.a.stringValue2??""}};if(e.startsWith("value")){const a=A(b(s,"customFilters"),"customFilter");return a.length===0?null:{valueFilter:{op:e,data:Number(t.a.iMeasureFld??0),value:Number(a[0].a.val),value2:a[1]?Number(a[1].a.val):void 0}}}return null}function xt(t){for(const e of A(b(t,"extLst"),"ext")){const s=b(e,"x14:pivotTableDefinition");if(s)return s}return null}function yt(t,e){const s=t?b(t,"extLst"):null,a=[];let n=!1;for(const l of s?.c??[]){const o=b(l,"x14:pivotTableDefinition");if(!o){a.push(l);continue}n=!0;const c={...o.a};delete c.hideValuesRow,e&&(c.hideValuesRow="1"),a.push(m("ext",l.a,l.c.map(r=>r===o?m(o.n,c,o.c):r)))}return!n&&e&&a.push(m("ext",{uri:lt,"xmlns:x14":z},[m("x14:pivotTableDefinition",{hideValuesRow:"1"})])),a.length>0?m("extLst",{},a):null}function vt(t,e,{numFmtOf:s,sheet:a}={}){const n={name:t.a.name??"PivotTable1",fieldOptions:{},rows:A(b(t,"rowFields"),"field").map(d=>Number(d.a.x)),cols:A(b(t,"colFields"),"field").map(d=>Number(d.a.x)),filters:[],values:[],grandRow:T(t.a.colGrandTotals,!0),grandCol:T(t.a.rowGrandTotals,!0),rowCaption:t.a.rowHeaderCaption??null,colCaption:t.a.colHeaderCaption??null,dataCaption:t.a.dataCaption??"Values",grandCaption:t.a.grandTotalCaption??null,emptyText:T(t.a.showMissing,!0)?t.a.missingCaption??"":"",showMissing:T(t.a.showMissing,!0),errorText:T(t.a.showError,!1)?t.a.errorCaption??"":null,showExpandButtons:T(t.a.showDrill,!0),showFieldHeaders:T(t.a.showHeaders,!0),hideValuesRow:T(xt(t)?.a.hideValuesRow,!1)},l=A(b(t,"pivotFields"),"pivotField"),o={root:t,fields:l,itemAttrs:[],pageFields:new Map,rawFilters:[]},c=[];l.forEach((d,h)=>{const g={},w=se(e,h),x=A(b(d,"items"),"item"),v=[],y=[],F=[],S={},C=new Map;for(const N of x){if(N.a.t!==void 0&&N.a.t!=="data")continue;const R=Number(N.a.x??0),k=$(w[R]??null);F.push(k),C.set(k,N.a),T(N.a.h,!1)&&v.push(k),N.a.sd!==void 0&&!T(N.a.sd,!0)&&y.push(k),N.a.n!==void 0&&(S[k]=N.a.n)}o.itemAttrs[h]=C,v.length&&(g.hidden=v),y.length&&(g.collapsedItems=y),Object.keys(S).length&&(g.itemCaptions=S),d.a.name!==void 0&&(g.caption=d.a.name);const D=d.a.sortType??"manual";if(D==="ascending"||D==="descending"){g.sort={order:D==="ascending"?"asc":"desc"};const N=b(b(d,"autoSortScope"),"pivotArea"),R=b(b(N,"references"),"reference");R&&Number(R.a.field)===ve&&(g.sort.data=Number(b(R,"x")?.a.v??0))}else F.length>0&&d.a.axis&&(g.sort={order:"manual",keys:F});const B=Object.entries(te).filter(([,N])=>T(d.a[N],!1)).map(([N])=>N);B.length>0?g.subtotals=B:T(d.a.defaultSubtotal,!0)||(g.subtotals="none"),d.a.subtotalTop!==void 0&&(g.subtotalTop=T(d.a.subtotalTop,!0)),T(d.a.insertBlankRow,!1)&&(g.blankLine=!0),d.a.axis&&T(d.a.showAll,!0)&&(g.showAll=!0),T(d.a.insertPageBreak,!1)&&(g.pageBreak=!0);for(const N of A(b(d,"extLst"),"ext"))T(b(N,"x14:pivotField")?.a.fillDownLabels,!1)&&(g.repeatLabels=!0);if(d.a.axis==="axisRow"||d.a.axis==="axisCol"){const N=T(d.a.compact,!0)?"compact":T(d.a.outline,!0)?"outline":"tabular";c.push([h,N])}Object.keys(g).length>0&&(n.fieldOptions[h]=g)});const r=new Map;for(const[,d]of c)r.set(d,(r.get(d)??0)+1);n.layout=[...r.entries()].sort((d,h)=>h[1]-d[1])[0]?.[0]??"compact";for(const[d,h]of c)h!==n.layout&&(n.fieldOptions[d]??={},n.fieldOptions[d].layout=h);for(const d of A(b(t,"pageFields"),"pageField")){const h=Number(d.a.fld);if(n.filters.push(h),o.pageFields.set(h,d.a),d.a.item!==void 0){const g=A(b(l[h],"items"),"item"),w=g[Number(d.a.item)],x=se(e,h);if(w){const v=$(x[Number(w.a.x??0)]??null),y=[];for(const F of g){if(F.a.t!==void 0&&F.a.t!=="data")continue;const S=$(x[Number(F.a.x??0)]??null);S!==v&&y.push(S)}n.fieldOptions[h]??={},n.fieldOptions[h].hidden=y}}}for(const d of A(b(t,"dataFields"),"dataField")){const h=Number(d.a.fld),g={field:h,name:d.a.name??rt(d.a.subtotal??"sum",e.fields[h].name),agg:d.a.subtotal??"sum",xml:d};let w=d.a.showDataAs??"normal";const x=b(b(d,"extLst"),"ext"),v=x?b(x,"x14:dataField"):null;if(v?.a.pivotShowAs&&(w=v.a.pivotShowAs),w!=="normal"&&(g.showAs={type:w},d.a.baseField!==void 0&&(g.showAs.baseField=Number(d.a.baseField)),d.a.baseItem!==void 0)){const y=Number(d.a.baseItem);if(y===xe)g.showAs.baseItem="prev";else if(y===ye)g.showAs.baseItem="next";else{const F=g.showAs.baseField,S=A(b(l[F],"items"),"item"),C=se(e,F),D=S[y];g.showAs.baseItem=D?$(C[Number(D.a.x??0)]??null):"prev"}}if(d.a.numFmtId!==void 0){const y=Number(d.a.numFmtId),F=K[y]??s?.(y);F&&(g.numFmt=F)}n.values.push(g)}for(const d of A(b(t,"filters"),"filter")){const h=bt(d),g=Number(d.a.fld);if(h===null){o.rawFilters.push(d);continue}n.fieldOptions[g]??={},Object.assign(n.fieldOptions[g],h)}T(t.a.mergeItem,!1)&&(n.mergeLabels=!0);const i=b(t,"pivotTableStyleInfo");i&&(n.style={name:i.a.name??"PivotStyleLight16",rowHeaders:T(i.a.showRowHeaders,!0),colHeaders:T(i.a.showColHeaders,!0),rowStripes:T(i.a.showRowStripes,!1),colStripes:T(i.a.showColStripes,!1),lastColumn:T(i.a.showLastColumn,!0)});const u=new st(e,n);u.xml=o,u.dirty=!1;const p=b(t,"location"),f=p?de(p.a.ref??""):null;if(f){const d=n.filters.length>0?n.filters.length+1:0;u.anchor={sheet:a??null,row:Math.max(0,f.r0-d),col:f.c0},u.renderedRange={r0:u.anchor.row,c0:f.c0,r1:f.r1,c1:f.c1}}return u}async function ae(t,e){const s=Ze(e);if(!t.has(s))return[];const a=Ne(await t.bytes(s));return A(a,"Relationship").map(n=>({id:n.a.Id,type:n.a.Type,target:ze(e,n.a.Target??"")}))}async function zt(t,{sheets:e,book:s,tables:a=[],numFmtOf:n,readRecords:l=!0}){const o=new Map,c=[];for(const{part:r,sheet:i}of e)for(const u of await ae(t,r)){if(u.type!==_.table||!t.has(u.target))continue;const p=Ne(await t.bytes(u.target)),d=(await ae(t,u.target)).find(w=>w.type===_.definition);if(!d||!t.has(d.target))continue;let h=o.get(d.target);if(h===void 0){const w=await ht(await t.stream(d.target)),v=(await ae(t,d.target)).find(F=>F.type===_.records);let y=null;l&&v&&t.has(v.target)&&(y=await mt(await t.stream(v.target),w)),h=wt(w,y,{numFmtOf:n}),h.part=d.target,h.id=p.a.cacheId!==void 0?Number(p.a.cacheId):0,Ft(h,w,s,a),o.set(d.target,h)}const g=vt(p,h,{numFmtOf:n,sheet:i});g.part=u.target,c.push(g)}return{caches:[...o.values()],pivots:c}}function Ft(t,e,s,a){if(!s)return;const n=b(b(e.root,"cacheSource"),"worksheetSource");if(!n)return;if(n.a.name!==void 0){const c=a.find(r=>r.name?.toLowerCase()===n.a.name.toLowerCase());c&&(t.source={type:"table",book:s,table:c});return}const l=de(n.a.ref??""),o=s.sheets.find(c=>c.name===n.a.sheet);l&&o&&(t.source={type:"range",book:s,sheet:o,range:l})}const W=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- `,oe=new TextEncoder;function ke(t){for(const[e,s]of Object.entries(K))if(s===t)return Number(e);return null}function re(t,e){if(t==null)return"<m/>";switch(typeof t){case"number":return e?`<d v="${H(t)}"/>`:`<n v="${t}"/>`;case"string":return`<s v="${ge(t)}"/>`;case"boolean":return`<b v="${t?1:0}"/>`;default:return`<e v="${Y(t.code)}"/>`}}function Ae(t,e){const{hasNum:s,hasInt:a,hasText:n,hasBlank:l,hasOther:o,min:c,max:r,longText:i}=e,u=t.isDate&&s&&!n&&!o,p={};return!n&&!l&&!o&&(p.containsSemiMixedTypes="0"),u&&!l&&(p.containsNonDate="0"),u&&(p.containsDate="1"),n||(p.containsString="0"),l&&(p.containsBlank="1"),(s?1:0)+(n?1:0)+(o?1:0)>1&&(p.containsMixedTypes="1"),s&&!u&&(p.containsNumber="1",a&&(p.containsInteger="1"),p.minValue=String(c),p.maxValue=String(r)),u&&(p.minDate=H(c),p.maxDate=H(Math.floor(r)+1)),i&&(p.longText="1"),{attrs:p,date:u}}function St(t){const e={hasNum:!1,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(const s of t)typeof s=="number"?(e.hasNum=!0,Number.isInteger(s)||(e.hasInt=!1),s<e.min&&(e.min=s),s>e.max&&(e.max=s)):typeof s=="string"?(e.hasText=!0,s.length>255&&(e.longText=!0)):s==null?e.hasBlank=!0:e.hasOther=!0;return e}function Tt(t){const e={hasNum:t.length>0,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(let s=0;s<t.length;s++){const a=t[s];a<e.min&&(e.min=a),a>e.max&&(e.max=a),e.hasInt&&Math.floor(a)!==a&&(e.hasInt=!1)}return e}function De(t){return t.ensureColumn(),t.rawIds!==null?!0:!(t.nums!==null&&t.kinds===null)}function It(t,e){const s=e.group;if(s===null)return e.par>=0?m("fieldGroup",{par:String(e.par)}):null;e.ensure();const a={};e.par>=0&&(a.par=String(e.par)),a.base=String(e.base>=0?e.base:e.index);const n=[],l=e.items.map(c=>re(c,!1)).join("");if(s.kind==="date"){const c={groupBy:s.part,startDate:H(s.start),endDate:H(s.end+1)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else if(s.kind==="bins"){const c={startNum:String(s.start),endNum:String(s.end),groupInterval:String(s.interval)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else{const c=e.groupMap,r=m("discretePr",{count:String(c.length)});for(let i=0;i<c.length;i++)r.c.push(m("x",{v:String(c[i])}));n.push(r)}const o=m("groupItems",{count:String(e.items.length)});return o.c.push(l),n.push(o),m("fieldGroup",a,n)}function Nt(t,e,s){const a=e.xml?.node??null,n={...a?.a??{}};if(n.name=e.name,n.numFmtId===void 0){const c=e.numFmt!=="General"?ke(e.numFmt)??s.numFmtId?.(e.numFmt)??(e.isDate?14:0):0;n.numFmtId=String(c)}const l=[];if(e.isCalculated)n.formula=e.formula,n.databaseField="0",delete n.uniqueList;else if(e.base>=0)n.databaseField="0";else if(t.recordCount===0&&a&&b(a,"sharedItems")){const c=b(a,"sharedItems"),r=m("sharedItems",{...c.a}),i=T(c.a.containsDate,!1);c.items.length>0&&r.c.push(c.items.map(u=>re(u,i&&typeof u=="number")).join("")),l.push(r)}else if(De(e)){e.ensureRaw();const{attrs:c,date:r}=Ae(e,St(e.shared)),i=m("sharedItems",{...c,count:String(e.shared.length)});i.c.push(e.shared.map(u=>re(u,r&&typeof u=="number")).join("")),l.push(i)}else{const{attrs:c}=Ae(e,Tt(e.nums));l.push(m("sharedItems",c))}const o=It(t,e);if(o&&l.push(o),a)for(const c of a.c)c.n!=="sharedItems"&&c.n!=="fieldGroup"&&l.push(c);return m("cacheField",n,l)}function Ct(t,{recordsRel:e=null,numFmtId:s,refreshOnLoad:a=!0,sourceSheetName:n}={}){const l=t.xml?.root??null,o={...l?.a??{}};o.xmlns??=Z,o["xmlns:r"]??=V,e?o["r:id"]=e:delete o["r:id"],a&&(o.refreshOnLoad="1"),o.refreshedBy??="8sheets",o.refreshedDate=String(Et()),o.createdVersion??="6",o.refreshedVersion??="6",o.minRefreshableVersion??="3",o.recordCount=String(t.recordCount),e?delete o.saveData:o.saveData="0";const c=[],r=l?b(l,"cacheSource"):null;c.push(Rt(t,r,n));const i=m("cacheFields",{count:"0"}),u=t.fields;for(const p of u)i.c.push(Nt(t,p,{numFmtId:s}));if(i.a.count=String(u.length),c.push(i),l)for(const p of l.c)p.n!=="cacheSource"&&p.n!=="cacheFields"&&c.push(p);return W+ne(m("pivotCacheDefinition",o,c)).join("")}function Et(){return Math.round((Date.now()/864e5+25569)*1e5)/1e5}function Rt(t,e,s){const a=t.source;if(a===null)return e??m("cacheSource",{type:"worksheet"},[m("worksheetSource",{ref:"A1",sheet:"Sheet1"})]);const n={};if(a.type==="table")n.name=a.table.name;else{const i=a.range,u=s??(typeof a.sheet=="string"?a.sheet:a.sheet.name);n.ref=fe({r0:i.r0,c0:i.c0,r1:i.r1,c1:Math.min(i.c1,Ge-1)}),n.sheet=u}const l=e?{...e.a}:{type:"worksheet"},o=e?e.c.filter(i=>i.n!=="worksheetSource"):[],c=e?b(e,"worksheetSource"):null,r=c?{...c.a,...n}:n;return a.type==="table"&&(delete r.ref,delete r.sheet),m("cacheSource",l,[m("worksheetSource",r),...o])}const kt=4096;async function Oe(t,e){const s=t.recordCount,a=[];for(const l of t.fields)l.isVirtual||(De(l)?(l.ensureRaw(),a.push(At(l.rawIds))):a.push(Dt(l.nums,l.isDate)));await e(oe.encode(`${W}<pivotCacheRecords xmlns="${Z}" xmlns:r="${V}" count="${s}">`));const n=[];for(let l=0;l<s;l++){n.push("<r>");for(let o=0;o<a.length;o++)n.push(a[o](l));n.push("</r>"),(l+1)%kt===0&&(await e(oe.encode(n.join(""))),n.length=0)}n.push("</pivotCacheRecords>"),await e(oe.encode(n.join("")))}function At(t){return e=>`<x v="${t[e]}"/>`}function Dt(t,e){return e?s=>`<d v="${H(t[s])}"/>`:s=>`<n v="${t[s]}"/>`}async function en(t){const e="application/xml";let s=new Blob([],{type:e}),a=[],n=0;return await Oe(t,l=>{a.push(l),n+=l.length,n>=1<<24&&(s=new Blob([s,...a],{type:e}),a=[],n=0)}),new Blob([s,...a],{type:e})}const Le=["location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","formats","conditionalFormats","chartFormats","pivotHierarchies","pivotTableStyleInfo","filters","rowHierarchiesUsage","colHierarchiesUsage","extLst"];function Ot(t,e){const s=t.cache.fields[e].ensure(),a=s.rank(),n=Array.from(s.items.keys()),o=t.spec.fieldOptions[e]?.sort;if(o?.order==="manual"){const r=new Map((o.keys??[]).map((p,f)=>[p,f])),i=r.size,u=p=>r.get($(s.items[p]))??i+a[p];n.sort((p,f)=>u(p)-u(f))}else o?.order==="desc"&&(o.data===void 0||o.data===null)?n.sort((r,i)=>a[i]-a[r]):n.sort((r,i)=>a[r]-a[i]);const c=new Int32Array(n.length);return n.forEach((r,i)=>{c[r]=i}),{order:n,position:c}}function Lt(t){return t.group!==null||t.base>=0}function Pt(t,e){return t.spec.fieldOptions[e]?.layout??t.spec.layout}const Bt=["axis","dataField","compact","outline","subtotalTop","sortType","defaultSubtotal","insertBlankRow","name","showDropDowns","dragToRow","dragToCol","dragToPage",...Object.values(te)];function Mt(t,e,s){const{spec:a,cache:n}=t,l=n.fields[e],o=a.fieldOptions[e]??{},c=t.xml?.fields?.[e]??null,r={...c?.a??{}};for(const S of Bt)delete r[S];o.caption!==void 0&&(r.name=o.caption);const i=a.rows.includes(e),u=a.cols.includes(e),p=a.filters.includes(e),f=a.values.some(S=>S.field===e);i?r.axis="axisRow":u?r.axis="axisCol":p&&(r.axis="axisPage"),f&&(r.dataField="1");const d=Pt(t,e);d!=="compact"&&(r.compact="0"),d==="tabular"&&(r.outline="0"),l.isCalculated&&(r.dragToRow="0",r.dragToCol="0",r.dragToPage="0"),r.showAll=o.showAll?"1":"0",o.pageBreak?r.insertPageBreak="1":delete r.insertPageBreak,(o.subtotalTop??a.subtotalTop)===!1&&(i||u)&&(r.subtotalTop="0"),o.blankLine&&(r.insertBlankRow="1"),o.sort?.order==="asc"?r.sortType="ascending":o.sort?.order==="desc"&&(r.sortType="descending");const h=o.subtotals??"auto",g=i||u||p,w=(o.hidden?.length??0)>0,x=g||Lt(l)||w||!!(o.range||o.dateFilter);if((l.isCalculated||h==="none"||Array.isArray(h)||l.base>=0&&!g)&&(r.defaultSubtotal="0"),Array.isArray(h))for(const S of h)r[te[S]]="1";const v=[];if(x&&!l.isCalculated){const{order:S}=s(e),C=m("items",{}),D=new Set(o.hidden??[]),B=new Set(o.collapsedItems??[]),N=t.xml?.itemAttrs?.[e]??null,R=o.itemCaptions??null;for(const k of S){const P=l.keyOf(k),O={...N?.get(P)??{}};delete O.h,delete O.sd,delete O.n,O.x=String(k),D.has(P)&&(O.h="1"),B.has(P)&&(O.sd="0"),R&&R[P]!==void 0&&(O.n=R[P]),C.c.push(m("item",O))}if((g||w||o.range||o.dateFilter)&&r.defaultSubtotal===void 0&&C.c.push(m("item",{t:"default"})),Array.isArray(h))for(const k of h)C.c.push(m("item",{t:Fe[k]}));C.a.count=String(C.c.length),v.push(C)}if(o.sort?.data!==void 0&&o.sort?.data!==null&&(o.sort.order==="asc"||o.sort.order==="desc")&&v.push(m("autoSortScope",{},[m("pivotArea",{dataOnly:"0",outline:"0",fieldPosition:"0"},[m("references",{count:"1"},[m("reference",{field:String(ve),count:"1",selected:"0"},[m("x",{v:String(o.sort.data)})])])])])),c)for(const S of c.c)S.n!=="items"&&S.n!=="autoSortScope"&&S.n!=="extLst"&&v.push(S);const y=o.repeatLabels===!0||a.repeatLabels===!0&&i&&d!=="compact",F=$t(c,y);return F&&v.push(F),m("pivotField",r,v)}function $t(t,e){const s=[];let a=!1;for(const n of A(t?b(t,"extLst"):null,"ext")){const l=b(n,"x14:pivotField");if(!l){s.push(n);continue}a=!0;const o={...l.a};delete o.fillDownLabels,e&&(o.fillDownLabels="1"),s.push(m("ext",n.a,n.c.map(c=>c===l?m(l.n,o,l.c):c)))}return!a&&e&&s.push(m("ext",{uri:ct,"xmlns:x14":z},[m("x14:pivotField",{fillDownLabels:"1"})])),s.length>0?m("extLst",{},s):null}function Pe(t,e,s,a){const n=s.lines,l=m(t,{}),{slots:o}=s;let c=[];for(let r=0;r<n.node.length;r++){const i=n.type[r],u=n.level[r],p={},f=[];if(o.length===0){l.c.push(m("i",{}));continue}if(i===j.GRAND){p.t="grand";const w=n.data[r];w>0&&(p.i=String(w));const x=m("i",p,[m("x",w>0?{v:String(w)}:{})]);l.c.push(x),c=[];continue}i===j.BLANK?p.t="blank":i===j.SUBTOTAL&&(p.t=n.func[r]?Fe[n.func[r]]:"default");let d=0;for(let w=0;w<=u;w++)if(o[w]===Q)f.push(n.data[r]>=0?n.data[r]:0);else{d++;const x=s.ancestorAt(n.node[r],d);f.push(a(o[w]).position[s.item[x]])}n.data[r]>0&&(p.i=String(n.data[r]));let h=0;if(i===j.ITEM)for(;h<f.length-1&&h<c.length&&c[h]===f[h];)h++;h>0&&(p.r=String(h));const g=m("i",p);for(let w=h;w<f.length;w++)g.c.push(m("x",f[w]===0?{}:{v:String(f[w])}));l.c.push(g),c=f}return l.c.length===0&&l.c.push(m("i",{})),l.a.count=String(l.c.length),l}function _t(t,e){const{spec:s}=t,a=[];let n=1;const l=(c,r,i,u)=>m("filter",{fld:String(c),type:r,evalOrder:"-1",id:String(n++),...i},[m("autoFilter",{ref:"A1"},[m("filterColumn",{colId:"0"},[u])])]),o=(c,r)=>m("customFilters",r?{and:"1"}:{},c.map(i=>m("customFilter",i)));for(const c of e){const r=s.fieldOptions[c];if(r){if(r.labelFilter){const i=r.labelFilter,u=String(i.value??""),p=String(i.value2??""),f={stringValue1:u};(i.op==="captionBetween"||i.op==="captionNotBetween")&&(f.stringValue2=p);const d={captionEqual:()=>o([{val:u}]),captionNotEqual:()=>o([{operator:"notEqual",val:u}]),captionBeginsWith:()=>o([{val:`${u}*`}]),captionNotBeginsWith:()=>o([{operator:"notEqual",val:`${u}*`}]),captionEndsWith:()=>o([{val:`*${u}`}]),captionNotEndsWith:()=>o([{operator:"notEqual",val:`*${u}`}]),captionContains:()=>o([{val:`*${u}*`}]),captionNotContains:()=>o([{operator:"notEqual",val:`*${u}*`}]),captionGreaterThan:()=>o([{operator:"greaterThan",val:u}]),captionGreaterThanOrEqual:()=>o([{operator:"greaterThanOrEqual",val:u}]),captionLessThan:()=>o([{operator:"lessThan",val:u}]),captionLessThanOrEqual:()=>o([{operator:"lessThanOrEqual",val:u}]),captionBetween:()=>o([{operator:"greaterThanOrEqual",val:u},{operator:"lessThanOrEqual",val:p}],!0),captionNotBetween:()=>o([{operator:"lessThan",val:u},{operator:"greaterThan",val:p}])}[i.op];d&&a.push(l(c,i.op,f,d()))}if(r.valueFilter){const i=r.valueFilter,u=String(i.value),p=String(i.value2??""),f={valueEqual:[[{val:u}]],valueNotEqual:[[{operator:"notEqual",val:u}]],valueGreaterThan:[[{operator:"greaterThan",val:u}]],valueGreaterThanOrEqual:[[{operator:"greaterThanOrEqual",val:u}]],valueLessThan:[[{operator:"lessThan",val:u}]],valueLessThanOrEqual:[[{operator:"lessThanOrEqual",val:u}]],valueBetween:[[{operator:"greaterThanOrEqual",val:u},{operator:"lessThanOrEqual",val:p}],!0],valueNotBetween:[[{operator:"lessThan",val:u},{operator:"greaterThan",val:p}]]}[i.op];f&&a.push(l(c,i.op,{iMeasureFld:String(i.data??0)},o(f[0],f[1]===!0)))}if(a.push(...qe(r,c,m,()=>n++)),r.top){const i=r.top,u={val:String(i.count??10),filterVal:String(i.count??10)};i.by==="percent"&&(u.percent="1"),i.bottom&&(u.top="0");const p=i.by==="percent"?"percent":i.by==="sum"?"sum":"count";a.push(l(c,p,{iMeasureFld:String(i.data??0)},m("top10",u)))}}}return a}function qt(t,e,s,a){const n=e.xml??null,l={...n?.a??{}};l.name=e.name,l.fld=String(e.field),e.agg&&e.agg!=="sum"?l.subtotal=e.agg:delete l.subtotal,delete l.showDataAs;const o=e.showAs?.type??"normal",c=n?n.c.filter(g=>g.n!=="extLst"):[];let r=null;ut.has(o)?r=o:o!=="normal"&&(l.showDataAs=o);const i=e.showAs?.baseField??0;l.baseField=String(i>=0?i:0);let u=0;const p=e.showAs?.baseItem;if(p==="prev")u=xe;else if(p==="next")u=ye;else if(p!==void 0&&e.showAs?.baseField>=0){const g=t.cache.fields[e.showAs.baseField].ensure(),w=g.keyIndex.get(p);w!==void 0&&(u=s(g.index).position[w])}l.baseItem=String(u);const f=e.numFmt??(o!=="normal"&&!o.startsWith("rank")&&o!=="difference"&&o!=="runTotal"?o==="index"?"0.00":"0.00%":null);if(f){const g=ke(f)??a.numFmtId?.(f);g!=null&&(l.numFmtId=String(g))}else delete l.numFmtId;const d=[],h=n?b(n,"extLst"):null;if(h)for(const g of h.c)if(b(g,"x14:dataField")){const w={...b(g,"x14:dataField").a};delete w.pivotShowAs,r&&(w.pivotShowAs=r),d.push(m("ext",g.a,[m("x14:dataField",w)])),r=null}else d.push(g);return r&&d.push(m("ext",{uri:it,"xmlns:x14":z},[m("x14:dataField",{pivotShowAs:r})])),d.length&&c.push(m("extLst",{},d)),m("dataField",l,c)}function Ht(t,{cacheId:e,numFmtId:s}={}){const a=t.result??t.update(),{spec:n,cache:l}=t,{layout:o,rows:c,cols:r}=a,i=new Map,u=I=>{let E=i.get(I);return E===void 0&&(E=Ot(t,I),i.set(I,E)),E},p=t.xml?.root??null,f={...p?.a??{}};f.xmlns??=Z,f.name=n.name,f.cacheId=String(e??l.id??1),f.applyNumberFormats??="0",f.applyBorderFormats??="0",f.applyFontFormats??="0",f.applyPatternFormats??="0",f.applyAlignmentFormats??="0",f.applyWidthHeightFormats??="1",f.dataCaption=n.dataCaption,f.updatedVersion??="6",f.minRefreshableVersion??="3",f.useAutoFormatting??="1",f.itemPrintTitles??="1",f.createdVersion??="6",f.indent??="0",n.mergeLabels?f.mergeItem="1":delete f.mergeItem,t.fileAttrs&&Object.assign(f,t.fileAttrs);const d=(I,E,G)=>{E===G?delete f[I]:f[I]=E?"1":"0"};d("compact",n.layout==="compact",!0),d("compactData",n.layout==="compact",!0),f.outline=n.layout==="tabular"?f.outline??"1":"1",f.outlineData=n.layout==="tabular"?f.outlineData??"1":"1",d("colGrandTotals",n.grandRow,!0),d("rowGrandTotals",n.grandCol,!0),n.rowCaption!=null?f.rowHeaderCaption=n.rowCaption:delete f.rowHeaderCaption,n.colCaption!=null?f.colHeaderCaption=n.colCaption:delete f.colHeaderCaption,n.grandCaption!=null?f.grandTotalCaption=n.grandCaption:delete f.grandTotalCaption,n.emptyText!==""&&n.showMissing!==!1?f.missingCaption=n.emptyText:delete f.missingCaption,n.showMissing===!1?f.showMissing="0":delete f.showMissing,n.errorText!==null?(f.showError="1",f.errorCaption=n.errorText):(delete f.showError,delete f.errorCaption),c.slots.includes(Q)?(f.dataOnRows="1",f.dataPosition=String(c.slots.indexOf(Q))):(delete f.dataOnRows,delete f.dataPosition);const h=Object.keys(n.fieldOptions).map(Number),g=h.some(I=>{const E=n.fieldOptions[I];return(E.labelFilter?1:0)+(E.valueFilter?1:0)+(E.top?1:0)>1});f.multipleFieldFilters=g?"1":"0";const w=t.anchor??{row:0,col:0},x=w.row+o.pageRows,v={ref:fe({r0:x,c0:w.col,r1:w.row+o.rows-1,c1:w.col+Math.max(o.bodyCols,1)-1}),firstHeaderRow:String(o.firstHeaderRow),firstDataRow:String(o.firstDataRow),firstDataCol:String(o.firstDataCol)};n.filters.length>0&&(v.rowPageCount=String(n.filters.length),v.colPageCount="1");const y=new Map;y.set("location",m("location",v));const F=m("pivotFields",{count:String(l.fields.length)});for(let I=0;I<l.fields.length;I++)F.c.push(Mt(t,I,u));y.set("pivotFields",F);const S=(I,E)=>m(I,{count:String(E.length)},E.map(G=>m("field",{x:String(G)})));if(c.slots.length>0&&y.set("rowFields",S("rowFields",c.slots)),y.set("rowItems",Pe("rowItems",a,c,u)),r.slots.length>0&&y.set("colFields",S("colFields",r.slots)),y.set("colItems",Pe("colItems",a,r,u)),n.filters.length>0){const I=m("pageFields",{count:String(n.filters.length)});for(const E of n.filters){const X={...t.xml?.pageFields?.get(E)??{},fld:String(E)};delete X.item,X.hier??="-1";const le=l.fields[E].ensure(),ce=n.fieldOptions[E]?.hidden??[];if(ce.length===le.items.length-1){const Be=new Set(ce),ue=u(E).order.findIndex(Me=>!Be.has(le.keyOf(Me)));ue>=0&&(X.item=String(ue))}I.c.push(m("pageField",X))}y.set("pageFields",I)}n.values.length>0&&y.set("dataFields",m("dataFields",{count:String(n.values.length)},n.values.map(I=>qt(t,I,u,{numFmtId:s}))));const C=n.style,D=p?b(p,"pivotTableStyleInfo"):null;y.set("pivotTableStyleInfo",m("pivotTableStyleInfo",{...D?.a??{},name:C.name,showRowHeaders:C.rowHeaders?"1":"0",showColHeaders:C.colHeaders?"1":"0",showRowStripes:C.rowStripes?"1":"0",showColStripes:C.colStripes?"1":"0",showLastColumn:C.lastColumn===!1?"0":"1"}));const B=_t(t,h),N=t.xml?.rawFilters??[],R=[...B,...N];R.length>0&&y.set("filters",m("filters",{count:String(R.length)},R));const k=$e(t,m);k&&y.set("conditionalFormats",k);const P=_e(t,m);P&&y.set("chartFormats",P);const O=yt(p,n.hideValuesRow);O&&y.set("extLst",O);const M=[];for(const I of Le)if(y.has(I))M.push(y.get(I));else if(p&&!Vt.has(I)){const E=b(p,I);E&&M.push(E)}if(p)for(const I of p.c)Le.includes(I.n)||M.splice(M.length-(M[M.length-1]?.n==="extLst"?1:0),0,I);return W+ne(m("pivotTableDefinition",f,M)).join("")}const Vt=new Set(["extLst","location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","pivotTableStyleInfo","filters"]);function ie(t,e){for(let s=1;;s++){const a=e(s);if(!t.has(a))return t.add(a),a}}function tn(t){const e=t.map(s=>`<Relationship Id="${s.id}" Type="${s.type}" Target="${Y(s.target)}"/>`).join("");return`${W}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${e}</Relationships>`}function nn(t,{existing:e=[],saveRecords:s=!0,numFmtId:a,refreshOnLoad:n=!0,firstCacheId:l=1}={}){const o=new Set(e),c=[],r=[],i=[],u=[],p=new Map;let f=l;const d=x=>{c.push(x),i.push({partName:`/${x.name}`,contentType:x.contentType})},h=t.filter(x=>x.dirty||!x.part),g=[],w=new Set(t.filter(x=>!h.includes(x)).map(x=>x.cache));for(const x of h){const{cache:v}=x;x.part&&g.push(x.part),v.part&&!w.has(v)&&(g.push(v.part),v.part=null);let y=p.get(v);if(y===void 0){const S=f++,C=ie(o,R=>`xl/pivotCache/pivotCacheDefinition${R}.xml`);v.id=S;let D=null;if(s&&v.recordCount>0){const R=ie(o,k=>`xl/pivotCache/pivotCacheRecords${k}.xml`);D="rId1",r.push({from:C,id:D,type:_.records,target:`/${R}`}),d({name:R,contentType:ee.records,large:!0,produce:k=>Oe(v,k)})}const N={name:C,contentType:ee.definition,xml:null};d(N),y={cacheId:S,defName:C,defPart:N,recordsRel:D},p.set(v,y),u.push({cacheId:S,target:`/${C}`,type:_.definition})}x.result||x.update();const F=ie(o,S=>`xl/pivotTables/pivotTable${S}.xml`);d({name:F,contentType:ee.table,xml:Ht(x,{cacheId:y.cacheId,numFmtId:a})}),r.push({from:F,id:"rId1",type:_.definition,target:`/${y.defName}`}),r.push({from:null,sheet:x.anchor?.sheet??null,id:null,type:_.table,target:`/${F}`}),x.part=F}for(const[x,v]of p)v.defPart.xml=Ct(x,{recordsRel:v.recordsRel,numFmtId:a,refreshOnLoad:n});return{parts:c,relationships:r,contentTypes:i,replaced:g,workbook:{pivotCaches:u,pivotCachesXml(x){return u.length===0?"":`<pivotCaches>${u.map(v=>`<pivotCache cacheId="${v.cacheId}" r:id="${x(v.cacheId)}"/>`).join("")}</pivotCaches>`}}}}export{ee as CONTENT_TYPE,pt as CacheRecordsReader,We as EMPTY,Ye as ERRORS,Ie as NodeReader,_ as REL_TYPE,et as XlError,nn as buildPivotPackage,Ct as cacheDefinitionXml,wt as cacheFromXml,U as isoToSerial,Ne as parseNode,vt as pivotFromXml,Ht as pivotTableXml,ht as readCacheDefinition,mt as readCacheRecords,zt as readPivotParts,en as recordsBlob,tn as relationshipsXml,H as serialToIso,ne as serializeNode,Oe as writeCacheRecords};
1
+ import{pivotCfNode as $e,pivotChartFormatsNode as _e}from"../slicers/pivot-file.js";import{dateFilterNodes as qe,isDateFilterType as He,parseDateFilter as Ve}from"../slicers/date-filters.js";import{MAX_COLS as Ge,parseRangeRef as de,rangeRef as fe}from"../core/address.js";import{BUILTIN_FORMATS as Y,partsToSerial as Xe,serialToParts as je}from"../core/numfmt.js";import{BOOL as Ue,EMPTY as We,ERR as Ke,ERRORS as Ye,NUM as pe,STR as Je}from"../core/sheet.js";import{decodeRange as L,unescapeXml as Qe,unescapeXstring as he,XmlScanner as me}from"../io/xml-scan.js";import{escapeMarkup as J,xmlAttr as ge}from"../io/xml-escape.js";import{relsPathOf as Ze,resolveTarget as ze}from"../io/package-paths.js";import{ERR_BY_CODE as we,ERR_BY_INDEX as be,XlError as et}from"../calc/values.js";import{applyNumFmt as Q,itemKey as $,LINE as j,PivotCache as tt,PivotField as nt,PivotTable as st,storeColumn as at,VALUES as Z,compileCalc as ot,valueFieldName as rt}from"./engine.js";const U="http://schemas.openxmlformats.org/spreadsheetml/2006/main",V="http://schemas.openxmlformats.org/officeDocument/2006/relationships",z="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",it="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}",lt="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}",ct="{2946ED86-A175-432a-8AC1-64E0C546D7DE}",ee={table:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",definition:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",records:"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"},_={table:`${V}/pivotTable`,definition:`${V}/pivotCacheDefinition`,records:`${V}/pivotCacheRecords`},xe=1048828,ye=1048829,ve=4294967294,ut=new Set(["percentOfParent","percentOfParentRow","percentOfParentCol","percentOfRunningTotal","rankAscending","rankDescending"]),te={sum:"sumSubtotal",count:"countASubtotal",average:"avgSubtotal",max:"maxSubtotal",min:"minSubtotal",product:"productSubtotal",countNums:"countSubtotal",stdDev:"stdDevSubtotal",stdDevp:"stdDevPSubtotal",var:"varSubtotal",varp:"varPSubtotal"},Fe={sum:"sum",count:"countA",average:"avg",max:"max",min:"min",product:"product",countNums:"count",stdDev:"stdDev",stdDevp:"stdDevP",var:"var",varp:"varP"},m=(t,e={},s=[])=>({n:t,a:e,c:s,t:""}),b=(t,e)=>t?.c.find(s=>s.n===e)??null,A=(t,e)=>t?t.c.filter(s=>s.n===e):[],T=(t,e)=>t===void 0?e:t==="1"||t==="true";function Se(t,e,s){const a={};let n=e;for(;n<s;){for(;n<s&&t[n]<=32;)n++;if(n>=s)break;const l=n;for(;n<s&&t[n]!==61&&t[n]>32;)n++;const o=n;for(;n<s&&t[n]!==34&&t[n]!==39;)n++;if(n>=s)break;const c=t[n++],r=n,i=t.indexOf(c,n),d=i<0||i>s?s:i;a[L(t,l,o)]=he(L(t,r,d)),n=d+1}return a}function dt(t,e,s){let a=e;for(;a>0&&t[a-1]!==60;)a--;return L(t,a,s)}function ne(t,e=[]){e.push("<",t.n);for(const s of Object.keys(t.a)){const a=t.a[s];a!=null&&e.push(" ",s,'="',ge(a),'"')}if(t.c.length===0&&t.t==="")return e.push("/>"),e;e.push(">"),t.t&&e.push(J(t.t));for(const s of t.c)typeof s=="string"?e.push(s):ne(s,e);return e.push("</",t.n,">"),e}const ft=new Set(["s","n","d","b","e","m"]);function Te(t,e){switch(t){case"n":return Number(e.v);case"s":return e.v??"";case"d":return W(e.v);case"b":return e.v==="1"||e.v==="true";case"e":return we.get(e.v)??be[6];default:return null}}class Ie{constructor(){this.root=m("#root"),this.stack=[this.root],this.shared=null,this.sharedDepth=0,this.scanner=new me(this)}feed(e){this.scanner.feed(e)}finish(){return this.root.c[0]??null}open(e,s,a,n,l,o){const c=this.stack[this.stack.length-1];if(this.shared!==null&&c===this.shared){const f=L(e,s,a);if(ft.has(f)){const u=Se(e,n,l);c.items.push(Te(f,u)),o||this.sharedDepth++;return}}if(this.sharedDepth>0){o||this.sharedDepth++;return}const r=Se(e,n,l);let i=dt(e,s,a);const d=i.indexOf(":");if(d>=0){const f="xmlns:"+i.slice(0,d);let u=r[f];for(let h=this.stack.length-1;u===void 0&&h>0;h--)u=this.stack[h].a[f];u===U&&(i=i.slice(d+1))}const p=m(i,r);p.n==="sharedItems"&&(p.items=[],this.shared=p),c.c.push(p),o?p.n==="sharedItems"&&(this.shared=null):this.stack.push(p)}close(){if(this.sharedDepth>0){this.sharedDepth--;return}this.stack.pop()===this.shared&&(this.shared=null),this.stack.length===0&&this.stack.push(this.root)}text(e,s,a){if(this.sharedDepth>0)return;let n=!0;for(let l=s;l<a;l++)if(e[l]>32){n=!1;break}n||(this.stack[this.stack.length-1].t+=Qe(L(e,s,a)))}}function Ne(t){const e=new Ie;return e.feed(typeof t=="string"?new TextEncoder().encode(t):t),e.finish()}async function Ce(t,e){if(t instanceof Uint8Array)e.feed(t);else if(t.getReader){const s=t.getReader();for(;;){const{done:a,value:n}=await s.read();if(a)break;e.feed(n)}}else for await(const s of t)e.feed(s);return e.finish()}function W(t){const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(\.\d+)?)?/.exec(t??"");if(!e)return 0;const s=Xe(Number(e[1]),Number(e[2]),Number(e[3]));return e[4]===void 0?s:s+(Number(e[4])*3600+Number(e[5])*60+Number(e[6])+Number(e[7]??0))/86400}const q=(t,e=2)=>String(t).padStart(e,"0");function H(t){const e=je(t),s=Math.floor(e.ms/1e3);return`${q(e.year,4)}-${q(e.month)}-${q(e.day)}T${q(Math.floor(s/3600))}:${q(Math.floor(s/60)%60)}:${q(s%60)}`}class pt{constructor(e){this.positions=e.fields.filter(a=>a.a.databaseField===void 0||T(a.a.databaseField,!0));const s=e.c?Number(e.a.recordCount??1024):1024;this.capacity=Math.max(s,16),this.count=0,this.columns=this.positions.map(()=>({ids:null,kinds:null,nums:null})),this.pool=new Map,this.strings=[],this.at=-1,this.scanner=new me(this),this.inRecord=!1}feed(e){this.scanner.feed(e)}_grow(){this.capacity*=2;const e=(s,a)=>{if(a===null)return null;const n=new s(this.capacity);return n.set(a),n};for(const s of this.columns)s.ids=e(Int32Array,s.ids),s.kinds=e(Uint8Array,s.kinds),s.nums=e(Float64Array,s.nums)}open(e,s,a,n,l){if(a-s!==1)return;const o=e[s];if(o===114){this.count===this.capacity&&this._grow(),this.count++,this.at=0;return}if(this.at<0)return;const c=this.at++,r=this.columns[c];if(r===void 0)return;const i=this.count-1;if(o===120){r.ids===null&&(r.ids=new Int32Array(this.capacity));let u=0,h=Ee(e,n,l);if(h>=0)for(;h<l;h++){const g=e[h]-48;if(g<0||g>9)break;u=u*10+g}r.ids[i]=u;return}if(r.kinds===null&&(r.kinds=new Uint8Array(this.capacity),r.nums=new Float64Array(this.capacity)),o===109)return;const d=Ee(e,n,l);if(d<0)return;let p=d;const f=e[d-1];for(;p<l&&e[p]!==f;)p++;switch(o){case 110:r.kinds[i]=pe,r.nums[i]=Number(L(e,d,p));break;case 115:{const u=he(L(e,d,p));let h=this.pool.get(u);h===void 0&&(h=this.strings.length,this.strings.push(u),this.pool.set(u,h)),r.kinds[i]=Je,r.nums[i]=h;break}case 100:r.kinds[i]=pe,r.nums[i]=W(L(e,d,p)),r.dates=!0;break;case 98:r.kinds[i]=Ue,r.nums[i]=e[d]===49||e[d]===116?1:0;break;case 101:{const u=we.get(L(e,d,p));r.kinds[i]=Ke,r.nums[i]=u?u.index:6;break}default:}}close(e,s,a){a-s===1&&e[s]===114&&(this.at=-1)}text(){}finish(){return this}}function Ee(t,e,s){for(let a=e;a<s-2;a++)if(t[a]===118&&t[a+1]===61&&t[a-1]<=32)return a+3;return-1}async function ht(t){const e=await Ce(t,new Ie),s=b(e,"cacheFields");return{root:e,fields:s?A(s,"cacheField"):[],a:e.a,c:e.c}}async function mt(t,e){return Ce(t,new pt(e))}function Re(t){const e=b(t,"groupItems");return e?e.c.map(s=>Te(s.n,s.a)):[]}function gt(t,e){const s=Number(t.numFmtId??0);return Y[s]??e?.(s)??"General"}function wt(t,e,{numFmtOf:s}={}){const a=new tt,{fields:n}=t;a.xml={root:t.root},a.needsRefresh=e==null;const l=e?e.count:0;a.recordCount=l,e&&(a.strings.list=e.strings,a.strings.index=e.pool);let o=0;n.forEach((c,r)=>{const i=new nt(a,r,c.a.name??`Field${r+1}`);i.xml={node:c},Q(i,gt(c.a,s));const d=b(c,"sharedItems"),p=d?.items??[],f=c.a.databaseField===void 0||T(c.a.databaseField,!0);if(d&&T(d.a.containsDate,!1)&&i.numFmt==="General"&&Q(i,"m/d/yyyy"),c.a.formula!==void 0)i.formula=c.a.formula;else if(f&&e){const u=e.columns[o];u?.ids?(i.rawIds=u.ids.subarray(0,l),i.shared=p.slice()):u?.kinds&&(at(i,u.kinds.subarray(0,l),u.nums.subarray(0,l),l),u.dates&&i.numFmt==="General"&&Q(i,"m/d/yyyy"))}else f&&(i.shared=p.slice(),i.rawIds=new Int32Array(0));f&&o++,a.fields.push(i)}),n.forEach((c,r)=>{const i=b(c,"fieldGroup");if(!i)return;const d=a.fields[r],p=i.a.base!==void 0?Number(i.a.base):r;i.a.par!==void 0&&(d.par=Number(i.a.par)),p!==r&&(d.base=p);const f=b(i,"rangePr"),u=b(i,"discretePr"),h=Re(i);if(f){const g=f.a.groupBy??"range",w=T(f.a.autoStart,!0),x=T(f.a.autoEnd,!0);if(g==="range"){const v=Number(f.a.startNum??0),y=Number(f.a.endNum??0),F=Number(f.a.groupInterval??1),S=h.length>1&&/^-?\d+--?\d+$/.test(String(h[1]))&&Number.isInteger(v)&&Number.isInteger(F)&&Number(String(h[1]).match(/^-?\d+-(-?\d+)$/)?.[1])===v+F-1;d.group={kind:"bins",start:v,end:y,interval:F,integer:S,autoStart:w,autoEnd:x,labels:h}}else d.group={kind:"date",part:g,start:Math.floor(W(f.a.startDate)),end:Math.floor(W(f.a.endDate))-1,autoStart:w,autoEnd:x,labels:h}}else if(u&&p!==r){const g=a.fields[p],w=A(u,"x").map(F=>Number(F.a.v??0)),x=h.map(()=>[]),v=b(n[p],"sharedItems")?.items??g.shared??[];w.forEach((F,S)=>{x[F]&&x[F].push($(v[S]??null))});const y=[];h.forEach((F,S)=>{x[S].length===1&&x[S][0]===$(F)||y.push({name:String(F),keys:x[S]})}),d.group={kind:"discrete",groups:y}}});for(const c of a.fields)if(c.formula!==null)try{c.calc=ot(c.formula,a)}catch{c.calc={fn:()=>{throw be[4]},refs:[]}}return a}function se(t,e){const s=t.fields[e].xml?.node,a=s?b(s,"fieldGroup"):null,n=a?Re(a):[];return n.length>0?n:(s?b(s,"sharedItems"):null)?.items??[]}function bt(t){const e=t.a.type??"",s=b(b(t,"autoFilter"),"filterColumn");if(e==="count"||e==="percent"||e==="sum"){const a=b(s,"top10");return a?{top:{count:Number(a.a.val??10),by:e==="count"?"items":e,bottom:a.a.top==="0"||a.a.top==="false",data:Number(t.a.iMeasureFld??0)}}:null}if(He(e))return{dateFilter:Ve(t)};if(e.startsWith("caption"))return{labelFilter:{op:e,value:t.a.stringValue1??"",value2:t.a.stringValue2??""}};if(e.startsWith("value")){const a=A(b(s,"customFilters"),"customFilter");return a.length===0?null:{valueFilter:{op:e,data:Number(t.a.iMeasureFld??0),value:Number(a[0].a.val),value2:a[1]?Number(a[1].a.val):void 0}}}return null}function xt(t){for(const e of A(b(t,"extLst"),"ext")){const s=b(e,"x14:pivotTableDefinition");if(s)return s}return null}function yt(t,e){const s=t?b(t,"extLst"):null,a=[];let n=!1;for(const l of s?.c??[]){const o=b(l,"x14:pivotTableDefinition");if(!o){a.push(l);continue}n=!0;const c={...o.a};delete c.hideValuesRow,e&&(c.hideValuesRow="1"),a.push(m("ext",l.a,l.c.map(r=>r===o?m(o.n,c,o.c):r)))}return!n&&e&&a.push(m("ext",{uri:lt,"xmlns:x14":z},[m("x14:pivotTableDefinition",{hideValuesRow:"1"})])),a.length>0?m("extLst",{},a):null}function vt(t,e,{numFmtOf:s,sheet:a}={}){const n={name:t.a.name??"PivotTable1",fieldOptions:{},rows:A(b(t,"rowFields"),"field").map(u=>Number(u.a.x)),cols:A(b(t,"colFields"),"field").map(u=>Number(u.a.x)),filters:[],values:[],grandRow:T(t.a.colGrandTotals,!0),grandCol:T(t.a.rowGrandTotals,!0),rowCaption:t.a.rowHeaderCaption??null,colCaption:t.a.colHeaderCaption??null,dataCaption:t.a.dataCaption??"Values",grandCaption:t.a.grandTotalCaption??null,emptyText:T(t.a.showMissing,!0)?t.a.missingCaption??"":"",showMissing:T(t.a.showMissing,!0),errorText:T(t.a.showError,!1)?t.a.errorCaption??"":null,showExpandButtons:T(t.a.showDrill,!0),showFieldHeaders:T(t.a.showHeaders,!0),hideValuesRow:T(xt(t)?.a.hideValuesRow,!1)},l=A(b(t,"pivotFields"),"pivotField"),o={root:t,fields:l,itemAttrs:[],pageFields:new Map,rawFilters:[]},c=[];l.forEach((u,h)=>{const g={},w=se(e,h),x=A(b(u,"items"),"item"),v=[],y=[],F=[],S={},C=new Map;for(const N of x){if(N.a.t!==void 0&&N.a.t!=="data")continue;const R=Number(N.a.x??0),k=$(w[R]??null);F.push(k),C.set(k,N.a),T(N.a.h,!1)&&v.push(k),N.a.sd!==void 0&&!T(N.a.sd,!0)&&y.push(k),N.a.n!==void 0&&(S[k]=N.a.n)}o.itemAttrs[h]=C,v.length&&(g.hidden=v),y.length&&(g.collapsedItems=y),Object.keys(S).length&&(g.itemCaptions=S),u.a.name!==void 0&&(g.caption=u.a.name);const D=u.a.sortType??"manual";if(D==="ascending"||D==="descending"){g.sort={order:D==="ascending"?"asc":"desc"};const N=b(b(u,"autoSortScope"),"pivotArea"),R=b(b(N,"references"),"reference");R&&Number(R.a.field)===ve&&(g.sort.data=Number(b(R,"x")?.a.v??0))}else F.length>0&&u.a.axis&&(g.sort={order:"manual",keys:F});const B=Object.entries(te).filter(([,N])=>T(u.a[N],!1)).map(([N])=>N);B.length>0?g.subtotals=B:T(u.a.defaultSubtotal,!0)||(g.subtotals="none"),u.a.subtotalTop!==void 0&&(g.subtotalTop=T(u.a.subtotalTop,!0)),T(u.a.insertBlankRow,!1)&&(g.blankLine=!0),u.a.axis&&T(u.a.showAll,!0)&&(g.showAll=!0),T(u.a.insertPageBreak,!1)&&(g.pageBreak=!0);for(const N of A(b(u,"extLst"),"ext"))T(b(N,"x14:pivotField")?.a.fillDownLabels,!1)&&(g.repeatLabels=!0);if(u.a.axis==="axisRow"||u.a.axis==="axisCol"){const N=T(u.a.compact,!0)?"compact":T(u.a.outline,!0)?"outline":"tabular";c.push([h,N])}Object.keys(g).length>0&&(n.fieldOptions[h]=g)});const r=new Map;for(const[,u]of c)r.set(u,(r.get(u)??0)+1);n.layout=[...r.entries()].sort((u,h)=>h[1]-u[1])[0]?.[0]??"compact";for(const[u,h]of c)h!==n.layout&&(n.fieldOptions[u]??={},n.fieldOptions[u].layout=h);for(const u of A(b(t,"pageFields"),"pageField")){const h=Number(u.a.fld);if(n.filters.push(h),o.pageFields.set(h,u.a),u.a.item!==void 0){const g=A(b(l[h],"items"),"item"),w=g[Number(u.a.item)],x=se(e,h);if(w){const v=$(x[Number(w.a.x??0)]??null),y=[];for(const F of g){if(F.a.t!==void 0&&F.a.t!=="data")continue;const S=$(x[Number(F.a.x??0)]??null);S!==v&&y.push(S)}n.fieldOptions[h]??={},n.fieldOptions[h].hidden=y}}}for(const u of A(b(t,"dataFields"),"dataField")){const h=Number(u.a.fld),g={field:h,name:u.a.name??rt(u.a.subtotal??"sum",e.fields[h].name),agg:u.a.subtotal??"sum",xml:u};let w=u.a.showDataAs??"normal";const x=b(b(u,"extLst"),"ext"),v=x?b(x,"x14:dataField"):null;if(v?.a.pivotShowAs&&(w=v.a.pivotShowAs),w!=="normal"&&(g.showAs={type:w},u.a.baseField!==void 0&&(g.showAs.baseField=Number(u.a.baseField)),u.a.baseItem!==void 0)){const y=Number(u.a.baseItem);if(y===xe)g.showAs.baseItem="prev";else if(y===ye)g.showAs.baseItem="next";else{const F=g.showAs.baseField,S=A(b(l[F],"items"),"item"),C=se(e,F),D=S[y];g.showAs.baseItem=D?$(C[Number(D.a.x??0)]??null):"prev"}}if(u.a.numFmtId!==void 0){const y=Number(u.a.numFmtId),F=Y[y]??s?.(y);F&&(g.numFmt=F)}n.values.push(g)}for(const u of A(b(t,"filters"),"filter")){const h=bt(u),g=Number(u.a.fld);if(h===null){o.rawFilters.push(u);continue}n.fieldOptions[g]??={},Object.assign(n.fieldOptions[g],h)}T(t.a.mergeItem,!1)&&(n.mergeLabels=!0);const i=b(t,"pivotTableStyleInfo");i&&(n.style={name:i.a.name??"PivotStyleLight16",rowHeaders:T(i.a.showRowHeaders,!0),colHeaders:T(i.a.showColHeaders,!0),rowStripes:T(i.a.showRowStripes,!1),colStripes:T(i.a.showColStripes,!1),lastColumn:T(i.a.showLastColumn,!0)});const d=new st(e,n);d.xml=o,d.dirty=!1;const p=b(t,"location"),f=p?de(p.a.ref??""):null;if(f){const u=n.filters.length>0?n.filters.length+1:0;d.anchor={sheet:a??null,row:Math.max(0,f.r0-u),col:f.c0},d.renderedRange={r0:d.anchor.row,c0:f.c0,r1:f.r1,c1:f.c1}}return d}async function ae(t,e){const s=Ze(e);if(!t.has(s))return[];const a=Ne(await t.bytes(s));return A(a,"Relationship").map(n=>({id:n.a.Id,type:n.a.Type,target:ze(e,n.a.Target??"")}))}async function zt(t,{sheets:e,book:s,tables:a=[],numFmtOf:n,readRecords:l=!0}){const o=new Map,c=[];for(const{part:r,sheet:i}of e)if(r)for(const d of await ae(t,r)){if(d.type!==_.table||!t.has(d.target))continue;const p=Ne(await t.bytes(d.target)),u=(await ae(t,d.target)).find(w=>w.type===_.definition);if(!u||!t.has(u.target))continue;let h=o.get(u.target);if(h===void 0){const w=await ht(await t.stream(u.target)),v=(await ae(t,u.target)).find(F=>F.type===_.records);let y=null;l&&v&&t.has(v.target)&&(y=await mt(await t.stream(v.target),w)),h=wt(w,y,{numFmtOf:n}),h.refreshOnLoad=["1","true"].includes(w.a.refreshOnLoad),h.part=u.target,h.id=p.a.cacheId!==void 0?Number(p.a.cacheId):0,Ft(h,w,s,a),o.set(u.target,h)}const g=vt(p,h,{numFmtOf:n,sheet:i});g.part=d.target,c.push(g)}return{caches:[...o.values()],pivots:c}}function Ft(t,e,s,a){if(!s)return;const n=b(b(e.root,"cacheSource"),"worksheetSource");if(!n)return;if(n.a.name!==void 0){const c=a.find(r=>r.name?.toLowerCase()===n.a.name.toLowerCase());c&&(t.source={type:"table",book:s,table:c});return}const l=de(n.a.ref??""),o=s.sheets.find(c=>c.name===n.a.sheet);l&&o&&(t.source={type:"range",book:s,sheet:o,range:l})}const K=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ `,oe=new TextEncoder;function ke(t){for(const[e,s]of Object.entries(Y))if(s===t)return Number(e);return null}function re(t,e){if(t==null)return"<m/>";switch(typeof t){case"number":return e?`<d v="${H(t)}"/>`:`<n v="${t}"/>`;case"string":return`<s v="${ge(t)}"/>`;case"boolean":return`<b v="${t?1:0}"/>`;default:return`<e v="${J(t.code)}"/>`}}function Ae(t,e){const{hasNum:s,hasInt:a,hasText:n,hasBlank:l,hasOther:o,min:c,max:r,longText:i}=e,d=t.isDate&&s&&!n&&!o,p={};return!n&&!l&&!o&&(p.containsSemiMixedTypes="0"),d&&!l&&(p.containsNonDate="0"),d&&(p.containsDate="1"),n||(p.containsString="0"),l&&(p.containsBlank="1"),(s?1:0)+(n?1:0)+(o?1:0)>1&&(p.containsMixedTypes="1"),s&&!d&&(p.containsNumber="1",a&&(p.containsInteger="1"),p.minValue=String(c),p.maxValue=String(r)),d&&(p.minDate=H(c),p.maxDate=H(Math.floor(r)+1)),i&&(p.longText="1"),{attrs:p,date:d}}function St(t){const e={hasNum:!1,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(const s of t)typeof s=="number"?(e.hasNum=!0,Number.isInteger(s)||(e.hasInt=!1),s<e.min&&(e.min=s),s>e.max&&(e.max=s)):typeof s=="string"?(e.hasText=!0,s.length>255&&(e.longText=!0)):s==null?e.hasBlank=!0:e.hasOther=!0;return e}function Tt(t){const e={hasNum:t.length>0,hasInt:!0,hasText:!1,hasBlank:!1,hasOther:!1,min:1/0,max:-1/0,longText:!1};for(let s=0;s<t.length;s++){const a=t[s];a<e.min&&(e.min=a),a>e.max&&(e.max=a),e.hasInt&&Math.floor(a)!==a&&(e.hasInt=!1)}return e}function De(t){return t.ensureColumn(),t.rawIds!==null?!0:!(t.nums!==null&&t.kinds===null)}function It(t,e){const s=e.group;if(s===null)return e.par>=0?m("fieldGroup",{par:String(e.par)}):null;e.ensure();const a={};e.par>=0&&(a.par=String(e.par)),a.base=String(e.base>=0?e.base:e.index);const n=[],l=e.items.map(c=>re(c,!1)).join("");if(s.kind==="date"){const c={groupBy:s.part,startDate:H(s.start),endDate:H(s.end+1)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else if(s.kind==="bins"){const c={startNum:String(s.start),endNum:String(s.end),groupInterval:String(s.interval)};s.autoStart||(c.autoStart="0"),s.autoEnd||(c.autoEnd="0"),n.push(m("rangePr",c))}else{const c=e.groupMap,r=m("discretePr",{count:String(c.length)});for(let i=0;i<c.length;i++)r.c.push(m("x",{v:String(c[i])}));n.push(r)}const o=m("groupItems",{count:String(e.items.length)});return o.c.push(l),n.push(o),m("fieldGroup",a,n)}function Nt(t,e,s){const a=e.xml?.node??null,n={...a?.a??{}};if(n.name=e.name,n.numFmtId===void 0){const c=e.numFmt!=="General"?ke(e.numFmt)??s.numFmtId?.(e.numFmt)??(e.isDate?14:0):0;n.numFmtId=String(c)}const l=[];if(e.isCalculated)n.formula=e.formula,n.databaseField="0",delete n.uniqueList;else if(e.base>=0)n.databaseField="0";else if(t.recordCount===0&&a&&b(a,"sharedItems")){const c=b(a,"sharedItems"),r=m("sharedItems",{...c.a}),i=T(c.a.containsDate,!1);c.items.length>0&&r.c.push(c.items.map(d=>re(d,i&&typeof d=="number")).join("")),l.push(r)}else if(De(e)){e.ensureRaw();const{attrs:c,date:r}=Ae(e,St(e.shared)),i=m("sharedItems",{...c,count:String(e.shared.length)});i.c.push(e.shared.map(d=>re(d,r&&typeof d=="number")).join("")),l.push(i)}else{const{attrs:c}=Ae(e,Tt(e.nums));l.push(m("sharedItems",c))}const o=It(t,e);if(o&&l.push(o),a)for(const c of a.c)c.n!=="sharedItems"&&c.n!=="fieldGroup"&&l.push(c);return m("cacheField",n,l)}function Ct(t,{recordsRel:e=null,numFmtId:s,refreshOnLoad:a=!0,sourceSheetName:n}={}){const l=t.xml?.root??null,o={...l?.a??{}};o.xmlns??=U,o["xmlns:r"]??=V,e?o["r:id"]=e:delete o["r:id"],a&&(o.refreshOnLoad="1"),o.refreshedBy??="8sheets",o.refreshedDate=String(Et()),o.createdVersion??="6",o.refreshedVersion??="6",o.minRefreshableVersion??="3",o.recordCount=String(t.recordCount),e?delete o.saveData:o.saveData="0";const c=[],r=l?b(l,"cacheSource"):null;c.push(Rt(t,r,n));const i=m("cacheFields",{count:"0"}),d=t.fields;for(const p of d)i.c.push(Nt(t,p,{numFmtId:s}));if(i.a.count=String(d.length),c.push(i),l)for(const p of l.c)p.n!=="cacheSource"&&p.n!=="cacheFields"&&c.push(p);return K+ne(m("pivotCacheDefinition",o,c)).join("")}function Et(){return Math.round((Date.now()/864e5+25569)*1e5)/1e5}function Rt(t,e,s){const a=t.source;if(a===null)return e??m("cacheSource",{type:"worksheet"},[m("worksheetSource",{ref:"A1",sheet:"Sheet1"})]);const n={};if(a.type==="table")n.name=a.table.name;else{const i=a.range,d=s??(typeof a.sheet=="string"?a.sheet:a.sheet.name);n.ref=fe({r0:i.r0,c0:i.c0,r1:i.r1,c1:Math.min(i.c1,Ge-1)}),n.sheet=d}const l=e?{...e.a}:{type:"worksheet"},o=e?e.c.filter(i=>i.n!=="worksheetSource"):[],c=e?b(e,"worksheetSource"):null,r=c?{...c.a,...n}:n;return a.type==="table"&&(delete r.ref,delete r.sheet),m("cacheSource",l,[m("worksheetSource",r),...o])}const kt=4096;async function Oe(t,e){const s=t.recordCount,a=[];for(const l of t.fields)l.isVirtual||(De(l)?(l.ensureRaw(),a.push(At(l.rawIds))):a.push(Dt(l.nums,l.isDate)));await e(oe.encode(`${K}<pivotCacheRecords xmlns="${U}" xmlns:r="${V}" count="${s}">`));const n=[];for(let l=0;l<s;l++){n.push("<r>");for(let o=0;o<a.length;o++)n.push(a[o](l));n.push("</r>"),(l+1)%kt===0&&(await e(oe.encode(n.join(""))),n.length=0)}n.push("</pivotCacheRecords>"),await e(oe.encode(n.join("")))}function At(t){return e=>`<x v="${t[e]}"/>`}function Dt(t,e){return e?s=>`<d v="${H(t[s])}"/>`:s=>`<n v="${t[s]}"/>`}async function en(t){const e="application/xml";let s=new Blob([],{type:e}),a=[],n=0;return await Oe(t,l=>{a.push(l),n+=l.length,n>=1<<24&&(s=new Blob([s,...a],{type:e}),a=[],n=0)}),new Blob([s,...a],{type:e})}const Le=["location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","formats","conditionalFormats","chartFormats","pivotHierarchies","pivotTableStyleInfo","filters","rowHierarchiesUsage","colHierarchiesUsage","extLst"];function Ot(t,e){const s=t.cache.fields[e].ensure(),a=s.rank(),n=Array.from(s.items.keys()),o=t.spec.fieldOptions[e]?.sort;if(o?.order==="manual"){const r=new Map((o.keys??[]).map((p,f)=>[p,f])),i=r.size,d=p=>r.get($(s.items[p]))??i+a[p];n.sort((p,f)=>d(p)-d(f))}else o?.order==="desc"&&(o.data===void 0||o.data===null)?n.sort((r,i)=>a[i]-a[r]):n.sort((r,i)=>a[r]-a[i]);const c=new Int32Array(n.length);return n.forEach((r,i)=>{c[r]=i}),{order:n,position:c}}function Lt(t){return t.group!==null||t.base>=0}function Pt(t,e){return t.spec.fieldOptions[e]?.layout??t.spec.layout}const Bt=["axis","dataField","compact","outline","subtotalTop","sortType","defaultSubtotal","insertBlankRow","name","showDropDowns","dragToRow","dragToCol","dragToPage",...Object.values(te)];function Mt(t,e,s){const{spec:a,cache:n}=t,l=n.fields[e],o=a.fieldOptions[e]??{},c=t.xml?.fields?.[e]??null,r={...c?.a??{}};for(const S of Bt)delete r[S];o.caption!==void 0&&(r.name=o.caption);const i=a.rows.includes(e),d=a.cols.includes(e),p=a.filters.includes(e),f=a.values.some(S=>S.field===e);i?r.axis="axisRow":d?r.axis="axisCol":p&&(r.axis="axisPage"),f&&(r.dataField="1");const u=Pt(t,e);u!=="compact"&&(r.compact="0"),u==="tabular"&&(r.outline="0"),l.isCalculated&&(r.dragToRow="0",r.dragToCol="0",r.dragToPage="0"),r.showAll=o.showAll?"1":"0",o.pageBreak?r.insertPageBreak="1":delete r.insertPageBreak,(o.subtotalTop??a.subtotalTop)===!1&&(i||d)&&(r.subtotalTop="0"),o.blankLine&&(r.insertBlankRow="1"),o.sort?.order==="asc"?r.sortType="ascending":o.sort?.order==="desc"&&(r.sortType="descending");const h=o.subtotals??"auto",g=i||d||p,w=(o.hidden?.length??0)>0,x=g||Lt(l)||w||!!(o.range||o.dateFilter);if((l.isCalculated||h==="none"||Array.isArray(h)||l.base>=0&&!g)&&(r.defaultSubtotal="0"),Array.isArray(h))for(const S of h)r[te[S]]="1";const v=[];if(x&&!l.isCalculated){const{order:S}=s(e),C=m("items",{}),D=new Set(o.hidden??[]),B=new Set(o.collapsedItems??[]),N=t.xml?.itemAttrs?.[e]??null,R=o.itemCaptions??null;for(const k of S){const P=l.keyOf(k),O={...N?.get(P)??{}};delete O.h,delete O.sd,delete O.n,O.x=String(k),D.has(P)&&(O.h="1"),B.has(P)&&(O.sd="0"),R&&R[P]!==void 0&&(O.n=R[P]),C.c.push(m("item",O))}if((g||w||o.range||o.dateFilter)&&r.defaultSubtotal===void 0&&C.c.push(m("item",{t:"default"})),Array.isArray(h))for(const k of h)C.c.push(m("item",{t:Fe[k]}));C.a.count=String(C.c.length),v.push(C)}if(o.sort?.data!==void 0&&o.sort?.data!==null&&(o.sort.order==="asc"||o.sort.order==="desc")&&v.push(m("autoSortScope",{},[m("pivotArea",{dataOnly:"0",outline:"0",fieldPosition:"0"},[m("references",{count:"1"},[m("reference",{field:String(ve),count:"1",selected:"0"},[m("x",{v:String(o.sort.data)})])])])])),c)for(const S of c.c)S.n!=="items"&&S.n!=="autoSortScope"&&S.n!=="extLst"&&v.push(S);const y=o.repeatLabels===!0||a.repeatLabels===!0&&i&&u!=="compact",F=$t(c,y);return F&&v.push(F),m("pivotField",r,v)}function $t(t,e){const s=[];let a=!1;for(const n of A(t?b(t,"extLst"):null,"ext")){const l=b(n,"x14:pivotField");if(!l){s.push(n);continue}a=!0;const o={...l.a};delete o.fillDownLabels,e&&(o.fillDownLabels="1"),s.push(m("ext",n.a,n.c.map(c=>c===l?m(l.n,o,l.c):c)))}return!a&&e&&s.push(m("ext",{uri:ct,"xmlns:x14":z},[m("x14:pivotField",{fillDownLabels:"1"})])),s.length>0?m("extLst",{},s):null}function Pe(t,e,s,a){const n=s.lines,l=m(t,{}),{slots:o}=s;let c=[];for(let r=0;r<n.node.length;r++){const i=n.type[r],d=n.level[r],p={},f=[];if(o.length===0){l.c.push(m("i",{}));continue}if(i===j.GRAND){p.t="grand";const w=n.data[r];w>0&&(p.i=String(w));const x=m("i",p,[m("x",w>0?{v:String(w)}:{})]);l.c.push(x),c=[];continue}i===j.BLANK?p.t="blank":i===j.SUBTOTAL&&(p.t=n.func[r]?Fe[n.func[r]]:"default");let u=0;for(let w=0;w<=d;w++)if(o[w]===Z)f.push(n.data[r]>=0?n.data[r]:0);else{u++;const x=s.ancestorAt(n.node[r],u);f.push(a(o[w]).position[s.item[x]])}n.data[r]>0&&(p.i=String(n.data[r]));let h=0;if(i===j.ITEM)for(;h<f.length-1&&h<c.length&&c[h]===f[h];)h++;h>0&&(p.r=String(h));const g=m("i",p);for(let w=h;w<f.length;w++)g.c.push(m("x",f[w]===0?{}:{v:String(f[w])}));l.c.push(g),c=f}return l.c.length===0&&l.c.push(m("i",{})),l.a.count=String(l.c.length),l}function _t(t,e){const{spec:s}=t,a=[];let n=1;const l=(c,r,i,d)=>m("filter",{fld:String(c),type:r,evalOrder:"-1",id:String(n++),...i},[m("autoFilter",{ref:"A1"},[m("filterColumn",{colId:"0"},[d])])]),o=(c,r)=>m("customFilters",r?{and:"1"}:{},c.map(i=>m("customFilter",i)));for(const c of e){const r=s.fieldOptions[c];if(r){if(r.labelFilter){const i=r.labelFilter,d=String(i.value??""),p=String(i.value2??""),f={stringValue1:d};(i.op==="captionBetween"||i.op==="captionNotBetween")&&(f.stringValue2=p);const u={captionEqual:()=>o([{val:d}]),captionNotEqual:()=>o([{operator:"notEqual",val:d}]),captionBeginsWith:()=>o([{val:`${d}*`}]),captionNotBeginsWith:()=>o([{operator:"notEqual",val:`${d}*`}]),captionEndsWith:()=>o([{val:`*${d}`}]),captionNotEndsWith:()=>o([{operator:"notEqual",val:`*${d}`}]),captionContains:()=>o([{val:`*${d}*`}]),captionNotContains:()=>o([{operator:"notEqual",val:`*${d}*`}]),captionGreaterThan:()=>o([{operator:"greaterThan",val:d}]),captionGreaterThanOrEqual:()=>o([{operator:"greaterThanOrEqual",val:d}]),captionLessThan:()=>o([{operator:"lessThan",val:d}]),captionLessThanOrEqual:()=>o([{operator:"lessThanOrEqual",val:d}]),captionBetween:()=>o([{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:p}],!0),captionNotBetween:()=>o([{operator:"lessThan",val:d},{operator:"greaterThan",val:p}])}[i.op];u&&a.push(l(c,i.op,f,u()))}if(r.valueFilter){const i=r.valueFilter,d=String(i.value),p=String(i.value2??""),f={valueEqual:[[{val:d}]],valueNotEqual:[[{operator:"notEqual",val:d}]],valueGreaterThan:[[{operator:"greaterThan",val:d}]],valueGreaterThanOrEqual:[[{operator:"greaterThanOrEqual",val:d}]],valueLessThan:[[{operator:"lessThan",val:d}]],valueLessThanOrEqual:[[{operator:"lessThanOrEqual",val:d}]],valueBetween:[[{operator:"greaterThanOrEqual",val:d},{operator:"lessThanOrEqual",val:p}],!0],valueNotBetween:[[{operator:"lessThan",val:d},{operator:"greaterThan",val:p}]]}[i.op];f&&a.push(l(c,i.op,{iMeasureFld:String(i.data??0)},o(f[0],f[1]===!0)))}if(a.push(...qe(r,c,m,()=>n++)),r.top){const i=r.top,d={val:String(i.count??10),filterVal:String(i.count??10)};i.by==="percent"&&(d.percent="1"),i.bottom&&(d.top="0");const p=i.by==="percent"?"percent":i.by==="sum"?"sum":"count";a.push(l(c,p,{iMeasureFld:String(i.data??0)},m("top10",d)))}}}return a}function qt(t,e,s,a){const n=e.xml??null,l={...n?.a??{}};l.name=e.name,l.fld=String(e.field),e.agg&&e.agg!=="sum"?l.subtotal=e.agg:delete l.subtotal,delete l.showDataAs;const o=e.showAs?.type??"normal",c=n?n.c.filter(g=>g.n!=="extLst"):[];let r=null;ut.has(o)?r=o:o!=="normal"&&(l.showDataAs=o);const i=e.showAs?.baseField??0;l.baseField=String(i>=0?i:0);let d=0;const p=e.showAs?.baseItem;if(p==="prev")d=xe;else if(p==="next")d=ye;else if(p!==void 0&&e.showAs?.baseField>=0){const g=t.cache.fields[e.showAs.baseField].ensure(),w=g.keyIndex.get(p);w!==void 0&&(d=s(g.index).position[w])}l.baseItem=String(d);const f=e.numFmt??(o!=="normal"&&!o.startsWith("rank")&&o!=="difference"&&o!=="runTotal"?o==="index"?"0.00":"0.00%":null);if(f){const g=ke(f)??a.numFmtId?.(f);g!=null&&(l.numFmtId=String(g))}else delete l.numFmtId;const u=[],h=n?b(n,"extLst"):null;if(h)for(const g of h.c)if(b(g,"x14:dataField")){const w={...b(g,"x14:dataField").a};delete w.pivotShowAs,r&&(w.pivotShowAs=r),u.push(m("ext",g.a,[m("x14:dataField",w)])),r=null}else u.push(g);return r&&u.push(m("ext",{uri:it,"xmlns:x14":z},[m("x14:dataField",{pivotShowAs:r})])),u.length&&c.push(m("extLst",{},u)),m("dataField",l,c)}function Ht(t,{cacheId:e,numFmtId:s}={}){const a=t.result??t.update(),{spec:n,cache:l}=t,{layout:o,rows:c,cols:r}=a,i=new Map,d=I=>{let E=i.get(I);return E===void 0&&(E=Ot(t,I),i.set(I,E)),E},p=t.xml?.root??null,f={...p?.a??{}};f.xmlns??=U,f.name=n.name,f.cacheId=String(e??l.id??1),f.applyNumberFormats??="0",f.applyBorderFormats??="0",f.applyFontFormats??="0",f.applyPatternFormats??="0",f.applyAlignmentFormats??="0",f.applyWidthHeightFormats??="1",f.dataCaption=n.dataCaption,f.updatedVersion??="6",f.minRefreshableVersion??="3",f.useAutoFormatting??="1",f.itemPrintTitles??="1",f.createdVersion??="6",f.indent??="0",n.mergeLabels?f.mergeItem="1":delete f.mergeItem,t.fileAttrs&&Object.assign(f,t.fileAttrs);const u=(I,E,G)=>{E===G?delete f[I]:f[I]=E?"1":"0"};u("compact",n.layout==="compact",!0),u("compactData",n.layout==="compact",!0),f.outline=n.layout==="tabular"?f.outline??"1":"1",f.outlineData=n.layout==="tabular"?f.outlineData??"1":"1",u("colGrandTotals",n.grandRow,!0),u("rowGrandTotals",n.grandCol,!0),n.rowCaption!=null?f.rowHeaderCaption=n.rowCaption:delete f.rowHeaderCaption,n.colCaption!=null?f.colHeaderCaption=n.colCaption:delete f.colHeaderCaption,n.grandCaption!=null?f.grandTotalCaption=n.grandCaption:delete f.grandTotalCaption,n.emptyText!==""&&n.showMissing!==!1?f.missingCaption=n.emptyText:delete f.missingCaption,n.showMissing===!1?f.showMissing="0":delete f.showMissing,n.errorText!==null?(f.showError="1",f.errorCaption=n.errorText):(delete f.showError,delete f.errorCaption),c.slots.includes(Z)?(f.dataOnRows="1",f.dataPosition=String(c.slots.indexOf(Z))):(delete f.dataOnRows,delete f.dataPosition);const h=Object.keys(n.fieldOptions).map(Number),g=h.some(I=>{const E=n.fieldOptions[I];return(E.labelFilter?1:0)+(E.valueFilter?1:0)+(E.top?1:0)>1});f.multipleFieldFilters=g?"1":"0";const w=t.anchor??{row:0,col:0},x=w.row+o.pageRows,v={ref:fe({r0:x,c0:w.col,r1:w.row+o.rows-1,c1:w.col+Math.max(o.bodyCols,1)-1}),firstHeaderRow:String(o.firstHeaderRow),firstDataRow:String(o.firstDataRow),firstDataCol:String(o.firstDataCol)};n.filters.length>0&&(v.rowPageCount=String(n.filters.length),v.colPageCount="1");const y=new Map;y.set("location",m("location",v));const F=m("pivotFields",{count:String(l.fields.length)});for(let I=0;I<l.fields.length;I++)F.c.push(Mt(t,I,d));y.set("pivotFields",F);const S=(I,E)=>m(I,{count:String(E.length)},E.map(G=>m("field",{x:String(G)})));if(c.slots.length>0&&y.set("rowFields",S("rowFields",c.slots)),y.set("rowItems",Pe("rowItems",a,c,d)),r.slots.length>0&&y.set("colFields",S("colFields",r.slots)),y.set("colItems",Pe("colItems",a,r,d)),n.filters.length>0){const I=m("pageFields",{count:String(n.filters.length)});for(const E of n.filters){const X={...t.xml?.pageFields?.get(E)??{},fld:String(E)};delete X.item,X.hier??="-1";const le=l.fields[E].ensure(),ce=n.fieldOptions[E]?.hidden??[];if(ce.length===le.items.length-1){const Be=new Set(ce),ue=d(E).order.findIndex(Me=>!Be.has(le.keyOf(Me)));ue>=0&&(X.item=String(ue))}I.c.push(m("pageField",X))}y.set("pageFields",I)}n.values.length>0&&y.set("dataFields",m("dataFields",{count:String(n.values.length)},n.values.map(I=>qt(t,I,d,{numFmtId:s}))));const C=n.style,D=p?b(p,"pivotTableStyleInfo"):null;y.set("pivotTableStyleInfo",m("pivotTableStyleInfo",{...D?.a??{},name:C.name,showRowHeaders:C.rowHeaders?"1":"0",showColHeaders:C.colHeaders?"1":"0",showRowStripes:C.rowStripes?"1":"0",showColStripes:C.colStripes?"1":"0",showLastColumn:C.lastColumn===!1?"0":"1"}));const B=_t(t,h),N=t.xml?.rawFilters??[],R=[...B,...N];R.length>0&&y.set("filters",m("filters",{count:String(R.length)},R));const k=$e(t,m);k&&y.set("conditionalFormats",k);const P=_e(t,m);P&&y.set("chartFormats",P);const O=yt(p,n.hideValuesRow);O&&y.set("extLst",O);const M=[];for(const I of Le)if(y.has(I))M.push(y.get(I));else if(p&&!Vt.has(I)){const E=b(p,I);E&&M.push(E)}if(p)for(const I of p.c)Le.includes(I.n)||M.splice(M.length-(M[M.length-1]?.n==="extLst"?1:0),0,I);return K+ne(m("pivotTableDefinition",f,M)).join("")}const Vt=new Set(["extLst","location","pivotFields","rowFields","rowItems","colFields","colItems","pageFields","dataFields","pivotTableStyleInfo","filters"]);function ie(t,e){for(let s=1;;s++){const a=e(s);if(!t.has(a))return t.add(a),a}}function tn(t){const e=t.map(s=>`<Relationship Id="${s.id}" Type="${s.type}" Target="${J(s.target)}"/>`).join("");return`${K}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${e}</Relationships>`}function nn(t,{existing:e=[],saveRecords:s=!0,numFmtId:a,refreshOnLoad:n=!0,firstCacheId:l=1}={}){const o=new Set(e),c=[],r=[],i=[],d=[],p=new Map;let f=l;const u=x=>{c.push(x),i.push({partName:`/${x.name}`,contentType:x.contentType})},h=t.filter(x=>x.dirty||!x.part),g=[],w=new Set(t.filter(x=>!h.includes(x)).map(x=>x.cache));for(const x of h){const{cache:v}=x;x.part&&g.push(x.part),v.part&&!w.has(v)&&(g.push(v.part),v.part=null);let y=p.get(v);if(y===void 0){const S=f++,C=ie(o,R=>`xl/pivotCache/pivotCacheDefinition${R}.xml`);v.id=S;let D=null;if(s&&v.recordCount>0){const R=ie(o,k=>`xl/pivotCache/pivotCacheRecords${k}.xml`);D="rId1",r.push({from:C,id:D,type:_.records,target:`/${R}`}),u({name:R,contentType:ee.records,large:!0,produce:k=>Oe(v,k)})}const N={name:C,contentType:ee.definition,xml:null};u(N),y={cacheId:S,defName:C,defPart:N,recordsRel:D},p.set(v,y),d.push({cacheId:S,target:`/${C}`,type:_.definition})}x.result||x.update();const F=ie(o,S=>`xl/pivotTables/pivotTable${S}.xml`);u({name:F,contentType:ee.table,xml:Ht(x,{cacheId:y.cacheId,numFmtId:a})}),r.push({from:F,id:"rId1",type:_.definition,target:`/${y.defName}`}),r.push({from:null,sheet:x.anchor?.sheet??null,id:null,type:_.table,target:`/${F}`}),x.part=F}for(const[x,v]of p)v.defPart.xml=Ct(x,{recordsRel:v.recordsRel,numFmtId:a,refreshOnLoad:n});return{parts:c,relationships:r,contentTypes:i,replaced:g,workbook:{pivotCaches:d,pivotCachesXml(x){return d.length===0?"":`<pivotCaches>${d.map(v=>`<pivotCache cacheId="${v.cacheId}" r:id="${x(v.cacheId)}"/>`).join("")}</pivotCaches>`}}}}export{ee as CONTENT_TYPE,pt as CacheRecordsReader,We as EMPTY,Ye as ERRORS,Ie as NodeReader,_ as REL_TYPE,et as XlError,nn as buildPivotPackage,Ct as cacheDefinitionXml,wt as cacheFromXml,W as isoToSerial,Ne as parseNode,vt as pivotFromXml,Ht as pivotTableXml,ht as readCacheDefinition,mt as readCacheRecords,zt as readPivotParts,en as recordsBlob,tn as relationshipsXml,H as serialToIso,ne as serializeNode,Oe as writeCacheRecords};
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};
@@ -1,3 +1,3 @@
1
- import{readingDirection as at,visualOrder as ht,wrapsByAlign as dt}from"../cells/text-layout.js";import{gradientPatches as q}from"../cells/paint.js";import{paintWatermarks as ut}from"../shapes/watermark.js";import{BOOL as mt,CHUNK_BITS as Q,CHUNK_MASK as H,EMPTY as K,ERR as tt,ERRORS as gt,KIND_MASK as U,NUM as W,STR as v,FORMULA as et,SPILL as nt}from"../core/sheet.js";import{isBarcodeText as bt,paintBarcodeValue as pt}from"../celltypes/barcode.js";import{printCellType as ot,printEmptyTypedCells as wt}from"../celltypes/cell-types.js";import{FILL_MARK as it,formatGeneral as st,getFormatter as V}from"../core/numfmt.js";import{colName as kt}from"../core/address.js";import{cssFont as E}from"../core/styles.js";import{CondFormats as yt}from"../core/cond-format.js";import{drawCfIcon as Tt,iconSide as xt,monoContext as St,paintCfBar as Dt}from"../cells/cf-paint.js";import{sparklineIndex as At}from"../core/sparklines.js";import{paintSparkline as Ot}from"../sparklines/excel-paint.js";import{isSparklineText as Rt,paintSparklineValue as Ft}from"../sparklines/paint.js";import{paintSparkRulesOnPage as Pt,sparkRuleHidesValue as Ct}from"../sparklines/rule.js";import{preparePicturesForPrint as Mt}from"../sparklines/print.js";import{tableColors as It,tablesOf as zt}from"../core/tables.js";import{paintCustomTable as Nt}from"../slicers/custom-styles.js";import{resolveColor as vt}from"../io/xlsx-styles.js";import{parseHeaderFooter as Lt}from"./page-setup.js";const Wt=2,Ht=6,Et=32,Y="#000000",$=.25,j=10,Bt={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},_t={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]},rt=new WeakMap;function J(n){let i=rt.get(n);return i===void 0&&(i=E(n,n.fontSize),rt.set(n,i)),i}function Gt(n,i,l,s){switch(i){case W:return s.numFmt==="General"?st(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 mt:return l?"TRUE":"FALSE";case tt:return gt[l]??"#N/A";default:return""}}class Xt{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=xt(p,1,o.fontSize),r=o.vAlign==="top"?s+1:o.vAlign==="center"?s+(p-t)/2:s+p-t-1;Tt(this.mono?St(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=Gt(this.book,s,p,u);if(s===tt&&this.errors!=="displayed"&&(b=this.errors==="blank"?"":this.errors==="dash"?"--":"#N/A"),b===""||s===v&&bt(b)&&(w.kind(i,l)&(et|nt))!==0&&pt(a,b,o,t,r,h,1)||s===v&&Rt(b)&&(w.kind(i,l)&(et|nt))!==0&&Ft(a,b,o,t,r,h,1,{ink:u.color??"#000000",snap:!1,mono:this.mono})||w.sparkRules!==null&&Ct(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=Wt,P=s===v?at(u.readingOrder,b):null;s===v&&!("direction"in a)&&(b=ht(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||dt(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){if(u.numFmt==="General"){let c=10;for(;c>=1&&S>D;)b=st(p,c),S=this.width(b),c--}if(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*Ht;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=Bt[i.style]??.5;if(t.strokeStyle=this.mono?"#000000":i.color??"#000000",t.lineWidth=r,t.setLineDash(_t[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 lt(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=lt(t.cols,a,w),b=lt(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=zt(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=It(f.styleName,M.theme);g&&(f._colors=g,Nt(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(ft(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?ft(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 yt(M,t,f=>vt(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&&(Dt(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 At(t)){const g=Math.floor(e/16384),m=e-g*16384;g<d||g>T||m<a||m>w||Ot(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&&Pt(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-Et);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&&wt(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 Kt(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(kt(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 Ut(n){let i=_.get(n);return i===void 0&&(i=Lt(n),_.size>256&&_.clear(),_.set(n,i)),i}function Vt(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 Yt(n,i){const l=[[]];for(const s of n)(s.field?Vt(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 $t(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=Yt(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=Ut(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 ct(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)),ut(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};$t(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 Xt(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&&Kt(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 we(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),ct(h,r,t,{pageNumber:o.pageNumber,totalPages:o.totalPages,sheetPage:o.sheetPage,...p}),o}const Jt=()=>new Promise(n=>setTimeout(n,0)),Zt={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 ft(n){if(!n.pattern)return n.fill;const i=Zt[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 ke(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"),Mt(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);ct(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 Jt(),b=performance.now())}return await w.finish(),{pages:w.pageCount,bytes:w.offset,missing:[...w.missing],fontWarnings:w.fontWarnings}}export{Gt as displayText,$t as paintHeaderFooter,we as renderJobPageToCanvas,ct as renderPage,ke as writeJobPdf};
1
+ import{hasCellTypes as q}from"../core/cell-type-rules.js";import{readingDirection as at,visualOrder as ht,wrapsByAlign as dt}from"../cells/text-layout.js";import{gradientPatches as Q}from"../cells/paint.js";import{paintWatermarks as ut}from"../shapes/watermark.js";import{BOOL as mt,CHUNK_BITS as tt,CHUNK_MASK as H,EMPTY as K,ERR as et,ERRORS as gt,KIND_MASK as U,NUM as W,STR as v,FORMULA as nt,SPILL as ot}from"../core/sheet.js";import{isBarcodeText as bt,paintBarcodeValue as pt}from"../celltypes/barcode.js";import{printCellType as it,printEmptyTypedCells as wt}from"../celltypes/cell-types.js";import{FILL_MARK as st,fitGeneral as kt,formatGeneral as yt,getFormatter as V}from"../core/numfmt.js";import{colName as Tt}from"../core/address.js";import{cssFont as E}from"../core/styles.js";import{CondFormats as xt}from"../core/cond-format.js";import{drawCfIcon as St,iconSide as Dt,monoContext as At,paintCfBar as Ot}from"../cells/cf-paint.js";import{sparklineIndex as Rt}from"../core/sparklines.js";import{paintSparkline as Ft}from"../sparklines/excel-paint.js";import{isSparklineText as Pt,paintSparklineValue as Ct}from"../sparklines/paint.js";import{paintSparkRulesOnPage as Mt,sparkRuleHidesValue as It}from"../sparklines/rule.js";import{preparePicturesForPrint as zt}from"../sparklines/print.js";import{tableColors as Nt,tablesOf as vt}from"../core/tables.js";import{paintCustomTable as Lt}from"../slicers/custom-styles.js";import{resolveColor as Wt}from"../io/xlsx-styles.js";import{parseHeaderFooter as Ht}from"./page-setup.js";const Et=2,Bt=6,_t=32,Y="#000000",$=.25,j=10,Gt={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},Xt={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]},rt=new WeakMap;function J(e){let i=rt.get(e);return i===void 0&&(i=E(e,e.fontSize),rt.set(e,i)),i}function Kt(e,i,l,s){switch(i){case W:return s.numFmt==="General"?yt(l):V(s.numFmt).number(l,e.dateOffset);case v:{const p=e.strings.get(l);return s.numFmt==="General"||s.numFmt==="@"?p:V(s.numFmt).text(p)}case mt:return l?"TRUE":"FALSE";case et:return gt[l]??"#N/A";default:return""}}class Ut{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=Dt(p,1,o.fontSize),r=o.vAlign==="top"?s+1:o.vAlign==="center"?s+(p-t)/2:s+p-t-1;St(this.mono?At(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(q(w)&&this.reachX===null&&it(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=Kt(this.book,s,p,u);if(s===et&&this.errors!=="displayed"&&(b=this.errors==="blank"?"":this.errors==="dash"?"--":"#N/A"),b===""||s===v&&bt(b)&&(w.kind(i,l)&(nt|ot))!==0&&pt(a,b,o,t,r,h,1)||s===v&&Pt(b)&&(w.kind(i,l)&(nt|ot))!==0&&Ct(a,b,o,t,r,h,1,{ink:u.color??"#000000",snap:!1,mono:this.mono})||w.sparkRules!==null&&It(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=Et,P=s===v?at(u.readingOrder,b):null;s===v&&!("direction"in a)&&(b=ht(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||dt(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(st)>=0){if(this.reachX!==null)return;const c=b.split(st),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=kt(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*Bt;x==="left"?(o+=c,r-=c):x==="right"&&(r-=c)}let n,f=!1,g=o,m=o+r;if(x==="center"||x==="centerContinuous")n=o+(r-S)/2;else if(x==="right")n=o+r-k-S;else if(x==="fill"){const c=Math.max(1,Math.floor(D/(S||1)));b=b.repeat(c),S*=c,n=o+k}else n=o+k;if(this.reachX!==null&&n+S<=this.reachX){A&&this.setFont(C);return}if(S>D||n<o+k)if(T)f=!0;else if(s===v){if(n+S>m){let c=l+1,y=m;for(;y<n+S&&c<=d.c1&&(w.kind(i,c)&15)===0&&w.mergeAt(i,c)===null;)y+=w.cols.sizeOf(c),c++;m=y}if(n<g){let c=l-1,y=g;for(;y>n&&c>=d.c0&&(w.kind(i,c)&15)===0&&w.mergeAt(i,c)===null;)y-=w.cols.sizeOf(c),c--;g=y}f=n+S>m||n<g}else f=!0;a.textAlign="left",f?(a.save(),a.beginPath(),a.rect(g,t,m-g,h),a.clip(),a.fillText(b,n,O),this.decorate(u,n,O,S,I),a.restore()):(a.fillText(b,n,O),(u.underline!==0||u.strike)&&this.decorate(u,n,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=Gt[i.style]??.5;if(t.strokeStyle=this.mono?"#000000":i.color??"#000000",t.lineWidth=r,t.setLineDash(Xt[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 lt(e,i,l){const s=new Float64Array(l-i+2);let p=0;for(let o=i;o<=l;o++)s[o-i]=p,p+=e.sizeOf(o);return s[l-i+1]=p,s}function B(e,i,l,s,p){const{ctx:o,sheet:t}=e,{x:r,y:h,r0:d,r1:T,c0:a,c1:w}=i,u=lt(t.cols,a,w),b=lt(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(),e.reset(),l){o.strokeStyle=Y,o.lineWidth=$,o.setLineDash([]),o.beginPath();for(let n=0;n<=C;n++)n>0&&u[n]===u[n-1]||(o.moveTo(r+u[n],h),o.lineTo(r+u[n],h+P));for(let n=0;n<=F;n++)n>0&&b[n]===b[n-1]||(o.moveTo(r,h+b[n]),o.lineTo(r+k,h+b[n]));o.stroke()}const x=t.mergesInRows(d,T).filter(n=>n.c1>=a&&n.c0<=w),D=x.length>0,I=t.rowStyles!==null||t.colStyles!==null,N=e.styles[0].fill===null&&e.styles[0].borders===null;e.tables=null;const{book:M}=e;if(M.engine&&M.engine.tables.size>0){const n=vt(M,t);n.length>0&&(e.tables=n);for(const f of n){if(f.r1<d||f.r0>T||f.c1<a||f.c0>w)continue;const g=Nt(f.styleName,M.theme);g&&(f._colors=g,Lt(o,f,g,{ra:d,rb:T,ca:a,cb:w,xs:u,ys:b,ox:r,oy:h,line:.5,noFill:e.mono,setInk:m=>e.setInk(e.mono?"#000000":m)}))}}let O=null;for(let n=a;n<=w;n++){const f=u[n-a+1]-u[n-a];if(f===0)continue;const g=t.columns[n];if(!(g===void 0&&!I&&N))for(let m=d;m<=T;m++){if(!I&&N){const R=g[m>>>tt];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=e.style(m,n);y.fill===null&&y.borders===null||D&&t.mergeAt(m,n)!==null||(y.fill!==null&&!e.mono&&(y.gradient?Q(y.gradient,r+u[n-a],h+b[m-d],f,c,(R,z,L,G,X)=>{e.setInk(R),o.fillRect(z,L,G,X)}):(e.setInk(ft(y)),o.fillRect(r+u[n-a],h+b[m-d],f,c))),y.borders!==null&&(O??=[]).push(m,n,y.borders))}}const S=n=>{const f=r+t.cols.offsetOf(n.c0)-t.cols.offsetOf(a),g=h+t.rows.offsetOf(n.r0)-t.rows.offsetOf(d);return{x:f,y:g,w:t.cols.offsetOf(n.c1+1)-t.cols.offsetOf(n.c0),h:t.rows.offsetOf(n.r1+1)-t.rows.offsetOf(n.r0)}};for(const n of x){const f=S(n),g=e.style(n.r0,n.c0);(l||g.fill!==null&&!e.mono)&&(g.gradient&&!e.mono?Q(g.gradient,f.x,f.y,f.w,f.h,(m,c,y,R,z)=>{e.setInk(m),o.fillRect(c,y,R,z)}):(e.setInk(g.fill!==null&&!e.mono?ft(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(e.cfFrame=null,t.cf&&t.cf.length>0){t.cfEval||(t.cfEval=new xt(M,t,f=>Wt(f,M.theme??[])));const n=new Map;e.cfFrame=n;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;n.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&&!e.mono&&(e.setInk("#FFFFFF"),o.fillRect(y,R,g,z)),c.fill&&!e.mono&&(e.setInk(c.fill),o.fillRect(y,R,g,z)),c.bar&&!e.mono&&(Ot(o,c.bar,y,R,g,z,1,!1,!0),e.ink=""),c.borders&&(O??=[]).push(m,f,c.borders)}}}if(O!==null)for(let n=0;n<O.length;n+=3){const f=O[n],g=O[n+1],m=O[n+2],c=r+u[g-a],y=r+u[g-a+1],R=h+b[f-d],z=h+b[f-d+1];e.side(m.t,c,R,y,R),e.side(m.b,c,z,y,z),e.side(m.l,c,R,c,z),e.side(m.r,y,R,y,z),m.d&&m.down&&e.side(m.d,c,R,y,z),m.d&&m.up&&e.side(m.d,c,z,y,R)}for(const n of x){const f=S(n);for(let g=n.c0;g<=n.c1;g++){const m=t.cols.sizeOf(g),c=f.x+t.cols.offsetOf(g)-t.cols.offsetOf(n.c0),y=e.style(n.r0,g).borders;y?.t&&e.side(y.t,c,f.y,c+m,f.y);const R=e.style(n.r1,g).borders;R?.b&&e.side(R.b,c,f.y+f.h,c+m,f.y+f.h)}for(let g=n.r0;g<=n.r1;g++){const m=t.rows.sizeOf(g),c=f.y+t.rows.offsetOf(g)-t.rows.offsetOf(n.r0),y=e.style(g,n.c0).borders;y?.l&&e.side(y.l,f.x,c,f.x,c+m);const R=e.style(g,n.c1).borders;R?.r&&e.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[n,f]of Rt(t)){const g=Math.floor(n/16384),m=n-g*16384;g<d||g>T||m<a||m>w||Ft(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:e.mono})}t.sparkRules!==null&&Mt(o,M,t,{r0:d,r1:T,c0:a,c1:w,xs:u,ys:b,ox:r,oy:h,mono:e.mono}),e.reset(),o.textBaseline="alphabetic",o.textAlign="left";const A={c0:a,c1:w};for(let n=a;n<=w;n++){const f=r+u[n-a],g=u[n-a+1]-u[n-a];if(g===0)continue;const m=t.columns[n];if(m!==void 0)for(let c=d;c<=T;c++){const y=m[c>>>tt];if(y===void 0){c|=H;continue}const R=c&H,z=y.kinds[R]&U;if(z===K||D&&t.mergeAt(c,n)!==null)continue;const L=b[c-d+1]-b[c-d];L!==0&&e.text(c,n,z,y.values[R],f,h+b[c-d],g,L,A)}}if(s<a)for(let n=d;n<=T;n++){const f=b[n-d+1]-b[n-d];if(f===0||t.kind(n,a)!==0)continue;let g=0;for(let m=a-1;m>=Math.max(s,a-_t);m--){g+=t.cols.sizeOf(m);const c=t.kind(n,m)&U;if(c!==K){c===v&&t.mergeAt(n,m)===null&&(e.reachX=r,e.text(n,m,c,t.value(n,m),r-g,h+b[n-d],t.cols.sizeOf(m),f,A),e.reachX=null);break}}}for(const n of x){const f=t.kind(n.r0,n.c0)&U;if(f===K)continue;const g=S(n);e.text(n.r0,n.c0,f,t.value(n.r0,n.c0),g.x,g.y,g.w,g.h,A,!0)}q(t)&&wt(e.book,t,d,T,a,w,(n,f)=>{it(e.ctx,e.book,t,n,f,r+u[f-a],h+b[n-d],u[f-a+1]-u[f-a],b[n-d+1]-b[n-d]),e.reset()}),p&&(e.reset(),p(i),e.reset()),o.restore(),e.reset()}function Vt(e,i,l){const{ctx:s,sheet:p}=e,{headingW:o,headingH:t,titleW:r,titleH:h}=i,d=r+i.bodyW,T=h+i.bodyH;s.strokeStyle=Y,s.lineWidth=$,s.setLineDash([]),e.reset(),s.font=l,s.textBaseline="alphabetic",s.textAlign="center",e.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(Tt(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 Yt(e){let i=_.get(e);return i===void 0&&(i=Ht(e),_.size>256&&_.clear(),_.set(e,i)),i}function $t(e,i){switch(e.field){case"page":return String(i.pageNumber+(e.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 jt(e,i){const l=[[]];for(const s of e)(s.field?$t(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(e,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;e.save(),e.textBaseline="alphabetic",e.textAlign="left";const F=(x,D,I,N)=>{const M=x.map(A=>{const n=(A.size??j)*p*(A.script!==0?.66:1),f=E({...u,fontName:A.font??u.fontName,bold:A.bold,italic:A.italic},n);return e.font=f,{run:A,size:n,font:f,width:e.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:n,font:f,width:g}of M){e.font=f;const m=t.blackAndWhite?"#000000":A.color??"#000000";e.fillStyle=m;const c=N-(A.script===1?n*.5:A.script===-1?-n*.2:0);e.fillText(A.text,S,c);const y=Math.max(.4,n/14);A.underline&&(e.fillRect(S,c+n*.14,g,y),A.underline===2&&e.fillRect(S,c+n*.14+y*2,g,y)),A.strike&&e.fillRect(S,c-n*.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=jt(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=Yt(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)}e.restore()}function Zt(e,i){e.translate((i.paperW-2*i.originX)/i.scale,0),e.scale(-1,1);const l=Object.prototype.hasOwnProperty.call(e,"fillText"),s=e.fillText;return e.fillText=function(o,t,r){const h=e.measureText(o).width,d=e.textAlign,T=d==="right"||d==="end"?t-h:d==="center"?t-h/2:t;e.save(),e.scale(-1,1),e.textAlign="left",s.call(e,o,-T-h,r),e.restore()},()=>{l?e.fillText=s:delete e.fillText}}function ct(e,i,l,s={}){const{book:p,sheet:o,setup:t}=i,r=p.styles.list[0];e.save(),s.background!==!1&&(e.fillStyle="#ffffff",e.fillRect(0,0,l.paperW,l.paperH)),ut(e,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(e,i,l,h,t.scaleWithDoc?l.scale:1),e.save(),e.translate(l.originX,l.originY),e.scale(l.scale,l.scale);const d=o.rtl===!0?Zt(e,l):null,T=new Ut(e,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&&Vt(T,l,E(r,r.fontSize));const M=s.objectPainters??null,O=M&&M.length>0?n=>{const f=n.x-o.cols.offsetOf(n.c0),g=n.y-o.rows.offsetOf(n.r0),m={printing:!0,dpr:1,zoom:1,hx:n.x,hy:n.y,cssW:n.x+o.cols.offsetOf(n.c1+1)-o.cols.offsetOf(n.c0),cssH:n.y+o.rows.offsetOf(n.r1+1)-o.rows.offsetOf(n.r0),toScreen:(c,y)=>({x:f+c,y:g+y}),sheet:o};for(const c of M)c(e,m)}:null;if(l.chartBox){if(M){const n={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(e,n)}e.restore(),e.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?.(),e.restore(),e.restore()}function Te(e,i,l,{pxPerPt:s=2,...p}={}){const o=i.at(l);if(o===null)return null;const{page:t,pagination:r}=o;e.width=Math.max(1,Math.round(t.paperW*s)),e.height=Math.max(1,Math.round(t.paperH*s));const h=e.getContext("2d",{alpha:!1});return h.setTransform(s,0,0,s,0,0),ct(h,r,t,{pageNumber:o.pageNumber,totalPages:o.totalPages,sheetPage:o.sheetPage,...p}),o}const qt=()=>new Promise(e=>setTimeout(e,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 ft(e){if(!e.pattern)return e.fill;const i=Qt[e.pattern.type]??.5,l=s=>{const p=parseInt(e.pattern.fg.slice(s,s+2),16),o=parseInt(e.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 xe(e,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"),zt(e)]),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<e.pageCount;C++){h?.throwIfAborted();const F=e.at(C),{page:k,pagination:P}=F,x=w.beginPage(k.paperW,k.paperH);ct(x,P,k,{...T,now:u,background:!1,pageNumber:F.pageNumber,totalPages:F.totalPages,sheetPage:F.sheetPage}),await w.endPage(),d?.(C+1,e.pageCount),performance.now()-b>12&&(await qt(),b=performance.now())}return await w.finish(),{pages:w.pageCount,bytes:w.offset,missing:[...w.missing],fontWarnings:w.fontWarnings}}export{Kt as displayText,Jt as paintHeaderFooter,Te as renderJobPageToCanvas,ct as renderPage,xe as writeJobPdf};
package/slicers/format.js CHANGED
@@ -1,2 +1,2 @@
1
- import{parseNode as p}from"../pivot/xml.js";import{xmlAttr as D}from"../io/xml-escape.js";import{unescapeXstring as w}from"../io/xml-scan.js";const a={main:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",x14:"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",x15:"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main",xr10:"http://schemas.microsoft.com/office/spreadsheetml/2016/revision10",xdr:"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",a:"http://schemas.openxmlformats.org/drawingml/2006/main",a14:"http://schemas.microsoft.com/office/drawing/2010/main",sle:"http://schemas.microsoft.com/office/drawing/2010/slicer",sle15:"http://schemas.microsoft.com/office/drawing/2012/slicer",tsle:"http://schemas.microsoft.com/office/drawing/2012/timeslicer"},P={slicerCache:"http://schemas.microsoft.com/office/2007/relationships/slicerCache",slicer:"http://schemas.microsoft.com/office/2007/relationships/slicer",timelineCache:"http://schemas.microsoft.com/office/2011/relationships/timelineCache",timeline:"http://schemas.microsoft.com/office/2011/relationships/timeline",drawing:`${a.r}/drawing`},O={slicerCache:"application/vnd.ms-excel.slicerCache+xml",slicer:"application/vnd.ms-excel.slicer+xml",timelineCache:"application/vnd.ms-excel.timelineCache+xml",timeline:"application/vnd.ms-excel.timeline+xml",drawing:"application/vnd.openxmlformats-officedocument.drawing+xml"},h={wbPivotSlicerCaches:"{BBE1A952-AA13-448e-AADC-164F8A28A991}",wbTableSlicerCaches:"{46BE6895-7355-4a93-B00E-2C351335B9C9}",wbTimelineCaches:"{D0CA8CA8-9F24-4464-BF8E-62219DCF47F9}",wsPivotSlicers:"{A8765BA9-456A-4dab-B4F3-ACF838C121DE}",wsTableSlicers:"{3A4CF648-6AED-40f4-86FF-DC5316D8AED3}",wsTimelines:"{7E03D99C-DC04-49d9-9315-930204A7B6E9}",tableSlicerCache:"{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}",hideNoData:"{470722E0-AACD-4C17-9CDC-17EF765DBC7E}",pivotCacheId:"{725AE2AE-9491-48be-B2B4-4EB974FC3084}",slicerStyles:"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}",timelineStyles:"{9260A510-F301-46a8-8635-F512D64BE5F5}"},B=t=>`@@TAB${t}@@`,b=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- `,C=D,d=t=>Object.entries(t).filter(([,i])=>i!=null).map(([i,e])=>` ${i}="${C(e)}"`).join(""),x=(t,i)=>t?.c?.find(e=>e.n===i)??null,v=(t,i)=>t?t.c.filter(e=>e.n===i):[],$=t=>t.slice(t.indexOf(":")+1),f=(t,i)=>t===void 0?i:t==="1"||t==="true";function R(t){const i=d({name:t.name,"xr10:uid":t.uid??void 0,sourceName:t.sourceName,...t.extra??{}}),e=`${b}<slicerCacheDefinition xmlns="${a.x14}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}"${i}>`,n={sortOrder:t.sortOrder&&t.sortOrder!=="ascending"?t.sortOrder:void 0,customListSort:t.customListSort===!1?"0":void 0,crossFilter:t.crossFilter&&t.crossFilter!=="showItemsWithDataAtTop"?t.crossFilter:void 0},r=[];let o="";if(t.kind==="table")r.push(`<x:ext uri="${h.tableSlicerCache}" xmlns:x15="${a.x15}"><x15:tableSlicerCache${d({tableId:t.tableId,column:t.column,...n})}/></x:ext>`);else{const l=(t.pivotTables??[]).map(m=>`<pivotTable${d({tabId:m.tabId,name:m.name})}/>`).join("");o+=`<pivotTables>${l}</pivotTables>`;const c=(t.items??[]).map(m=>`<i${d({x:m.x,s:m.s?"1":void 0,nd:m.nd?"1":void 0})}/>`).join(""),s={pivotCacheId:t.pivotCacheId,...n,showMissing:t.showMissing===!1?"0":void 0};o+=`<data><tabular${d(s)}><items count="${(t.items??[]).length}">${c}</items></tabular></data>`}t.hideNoData&&r.push(`<x:ext uri="${h.hideNoData}" xmlns:x15="${a.x15}"><x15:slicerCacheHideItemsWithNoData/></x:ext>`);for(const l of t.rawExt??[])r.push(l);return`${e}${o}${r.length?`<extLst>${r.join("")}</extLst>`:""}</slicerCacheDefinition>`}function k(t){const i=e=>{const n={name:e.name,"xr10:uid":e.uid??void 0,cache:e.cache,caption:e.caption,startItem:e.startItem?e.startItem:void 0,columnCount:e.columnCount&&e.columnCount!==1?e.columnCount:void 0,showCaption:e.showCaption===!1?"0":void 0,level:e.level?e.level:void 0,style:e.style&&e.style!=="SlicerStyleLight1"?e.style:void 0,lockedPosition:e.lockedPosition?"1":void 0,rowHeight:e.rowHeight??241300,...e.extra??{}};return`<slicer${d(n)}/>`};return`${b}<slicers xmlns="${a.x14}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}">${t.map(i).join("")}</slicers>`}function H(t){const i=(t.pivotTables??[]).map(r=>`<pivotTable${d({tabId:r.tabId,name:r.name})}/>`).join(""),e=(r,o)=>o?`<${r}${d({startDate:o.start,endDate:o.end})}/>`:"",n=d({singleRangeFilterState:t.singleRange===!1?"0":void 0,minimalRefreshVersion:t.minimalRefreshVersion??6,lastRefreshVersion:t.lastRefreshVersion??6,pivotCacheId:t.pivotCacheId,filterType:t.selection?"dateBetween":"unknown",filterId:t.selection?t.filterId:void 0,filterTabId:t.selection?t.filterTabId:void 0,filterPivotName:t.selection?t.filterPivotName:void 0});return`${b}<timelineCacheDefinition xmlns="${a.x15}" xmlns:x15="${a.x15}" xmlns:mc="${a.mc}" mc:Ignorable="xr10" xmlns:xr10="${a.xr10}"${d({name:t.name,"xr10:uid":t.uid??void 0,sourceName:t.sourceName,...t.extra??{}})}><pivotTables>${i}</pivotTables><state${n}>${e("selection",t.selection)}${e("bounds",t.bounds)}</state></timelineCacheDefinition>`}function X(t){const i=e=>`<timeline${d({name:e.name,"xr10:uid":e.uid??void 0,cache:e.cache,caption:e.caption,showHeader:e.showHeader===!1?"0":void 0,showSelectionLabel:e.showSelectionLabel===!1?"0":void 0,showTimeLevel:e.showTimeLevel===!1?"0":void 0,showHorizontalScrollbar:e.showHorizontalScrollbar===!1?"0":void 0,level:e.level??2,selectionLevel:e.selectionLevel??e.level??2,scrollPosition:e.scrollPosition??void 0,style:e.style&&e.style!=="TimeSlicerStyleLight1"?e.style:void 0,...e.extra??{}})}/>`;return`${b}<timelines xmlns="${a.x15}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}">${t.map(i).join("")}</timelines>`}const S={pivot:{choice:`xmlns:a14="${a.a14}" Requires="a14"`,uri:a.sle,inner:t=>`<sle:slicer xmlns:sle="${a.sle}" name="${C(t)}"/>`},table:{choice:`xmlns:sle15="${a.sle15}" Requires="sle15"`,uri:a.sle,inner:t=>`<sle:slicer xmlns:sle="${a.sle}" name="${C(t)}"/>`},timeline:{choice:`xmlns:tsle="${a.tsle}" Requires="tsle"`,uri:a.tsle,inner:t=>`<tsle:timeslicer xmlns:tsle="${a.tsle}" name="${C(t)}"/>`}},T={pivot:"This shape represents a slicer. Slicers are supported in Excel 2010 or later.",table:"This shape represents a table slicer. Table slicers are supported in Excel 2013 or later.",timeline:"Timeline: Works in Excel 2013 or higher. Do not move or resize."};function M({kind:t,name:i,id:e,from:n,to:r,cx:o=1828800,cy:l=2524125}){const c=S[t],s=(m,u)=>`<xdr:${m}><xdr:col>${u.col}</xdr:col><xdr:colOff>${u.colOff}</xdr:colOff><xdr:row>${u.row}</xdr:row><xdr:rowOff>${u.rowOff}</xdr:rowOff></xdr:${m}>`;return`<xdr:twoCellAnchor editAs="absolute">${s("from",n)}${s("to",r)}<mc:AlternateContent xmlns:mc="${a.mc}"><mc:Choice ${c.choice}><xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="${e}" name="${C(i)}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="${c.uri}">${c.inner(i)}</a:graphicData></a:graphic></xdr:graphicFrame></mc:Choice><mc:Fallback xmlns=""><xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="0" name=""/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${o}" cy="${l}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:prstClr val="white"/></a:solidFill><a:ln w="1"><a:solidFill><a:prstClr val="green"/></a:solidFill></a:ln></xdr:spPr><xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" sz="1100"/><a:t>${T[t]}</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback></mc:AlternateContent><xdr:clientData/></xdr:twoCellAnchor>`}const j=t=>`${b}<xdr:wsDr xmlns:xdr="${a.xdr}" xmlns:a="${a.a}">${t}</xdr:wsDr>`,g=/<xdr:(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/xdr:\1>/g,I=/<(?:\w+:)?(slicer|timeslicer)\b[^>]*\bname="([^"]*)"/;function z(t){const i=[];for(const e of t.matchAll(g)){const n=e[0];if(!/drawing\/20(?:10|12)\/(?:time)?slicer/.test(n))continue;const r=I.exec(n);if(!r)continue;const o=l=>{const c=new RegExp(`<xdr:${l}>\\s*<xdr:col>(\\d+)</xdr:col>\\s*<xdr:colOff>(-?\\d+)</xdr:colOff>\\s*<xdr:row>(\\d+)</xdr:row>\\s*<xdr:rowOff>(-?\\d+)</xdr:rowOff>`).exec(n);return c?{col:Number(c[1]),colOff:Number(c[2]),row:Number(c[3]),rowOff:Number(c[4])}:null};i.push({kind:r[1]==="timeslicer"?"timeline":/Requires="sle15"/.test(n)?"table":"pivot",name:w(r[2]),id:Number(/<xdr:cNvPr\b[^>]*\bid="(\d+)"/.exec(n)?.[1]??0),from:o("from"),to:o("to"),raw:n})}return i}function V(t,{upsert:i=[],remove:e=[]}){const n=new Map(i.map(s=>[s.name,s.xml])),r=new Set(e),o=new Set;let l=t.replace(g,s=>{if(!/drawing\/20(?:10|12)\/(?:time)?slicer/.test(s))return s;const m=I.exec(s);if(!m)return s;const u=w(m[2]);return r.has(u)?"":n.has(u)?(o.add(u),n.get(u)):s});const c=i.filter(s=>!o.has(s.name)).map(s=>s.xml).join("");return c&&(l=l.replace(/<\/(\w+:)?wsDr>\s*$/,s=>`${c}${s}`)),l}const F=new Set(["name","xr10:uid","cache","caption","startItem","columnCount","showCaption","level","style","lockedPosition","rowHeight"]),A=new Set(["name","xr10:uid","cache","caption","showHeader","showSelectionLabel","showTimeLevel","showHorizontalScrollbar","level","selectionLevel","scrollPosition","style"]),N=(t,i)=>{const e={};for(const[n,r]of Object.entries(t))!i.has(n)&&!n.startsWith("xmlns")&&n!=="mc:Ignorable"&&(e[n]=r);return e};function W(t){const i=p(t),e={name:i.a.name,sourceName:i.a.sourceName,uid:i.a["xr10:uid"]??null,kind:"pivot",sortOrder:"ascending",customListSort:!0,crossFilter:"showItemsWithDataAtTop",showMissing:!0,hideNoData:!1,pivotTables:[],items:[],pivotCacheId:null,tableId:null,column:null},n=o=>{o.sortOrder&&(e.sortOrder=o.sortOrder),e.customListSort=f(o.customListSort,!0),o.crossFilter&&(e.crossFilter=o.crossFilter)};for(const o of v(x(i,"pivotTables"),"pivotTable"))e.pivotTables.push({tabId:Number(o.a.tabId),name:o.a.name});const r=x(x(i,"data"),"tabular");if(r){e.pivotCacheId=Number(r.a.pivotCacheId),n(r.a),e.showMissing=f(r.a.showMissing,!0);for(const o of v(x(r,"items"),"i"))e.items.push({x:Number(o.a.x),s:f(o.a.s,!1),nd:f(o.a.nd,!1)})}for(const o of x(i,"extLst")?.c??[])if($(o.n)==="ext")if(o.a.uri===h.tableSlicerCache){const l=o.c.find(c=>$(c.n)==="tableSlicerCache");l&&(e.kind="table",e.tableId=Number(l.a.tableId),e.column=Number(l.a.column),n(l.a))}else o.a.uri===h.hideNoData&&(e.hideNoData=!0);return e}function _(t){const i=p(t);return v(i,"slicer").map(e=>({name:e.a.name,uid:e.a["xr10:uid"]??null,cache:e.a.cache,caption:e.a.caption??e.a.name,startItem:Number(e.a.startItem??0),columnCount:Number(e.a.columnCount??1),showCaption:f(e.a.showCaption,!0),level:Number(e.a.level??0),style:e.a.style??"SlicerStyleLight1",lockedPosition:f(e.a.lockedPosition,!1),rowHeight:Number(e.a.rowHeight??241300),extra:N(e.a,F)}))}function G(t){const i=p(t),e=x(i,"state"),n=r=>{const o=x(e,r);return o?{start:o.a.startDate,end:o.a.endDate}:null};return{name:i.a.name,sourceName:i.a.sourceName,uid:i.a["xr10:uid"]??null,pivotTables:v(x(i,"pivotTables"),"pivotTable").map(r=>({tabId:Number(r.a.tabId),name:r.a.name})),singleRange:f(e?.a.singleRangeFilterState,!0),minimalRefreshVersion:Number(e?.a.minimalRefreshVersion??6),lastRefreshVersion:Number(e?.a.lastRefreshVersion??6),pivotCacheId:Number(e?.a.pivotCacheId??0),filterType:e?.a.filterType??"unknown",filterId:e?.a.filterId!==void 0?Number(e.a.filterId):null,filterTabId:e?.a.filterTabId!==void 0?Number(e.a.filterTabId):null,filterPivotName:e?.a.filterPivotName??null,selection:n("selection"),bounds:n("bounds")}}function q(t){const i=p(t);return v(i,"timeline").map(e=>({name:e.a.name,uid:e.a["xr10:uid"]??null,cache:e.a.cache,caption:e.a.caption??e.a.name,showHeader:f(e.a.showHeader,!0),showSelectionLabel:f(e.a.showSelectionLabel,!0),showTimeLevel:f(e.a.showTimeLevel,!0),showHorizontalScrollbar:f(e.a.showHorizontalScrollbar,!0),level:Number(e.a.level??2),selectionLevel:Number(e.a.selectionLevel??e.a.level??2),scrollPosition:e.a.scrollPosition??null,style:e.a.style??"TimeSlicerStyleLight1",extra:N(e.a,A)}))}function K(t){const i=p(t);for(const e of x(i,"extLst")?.c??[]){if(e.a.uri!==h.pivotCacheId)continue;const n=e.c.find(r=>$(r.n)==="pivotCacheDefinition");if(n?.a.pivotCacheId!==void 0)return Number(n.a.pivotCacheId)}return null}function U(t,i){const e=`<ext uri="${h.pivotCacheId}" xmlns:x14="${a.x14}"><x14:pivotCacheDefinition pivotCacheId="${i}"/></ext>`;return t.includes(h.pivotCacheId)?t.replace(/(<x14:pivotCacheDefinition\b[^>]*\bpivotCacheId=")\d+/,`$1${i}`):/<extLst>/.test(t)?t.replace(/<extLst>/,`<extLst>${e}`):t.replace("</pivotCacheDefinition>",`<extLst>${e}</extLst></pivotCacheDefinition>`)}import{isoToSerial as Y,serialToIso as Z}from"../pivot/xml.js";export{O as CT,h as EXT,a as NS,P as REL,b as XML_HEAD,M as frameXml,Y as isoToSerial,j as newDrawingXml,z as parseFrames,W as parseSlicerCacheXml,_ as parseSlicersXml,G as parseTimelineCacheXml,q as parseTimelinesXml,V as patchDrawingFrames,K as pivotCacheExtId,Z as serialToIso,U as setPivotCacheExtId,R as slicerCacheXml,k as slicersXml,B as tabPlaceholder,H as timelineCacheXml,X as timelinesXml};
1
+ import{parseNode as p}from"../pivot/xml.js";import{xmlAttr as A}from"../io/xml-escape.js";import{unescapeXstring as I}from"../io/xml-scan.js";const a={main:"http://schemas.openxmlformats.org/spreadsheetml/2006/main",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",x14:"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",x15:"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main",xr10:"http://schemas.microsoft.com/office/spreadsheetml/2016/revision10",xdr:"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing",a:"http://schemas.openxmlformats.org/drawingml/2006/main",a14:"http://schemas.microsoft.com/office/drawing/2010/main",sle:"http://schemas.microsoft.com/office/drawing/2010/slicer",sle15:"http://schemas.microsoft.com/office/drawing/2012/slicer",tsle:"http://schemas.microsoft.com/office/drawing/2012/timeslicer"},k={slicerCache:"http://schemas.microsoft.com/office/2007/relationships/slicerCache",slicer:"http://schemas.microsoft.com/office/2007/relationships/slicer",timelineCache:"http://schemas.microsoft.com/office/2011/relationships/timelineCache",timeline:"http://schemas.microsoft.com/office/2011/relationships/timeline",drawing:`${a.r}/drawing`},H={slicerCache:"application/vnd.ms-excel.slicerCache+xml",slicer:"application/vnd.ms-excel.slicer+xml",timelineCache:"application/vnd.ms-excel.timelineCache+xml",timeline:"application/vnd.ms-excel.timeline+xml",drawing:"application/vnd.openxmlformats-officedocument.drawing+xml"},h={wbPivotSlicerCaches:"{BBE1A952-AA13-448e-AADC-164F8A28A991}",wbTableSlicerCaches:"{46BE6895-7355-4a93-B00E-2C351335B9C9}",wbTimelineCaches:"{D0CA8CA8-9F24-4464-BF8E-62219DCF47F9}",wsPivotSlicers:"{A8765BA9-456A-4dab-B4F3-ACF838C121DE}",wsTableSlicers:"{3A4CF648-6AED-40f4-86FF-DC5316D8AED3}",wsTimelines:"{7E03D99C-DC04-49d9-9315-930204A7B6E9}",tableSlicerCache:"{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}",hideNoData:"{470722E0-AACD-4C17-9CDC-17EF765DBC7E}",pivotCacheId:"{725AE2AE-9491-48be-B2B4-4EB974FC3084}",slicerStyles:"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}",timelineStyles:"{9260A510-F301-46a8-8635-F512D64BE5F5}"},X=t=>`@@TAB${t}@@`,b=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ `,C=A,u=t=>Object.entries(t).filter(([,i])=>i!=null).map(([i,e])=>` ${i}="${C(e)}"`).join(""),f=(t,i)=>t?.c?.find(e=>e.n===i)??null,v=(t,i)=>t?t.c.filter(e=>e.n===i):[],$=t=>t.slice(t.indexOf(":")+1),x=(t,i)=>t===void 0?i:t==="1"||t==="true";function M(t){const i=u({name:t.name,"xr10:uid":t.uid??void 0,sourceName:t.sourceName,...t.extra??{}}),e=`${b}<slicerCacheDefinition xmlns="${a.x14}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}"${i}>`,n={sortOrder:t.sortOrder&&t.sortOrder!=="ascending"?t.sortOrder:void 0,customListSort:t.customListSort===!1?"0":void 0,crossFilter:t.crossFilter&&t.crossFilter!=="showItemsWithDataAtTop"?t.crossFilter:void 0},r=[];let o="";if(t.kind==="table")r.push(`<x:ext uri="${h.tableSlicerCache}" xmlns:x15="${a.x15}"><x15:tableSlicerCache${u({tableId:t.tableId,column:t.column,...n})}/></x:ext>`);else{const l=(t.pivotTables??[]).map(c=>`<pivotTable${u({tabId:c.tabId,name:c.name})}/>`).join("");o+=`<pivotTables>${l}</pivotTables>`;const m=(t.items??[]).map(c=>`<i${u({x:c.x,s:c.s?"1":void 0,nd:c.nd?"1":void 0})}/>`).join(""),s={pivotCacheId:t.pivotCacheId,...n,showMissing:t.showMissing===!1?"0":void 0};o+=`<data><tabular${u(s)}><items count="${(t.items??[]).length}">${m}</items></tabular></data>`}t.hideNoData&&r.push(`<x:ext uri="${h.hideNoData}" xmlns:x15="${a.x15}"><x15:slicerCacheHideItemsWithNoData/></x:ext>`);for(const l of t.rawExt??[])r.push(l);return`${e}${o}${r.length?`<extLst>${r.join("")}</extLst>`:""}</slicerCacheDefinition>`}function j(t){const i=e=>{const n={name:e.name,"xr10:uid":e.uid??void 0,cache:e.cache,caption:e.caption,startItem:e.startItem?e.startItem:void 0,columnCount:e.columnCount&&e.columnCount!==1?e.columnCount:void 0,showCaption:e.showCaption===!1?"0":void 0,level:e.level?e.level:void 0,style:e.style&&e.style!=="SlicerStyleLight1"?e.style:void 0,lockedPosition:e.lockedPosition?"1":void 0,rowHeight:e.rowHeight??241300,...e.extra??{}};return`<slicer${u(n)}/>`};return`${b}<slicers xmlns="${a.x14}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}">${t.map(i).join("")}</slicers>`}function z(t){const i=(t.pivotTables??[]).map(r=>`<pivotTable${u({tabId:r.tabId,name:r.name})}/>`).join(""),e=(r,o)=>o?`<${r}${u({startDate:o.start,endDate:o.end})}/>`:"",n=u({singleRangeFilterState:t.singleRange===!1?"0":void 0,minimalRefreshVersion:t.minimalRefreshVersion??6,lastRefreshVersion:t.lastRefreshVersion??6,pivotCacheId:t.pivotCacheId,filterType:t.selection?"dateBetween":"unknown",filterId:t.selection?t.filterId:void 0,filterTabId:t.selection?t.filterTabId:void 0,filterPivotName:t.selection?t.filterPivotName:void 0});return`${b}<timelineCacheDefinition xmlns="${a.x15}" xmlns:x15="${a.x15}" xmlns:mc="${a.mc}" mc:Ignorable="xr10" xmlns:xr10="${a.xr10}"${u({name:t.name,"xr10:uid":t.uid??void 0,sourceName:t.sourceName,...t.extra??{}})}><pivotTables>${i}</pivotTables><state${n}>${e("selection",t.selection)}${e("bounds",t.bounds)}</state></timelineCacheDefinition>`}function V(t){const i=e=>`<timeline${u({name:e.name,"xr10:uid":e.uid??void 0,cache:e.cache,caption:e.caption,showHeader:e.showHeader===!1?"0":void 0,showSelectionLabel:e.showSelectionLabel===!1?"0":void 0,showTimeLevel:e.showTimeLevel===!1?"0":void 0,showHorizontalScrollbar:e.showHorizontalScrollbar===!1?"0":void 0,level:e.level??2,selectionLevel:e.selectionLevel??e.level??2,scrollPosition:e.scrollPosition??void 0,style:e.style&&e.style!=="TimeSlicerStyleLight1"?e.style:void 0,...e.extra??{}})}/>`;return`${b}<timelines xmlns="${a.x15}" xmlns:mc="${a.mc}" mc:Ignorable="x xr10" xmlns:x="${a.main}" xmlns:xr10="${a.xr10}">${t.map(i).join("")}</timelines>`}const E={pivot:{choice:`xmlns:a14="${a.a14}" Requires="a14"`,uri:a.sle,inner:t=>`<sle:slicer xmlns:sle="${a.sle}" name="${C(t)}"/>`},table:{choice:`xmlns:sle15="${a.sle15}" Requires="sle15"`,uri:a.sle,inner:t=>`<sle:slicer xmlns:sle="${a.sle}" name="${C(t)}"/>`},timeline:{choice:`xmlns:tsle="${a.tsle}" Requires="tsle"`,uri:a.tsle,inner:t=>`<tsle:timeslicer xmlns:tsle="${a.tsle}" name="${C(t)}"/>`}},L={pivot:"This shape represents a slicer. Slicers are supported in Excel 2010 or later.",table:"This shape represents a table slicer. Table slicers are supported in Excel 2013 or later.",timeline:"Timeline: Works in Excel 2013 or higher. Do not move or resize."};function W({kind:t,name:i,id:e,from:n,to:r,cx:o=1828800,cy:l=2524125}){const m=E[t],s=(c,d)=>`<xdr:${c}><xdr:col>${d.col}</xdr:col><xdr:colOff>${d.colOff}</xdr:colOff><xdr:row>${d.row}</xdr:row><xdr:rowOff>${d.rowOff}</xdr:rowOff></xdr:${c}>`;return`<xdr:twoCellAnchor editAs="absolute">${s("from",n)}${s("to",r)}<mc:AlternateContent xmlns:mc="${a.mc}"><mc:Choice ${m.choice}><xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="${e}" name="${C(i)}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="${m.uri}">${m.inner(i)}</a:graphicData></a:graphic></xdr:graphicFrame></mc:Choice><mc:Fallback xmlns=""><xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="0" name=""/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${o}" cy="${l}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:prstClr val="white"/></a:solidFill><a:ln w="1"><a:solidFill><a:prstClr val="green"/></a:solidFill></a:ln></xdr:spPr><xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" sz="1100"/><a:t>${L[t]}</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback></mc:AlternateContent><xdr:clientData/></xdr:twoCellAnchor>`}const _=t=>`${b}<xdr:wsDr xmlns:xdr="${a.xdr}" xmlns:a="${a.a}">${t}</xdr:wsDr>`,D=/<xdr:(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/xdr:\1>/g,S=/<(?:\w+:)?(slicer|timeslicer)\b[^>]*\bname="([^"]*)"/;function G(t){const i=[];for(const e of t.matchAll(D)){const n=e[0];if(!/drawing\/20(?:10|12)\/(?:time)?slicer/.test(n))continue;const r=S.exec(n);if(!r)continue;const o=m=>{const s=new RegExp(`<xdr:${m}>\\s*<xdr:col>(\\d+)</xdr:col>\\s*<xdr:colOff>(-?\\d+)</xdr:colOff>\\s*<xdr:row>(\\d+)</xdr:row>\\s*<xdr:rowOff>(-?\\d+)</xdr:rowOff>`).exec(n);return s?{col:Number(s[1]),colOff:Number(s[2]),row:Number(s[3]),rowOff:Number(s[4])}:null},l=(m,s,c)=>{const d=new RegExp(`<xdr:${m}\\b[^>]*>`).exec(n)?.[0];if(d===void 0)return null;const w=F=>Number(new RegExp(`\\b${F}="(-?\\d+)"`).exec(d)?.[1]),g=w(s),N=w(c);return Number.isFinite(g)&&Number.isFinite(N)?{[s]:g,[c]:N}:null};i.push({kind:r[1]==="timeslicer"?"timeline":/Requires="sle15"/.test(n)?"table":"pivot",name:I(r[2]),id:Number(/<xdr:cNvPr\b[^>]*\bid="(\d+)"/.exec(n)?.[1]??0),from:o("from"),to:o("to"),pos:e[1]==="absoluteAnchor"?l("pos","x","y"):null,ext:e[1]==="twoCellAnchor"?null:l("ext","cx","cy"),raw:n})}return i}function q(t,{upsert:i=[],remove:e=[]}){const n=new Map(i.map(s=>[s.name,s.xml])),r=new Set(e),o=new Set;let l=t.replace(D,s=>{if(!/drawing\/20(?:10|12)\/(?:time)?slicer/.test(s))return s;const c=S.exec(s);if(!c)return s;const d=I(c[2]);return r.has(d)?"":n.has(d)?(o.add(d),n.get(d)):s});const m=i.filter(s=>!o.has(s.name)).map(s=>s.xml).join("");return m&&(l=l.replace(/<\/(\w+:)?wsDr>\s*$/,s=>`${m}${s}`)),l}const y=new Set(["name","xr10:uid","cache","caption","startItem","columnCount","showCaption","level","style","lockedPosition","rowHeight"]),P=new Set(["name","xr10:uid","cache","caption","showHeader","showSelectionLabel","showTimeLevel","showHorizontalScrollbar","level","selectionLevel","scrollPosition","style"]),T=(t,i)=>{const e={};for(const[n,r]of Object.entries(t))!i.has(n)&&!n.startsWith("xmlns")&&n!=="mc:Ignorable"&&(e[n]=r);return e};function K(t){const i=p(t),e={name:i.a.name,sourceName:i.a.sourceName,uid:i.a["xr10:uid"]??null,kind:"pivot",sortOrder:"ascending",customListSort:!0,crossFilter:"showItemsWithDataAtTop",showMissing:!0,hideNoData:!1,pivotTables:[],items:[],pivotCacheId:null,tableId:null,column:null},n=o=>{o.sortOrder&&(e.sortOrder=o.sortOrder),e.customListSort=x(o.customListSort,!0),o.crossFilter&&(e.crossFilter=o.crossFilter)};for(const o of v(f(i,"pivotTables"),"pivotTable"))e.pivotTables.push({tabId:Number(o.a.tabId),name:o.a.name});const r=f(f(i,"data"),"tabular");if(r){e.pivotCacheId=Number(r.a.pivotCacheId),n(r.a),e.showMissing=x(r.a.showMissing,!0);for(const o of v(f(r,"items"),"i"))e.items.push({x:Number(o.a.x),s:x(o.a.s,!1),nd:x(o.a.nd,!1)})}for(const o of f(i,"extLst")?.c??[])if($(o.n)==="ext")if(o.a.uri===h.tableSlicerCache){const l=o.c.find(m=>$(m.n)==="tableSlicerCache");l&&(e.kind="table",e.tableId=Number(l.a.tableId),e.column=Number(l.a.column),n(l.a))}else o.a.uri===h.hideNoData&&(e.hideNoData=!0);return e}function U(t){const i=p(t);return v(i,"slicer").map(e=>({name:e.a.name,uid:e.a["xr10:uid"]??null,cache:e.a.cache,caption:e.a.caption??e.a.name,startItem:Number(e.a.startItem??0),columnCount:Number(e.a.columnCount??1),showCaption:x(e.a.showCaption,!0),level:Number(e.a.level??0),style:e.a.style??"SlicerStyleLight1",lockedPosition:x(e.a.lockedPosition,!1),rowHeight:Number(e.a.rowHeight??241300),extra:T(e.a,y)}))}function J(t){const i=p(t),e=f(i,"state"),n=r=>{const o=f(e,r);return o?{start:o.a.startDate,end:o.a.endDate}:null};return{name:i.a.name,sourceName:i.a.sourceName,uid:i.a["xr10:uid"]??null,pivotTables:v(f(i,"pivotTables"),"pivotTable").map(r=>({tabId:Number(r.a.tabId),name:r.a.name})),singleRange:x(e?.a.singleRangeFilterState,!0),minimalRefreshVersion:Number(e?.a.minimalRefreshVersion??6),lastRefreshVersion:Number(e?.a.lastRefreshVersion??6),pivotCacheId:Number(e?.a.pivotCacheId??0),filterType:e?.a.filterType??"unknown",filterId:e?.a.filterId!==void 0?Number(e.a.filterId):null,filterTabId:e?.a.filterTabId!==void 0?Number(e.a.filterTabId):null,filterPivotName:e?.a.filterPivotName??null,selection:n("selection"),bounds:n("bounds")}}function Q(t){const i=p(t);return v(i,"timeline").map(e=>({name:e.a.name,uid:e.a["xr10:uid"]??null,cache:e.a.cache,caption:e.a.caption??e.a.name,showHeader:x(e.a.showHeader,!0),showSelectionLabel:x(e.a.showSelectionLabel,!0),showTimeLevel:x(e.a.showTimeLevel,!0),showHorizontalScrollbar:x(e.a.showHorizontalScrollbar,!0),level:Number(e.a.level??2),selectionLevel:Number(e.a.selectionLevel??e.a.level??2),scrollPosition:e.a.scrollPosition??null,style:e.a.style??"TimeSlicerStyleLight1",extra:T(e.a,P)}))}function Y(t){const i=p(t);for(const e of f(i,"extLst")?.c??[]){if(e.a.uri!==h.pivotCacheId)continue;const n=e.c.find(r=>$(r.n)==="pivotCacheDefinition");if(n?.a.pivotCacheId!==void 0)return Number(n.a.pivotCacheId)}return null}function Z(t,i){const e=`<ext uri="${h.pivotCacheId}" xmlns:x14="${a.x14}"><x14:pivotCacheDefinition pivotCacheId="${i}"/></ext>`;return t.includes(h.pivotCacheId)?t.replace(/(<x14:pivotCacheDefinition\b[^>]*\bpivotCacheId=")\d+/,`$1${i}`):/<extLst>/.test(t)?t.replace(/<extLst>/,`<extLst>${e}`):t.replace("</pivotCacheDefinition>",`<extLst>${e}</extLst></pivotCacheDefinition>`)}import{isoToSerial as ie,serialToIso as oe}from"../pivot/xml.js";export{H as CT,h as EXT,a as NS,k as REL,b as XML_HEAD,W as frameXml,ie as isoToSerial,_ as newDrawingXml,G as parseFrames,K as parseSlicerCacheXml,U as parseSlicersXml,J as parseTimelineCacheXml,Q as parseTimelinesXml,q as patchDrawingFrames,Y as pivotCacheExtId,oe as serialToIso,Z as setPivotCacheExtId,M as slicerCacheXml,j as slicersXml,X as tabPlaceholder,z as timelineCacheXml,V as timelinesXml};
@@ -1 +1 @@
1
- function D(s,h,o){const{r0:t,c0:c,r1:r,c1:e,headerRows:i,totalsRows:d,columns:R}=s,T=t+i,E=r-d;let a=h.slice(1,-1).trim(),S=!1;a[0]==="@"&&(S=!0,a=a.slice(1).trim());const g=[];if(a!=="")if(a[0]==="["){const l=/\[((?:[^\]']|'.)*)\]/g;let n;for(;(n=l.exec(a))!==null;)g.push(n[1].replace(/'(.)/g,"$1").trim())}else g.push(a.replace(/'(.)/g,"$1").trim());const u=new Set,p=[];for(const l of g){const n=l.toUpperCase();if(n==="#ALL"||n==="#DATA"||n==="#HEADERS"||n==="#TOTALS"||n==="#THIS ROW"){u.add(n),n==="#THIS ROW"&&(S=!0);continue}const f=R.findIndex(b=>b.toUpperCase()===n);if(f<0)return"REF";p.push(c+f)}let A=T,m=E;if(u.has("#ALL"))A=t,m=r;else{const l=u.has("#HEADERS"),n=u.has("#TOTALS"),f=u.has("#DATA");if(l&&i===0||n&&d===0||l&&n&&!f)return"REF";(l||n||f)&&(A=l?t:f?T:r,m=n?r:f?E:t)}const L=p.length?Math.min(...p):c,w=p.length?Math.max(...p):e;if(S){if(o<T||o>E)return"VALUE";A=o,m=o}return{top:A,left:L,bottom:m,right:w}}function F(s,h){if(!h||h.size===0)return s;let o="",t=0;const c=s.length;for(;t<c;){const r=s[t];if(r==='"'||r==="'"){let e=t+1;for(;e<c;){if(s[e]===r){if(s[e+1]!==r)break;e++}e++}o+=s.slice(t,e+1),t=e+1}else if(r==="["){let e=0,i=t;for(;i<c;i++)if(s[i]==="'")i++;else if(s[i]==="[")e++;else if(s[i]==="]"&&--e===0)break;o+=s.slice(t,i+1),t=i+1}else if(/[A-Za-z_\\]/.test(r)){let e=t+1;for(;e<c&&/[A-Za-z0-9_.\\]/.test(s[e]);)e++;const i=s.slice(t,e),d=o[o.length-1],R=h.has(i.toUpperCase())&&s[e]!=="["&&s[e]!=="("&&s[e]!=="!"&&d!=="!";o+=R?`${i}[]`:i,t=e}else o+=r,t++}return o}export{F as expandBareTables,D as resolveStructuredSpec};
1
+ function C(t,h,r){const{r0:s,c0:a,r1:o,c1:e,headerRows:n,totalsRows:d,columns:A}=t,T=s+n,E=o-d;let f=h.slice(1,-1),g=!1;f.trimStart()[0]==="@"&&(g=!0,f=f.trimStart().slice(1));const L=[];if(f.trim()!=="")if(f.trimStart()[0]==="["){const c=/\[((?:[^\]']|'.)*)\]/g;let l;for(;(l=c.exec(f))!==null;)L.push(l[1].replace(/'(.)/g,"$1"))}else L.push(f.replace(/'(.)/g,"$1"));const u=new Set,p=[];for(const c of L){const l=c.toUpperCase(),i=l.trim();if(i==="#ALL"||i==="#DATA"||i==="#HEADERS"||i==="#TOTALS"||i==="#THIS ROW"){u.add(i),i==="#THIS ROW"&&(g=!0);continue}let R=A.findIndex(w=>w.toUpperCase()===l);if(R<0&&(R=A.findIndex(w=>w.toUpperCase()===i)),R<0)return"REF";p.push(a+R)}let m=T,S=E;if(u.has("#ALL"))m=s,S=o;else{const c=u.has("#HEADERS"),l=u.has("#TOTALS"),i=u.has("#DATA");if(c&&n===0||l&&d===0||c&&l&&!i)return"REF";(c||l||i)&&(m=c?s:i?T:o,S=l?o:i?E:s)}const U=p.length?Math.min(...p):a,b=p.length?Math.max(...p):e;if(g){if(r<T||r>E)return"VALUE";m=r,S=r}return{top:m,left:U,bottom:S,right:b}}function D(t,h){if(!h||h.size===0)return t;let r="",s=0;const a=t.length;for(;s<a;){const o=t[s];if(o==='"'||o==="'"){let e=s+1;for(;e<a;){if(t[e]===o){if(t[e+1]!==o)break;e++}e++}r+=t.slice(s,e+1),s=e+1}else if(o==="["){let e=0,n=s;for(;n<a;n++)if(t[n]==="'")n++;else if(t[n]==="[")e++;else if(t[n]==="]"&&--e===0)break;r+=t.slice(s,n+1),s=n+1}else if(/[A-Za-z_\\]/.test(o)){let e=s+1;for(;e<a&&/[A-Za-z0-9_.\\]/.test(t[e]);)e++;const n=t.slice(s,e),d=r[r.length-1],A=h.has(n.toUpperCase())&&t[e]!=="["&&t[e]!=="("&&t[e]!=="!"&&d!=="!";r+=A?`${n}[]`:n,s=e}else r+=o,s++}return r}export{D as expandBareTables,C as resolveStructuredSpec};