@8sheets/data-grid 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +1 -1
  2. package/a11y/cell-alt-text.js +1 -1
  3. package/api/serialize.js +1 -1
  4. package/api/style-refs.js +1 -1
  5. package/calc/adjust.js +1 -1
  6. package/calc/compile.js +1 -1
  7. package/calc/engine.js +1 -1
  8. package/calc/functions/array.js +1 -1
  9. package/calc/functions/database.js +1 -1
  10. package/calc/functions/date.js +1 -1
  11. package/calc/functions/engineering.js +1 -1
  12. package/calc/functions/financial.js +1 -1
  13. package/calc/functions/helpers.js +1 -1
  14. package/calc/functions/index.js +3 -2
  15. package/calc/functions/info.js +1 -1
  16. package/calc/functions/logical.js +1 -1
  17. package/calc/functions/lookup.js +1 -1
  18. package/calc/functions/math.js +1 -1
  19. package/calc/functions/stat.js +1 -1
  20. package/calc/functions/text.js +1 -1
  21. package/calc/parser.js +2 -2
  22. package/calc/shown-refs.js +1 -0
  23. package/calc/values.js +1 -1
  24. package/calcx/calc-control.js +1 -0
  25. package/calcx/external-read.js +1 -1
  26. package/calcx/external.js +1 -1
  27. package/cells/axis-ops.js +1 -1
  28. package/cells/cell-styles-xml.js +1 -1
  29. package/cells/cf-engine.js +1 -1
  30. package/cells/cf-file.js +1 -1
  31. package/cells/docprops-xml.js +2 -2
  32. package/cells/filter-eval.js +1 -0
  33. package/cells/filter-file.js +1 -1
  34. package/cells/find-engine.js +1 -1
  35. package/cells/goto.js +1 -1
  36. package/cells/name-box.js +1 -1
  37. package/cells/note-box.js +3 -0
  38. package/cells/options.js +1 -1
  39. package/cells/outline-column.js +1 -1
  40. package/cells/protected-menu.js +1 -0
  41. package/cells/rich-data-xml.js +1 -1
  42. package/cells/sheet-views-file.js +2 -0
  43. package/cells/shift-check.js +1 -1
  44. package/cells/sort-compare.js +1 -0
  45. package/cells/ui-kit.js +1 -1
  46. package/cells/undo-group.js +1 -1
  47. package/celltypes/dropdowns.js +2 -2
  48. package/core/address.js +1 -1
  49. package/core/autofill.js +1 -1
  50. package/core/axis.js +1 -1
  51. package/core/cond-format.js +1 -1
  52. package/core/culture.js +5 -1
  53. package/core/custom-views.js +1 -1
  54. package/core/data-tools.js +1 -0
  55. package/core/date-codes.js +1 -0
  56. package/core/default-names.js +1 -1
  57. package/core/formula-refs.js +1 -1
  58. package/core/input.js +1 -1
  59. package/core/numfmt.js +1 -1
  60. package/core/precision.js +1 -0
  61. package/core/region-input.js +1 -1
  62. package/core/rule-refs.js +1 -0
  63. package/core/shared-view.js +1 -0
  64. package/core/sheet.js +1 -1
  65. package/core/sparklines.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/spills.js +1 -0
  68. package/core/strings.js +1 -1
  69. package/core/structure.js +1 -1
  70. package/core/table-columns.js +1 -0
  71. package/core/tables.js +2 -2
  72. package/core/validation-ranges.js +1 -1
  73. package/core/whatif.js +1 -1
  74. package/core/workbook.js +1 -1
  75. package/datasheets/formula.js +1 -1
  76. package/datasheets/path-binding.js +1 -1
  77. package/datasheets/persist-writer.js +1 -1
  78. package/datasheets/report.js +1 -1
  79. package/extras/getdata/persist.js +2 -2
  80. package/extras/getdata/rows.js +1 -1
  81. package/extras/getdata/shared-steps.js +1 -0
  82. package/extras/getdata/steps-formula.js +1 -0
  83. package/extras/getdata/steps-more.js +1 -0
  84. package/extras/getdata/steps-tables.js +1 -0
  85. package/extras/getdata/steps.js +1 -1
  86. package/i18n/de/a11y.js +1 -0
  87. package/i18n/de/cells.js +2 -0
  88. package/i18n/de/charts.js +1 -0
  89. package/i18n/de/common.js +1 -0
  90. package/i18n/de/datasheets.js +1 -0
  91. package/i18n/de/format.js +1 -0
  92. package/i18n/de/misc.js +1 -0
  93. package/i18n/de/pivot.js +1 -0
  94. package/i18n/de/proofing.js +1 -0
  95. package/i18n/de/ribbon.js +1 -0
  96. package/i18n/de/shapes.js +1 -0
  97. package/i18n/de/shell.js +3 -0
  98. package/i18n/de/touch.js +1 -0
  99. package/i18n/de.js +1 -0
  100. package/i18n/en/cells.js +2 -1
  101. package/i18n/en/charts.js +1 -1
  102. package/i18n/en/format.js +1 -1
  103. package/i18n/en/misc.js +1 -1
  104. package/i18n/en/pivot.js +1 -1
  105. package/i18n/en/proofing.js +1 -1
  106. package/i18n/en/ribbon.js +1 -1
  107. package/i18n/en/shapes.js +1 -1
  108. package/i18n/en/shell.js +3 -2
  109. package/i18n/en/touch.js +1 -1
  110. package/i18n/es/a11y.js +1 -0
  111. package/i18n/es/cells.js +2 -0
  112. package/i18n/es/charts.js +1 -0
  113. package/i18n/es/common.js +1 -0
  114. package/i18n/es/datasheets.js +1 -0
  115. package/i18n/es/format.js +1 -0
  116. package/i18n/es/misc.js +1 -0
  117. package/i18n/es/pivot.js +1 -0
  118. package/i18n/es/proofing.js +1 -0
  119. package/i18n/es/ribbon.js +1 -0
  120. package/i18n/es/shapes.js +1 -0
  121. package/i18n/es/shell.js +3 -0
  122. package/i18n/es/touch.js +1 -0
  123. package/i18n/es.js +1 -0
  124. package/i18n/fr/a11y.js +1 -0
  125. package/i18n/fr/cells.js +2 -0
  126. package/i18n/fr/charts.js +1 -0
  127. package/i18n/fr/common.js +1 -0
  128. package/i18n/fr/datasheets.js +1 -0
  129. package/i18n/fr/format.js +1 -0
  130. package/i18n/fr/misc.js +1 -0
  131. package/i18n/fr/pivot.js +1 -0
  132. package/i18n/fr/proofing.js +1 -0
  133. package/i18n/fr/ribbon.js +1 -0
  134. package/i18n/fr/shapes.js +1 -0
  135. package/i18n/fr/shell.js +3 -0
  136. package/i18n/fr/touch.js +1 -0
  137. package/i18n/fr.js +1 -0
  138. package/i18n/index.js +1 -1
  139. package/i18n/languages.js +1 -1
  140. package/i18n/pl/cells.js +2 -1
  141. package/i18n/pl/charts.js +1 -1
  142. package/i18n/pl/format.js +1 -1
  143. package/i18n/pl/misc.js +1 -1
  144. package/i18n/pl/pivot.js +1 -1
  145. package/i18n/pl/proofing.js +1 -1
  146. package/i18n/pl/ribbon.js +1 -1
  147. package/i18n/pl/shapes.js +1 -1
  148. package/i18n/pl/shell.js +3 -2
  149. package/i18n/pl/touch.js +1 -1
  150. package/io/blob-sink.js +1 -0
  151. package/io/canonical-xml.js +1 -0
  152. package/io/client.js +1 -1
  153. package/io/crypto/cfb-build.js +1 -0
  154. package/io/crypto/cfb-read.js +1 -1
  155. package/io/crypto/cfb-write.js +1 -1
  156. package/io/crypto/errors.js +1 -1
  157. package/io/csv.js +8 -8
  158. package/io/foreign-sheets.js +2 -2
  159. package/io/io.worker.js +1 -1
  160. package/io/open-package.js +1 -0
  161. package/io/package-paths.js +1 -1
  162. package/io/plan.js +1 -1
  163. package/io/text-split.js +3 -3
  164. package/io/xls/chart-sheet.js +1 -0
  165. package/io/xls/chart.js +1 -0
  166. package/io/xls/crypt.js +1 -0
  167. package/io/xls/dml-color.js +1 -0
  168. package/io/xls/drawing.js +1 -0
  169. package/io/xls/formula.js +1 -0
  170. package/io/xls/geometry.js +1 -0
  171. package/io/xls/index.js +1 -0
  172. package/io/xls/pictures.js +1 -0
  173. package/io/xls/pivot.js +1 -0
  174. package/io/xls/props.js +1 -0
  175. package/io/xls/records.js +1 -0
  176. package/io/xls/shapes.js +1 -0
  177. package/io/xls/sheet-ext.js +1 -0
  178. package/io/xls/sheet.js +1 -0
  179. package/io/xls/styles.js +1 -0
  180. package/io/xls/vba.js +1 -0
  181. package/io/xls/workbook.js +1 -0
  182. package/io/xlsb/filter.js +1 -0
  183. package/io/xlsb/formula.js +2 -0
  184. package/io/xlsb/functions.js +1 -0
  185. package/io/xlsb/index.js +1 -0
  186. package/io/xlsb/parts.js +1 -0
  187. package/io/xlsb/pivot.js +1 -0
  188. package/io/xlsb/records.js +1 -0
  189. package/io/xlsb/sheet-ext.js +1 -0
  190. package/io/xlsb/sheet.js +1 -0
  191. package/io/xlsb/slicer.js +1 -0
  192. package/io/xlsb/styles.js +1 -0
  193. package/io/xlsb/workbook.js +1 -0
  194. package/io/xlsb/xml.js +2 -0
  195. package/io/xlsx-read.js +1 -1
  196. package/io/xlsx-styles.js +2 -2
  197. package/io/xlsx-tail.js +1 -1
  198. package/io/xlsx-write.js +2 -2
  199. package/io/xml-escape.js +1 -1
  200. package/io/xml-scan.js +2 -2
  201. package/io/zip-reader.js +1 -1
  202. package/objects/chart-model.js +1 -1
  203. package/objects/drawing-xml.js +1 -1
  204. package/package.json +1 -1
  205. package/pivot/calc-items.js +1 -0
  206. package/pivot/engine.js +1 -1
  207. package/pivot/xml.js +2 -2
  208. package/print/note-pages.js +2 -2
  209. package/print/page-setup.js +1 -1
  210. package/print/paginate.js +1 -1
  211. package/print/pdf-crypt.js +1 -0
  212. package/print/pdf-tags.js +1 -0
  213. package/print/pdf.js +24 -13
  214. package/print/render-page.js +3 -3
  215. package/print/shown-notes.js +1 -0
  216. package/shapes/form-xml.js +1 -1
  217. package/slicers/custom-styles.js +1 -1
  218. package/slicers/format.js +1 -1
  219. package/slicers/structured.js +1 -1
  220. package/slicers/write.js +1 -1
  221. package/table-view/files.js +1 -1
  222. package/table-view/mount.js +1 -1
  223. package/table-view/version.js +1 -1
  224. package/ui/icons.js +1 -1
  225. package/ui/menu-base.js +1 -1
  226. package/ui/protection-ui.js +1 -1
package/core/tables.js CHANGED
@@ -1,2 +1,2 @@
1
- import{formulaEntryLimit as H}from"../calc/parser.js";import{patchTableColumns as q,totalsChildXml as B}from"../slicers/table-file.js";import{allUndo as J,cowTx as Q,rectsTouch as A}from"../cells/block.js";import{checkBandShift as V,MSG_OFF as k}from"../cells/shift-check.js";import{unmergeCells as ee}from"./merge.js";import{shiftBand as te}from"./structure.js";import{colName as re,MAX_COLS as ne,MAX_ROWS as se,rangeRef as L,sheetPrefix as le}from"./address.js";import{columnStem as M,freeColumnName as oe,newColumnName as ae,nextName as ce,tableStem as ie,totalLabel as ue}from"./default-names.js";import{FORMULA as D,KIND_MASK as _,STR as v}from"./sheet.js";import{translateFormula as fe}from"./formula-refs.js";import{autoFilterXml as me,sortStateXml as de}from"../cells/filter-file.js";import{PRESET_DXFS as pe,PRESET_STYLES as K}from"./table-presets.js";import{resolveColor as he}from"../io/xlsx-styles.js";import{elementTableColors as we}from"../slicers/custom-styles.js";import{undoGroup as be}from"../cells/undo-group.js";import{escapeMarkup as F,xmlAttr as I}from"../io/xml-escape.js";const Ce=["FFFFFF","000000","E8E8E8","0E2841","156082","E97132","196B24","0F9ED5","A02B93","4EA72E"],P=new Set;function qe(t){P.add(t)}function ge(t,e){const r=K[t];if(!r)return null;const s=e&&e.length>=10?e:Ce,n=c=>typeof c=="string"?`#${c}`:he({a:{theme:String(c[0]),tint:c[1]?String(c[1]):void 0}},s),a={},o={};for(const[c,l,i]of r){const u=pe[l],f={};u.bold&&(f.bold=!0),u.italic&&(f.italic=!0),u.c&&(f.color=n(u.c)),u.f&&(f.fill=n(u.f));for(const m of["l","r","t","b","v","h"])u[m]&&(f.borders??={},f.borders[m]={style:u[m][0],color:n(u[m][1])});a[c]=f,i&&(o[c]=i)}return{el:a,sizes:o}}const Z=new WeakMap,$e={};function Re(t,e){if(t&&K[t]&&t.startsWith("TableStyle")){const r=e&&e.length>=10?e:$e;let s=Z.get(r);s||Z.set(r,s=new Map);let n=s.get(t);if(!n){const{el:a,sizes:o}=ge(t,e),c=l=>o[l]??1;n=we(a,[c("firstRowStripe"),c("secondRowStripe")],[c("firstColumnStripe"),c("secondColumnStripe")]),s.set(t,n)}return n}for(const r of P){const s=r(t,e);if(s)return s}return null}function Je(t,e){const r=t.r0+t.headerRows,s=t.sheet?.rows;if(!s||s.hiddenSizes===null||s.hiddenSizes.size===0)return e-r;let n=t._bandRows;if(!n||n.version!==s.version||n.top!==r||n.r1!==t.r1||n.rows!==s){const c=[];for(const l of s.hiddenSizes.keys())l>=r&&l<=t.r1&&c.push(l);c.sort((l,i)=>l-i),n={version:s.version,top:r,r1:t.r1,rows:s,list:c},t._bandRows=n}let a=0,o=n.list.length;for(;a<o;){const c=a+o>>1;n.list[c]<e?a=c+1:o=c}return e-r-a}function Se(t){const e=t.engine;return ce(ie(),r=>e.tables.has(r.toUpperCase()))}function Qe(t,e,r,s,n="TableStyleMedium2",a=[]){const o=t.engine,c=[];let l={...r};const i={...l,r0:l.r0-1,r1:l.r0-1},u=S(t,e),f=!s&&l.r0>0&&!O(e,i.r0,l.c0,l.c1)&&!u.some(d=>A(d,i))&&!e.merges.some(d=>A(d,i))&&!a.some(d=>d.anchor?.sheet===e&&d.renderedRange&&A(d.renderedRange,i)),m=!s&&!f;let h=null;return t.transact("table",d=>{if(e.protection)return;if(m){const p=l.r1+1>=se?k:V(t,e,{...l,r1:l.r0},"down",1,a);if(p)throw new Te(p)}const w=[];if(e.merges.some(p=>A(p,l))&&w.push(ee(e,l)),m?(w.push(te(t,e,{axis:"row",at:l.r0,n:1,span:[l.c0,l.c1]})),d=Q(e),l.r1++):f&&l.r0--,!s)for(let p=l.c0;p<=l.c1;p++)t.setInput(d,l.r0,p,`${M()}${p-l.c0+1}`);const b=new Set;for(let p=l.c0;p<=l.c1;p++){let $=t.editText(e,l.r0,p).trim()||`${M()}${p-l.c0+1}`,g=$;for(let R=2;b.has(g.toLowerCase());R++)g=`${$}${R}`;b.add(g.toLowerCase()),c.push(g),(g!==$||(e.kind(l.r0,p)&_)!==v)&&($=g,d.saveCell(l.r0,p),e.setCell(l.r0,p,v,t.strings.add(g)))}h={name:Se(t),sheet:e,...l,headerRows:1,totalsRows:0,columns:c,styleName:n,showRowStripes:!0,showColumnStripes:!1,showFirstColumn:!1,showLastColumn:!1,filter:{r0:l.r0,c0:l.c0,r1:l.r1,c1:l.c1,columns:new Map},isNew:!0,dirty:!0},o.tables.set(h.name.toUpperCase(),h);const C=p=>()=>(p?o.tables.set(h.name.toUpperCase(),h):o.tables.delete(h.name.toUpperCase()),o.rebuild(),C(!p));return J([...w,C(!1)])}),h}class Te extends Error{}function O(t,e,r,s){for(let n=r;n<=s;n++)if(t.kind(e,n)!==0)return!0;return!1}function S(t,e){const r=[];if(t.engine)for(const s of t.engine.tables.values())s.sheet===e&&r.push(s);return r}function Ve(t,e,r,s){for(const n of S(t,e)){const a=r===n.r1+1-0&&n.totalsRows===0&&s>=n.c0&&s<=n.c1,o=s===n.c1+1&&r>=n.r0&&r<=n.r1;if(a)return n.r1=r,n.filter&&(n.filter.r1=r),n.dirty=!0,r-1>=n.r0+n.headerRows&&t.transact("table-row",c=>{for(let l=n.c0;l<=n.c1;l++)l===s||(e.kind(r-1,l)&D)===0||e.kind(r,l)!==0||t.setInput(c,r,l,`=${fe(t.editText(e,r-1,l).slice(1),1,0)}`,{overLimitAsText:!0})}),t.engine.rebuild(),n;if(o){n.c1=s;const c=t.editText(e,n.r0,s).trim()||ae(new Set(n.columns.map(l=>l.toLowerCase())),n.columns);return n.columns.push(c),n.filter&&(n.filter.c1=s),e.kind(n.r0,s)===0&&e.setCell(n.r0,s,v,t.strings.add(c)),n.dirty=!0,n.columnsChanged=!0,t.engine.rebuild(),n}}return null}function ke(t,e,r){for(const s of S(t,e)){if(r.r0!==s.r1+1||s.totalsRows!==0||r.c0<s.c0||r.c0>s.c1)continue;const n=r.r1;if(S(t,e).some(o=>o!==s&&o.r0<=n&&o.r1>=r.r0&&o.c0<=s.c1&&o.c1>=s.c0))return null;const a={r1:s.r1,filter:s.filter?{...s.filter}:null};return t.transact("table-expand",()=>{const o=i=>{s.r1=i.r1,s.filter=i.filter?{...i.filter}:null,s.dirty=!0,t.engine.rebuild()},c={r1:n,filter:s.filter?{...s.filter,r1:n}:null};o(c);const l=(i,u)=>()=>(o(i),l(u,i));return l(a,c)}),s}return null}function et(t,e,r,s,n,a){if(!n.startsWith("="))return!1;for(const o of S(t,e)){if(s<o.c0||s>o.c1||r<=o.r0||r>o.r1-o.totalsRows)continue;const c=o.r0+o.headerRows,l=o.r1-o.totalsRows;for(let i=c;i<=l;i++)if(i!==r&&e.kind(i,s)!==0)return!1;return l===c?!1:(t.transact("calculated-column",i=>{for(let u=c;u<=l;u++)u!==r&&t.setInput(i,u,s,`=${a(n.slice(1),u-r,0)}`,{overLimitAsText:!0})}),!0)}return!1}const j=(t,e)=>{const r=t.totals?.[e];return r?r.label!==void 0?` totalsRowLabel="${I(r.label)}"`:` totalsRowFunction="${r.fn}"`:""},W=t=>`<tableStyleInfo name="${I(t.styleName??"TableStyleMedium2")}" showFirstColumn="${t.showFirstColumn?1:0}" showLastColumn="${t.showLastColumn?1:0}" showRowStripes="${t.showRowStripes===!1?0:1}" showColumnStripes="${t.showColumnStripes?1:0}"/>`,xe=t=>L({r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1}),Y=t=>t.filter&&t.headerRows>0?me({...t.filter,r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1},!1)+de(t.filter.sortState):"",G=t=>`${t.headerRows===0?' headerRowCount="0"':""}${t.totalsRows?` totalsRowCount="${t.totalsRows}"`:' totalsRowShown="0"'}`;function tt(t,e){const r=t.columns.map((n,a)=>{const o=B(t,a),c=`<tableColumn id="${t.columnIds?.[a]??a+1}" name="${I(n)}"${j(t,a)}`;return o?`${c}>${o}</tableColumn>`:`${c}/>`}).join(""),s=Y(t);return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- <table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="${e}" name="${F(t.name)}" displayName="${F(t.name)}" ref="${L(t)}"${G(t)}>${s}<tableColumns count="${t.columns.length}">${r}</tableColumns>${W(t)}</table>`}function rt(t){return{name:t.name,ref:L(t),filterRef:t.filter&&t.headerRows>0?xe(t):null,filterXml:Y(t),counts:G(t),styleInfo:W(t),totals:t.totals?t.columns.map((e,r)=>j(t,r)):null,totalsChild:t.totals?t.columns.map((e,r)=>B(t,r)):null}}function nt(t,e){let r=t.replace(/<table\b[^>]*>/,s=>s.replace(/\bname="[^"]*"/,`name="${F(e.name)}"`).replace(/\bdisplayName="[^"]*"/,`displayName="${F(e.name)}"`).replace(/\bref="[^"]*"/,`ref="${e.ref}"`).replace(/\s(?:headerRowCount|totalsRowCount|totalsRowShown)="[^"]*"/g,"").replace(/\s*(\/?)>$/,`${e.counts}$1>`));return r=r.replace(/<autoFilter\b[^>]*\/>|<autoFilter\b[\s\S]*?<\/autoFilter>/,"").replace(/<sortState\b[^>]*\/>|<sortState\b[\s\S]*?<\/sortState>/,""),e.filterXml&&(r=r.replace("<tableColumns",`${e.filterXml}<tableColumns`)),/<tableStyleInfo\b/.test(r)?r=r.replace(/<tableStyleInfo\b[^>]*\/>/,e.styleInfo):r=r.replace("</tableColumns>",`</tableColumns>${e.styleInfo}`),e.totals&&(r=q(r,e)),r}const ye=/[[\]#']/g,U=t=>t.replace(ye,"'$&"),ve=/^[A-Za-z_\\][A-Za-z0-9_.\\]*$/;function z(t,e){const r=[];for(const s of t.sheets){const n=new Map;for(const[a,o]of s.formulas){const c=o.f??o.sf;if(typeof c!="string")continue;const l=o.f===void 0&&o.base!==void 0;let i=l?n.get(o):void 0;if(i===void 0){const u=e(c,s,Math.floor((l?o.base:a)/ne));i=u===c?null:o.f!==void 0?{...o,f:u,tpl:void 0}:{...o,sf:u,tpl:void 0},l&&n.set(o,i)}i!==null&&r.push([s.formulas,a,o,i])}}for(const[s,n]of t.engine.names){const a=e(n.text,null,0,s);a!==n.text&&r.push([t.engine.names,s,n,{...n,text:a}])}for(const s of t.engine.tables.values())s.totals?.forEach((n,a)=>{if(n?.fn!=="custom"||!n.formula)return;const o=e(n.formula,s.sheet,s.r1);o!==n.formula&&r.push([{set:(c,l)=>{s.totals[c]=l,s.dirty=!0}},a,n,{...n,formula:o}])});return t.formulasEdited=!0,r.some(s=>s[0]===t.engine.names)&&(t.namesChanged=!0),E(r,3),r}const E=(t,e)=>{for(const r of t)r[0].set(r[1],r[e])};function T(t,e,r,s,{rebuild:n=!1}={}){const a=t.engine;t.transact(r,o=>{const c={...e},l=s(o),i={...e};e.dirty=!0,n&&a.rebuild();const u=(f,m,h)=>()=>(Object.assign(e,f),e.dirty=!0,h?.(),n&&a.rebuild(),u(m,f,h));return u(c,i,l)})}function st(t,e,r,s){T(t,e,"table-option",()=>{e[r]=s})}function lt(t,e,r){r&&e.headerRows===0||T(t,e,"table-filter",()=>{e.filter=r?{r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}:null})}function ot(t,e,r){const s=t.engine;if(!ve.test(r)||/^[A-Za-z]{1,3}[0-9]+$/.test(r)||/^[Rr][Cc]?$|^[Cc]$/.test(r))return"That isn't a valid table name.";const n=r.toUpperCase();if(n===e.name.toUpperCase()&&r===e.name)return null;if(s.tables.has(n)&&s.tables.get(n)!==e)return"Another table already uses that name.";if(s.names.has(n))return"A defined name already uses that name.";const a=e.name;return t.transact("table-name",()=>{const o=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${a.replace(/[.\\]/g,"\\$&")}(?=\\[)`,"gi"),c=z(t,f=>f.replace(o,`$1${r}`)),l=(f,m,h)=>{s.tables.delete(f.toUpperCase()),e.name=m,s.tables.set(m.toUpperCase(),e),e.dirty=!0,E(c,h),s.rebuild()};l(a,r,3);const i=()=>(l(a,r,3),u),u=()=>(l(r,a,2),i);return u}),null}const Ee={average:101,countNums:102,count:103,max:104,min:105,stdDev:107,sum:109,var:110};function Ae(t,e,r){if(!r)return null;if(r.label!==void 0)return r.label;if(r.fn==="custom")return r.formula?`=${r.formula}`:null;const s=Ee[r.fn];return s?`=SUBTOTAL(${s},${t.name}[${U(t.columns[e])}])`:null}function at(t,e,r){const{sheet:s}=e;if(r===e.totalsRows>0)return null;if(r){const a=e.r1+1;if(O(s,a,e.c0,e.c1))return"Clear the row under the table to add a total row.";const o=e.columns.map((l,i)=>e.totals?.[i]??null);if(!o.some(Boolean)&&(o[0]={label:ue()},o.length>1)){let l=!1;for(let i=e.r0+e.headerRows;i<=e.r1&&!l;i++)l=(s.kind(i,e.c1)&_)===1;o[o.length-1]={fn:l?"sum":"count"}}const c=o.map((l,i)=>Ae(e,i,l));for(let l=0;l<c.length;l++){if(o[l]?.label!==void 0||!c[l])continue;const i=H(c[l].slice(1));if(i)return i}return T(t,e,"table-totals",l=>{e.totals=o,c.forEach((i,u)=>{o[u]?.label!==void 0?t.setRichInput(l,a,e.c0+u,i,null):i&&t.setInput(l,a,e.c0+u,i)}),e.totalsRows=1,e.r1=a,e.columnsChanged=e.source!==!0},{rebuild:!0}),null}const n=e.r1;return T(t,e,"table-totals",a=>{for(let o=e.c0;o<=e.c1;o++)t.setInput(a,n,o,"");e.totalsRows=0,e.r1=n-1},{rebuild:!0}),null}function ct(t,e,r){if(r===e.headerRows>0)return null;const{sheet:s}=e;return r?e.r0===0||O(s,e.r0-1,e.c0,e.c1)?"Clear the row above the table to show its headers.":(T(t,e,"table-header",n=>{e.r0-=1,e.headerRows=1,e.columns.forEach((a,o)=>t.setRichInput(n,e.r0,e.c0+o,a,null)),e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}},{rebuild:!0}),null):(T(t,e,"table-header",n=>{for(let a=e.c0;a<=e.c1;a++)t.setInput(n,e.r0,a,"");e.r0+=1,e.headerRows=0,e.filter=null},{rebuild:!0}),null)}function it(t,e,r){const{sheet:s}=e;if(r.r0!==e.r0)return"The header row must stay in the same row.";if(r.c0!==e.c0)return"The table must keep its first column.";if(r.r1<r.r0+e.headerRows+e.totalsRows)return"The table needs at least one data row.";for(const n of S(t,s))if(n!==e&&n.r0<=r.r1&&n.r1>=r.r0&&n.c0<=r.c1&&n.c1>=r.c0)return"A table can't overlap another table.";return T(t,e,"table-resize",()=>{const n=r.c1-r.c0+1,a=e.columns.slice(0,n);for(let o=a.length;o<n;o++){const c=e.c0+o;let l=e.headerRows?t.editText(s,e.r0,c).trim():"";l||(l=`${M()}${o+1}`),a.push(l)}e.columns=a,e.r1=r.r1,e.c1=r.c1,e.filter&&(e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}),e.columnsChanged=!0},{rebuild:!0}),null}function Fe(t,e,r){const{sheet:s}=e,n=e.r1-e.r0+1,a=e.c1-e.c0+1,o=new Map,c=(i,u,f,m)=>{const h=(i-e.r0)*a+(u-e.c0);let d=o.get(h);d||o.set(h,d={}),d[f]=m};for(const i of r.areas(e,e.r0,e.r1,e.c0,e.c1)){const u=i.borders;for(let f=Math.max(i.r0,e.r0);f<=Math.min(i.r1,e.r1);f++)for(let m=Math.max(i.c0,e.c0);m<=Math.min(i.c1,e.c1);m++)u.t&&f===i.r0&&c(f,m,"t",u.t),u.b&&f===i.r1&&c(f,m,"b",u.b),u.l&&m===i.c0&&c(f,m,"l",u.l),u.r&&m===i.c1&&c(f,m,"r",u.r),u.h&&f<i.r1&&c(f,m,"b",u.h),u.v&&m<i.c1&&c(f,m,"r",u.v)}const l=new Map;t.transact("format",i=>{for(let u=0;u<n;u++){const f=e.r0+u;for(let m=0;m<a;m++){const h=e.c0+m,d=r.format(e,f,h),w=o.get(u*a+m),b=s.style(f,h),C=t.styles.get(b),p={};if(d.fill&&!C.fill&&(p.fill=d.fill),d.color&&!C.color&&(p.color=d.color),d.bold&&!C.bold&&(p.bold=!0),d.italic&&!C.italic&&(p.italic=!0),w){const x=C.borders??{},X={l:x.l??null,r:x.r??null,t:x.t??null,b:x.b??null};let N=!1;for(const y of["l","r","t","b"])w[y]&&!x[y]&&(X[y]={style:w[y].style,color:w[y].color},N=!0);N&&(p.borders=X)}const $=JSON.stringify(p);if($==="{}")continue;const g=`${b}|${$}`;let R=l.get(g);R===void 0&&l.set(g,R=t.styles.derive(b,p,$)),R!==b&&(i.saveCell(f,h),s.setStyle(f,h,R))}}})}function ut(t,e){be(t,"Convert to Range",()=>Le(t,e))}function Le(t,e){const r=t.engine,{sheet:s}=e,n=Re(e.styleName,t.theme),a=t.activeSheet;t.activeSheet=t.sheets.indexOf(s),n?.format&&Fe(t,e,n),t.activeSheet=a;const o=e.name.toUpperCase(),c=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${e.name.replace(/[.\\]/g,"\\$&")}(\\[(?:[^\\[\\]']|'.|\\[(?:[^\\[\\]']|'.)*\\])*\\])`,"gi");t.transact("table-convert",()=>{const l=z(t,(m,h,d)=>m.replace(c,(w,b,C)=>{const p=r.tableSpecToA1(e,C,d);return p===null?w:`${b}${h===s?"":le(s.name)}${p}`})),i=e.source===!0&&e.part?{part:e.part,sheetIndex:t.sheets.indexOf(s)}:null,u=()=>{r.tables.delete(o),i&&(t.removedTables??=[]).push(i),E(l,3),r.rebuild()},f=()=>(r.tables.set(o,e),i&&(t.removedTables=t.removedTables.filter(m=>m!==i)),E(l,2),r.rebuild(),()=>(u(),f));return u(),f})}function Me(t,e,r,s){const n=t.toLowerCase(),a=`${e.toLowerCase()}[`;let o="",c=0;for(let l=n.indexOf(a);l>=0;l=n.indexOf(a,l+1)){const i=l+a.length-1;let u=0,f=i;for(;f<t.length;f++){const d=t[f];if(d==="'")f++;else if(d==="[")u++;else if(d==="]"&&--u===0)break}const m=t.slice(i,f+1),h=m.split(`[${r}]`).join(`[${s}]`);h!==m&&(o+=t.slice(c,i)+h,c=f+1)}return c===0?t:o+t.slice(c)}function _e(t,e,r,s){const n=e.columns[r],a=U(n),o=U(s),c=z(t,f=>f.includes("[")?Me(f,e.name,a,o):f),l=(f,m)=>{e.columns=e.columns.map((h,d)=>d===r?f:h),e.columnsChanged=!0,e.dirty=!0,E(c,m),t.engine?.rebuild()};l(s,3);const i=()=>(l(s,3),u),u=()=>(l(n,2),i);return u}function ft(t,e,r){let s=null;const{sheet:n}=e;for(const a of S(t,n))if(!(a.headerRows===0||a.dataSheet))for(let o=0;o<r.count;o++){if(r.rows[o]!==a.r0||r.cols[o]<a.c0||r.cols[o]>a.c1)continue;const c=r.cols[o],l=c-a.c0,i=n.kind(a.r0,c);let u=i===0?"":String(t.engine.read(n,a.r0,c)??"").trim();const f=new Set(a.columns.filter((w,b)=>b!==l).map(w=>w.toLowerCase()));if(u==="")u=oe(f);else if(f.has(u.toLowerCase())){const w=u;let b=2;for(;f.has(`${w}${b}`.toLowerCase());)b++;u=`${w}${b}`}if(((i&_)!==v||(i&D)!==0||t.strings.get(n.value(a.r0,c))!==u)&&(e.saveCell(a.r0,c),n.setFormula(a.r0,c,null),n.setCell(a.r0,c,v,t.strings.add(u))),a.columns[l]===u)continue;const m=_e(t,a,l,u),h=s,d=(w,b)=>b?()=>d(w(),b()):w;s=d(m,h)}return s}const mt=[...Array.from({length:21},(t,e)=>`TableStyleLight${e+1}`),...Array.from({length:28},(t,e)=>`TableStyleMedium${e+1}`),...Array.from({length:11},(t,e)=>`TableStyleDark${e+1}`)];export{Ee as SUBTOTAL_CODE,mt as TABLE_STYLE_NAMES,Te as TableCreationError,Je as bandRow,re as colName,ut as convertTableToRange,Qe as createTable,et as fillCalculatedColumn,ke as growTableOver,Ve as maybeExpandTable,Se as nextTableName,nt as patchTableXml,ge as presetElements,ot as renameTable,_e as renameTableColumn,it as resizeTable,z as rewriteFormulas,qe as setCustomTableResolver,lt as setTableFilterButton,ct as setTableHeaderRow,st as setTableOption,at as setTableTotals,U as structuredColumn,ft as syncTableHeaders,Re as tableColors,rt as tablePatch,tt as tableXml,S as tablesOf,Ae as totalInput};
1
+ import{columnIdsOf as ee}from"./table-columns.js";import{formulaEntryLimit as te}from"../calc/parser.js";import{patchTableColumns as re,totalsChildXml as D}from"../slicers/table-file.js";import{allUndo as ne,cowTx as se,rectsTouch as A}from"../cells/block.js";import{checkBandShift as le,MSG_OFF as oe}from"../cells/shift-check.js";import{unmergeCells as ie}from"./merge.js";import{buttonsFor as K,shiftBand as ce}from"./structure.js";import{colName as ae,MAX_COLS as ue,MAX_ROWS as fe,rangeRef as L,sheetPrefix as me}from"./address.js";import{columnStem as P,freeColumnName as de,newColumnName as Z,nextName as pe,tableStem as he,totalLabel as we}from"./default-names.js";import{EMPTY as be,FORMULA as E,KIND_MASK as M,STR as x}from"./sheet.js";import{formulaText as Ce,translateFormula as j}from"./formula-refs.js";import{autoFilterXml as Re,sortStateXml as $e}from"../cells/filter-file.js";import{PRESET_DXFS as Se,PRESET_STYLES as W}from"./table-presets.js";import{resolveColor as ye}from"../io/xlsx-styles.js";import{elementTableColors as Te}from"../slicers/custom-styles.js";import{applyFilter as xe,showFilteredRows as _}from"./data-tools.js";import{undoGroup as ge}from"../cells/undo-group.js";import{renameViewTable as ve,viewTableKey as Y}from"./shared-view.js";import{escapeMarkup as z,xmlAttr as I}from"../io/xml-escape.js";const Ee=["FFFFFF","000000","E8E8E8","0E2841","156082","E97132","196B24","0F9ED5","A02B93","4EA72E"],H=new Set;function ct(t){H.add(t)}function Fe(t,e){const r=W[t];if(!r)return null;const s=e&&e.length>=10?e:Ee,n=i=>typeof i=="string"?`#${i}`:ye({a:{theme:String(i[0]),tint:i[1]?String(i[1]):void 0}},s),c={},o={};for(const[i,l,a]of r){const u=Se[l],f={};u.bold&&(f.bold=!0),u.italic&&(f.italic=!0),u.c&&(f.color=n(u.c)),u.f&&(f.fill=n(u.f));for(const m of["l","r","t","b","v","h"])u[m]&&(f.borders??={},f.borders[m]={style:u[m][0],color:n(u[m][1])});c[i]=f,a&&(o[i]=a)}return{el:c,sizes:o}}const G=new WeakMap,Ae={};function Le(t,e){if(t&&W[t]&&t.startsWith("TableStyle")){const r=e&&e.length>=10?e:Ae;let s=G.get(r);s||G.set(r,s=new Map);let n=s.get(t);if(!n){const{el:c,sizes:o}=Fe(t,e),i=l=>o[l]??1;n=Te(c,[i("firstRowStripe"),i("secondRowStripe")],[i("firstColumnStripe"),i("secondColumnStripe")]),s.set(t,n)}return n}for(const r of H){const s=r(t,e);if(s)return s}return null}function at(t,e){const r=t.r0+t.headerRows,s=t.sheet?.rows;if(!s||s.hiddenSizes===null||s.hiddenSizes.size===0)return e-r;let n=t._bandRows;if(!n||n.version!==s.version||n.top!==r||n.r1!==t.r1||n.rows!==s){const i=[];for(const l of s.hiddenSizes.keys())l>=r&&l<=t.r1&&i.push(l);i.sort((l,a)=>l-a),n={version:s.version,top:r,r1:t.r1,rows:s,list:i},t._bandRows=n}let c=0,o=n.list.length;for(;c<o;){const i=c+o>>1;n.list[i]<e?c=i+1:o=i}return e-r-c}function Me(t){const e=t.engine;return pe(he(),r=>e.tables.has(r.toUpperCase()))}function ut(t,e,r,s,n="TableStyleMedium2",c=[]){const o=t.engine,i=[];let l={...r};const a={...l,r0:l.r0-1,r1:l.r0-1},u=T(t,e),f=!s&&l.r0>0&&!O(e,a.r0,l.c0,l.c1)&&!u.some(h=>A(h,a))&&!e.merges.some(h=>A(h,a))&&!c.some(h=>h.anchor?.sheet===e&&h.renderedRange&&A(h.renderedRange,a)),m=!s&&!f;let b=null;return t.transact("table",h=>{if(e.protection)return;if(m){const p=l.r1+1>=fe?oe:le(t,e,{...l,r1:l.r0},"down",1,c);if(p)throw new _e(p)}const R=[];if(e.merges.some(p=>A(p,l))&&R.push(ie(e,l)),m?(R.push(ce(t,e,{axis:"row",at:l.r0,n:1,span:[l.c0,l.c1]})),h=se(e),l.r1++):f&&l.r0--,!s)for(let p=l.c0;p<=l.c1;p++)t.setInput(h,l.r0,p,`${P()}${p-l.c0+1}`);const d=new Set;for(let p=l.c0;p<=l.c1;p++){let $=t.editText(e,l.r0,p).trim()||`${P()}${p-l.c0+1}`,C=$;for(let S=2;d.has(C.toLowerCase());S++)C=`${$}${S}`;d.add(C.toLowerCase()),i.push(C),(C!==$||(e.kind(l.r0,p)&M)!==x)&&($=C,h.saveCell(l.r0,p),e.setCell(l.r0,p,x,t.strings.add(C)))}b={name:Me(t),sheet:e,...l,headerRows:1,totalsRows:0,columns:i,styleName:n,showRowStripes:!0,showColumnStripes:!1,showFirstColumn:!1,showLastColumn:!1,filter:{r0:l.r0,c0:l.c0,r1:l.r1,c1:l.c1,columns:new Map},isNew:!0,dirty:!0},o.tables.set(b.name.toUpperCase(),b);const w=p=>()=>(p?o.tables.set(b.name.toUpperCase(),b):o.tables.delete(b.name.toUpperCase()),o.rebuild(),w(!p));return ne([...R,w(!1)])}),b}class _e extends Error{}function O(t,e,r,s){for(let n=r;n<=s;n++)if(t.kind(e,n)!==0)return!0;return!1}function T(t,e){const r=[];if(t.engine)for(const s of t.engine.tables.values())s.sheet===e&&r.push(s);return r}function ft(t,e,r,s){for(const n of T(t,e)){const c=r===n.r1+1-0&&n.totalsRows===0&&s>=n.c0&&s<=n.c1,o=s===n.c1+1&&r>=n.r0&&r<=n.r1;if(c)return n.r1=r,n.filter&&(n.filter.r1=r),n.dirty=!0,r-1>=n.r0+n.headerRows&&t.transact("table-row",i=>{for(let l=n.c0;l<=n.c1;l++)l===s||(e.kind(r-1,l)&E)===0||e.kind(r,l)!==0||t.setInput(i,r,l,`=${j(t.editText(e,r-1,l).slice(1),1,0)}`,{overLimitAsText:!0})}),t.engine.rebuild(),n;if(o){n.c1=s;const i=t.editText(e,n.r0,s).trim()||Z(new Set(n.columns.map(l=>l.toLowerCase())),n.columns);if(n.columns.push(i),n.filter){const l={...n.filter};n.filter.c1=s,n.filter.buttons=K(l,n.filter)}return e.kind(n.r0,s)===0&&e.setCell(n.r0,s,x,t.strings.add(i)),n.dirty=!0,n.columnsChanged=!0,t.engine.rebuild(),n}}return null}function mt(t,e,r){for(const s of T(t,e)){if(r.r0!==s.r1+1||s.totalsRows!==0||r.c0<s.c0||r.c0>s.c1)continue;const n=r.r1;if(T(t,e).some(o=>o!==s&&o.r0<=n&&o.r1>=r.r0&&o.c0<=s.c1&&o.c1>=s.c0))return null;const c={r1:s.r1,filter:s.filter?{...s.filter}:null};return t.transact("table-expand",()=>{const o=a=>{s.r1=a.r1,s.filter=a.filter?{...a.filter}:null,s.dirty=!0,t.engine.rebuild()},i={r1:n,filter:s.filter?{...s.filter,r1:n}:null};o(i);const l=(a,u)=>()=>(o(a),l(u,a));return l(c,i)}),s}return null}function dt(t,e,r,s,n,c){if(!n.startsWith("="))return!1;for(const o of T(t,e)){if(s<o.c0||s>o.c1||r<=o.r0||r>o.r1-o.totalsRows)continue;const i=o.r0+o.headerRows,l=o.r1-o.totalsRows;for(let a=i;a<=l;a++)if(a!==r&&e.kind(a,s)!==0)return!1;return l===i?!1:(t.transact("calculated-column",a=>{for(let u=i;u<=l;u++)u!==r&&t.setInput(a,u,s,`=${c(n.slice(1),u-r,0)}`,{overLimitAsText:!0})}),!0)}return!1}const q=(t,e)=>{const r=t.totals?.[e];return r?r.label!==void 0?` totalsRowLabel="${I(r.label)}"`:` totalsRowFunction="${r.fn}"`:""},J=t=>`<tableStyleInfo${t.styleName?` name="${I(t.styleName)}"`:""} showFirstColumn="${t.showFirstColumn?1:0}" showLastColumn="${t.showLastColumn?1:0}" showRowStripes="${t.showRowStripes===!1?0:1}" showColumnStripes="${t.showColumnStripes?1:0}"/>`,ze=t=>L({r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1}),V=t=>t.filter&&t.headerRows>0?Re({...t.filter,r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1},!1)+$e(t.filter.sortState):"",Q=t=>`${t.headerRows===0?' headerRowCount="0"':""}${t.totalsRows?` totalsRowCount="${t.totalsRows}"`:' totalsRowShown="0"'}`;function pt(t,e){const r=ee(t),s=t.columns.map((c,o)=>{const i=D(t,o),l=`<tableColumn id="${r[o]}" name="${I(c)}"${q(t,o)}`;return i?`${l}>${i}</tableColumn>`:`${l}/>`}).join(""),n=V(t);return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="${e}" name="${z(t.name)}" displayName="${z(t.name)}" ref="${L(t)}"${Q(t)}>${n}<tableColumns count="${t.columns.length}">${s}</tableColumns>${J(t)}</table>`}function ht(t){return{name:t.name,ref:L(t),filterRef:t.filter&&t.headerRows>0?ze(t):null,filterXml:V(t),counts:Q(t),styleInfo:J(t),totals:t.totals?t.columns.map((e,r)=>q(t,r)):null,totalsChild:t.totals?t.columns.map((e,r)=>D(t,r)):null}}function wt(t,e){let r=t.replace(/<table\b[^>]*>/,s=>s.replace(/\bname="[^"]*"/,()=>`name="${z(e.name)}"`).replace(/\bdisplayName="[^"]*"/,()=>`displayName="${z(e.name)}"`).replace(/\bref="[^"]*"/,()=>`ref="${e.ref}"`).replace(/\s(?:headerRowCount|totalsRowCount|totalsRowShown)="[^"]*"/g,"").replace(/\s*(\/?)>$/,`${e.counts}$1>`));return r=r.replace(/<autoFilter\b[^>]*\/>|<autoFilter\b[\s\S]*?<\/autoFilter>/,"").replace(/<sortState\b[^>]*\/>|<sortState\b[\s\S]*?<\/sortState>/,""),e.filterXml&&(r=r.replace("<tableColumns",()=>`${e.filterXml}<tableColumns`)),/<tableStyleInfo\b/.test(r)?r=r.replace(/<tableStyleInfo\b[^>]*\/>/,()=>e.styleInfo):r=r.replace("</tableColumns>",()=>`</tableColumns>${e.styleInfo}`),e.totals&&(r=re(r,e)),r}const Ie=/[[\]#']/g,U=t=>t.replace(Ie,"'$&"),Oe=/^[A-Za-z_\\][A-Za-z0-9_.\\]*$/;function X(t,e){const r=[];for(const s of t.sheets){const n=new Map;for(const[c,o]of s.formulas){const i=o.f??o.sf;if(typeof i!="string")continue;const l=o.f===void 0&&o.base!==void 0;let a=l?n.get(o):void 0;if(a===void 0){const u=e(i,s,Math.floor((l?o.base:c)/ue));a=u===i?null:o.f!==void 0?{...o,f:u,tpl:void 0}:{...o,sf:u,tpl:void 0},l&&n.set(o,a)}a!==null&&r.push([s.formulas,c,o,a])}}for(const[s,n]of t.engine.names){const c=e(n.text,null,0,s);c!==n.text&&r.push([t.engine.names,s,n,{...n,text:c}])}for(const s of t.engine.tables.values())s.totals?.forEach((n,c)=>{if(n?.fn!=="custom"||!n.formula)return;const o=e(n.formula,s.sheet,s.r1);o!==n.formula&&r.push([{set:(i,l)=>{s.totals[i]=l,s.dirty=!0}},c,n,{...n,formula:o}])});return t.formulasEdited=!0,r.some(s=>s[0]===t.engine.names)&&(t.namesChanged=!0),F(r,3),r}const F=(t,e)=>{if(t.side!==e){t.side=e;for(const r of t){const s=r[0].get?.(r[1]);r[0].set(r[1],r[e]),s!==void 0&&(r[5-e]=s)}}};function y(t,e,r,s,{rebuild:n=!1}={}){const c=t.engine;t.transact(r,o=>{const i={...e},l=s(o),a={...e};e.dirty=!0,n&&c.rebuild();const u=(f,m,b)=>()=>{Object.assign(e,f),e.dirty=!0;const h=b?.()??null;return n&&c.rebuild(),u(m,f,h)};return u(i,a,l)})}function bt(t,e,r,s){y(t,e,"table-option",()=>{e[r]=s})}function k(t){if(!t.filter)return!1;for(let e=t.c0;e<=t.c1;e++){const r=t.filter.buttons?.get(e);if(!r?.hidden&&!r?.noShow)return!0}return!1}function Ue(t,e,r){r&&e.headerRows===0||r===k(e)||y(t,e,"table-filter",()=>{const{filter:s}=e;if(!s)e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map};else if(!r&&s.columns.size===0)e.filter=null;else{const n=i=>s.buttons?.get(i)?.noShow===!0;let c=!0;for(let i=e.c0;i<=e.c1;i++)n(i)||(c=!1);const o=new Map;for(let i=e.c0;i<=e.c1;i++)(!r||n(i)&&!c)&&o.set(i,{hidden:!r,noShow:n(i)});e.filter={...s,buttons:o.size>0?o:null}}return null})}function Ct(t,e){if(!k(e)&&!(e.filter?.columns.size>0)){Ue(t,e,!0);return}y(t,e,"table-filter",()=>{const r=_(t,e.sheet,e.filter);return e.filter=null,r})}function Rt(t,e,r){const s=t.engine;if(!Oe.test(r)||/^[A-Za-z]{1,3}[0-9]+$/.test(r)||/^[Rr][Cc]?$|^[Cc]$/.test(r))return"That isn't a valid table name.";const n=r.toUpperCase();if(n===e.name.toUpperCase()&&r===e.name)return null;if(s.tables.has(n)&&s.tables.get(n)!==e)return"Another table already uses that name.";if(s.names.has(n))return"A defined name already uses that name.";const c=e.name;return t.transact("table-name",()=>{const o=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${c.replace(/[.\\]/g,"\\$&")}(?=\\[)`,"gi"),i=X(t,f=>f.replace(o,`$1${r}`)),l=(f,m,b)=>{s.tables.delete(f.toUpperCase()),e.name=m,ve(e.sheet,Y({name:f}),Y(e)),s.tables.set(m.toUpperCase(),e),e.dirty=!0,F(i,b),s.rebuild()};l(c,r,3);const a=()=>(l(c,r,3),u),u=()=>(l(r,c,2),a);return u}),null}const Xe={average:101,countNums:102,count:103,max:104,min:105,stdDev:107,sum:109,var:110};function Ne(t,e,r){if(!r)return null;if(r.label!==void 0)return r.label;if(r.fn==="custom")return r.formula?`=${r.formula}`:null;const s=Xe[r.fn];return s?`=SUBTOTAL(${s},${t.name}[${U(t.columns[e])}])`:null}function $t(t,e,r){const{sheet:s}=e;if(r===e.totalsRows>0)return null;if(r){const c=e.r1+1;if(O(s,c,e.c0,e.c1))return"Clear the row under the table to add a total row.";const o=e.columns.map((l,a)=>e.totals?.[a]??null);if(!o.some(Boolean)&&(o[0]={label:we()},o.length>1)){let l=!1;for(let a=e.r0+e.headerRows;a<=e.r1&&!l;a++)l=(s.kind(a,e.c1)&M)===1;o[o.length-1]={fn:l?"sum":"count"}}const i=o.map((l,a)=>Ne(e,a,l));for(let l=0;l<i.length;l++){if(o[l]?.label!==void 0||!i[l])continue;const a=te(i[l].slice(1));if(a)return a}return y(t,e,"table-totals",l=>{e.totals=o,i.forEach((a,u)=>{o[u]?.label!==void 0?t.setRichInput(l,c,e.c0+u,a,null):a&&t.setInput(l,c,e.c0+u,a)}),e.totalsRows=1,e.r1=c,e.columnsChanged=e.source!==!0},{rebuild:!0}),null}const n=e.r1;return y(t,e,"table-totals",c=>{for(let o=e.c0;o<=e.c1;o++)t.setInput(c,n,o,"");e.totalsRows=0,e.r1=n-1},{rebuild:!0}),null}function St(t,e,r){if(r===e.headerRows>0)return null;const{sheet:s}=e;return r?e.r0===0||O(s,e.r0-1,e.c0,e.c1)?"Clear the row above the table to show its headers.":(y(t,e,"table-header",n=>{e.r0-=1,e.headerRows=1,e.columns.forEach((c,o)=>t.setRichInput(n,e.r0,e.c0+o,c,null)),e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}},{rebuild:!0}),null):(y(t,e,"table-header",n=>{const c=e.filter?_(t,s,e.filter):null;for(let o=e.c0;o<=e.c1;o++)t.setInput(n,e.r0,o,"");return e.r0+=1,e.headerRows=0,e.filter=null,c},{rebuild:!0}),null)}function yt(t,e,r,{cells:s=!0}={}){const{sheet:n}=e;if(s&&e.totalsRows>0&&r.r1<e.r1&&(r={...r,r1:e.r1}),r.r0===e.r0&&r.c0===e.c0&&r.r1===e.r1&&r.c1===e.c1)return null;if(r.r0!==e.r0)return"The header row must stay in the same row.";if(r.c0!==e.c0)return"The table must keep its first column.";if(r.r1<r.r0+e.headerRows+e.totalsRows)return"The table needs at least one data row.";for(const c of T(t,n))if(c!==e&&c.r0<=r.r1&&c.r1>=r.r0&&c.c0<=r.c1&&c.c1>=r.c0)return"A table can't overlap another table.";return y(t,e,"table-resize",c=>{const o=r.c1-r.c0+1,i=e.columns.slice(0,o),l=new Set(i.map(d=>d.toLowerCase()));for(let d=i.length;d<o;d++){const w=e.c0+d,p=e.headerRows?t.editText(n,e.r0,w).trim():"";let $=p||Z(l,i,!0);for(let C=2;l.has($.toLowerCase());C++)$=`${p}${C}`;l.add($.toLowerCase()),i.push($),e.headerRows&&$!==p&&c.sheet===n&&(c.saveCell(e.r0,w),n.setFormula(e.r0,w,null),n.setCell(e.r0,w,x,t.strings.add($)))}const a=e.r1-e.totalsRows,u=[];if((s?r.r1>e.r1:e.totalsRows===0&&r.r1>a)&&a>=e.r0+e.headerRows&&c.sheet===n)for(let d=e.c0;d<=Math.min(e.c1,r.c1);d++)n.kind(a,d)&E&&!n.formula(a,d)?.ref&&u.push([d,t.editText(n,a,d).slice(1)]);if(s&&e.totalsRows>0&&r.r1>e.r1&&c.sheet===n){const d=e.r1;for(let w=e.c0;w<=Math.min(e.c1,r.c1);w++){const p=n.cellStyle(d,w);if(c.saveCell(d,w),n.kind(r.r1,w)===0){const $=n.kind(d,w),C=n.formula(d,w);if(c.saveCell(r.r1,w),$&E&&C){const S=Ce(C,d,w);n.setCell(r.r1,w,E|be,0),n.setFormula(r.r1,w,{f:S,typed:!0,...C.t==="array"?{t:"array",ref:L({r0:r.r1,c0:w,r1:r.r1,c1:w})}:{},...C.cm?{cm:C.cm}:{}}),t.formulasEdited=!0}else n.setFormula(r.r1,w,null),n.setCell(r.r1,w,$&M,n.value(d,w));p!==0&&n.setStyle(r.r1,w,p)}n.setFormula(d,w,null),n.setCell(d,w,0,0),n.setStyle(d,w,a>=e.r0+e.headerRows?n.cellStyle(a,w):0)}}e.columns=i,e.r1=r.r1,e.c1=r.c1;const f=e.r1-e.totalsRows;for(const[d,w]of u)for(let p=a+1;p<=f;p++)n.kind(p,d)===0&&t.setInput(c,p,d,`=${j(w,p-a,0)}`,{overLimitAsText:!0});if(e.columnsChanged=!0,!e.filter)return null;const m=e.filter,b=new Map([...m.columns].filter(([d])=>d<=e.c1)),h=m.buttons?new Map([...m.buttons].filter(([d])=>d<=e.c1)):m.buttons,R=_(t,n,m,b.size<m.columns.size?m.r0+1:Math.max(m.r0,e.r1-e.totalsRows)+1);return e.filter={...m,r1:e.r1-e.totalsRows,c1:e.c1,columns:b,buttons:K(m,{c0:e.c0,c1:e.c1,buttons:h})},b.size>0&&b.size<m.columns.size&&xe({book:t},n,e.filter),R},{rebuild:!0}),null}function Be(t,e,r){const{sheet:s}=e,n=e.r1-e.r0+1,c=e.c1-e.c0+1,o=new Map,i=(a,u,f,m)=>{const b=(a-e.r0)*c+(u-e.c0);let h=o.get(b);h||o.set(b,h={}),h[f]=m};for(const a of r.areas(e,e.r0,e.r1,e.c0,e.c1)){const u=a.borders;for(let f=Math.max(a.r0,e.r0);f<=Math.min(a.r1,e.r1);f++)for(let m=Math.max(a.c0,e.c0);m<=Math.min(a.c1,e.c1);m++)u.t&&f===a.r0&&i(f,m,"t",u.t),u.b&&f===a.r1&&i(f,m,"b",u.b),u.l&&m===a.c0&&i(f,m,"l",u.l),u.r&&m===a.c1&&i(f,m,"r",u.r),u.h&&f<a.r1&&i(f,m,"b",u.h),u.v&&m<a.c1&&i(f,m,"r",u.v)}const l=new Map;t.transact("format",a=>{for(let u=0;u<n;u++){const f=e.r0+u;for(let m=0;m<c;m++){const b=e.c0+m,h=r.format(e,f,b),R=o.get(u*c+m),d=s.style(f,b),w=t.styles.get(d),p={};if(h.fill&&!w.fill&&(p.fill=h.fill),h.color&&!w.color&&(p.color=h.color),h.bold&&!w.bold&&(p.bold=!0),h.italic&&!w.italic&&(p.italic=!0),R){const g=w.borders??{},N={l:g.l??null,r:g.r??null,t:g.t??null,b:g.b??null};let B=!1;for(const v of["l","r","t","b"])R[v]&&!g[v]&&(N[v]={style:R[v].style,color:R[v].color},B=!0);B&&(p.borders=N)}const $=JSON.stringify(p);if($==="{}")continue;const C=`${d}|${$}`;let S=l.get(C);S===void 0&&l.set(C,S=t.styles.derive(d,p,$)),S!==d&&(a.saveCell(f,b),s.setStyle(f,b,S))}}})}function Tt(t,e){ge(t,"Convert to Range",()=>De(t,e))}function De(t,e){const r=t.engine,{sheet:s}=e,n=Le(e.styleName,t.theme),c=t.activeSheet;t.activeSheet=t.sheets.indexOf(s),n?.format&&Be(t,e,n),t.activeSheet=c;const o=e.name.toUpperCase(),i=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${e.name.replace(/[.\\]/g,"\\$&")}(\\[(?:[^\\[\\]']|'.|\\[(?:[^\\[\\]']|'.)*\\])*\\])`,"gi");t.transact("table-convert",()=>{const l=X(t,(h,R,d)=>h.replace(i,(w,p,$)=>{const C=r.tableSpecToA1(e,$,d);return C===null?w:`${p}${R===s?"":me(s.name)}${C}`})),a=e.source===!0&&e.part?{part:e.part,sheetIndex:t.sheets.indexOf(s)}:null,u=e.filter;let f=null;const m=()=>{r.tables.delete(o),a&&(t.removedTables??=[]).push(a),F(l,3),u&&(f=_(t,s,u)),r.rebuild()},b=()=>(f?.(),r.tables.set(o,e),a&&(t.removedTables=t.removedTables.filter(h=>h!==a)),F(l,2),r.rebuild(),()=>(m(),b));return m(),b})}function Ke(t,e,r,s){const n=t.toLowerCase(),c=`${e.toLowerCase()}[`;let o="",i=0;for(let l=n.indexOf(c);l>=0;l=n.indexOf(c,l+1)){const a=l+c.length-1;let u=0,f=a;for(;f<t.length;f++){const h=t[f];if(h==="'")f++;else if(h==="[")u++;else if(h==="]"&&--u===0)break}const m=t.slice(a,f+1),b=m.split(`[${r}]`).join(`[${s}]`);b!==m&&(o+=t.slice(i,a)+b,i=f+1)}return i===0?t:o+t.slice(i)}function Pe(t,e,r,s){const n=e.columns[r],c=U(n),o=U(s),i=X(t,f=>f.includes("[")?Ke(f,e.name,c,o):f),l=(f,m)=>{e.columns=e.columns.map((b,h)=>h===r?f:b),e.columnsChanged=!0,e.dirty=!0,F(i,m),t.engine?.rebuild()};l(s,3);const a=()=>(l(s,3),u),u=()=>(l(n,2),a);return u}function xt(t,e,r){let s=null;const{sheet:n}=e;for(const c of T(t,n))if(!(c.headerRows===0||c.dataSheet))for(let o=0;o<r.count;o++){if(r.rows[o]!==c.r0||r.cols[o]<c.c0||r.cols[o]>c.c1)continue;const i=r.cols[o],l=i-c.c0,a=n.kind(c.r0,i);let u=a===0?"":String(t.engine.read(n,c.r0,i)??"").trim();const f=new Set(c.columns.filter((R,d)=>d!==l).map(R=>R.toLowerCase()));if(u==="")u=de(f);else if(f.has(u.toLowerCase())){const R=u;let d=2;for(;f.has(`${R}${d}`.toLowerCase());)d++;u=`${R}${d}`}if(((a&M)!==x||(a&E)!==0||t.strings.get(n.value(c.r0,i))!==u)&&(e.saveCell(c.r0,i),n.setFormula(c.r0,i,null),n.setCell(c.r0,i,x,t.strings.add(u))),c.columns[l]===u)continue;const m=Pe(t,c,l,u),b=s,h=(R,d)=>d?()=>h(R(),d()):R;s=h(m,b)}return s}const gt=[...Array.from({length:21},(t,e)=>`TableStyleLight${e+1}`),...Array.from({length:28},(t,e)=>`TableStyleMedium${e+1}`),...Array.from({length:11},(t,e)=>`TableStyleDark${e+1}`)];export{Xe as SUBTOTAL_CODE,gt as TABLE_STYLE_NAMES,_e as TableCreationError,at as bandRow,ae as colName,Tt as convertTableToRange,ut as createTable,dt as fillCalculatedColumn,mt as growTableOver,ft as maybeExpandTable,Me as nextTableName,wt as patchTableXml,Fe as presetElements,Rt as renameTable,Pe as renameTableColumn,yt as resizeTable,X as rewriteFormulas,ct as setCustomTableResolver,Ue as setTableFilterButton,St as setTableHeaderRow,bt as setTableOption,$t as setTableTotals,U as structuredColumn,xt as syncTableHeaders,Le as tableColors,k as tableHasButtons,ht as tablePatch,pt as tableXml,T as tablesOf,Ct as toggleTableFilter,Ne as totalInput};
@@ -1 +1 @@
1
- import{parseRangeRef as h,rangeRef as p}from"./address.js";const m=(n,r)=>n.r0<=r.r1&&n.r1>=r.r0&&n.c0<=r.c1&&n.c1>=r.c0;function u(n,r){if(!m(n,r))return[n];const s=[],o=Math.max(n.c0,r.c0),f=Math.min(n.c1,r.c1);return n.c0<r.c0&&s.push({...n,c1:r.c0-1}),n.c1>r.c1&&s.push({...n,c0:r.c1+1}),n.r0<r.r0&&s.push({r0:n.r0,c0:o,r1:r.r0-1,c1:f}),n.r1>r.r1&&s.push({r0:r.r1+1,c0:o,r1:n.r1,c1:f}),s}function d(n,r){let s=String(n).split(/\s+/).map(h).filter(Boolean);for(const o of r)s=s.flatMap(f=>u(f,o));return s.map(p).join(" ")}const a=({sqref:n,_ranges:r,...s})=>JSON.stringify(s,Object.keys(s).sort());function q(n,r,s){const o=[];for(const t of n??[]){const e=d(t.sqref,r);e!==""&&o.push(e===t.sqref?t:c(t,e))}if(s===null)return o;const f=r.map(p).join(" "),i=o.findIndex(t=>a(t)===a(s));return i>=0?o[i]=c(o[i],`${o[i].sqref} ${f}`):o.push(c(s,f)),o}function c(n,r){const{_ranges:s,...o}=n;return{...o,sqref:r}}export{d as subtractFromSqref,u as subtractRect,q as withRuleOn};
1
+ import{cellRef as l,parseRangeRef as m,rangeRef as u}from"./address.js";import{translateFormula as q}from"./formula-refs.js";const g=(r,o)=>r.r0<=o.r1&&r.r1>=o.r0&&r.c0<=o.c1&&r.c1>=o.c0;function x(r,o){if(!g(r,o))return[r];const n=[],f=Math.max(r.c0,o.c0),s=Math.min(r.c1,o.c1);return r.c0<o.c0&&n.push({...r,c1:o.c0-1}),r.c1>o.c1&&n.push({...r,c0:o.c1+1}),r.r0<o.r0&&n.push({r0:r.r0,c0:f,r1:o.r0-1,c1:s}),r.r1>o.r1&&n.push({r0:o.r1+1,c0:f,r1:r.r1,c1:s}),n}function R(r,o){let n=String(r).split(/\s+/).map(m).filter(Boolean);for(const f of o)n=n.flatMap(s=>x(s,f));return n.map(u).join(" ")}const h=({sqref:r,_ranges:o,...n})=>JSON.stringify(n,Object.keys(n).sort());function j(r,o,n,f=null){const s=[];for(const t of r??[]){const i=R(t.sqref,o);i!==""&&s.push(i===t.sqref?t:a(t,i))}if(n===null)return s;const c=o.map(u).join(" "),p=a(f?{...n,sqref:l(f.row,f.col)}:n,c),e=s.findIndex(t=>h(t)===h(a(p,t.sqref)));return e>=0?s[e]=a(s[e],`${s[e].sqref} ${c}`):s.push(p),s}const d=r=>m(String(r??"").split(/\s+/)[0]);function a(r,o){const{_ranges:n,...f}=r,s=d(r.sqref),c=d(o),p=s&&c?c.r0-s.r0:0,e=s&&c?c.c0-s.c0:0,t={...f,sqref:o};for(const i of["formula1","formula2"])(p!==0||e!==0)&&t[i]&&(t[i]=q(t[i],p,e));return t}const w=(r,o,n)=>a(r,l(o,n));export{w as ruleAt,R as subtractFromSqref,x as subtractRect,j as withRuleOn};
package/core/whatif.js CHANGED
@@ -1 +1 @@
1
- import{FORMULA as H,KIND_MASK as K,NUM as b,STR as $}from"./sheet.js";import{cellRef as I,MAX_COLS as W,parseRangeRef as F,rangeRef as X}from"./address.js";async function Z(t,n,r,e,a,{maxIter:o=200,tolerance:l=.001}={}){const u=t.engine,g=async d=>{t.transact("goal-seek",S=>{S.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,d)}),await u.whenIdle();const x=u.read(n,r.row,r.col);return typeof x=="number"?x-a:NaN},s=()=>t.undoStack.length,c=s(),f=n.value(e.row,e.col);let p=f,i=await g(p),v=f===0?1:f*1.01,M=await g(v),E={x:p,f:i},L=null,h=null;for(let d=0;d<o&&((Math.abs(M)<Math.abs(E.f)||Number.isNaN(E.f))&&(E={x:v,f:M}),!(Math.abs(M)<=l));d++){i*M<0&&(L=i<0?p:v,h=i<0?v:p);let x=M===i?v*1.5+1:v-M*(v-p)/(M-i);if(L!==null&&(!Number.isFinite(x)||x<Math.min(L,h)||x>Math.max(L,h))&&(x=(L+h)/2),!Number.isFinite(x))break;p=v,i=M,v=x,M=await g(v)}for(;s()>c;)t.undoStack.pop();t.transact("goal-seek",d=>{d.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,f)});const m=t.undoStack.pop();return t.transact("goal-seek",d=>{d.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,E.x)}),await u.whenIdle(),{value:E.x,found:Math.abs(E.f)<=l,result:u.read(n,r.row,r.col)}}const P=t=>{if(t===void 0)return 0;const n=t.indexOf('outlineLevel="');return n<0?0:t.charCodeAt(n+14)-48},U=(t,n)=>t.rowExtras===null?0:P(t.rowExtras.get(n));function j(t,n,r){t.rowExtras||(t.rowExtras=new Map);const e=(t.rowExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${e} outlineLevel="${r}"`.trim():e;a?t.rowExtras.set(n,a):t.rowExtras.delete(n)}const _=(t,n)=>t.colExtras===null?0:P(t.colExtras.get(n));function z(t,n,r){t.colExtras||(t.colExtras=new Map);const e=(t.colExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${e} outlineLevel="${r}"`.trim():e;a?t.colExtras.set(n,a):t.colExtras.delete(n)}function C(t,n,r,e,a){for(let o=r;o<=e;o++)n==="row"?j(t,o,Math.max(0,Math.min(7,U(t,o)+a))):z(t,o,Math.max(0,Math.min(7,_(t,o)+a)));t.outlineVersion=(t.outlineVersion??0)+1,n==="col"&&(t.colsChanged=!0),t.revision++}function tt(t,n){let r=0;const e=n==="row"?t.rowExtras:t.colExtras;if(e)for(const a of e.values()){const o=/outlineLevel="(\d+)"/.exec(a);o&&(r=Math.max(r,Number(o[1])))}return r}function nt(t,n,r){return n==="row"?U(t,r):_(t,r)}function rt(t,n,r){const e=n==="row"?t.rowExtras:t.colExtras,a=n==="row"?t.rows:t.cols;if(e){for(const[o,l]of e){const u=/outlineLevel="(\d+)"/.exec(l);u&&a.setHidden(o,Number(u[1])>=r)}n==="col"&&(t.colsChanged=!0),t.revision++}}function et(t,n,r,e,a,o){const l=[],u={1:"Average",2:"Count",3:"Count",4:"Max",5:"Min",6:"Product",7:"StdDev",8:"StdDevp",9:"Total",10:"Var",11:"Varp"}[a],g=c=>(n.kind(c,e)&K)===$?t.strings.get(n.value(c,e)):String(n.value(c,e));let s=r.r0+1;for(let c=r.r0+1;c<=r.r1+1;c++)(c>r.r1||g(c)!==g(s))&&(l.push({afterRow:c-1,from:s,to:c-1,title:`${g(s)} ${u}`}),s=c);return{groups:l,functionNum:a,sumCols:o,groupCol:e,grandTitle:`Grand ${u}`}}function ot(t,n,r,e,a){const o={r0:r.r0+1,c0:r.c0+1,r1:r.r1,c1:r.c1},l=e&&a,u={t:"dataTable",ref:X(o),dt2D:l?"1":"0",dtr:e?"1":"0",r1:I((e??a).row,(e??a).col)};l&&(u.r2=I(a.row,a.col));const g=t.engine,s={sheet:n,row:o.r0,col:o.c0,info:u};t.transact("data-table",c=>{for(let i=o.r0;i<=o.r1;i++)for(let v=o.c0;v<=o.c1;v++)c.saveCell(i,v),n.setFormula(i,v,null),n.setCell(i,v,b,0);n.setFormula(o.r0,o.c0,u),n.setCell(o.r0,o.c0,H|b,0),t.formulasEdited=!0,g.dataTables.push(s),g.tablesDirty=!0;const f=()=>(g.dataTables=g.dataTables.filter(i=>i!==s),p),p=()=>(g.dataTables.push(s),g.tablesDirty=!0,f);return f})}const q=(t,n,r,e)=>{const a=n.kind(r,e)&K;return a===0?"":a===$?t.strings.get(n.value(r,e)):String(n.value(r,e))};function at(t,n,r,e){const a=[],o=new Set;for(const l of r.split(/[\s,;]+/)){const u=F(l.replace(/\$/g,""));if(u)for(let g=u.r0;g<=u.r1&&a.length<32;g++)for(let s=u.c0;s<=u.c1&&a.length<32;s++){const c=I(g,s);if(o.has(c))continue;o.add(c);const f=e?.cells.find(p=>p.r===c);a.push({r:c,val:f?f.val:q(t,n,g,s)})}}return a}function ct(t,n,r){t.transact("scenario",e=>{for(const{r:a,val:o}of r.cells){const l=F(a);l&&t.setInput(e,l.r0,l.c0,o,{overLimitAsText:!0})}})}function st(t,n,r,e){const a=t.engine,o=[["Scenario Summary","Current Values",...r.map(s=>s.name)]],l=[];for(const s of r)for(const c of s.cells)l.includes(c.r)||l.push(c.r);const u=s=>{const c=F(s);return{row:c.r0,col:c.c0}};o.push(["Changing Cells:"]);for(const s of l){const{row:c,col:f}=u(s);o.push([s,q(t,n,c,f),...r.map(p=>p.cells.find(i=>i.r===s)?.val??"")])}if(e.length>0){o.push(["Result Cells:"]);const s=r.map(c=>a.evaluateWith(n,c.cells.map(f=>({...u(f.r),text:f.val})),()=>e.map(({row:f,col:p})=>a.read(n,f,p))));e.forEach(({row:c,col:f},p)=>{o.push([I(c,f),String(a.read(n,c,f)??""),...s.map(i=>String(i[p]??""))])})}const g=t.addSheet();return t.transact("scenario-summary",s=>{o.forEach((c,f)=>c.forEach((p,i)=>{p!==""&&t.setInput(s,f,i,String(p),{overLimitAsText:!0})}))}),g}const w=t=>t.filter(n=>typeof n=="number"),R=t=>t.reduce((n,r)=>n+r,0),B=t=>R(t)/t.length,O=(t,n)=>{const r=B(t);return R(t.map(e=>(e-r)**2))/n},J={Sum:t=>R(w(t)),Count:t=>t.filter(n=>n!==null&&n!=="").length,Average:t=>w(t).length?B(w(t)):null,Max:t=>w(t).length?Math.max(...w(t)):0,Min:t=>w(t).length?Math.min(...w(t)):0,Product:t=>w(t).length?w(t).reduce((n,r)=>n*r,1):0,"Count Numbers":t=>w(t).length,StdDev:t=>w(t).length>1?Math.sqrt(O(w(t),w(t).length-1)):null,StdDevp:t=>w(t).length?Math.sqrt(O(w(t),w(t).length)):null,Var:t=>w(t).length>1?O(w(t),w(t).length-1):null,Varp:t=>w(t).length?O(w(t),w(t).length):null};function lt(t,n,r,e,a,{topRow:o=!1,leftCol:l=!1}={}){const u=t.engine,g=J[a],s=[],c=[],f=new Map,p=new Map,i=new Map,v=(h,m,d)=>{const x=String(d).toLowerCase();let S=h.get(x);return S===void 0&&(S=m.length,h.set(x,S),m.push(d)),S};for(const{sheet:h,range:m,read:d}of e){const x=d??((y,T)=>u.read(h,y,T)),S=m.r0+(o?1:0),N=m.c0+(l?1:0);for(let y=S;y<=m.r1;y++){const T=l?x(y,m.c0):y-S;if(l&&(T===null||T===""))continue;const k=v(f,s,T);for(let D=N;D<=m.c1;D++){const A=o?x(m.r0,D):D-N;if(o&&(A===null||A===""))continue;const G=v(p,c,A),V=k*16384+G;i.has(V)||i.set(V,[]),i.get(V).push(x(y,D))}}}const M=r.row+(o?1:0),E=r.col+(l?1:0),L=(h,m,d,x)=>{h.saveCell(m,d),n.setFormula(m,d,null),typeof x=="number"?n.setCell(m,d,b,x):n.setCell(m,d,$,t.strings.add(String(x)))};return t.transact("consolidate",h=>{o&&c.forEach((m,d)=>L(h,r.row,E+d,m)),l&&s.forEach((m,d)=>L(h,M+d,r.col,m));for(const[m,d]of i){const x=Math.floor(m/16384),S=m-x*16384,N=g(d);N!==null&&L(h,M+x,E+S,N)}}),{rows:s.length,cols:c.length}}export{J as CONSOLIDATE_FUNCTIONS,W as MAX_COLS,C as changeOutline,lt as consolidate,ot as createDataTable,Z as goalSeek,tt as maxOutlineLevel,nt as outlineLevel,st as scenarioSummary,at as scenarioValues,rt as showOutlineLevel,ct as showScenario,et as subtotalPlan};
1
+ import{BOOL as X,ERR as j,ERRORS as z,FORMULA as V,KIND_MASK as $,NUM as A,SPILL as J,STR as F}from"./sheet.js";import{cellRef as O,MAX_COLS as Q,parseRangeRef as P,rangeRef as Y}from"./address.js";const k=25;async function Z(t,n,{maxIter:r,tolerance:o,pause:a}){let e={x:n,f:t(n)},u=600;const l=E=>{u--;const v={x:E,f:t(E)};return(Math.abs(v.f)<Math.abs(e.f)||Number.isNaN(e.f))&&(e=v),v},d=()=>Math.abs(e.f)<=o||u<=0,s=e;if(d())return e;let c=s,i=l(n===0?1:n*1.01);for(let E=0;E<r&&!d();E++){await a();const v=i.x-i.f*(i.x-c.x)/(i.f-c.f);if(!Number.isFinite(v)||v===i.x||(c=i,i=l(v),E>=20&&!(Math.abs(i.f)<Math.abs(s.f))))break}const g=async(E,v)=>{let w=E,f=v;for(let p=0;p<r&&!d();p++){await a();const h=(w.x+f.x)/2;if(h===w.x||h===f.x)return;const S=l(h);if(Number.isNaN(S.f))return;S.f<0==w.f<0?w=S:f=S}};let m=s,M=s,b=Math.max(Math.abs(n),1)*.01;for(let E=0;E<160&&!d();E++,b*=1.2){await a();for(const v of[1,-1]){const w=v>0?m:M,f=l(w.x+v*b);if(v>0?m=f:M=f,w.f*f.f<0&&await g(w,f),d())break}}return e}async function ot(t,n,r,o,a,{maxIter:e=100,tolerance:u=.001}={}){const l=t.engine;if(!(n.kind(r.row,r.col)&V)||n.kind(o.row,o.col)&(V|J))return null;await l.whenIdle();const d=m=>l.evaluateWith(n,[{...o,text:String(m)}],()=>{const M=l.read(n,r.row,r.col);return typeof M=="number"?M-a:NaN}),s=(n.kind(o.row,o.col)&$)===A;let c=performance.now()+k;const i=await Z(d,s?n.value(o.row,o.col):0,{maxIter:e,tolerance:u,async pause(){performance.now()<c||(await new Promise(m=>{setTimeout(m,0)}),c=performance.now()+k)}});let g=!1;return t.sheet===n&&t.transact("goal-seek",m=>{g=!0,m.saveCell(o.row,o.col),n.setCell(o.row,o.col,A,i.x)}),await l.whenIdle(),{value:i.x,found:Math.abs(i.f)<=u,result:l.read(n,r.row,r.col),applied:g}}const K=t=>{if(t===void 0)return 0;const n=t.indexOf('outlineLevel="');return n<0?0:t.charCodeAt(n+14)-48},_=(t,n)=>t.rowExtras===null?0:K(t.rowExtras.get(n));function C(t,n,r){t.rowExtras||(t.rowExtras=new Map);const o=(t.rowExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${o} outlineLevel="${r}"`.trim():o;a?t.rowExtras.set(n,a):t.rowExtras.delete(n)}const B=(t,n)=>t.colExtras===null?0:K(t.colExtras.get(n));function tt(t,n,r){t.colExtras||(t.colExtras=new Map);const o=(t.colExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${o} outlineLevel="${r}"`.trim():o;a?t.colExtras.set(n,a):t.colExtras.delete(n)}function at(t,n,r,o,a){for(let e=r;e<=o;e++)n==="row"?C(t,e,Math.max(0,Math.min(7,_(t,e)+a))):tt(t,e,Math.max(0,Math.min(7,B(t,e)+a)));t.outlineVersion=(t.outlineVersion??0)+1,n==="col"&&(t.colsChanged=!0),t.revision++}function ct(t,n){let r=0;const o=n==="row"?t.rowExtras:t.colExtras;if(o)for(const a of o.values()){const e=/outlineLevel="(\d+)"/.exec(a);e&&(r=Math.max(r,Number(e[1])))}return r}function st(t,n,r){return n==="row"?_(t,r):B(t,r)}function it(t,n,r){const o=n==="row"?t.rowExtras:t.colExtras,a=n==="row"?t.rows:t.cols;if(o){for(const[e,u]of o){const l=/outlineLevel="(\d+)"/.exec(u);l&&a.setHidden(e,Number(l[1])>=r)}n==="col"&&(t.colsChanged=!0),t.revision++}}function lt(t,n,r,o,a,e){const u=[],l={1:"Average",2:"Count",3:"Count",4:"Max",5:"Min",6:"Product",7:"StdDev",8:"StdDevp",9:"Total",10:"Var",11:"Varp"}[a],d=c=>(n.kind(c,o)&$)===F?t.strings.get(n.value(c,o)):String(n.value(c,o));let s=r.r0+1;for(let c=r.r0+1;c<=r.r1+1;c++)(c>r.r1||d(c)!==d(s))&&(u.push({afterRow:c-1,from:s,to:c-1,title:`${d(s)} ${l}`}),s=c);return{groups:u,functionNum:a,sumCols:e,groupCol:o,grandTitle:`Grand ${l}`}}function ft(t,n,r,o,a){const e={r0:r.r0+1,c0:r.c0+1,r1:r.r1,c1:r.c1},u=o&&a,l={t:"dataTable",ref:Y(e),dt2D:u?"1":"0",dtr:o?"1":"0",r1:O((o??a).row,(o??a).col)};u&&(l.r2=O(a.row,a.col));const d=t.engine,s={sheet:n,row:e.r0,col:e.c0,info:l};t.transact("data-table",c=>{for(let m=e.r0;m<=e.r1;m++)for(let M=e.c0;M<=e.c1;M++)c.saveCell(m,M),n.setFormula(m,M,null),n.setCell(m,M,A,0);n.setFormula(e.r0,e.c0,l),n.setCell(e.r0,e.c0,V|A,0),t.formulasEdited=!0,d.dataTables.push(s),d.tablesDirty=!0;const i=()=>(d.dataTables=d.dataTables.filter(m=>m!==s),g),g=()=>(d.dataTables.push(s),d.tablesDirty=!0,i);return i})}const q=(t,n,r,o)=>{const a=n.kind(r,o)&$;if(a===0)return"";const e=n.value(r,o);return a===F?t.strings.get(e):a===X?e?"TRUE":"FALSE":a===j?z[e]??"#N/A":String(e)};function ut(t,n,r,o){const a=[],e=new Set;for(const u of r.split(/[\s,;]+/)){const l=P(u.replace(/\$/g,""));if(l)for(let d=l.r0;d<=l.r1&&a.length<32;d++)for(let s=l.c0;s<=l.c1&&a.length<32;s++){const c=O(d,s);if(e.has(c))continue;e.add(c);const i=o?.cells.find(g=>g.r===c);a.push({r:c,val:i?i.val:q(t,n,d,s)})}}return a}function dt(t,n,r){t.transact("scenario",o=>{for(const{r:a,val:e}of r.cells){const u=P(a);u&&t.setInput(o,u.r0,u.c0,e,{overLimitAsText:!0})}})}function mt(t,n,r,o){const a=t.engine,e=[["Scenario Summary","Current Values",...r.map(s=>s.name)]],u=[];for(const s of r)for(const c of s.cells)u.includes(c.r)||u.push(c.r);const l=s=>{const c=P(s);return{row:c.r0,col:c.c0}};e.push(["Changing Cells:"]);for(const s of u){const{row:c,col:i}=l(s);e.push([s,q(t,n,c,i),...r.map(g=>g.cells.find(m=>m.r===s)?.val??"")])}if(o.length>0){e.push(["Result Cells:"]);const s=r.map(c=>a.evaluateWith(n,c.cells.map(i=>({...l(i.r),text:i.val})),()=>o.map(({row:i,col:g})=>a.read(n,i,g))));o.forEach(({row:c,col:i},g)=>{e.push([O(c,i),String(a.read(n,c,i)??""),...s.map(m=>String(m[g]??""))])})}const d=t.addSheet();return t.transact("scenario-summary",s=>{e.forEach((c,i)=>c.forEach((g,m)=>{g!==""&&t.setInput(s,i,m,String(g),{overLimitAsText:!0})}))}),d}const x=t=>t.filter(n=>typeof n=="number"),U=t=>t.reduce((n,r)=>n+r,0),W=t=>U(t)/t.length,R=(t,n)=>{const r=W(t);return U(t.map(o=>(o-r)**2))/n},nt={Sum:t=>U(x(t)),Count:t=>t.filter(n=>n!==null&&n!=="").length,Average:t=>x(t).length?W(x(t)):null,Max:t=>x(t).length?x(t).reduce((n,r)=>Math.max(n,r)):0,Min:t=>x(t).length?x(t).reduce((n,r)=>Math.min(n,r)):0,Product:t=>x(t).length?x(t).reduce((n,r)=>n*r,1):0,"Count Numbers":t=>x(t).length,StdDev:t=>x(t).length>1?Math.sqrt(R(x(t),x(t).length-1)):null,StdDevp:t=>x(t).length?Math.sqrt(R(x(t),x(t).length)):null,Var:t=>x(t).length>1?R(x(t),x(t).length-1):null,Varp:t=>x(t).length?R(x(t),x(t).length):null};function xt(t,n,r,o,a,{topRow:e=!1,leftCol:u=!1}={}){const l=t.engine,d=nt[a],s=[],c=[],i=new Map,g=new Map,m=new Map,M=(w,f,p)=>{const h=String(p).toLowerCase();let S=w.get(h);return S===void 0&&(S=f.length,w.set(h,S),f.push(p)),S};for(const{sheet:w,range:f,read:p}of o){const h=p??((L,N)=>l.read(w,L,N)),S=f.r0+(e?1:0),y=f.c0+(u?1:0);for(let L=S;L<=f.r1;L++){const N=u?h(L,f.c0):L-S;if(u&&(N===null||N===""))continue;const G=M(i,s,N);for(let T=y;T<=f.c1;T++){const D=e?h(f.r0,T):T-y;if(e&&(D===null||D===""))continue;const H=M(g,c,D),I=G*16384+H;m.has(I)||m.set(I,[]),m.get(I).push(h(L,T))}}}const b=r.row+(e?1:0),E=r.col+(u?1:0),v=(w,f,p,h)=>{w.saveCell(f,p),n.setFormula(f,p,null),typeof h=="number"?n.setCell(f,p,A,h):n.setCell(f,p,F,t.strings.add(String(h)))};return t.transact("consolidate",w=>{e&&c.forEach((f,p)=>v(w,r.row,E+p,f)),u&&s.forEach((f,p)=>v(w,b+p,r.col,f));for(const[f,p]of m){const h=Math.floor(f/16384),S=f-h*16384,y=d(p);y!==null&&v(w,b+h,E+S,y)}}),{rows:s.length,cols:c.length}}export{nt as CONSOLIDATE_FUNCTIONS,Q as MAX_COLS,at as changeOutline,xt as consolidate,ft as createDataTable,ot as goalSeek,ct as maxOutlineLevel,st as outlineLevel,mt as scenarioSummary,ut as scenarioValues,it as showOutlineLevel,dt as showScenario,lt as subtotalPlan};
package/core/workbook.js CHANGED
@@ -1 +1 @@
1
- import{expandBareTables as de}from"../slicers/structured.js";import{syncTableHeaders as me,tablesOf as pe}from"./tables.js";import{BOOL as P,CHUNK_BITS as U,CHUNK_MASK as W,EMPTY as O,ERR as L,ERRORS as ge,FORMULA as F,DIRTY as Z,EVALUATING as Y,KIND_MASK as X,NUM as B,Sheet as V,SPILL as ye,STR as E}from"./sheet.js";import{cellRef as Se,isValidName as we,MAX_COLS as R,MAX_ROWS as Q,quoteSheetName as ee,rangeRef as Ce,renameSheetInFormula as $,sheetReferencePattern as te}from"./address.js";import{translateFormula as ve}from"./formula-refs.js";import{sheetStem as se}from"./default-names.js";import{StringTable as ke}from"./strings.js";import{formatAxis as ne,formatSheetColumns as xe}from"./axis-styles.js";import{autoRowHeight as _e}from"./row-fit.js";import{StyleTable as Re}from"./styles.js";import{cellEntryText as ie,parseInput as oe}from"./input.js";import{DATE_1904_OFFSET as be}from"./numfmt.js";import{noteChanges as re}from"./changes.js";import{overrideRuns as Me}from"../cells/rich-runs.js";import{mapHostRules as le,rewriteHostEntry as ae}from"./host-rules.js";import{sheetRenameHooks as Fe}from"./sparse.js";import{shiftRuleFormulas as I}from"../cells/cf-file.js";import{expandStructured as Ee,formulaEntryLimit as Te,FormulaSyntaxError as N,tokenize as Ae,toDisplayFormula as he,toFileFormula as Oe}from"../calc/parser.js";const Ie=200,ze=new Set(["entry","clear","format","borders","fill"]);class Ue{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(s,e){if(s>=this.ids.length){let o=this.ids.length*2;for(;o<=s;)o*=2;const r=new Int32Array(o);r.set(this.ids),this.ids=r}const i=this.list.length;(i===0||this.list[i-1]!==e)&&this.list.push(e),this.ids[s]=this.list.length}get(s){const e=s<this.ids.length?this.ids[s]:0;return e===0?void 0:this.list[e-1]}}class D{constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const s=this.capacity*2,e=(i,o)=>{const r=new i(s);return r.set(o),r};this.rows=e(Uint32Array,this.rows),this.cols=e(Uint16Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.styles=e(Uint16Array,this.styles),this.values=e(Float64Array,this.values),this.capacity=s}push(s,e,i){this.count===this.capacity&&this._grow();const o=this.count++,r=s.kind(e,i)&~(Z|Y);if(this.rows[o]=e,this.cols[o]=i,this.kinds[o]=r,this.styles[o]=s.cellStyle(e,i),this.values[o]=s.value(e,i),r&F&&(this.formulas===null&&(this.formulas=new Ue),this.formulas.set(o,s.formula(e,i))),s.valueMeta!==null){const t=s.valueMeta.get(e*R+i);t!==void 0&&(this.vms??=new Map).set(o,t)}}}function Le(f,s,e){const i=t=>typeof t=="string"&&t!==""?$(t,s,e):t;le(f,ae(i,I));const o=f.cf?.map(t=>{const n=t.rules.map(l=>I(l,i));return JSON.stringify(n)===JSON.stringify(t.rules)?t:{...t,rules:n}});o?.some((t,n)=>t!==f.cf[n])&&(f.cf=o,f.cfChanged=!0,f.cfEval?.invalidate());const r=f.validations?.map(t=>{const n=i(t.formula1),l=i(t.formula2);return n===t.formula1&&l===t.formula2?t:{...t,formula1:n,formula2:l}});r?.some((t,n)=>t!==f.validations[n])&&(f.validations=r,f.validationsChanged=!0)}class nt{get namesChanged(){return this._namesChanged}set namesChanged(s){this._namesChanged=s,s&&(this.namesRevision=(this.namesRevision??0)+1)}constructor(){this.sheets=[new V(`${se()}1`)],this.activeSheet=0,this.date1904=!1,this.strings=new ke,this.styles=new Re,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dateOffset(){return this.date1904?be:0}get dirty(){return this._dirty}set dirty(s){s&&this.edits++,this._dirty=!!s}onChange(s){this.listeners.add(s)}clearHistory(){if(this.historyCleared=(this.historyCleared??0)+1,!(this.undoStack.length===0&&this.redoStack.length===0)){this.undoStack.length=0,this.redoStack.length=0;for(const s of this.listeners)s("history")}}_emit(s){(s==="cells"||s==="bulk")&&(this.formatValueRevision=(this.formatValueRevision??0)+1),this.dirty=!0;for(const e of this.listeners)e(s)}addSheet(s){const e=se();let i=1,o=s??`${e}${i}`;const r=n=>this.sheets.some(l=>l.name.toLowerCase()===n.toLowerCase());for(;r(o);)o=`${e}${++i}`;const t=new V(o);return this.sheets.push(t),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),t}deleteSheet(s){return this.sheets.filter(e=>!e.hidden).length<=1?!1:(this._shrink3D(s),this._refErrorsFor(s),this._removeSheet(s))}_removeSheet(s){if(this.sheets.length<=1)return!1;const[e]=this.sheets.splice(s,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,s),this.engine)for(const[o,r]of this.engine.tables)r.sheet===e&&this.engine.tables.delete(o);this._reindexNames(o=>o===s?-1:o>s?o-1:o),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);const i=this.activeSheet;for(;this.sheets[this.activeSheet].hidden&&(this.activeSheet=(this.activeSheet+1)%this.sheets.length,this.activeSheet!==i););return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(s,e){const i=r=>r.sheet===s||r.sheet===void 0&&r.sheetIndex===e||(r.extra?.parts??[]).some(i),o=r=>{r.sheetIndex>e&&r.sheetIndex--;for(const t of r.extra?.parts??[])o(t)};for(const r of[this.undoStack,this.redoStack]){const t=r.filter(n=>!i(n));t.forEach(o),r.splice(0,r.length,...t)}}moveSheet(s,e){if(s===e)return;const i=this.sheet,[o]=this.sheets.splice(s,1);this.sheets.splice(e,0,o),this.activeSheet=this.sheets.indexOf(i);const r=n=>n===s?e:s<e?n>s&&n<=e?n-1:n:n>=e&&n<s?n+1:n,t=n=>{n.sheetIndex=r(n.sheetIndex);for(const l of n.extra?.parts??[])t(l)};for(const n of this.undoStack)t(n);for(const n of this.redoStack)t(n);this.structureEdited=!0,this._reindexNames(r),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(s,e){const i=new Map,o=new Set;for(const r of pe(this,s)){const{sheet:t,part:n,id:l,source:c,sheetIndex:a,...h}=r;let u=this.engine.tables.size+i.size+2,p,d;do{const m=String(u++),g=r.name.slice(0,255-m.length);p=g+m,we(p)||(p=g.slice(0,254-m.length)+"_"+m),d=p.toUpperCase()}while(o.has(d)||this.engine.tables.has(d)||this.engine.names.has(d));o.add(d),i.set(r.name.toUpperCase(),{...T(h),name:p,sheet:e,isNew:!0,dirty:!0})}return i}_copyScopedNames(s,e,i,o){const{engine:r}=this;if(!r||r.names.size===0)return;const t=`${s}!`;let n=!1;for(const[l,c]of[...r.names])l.startsWith(t)&&(r.names.set(`${s+1}!${l.slice(t.length)}`,{...c,text:o($(c.text,e.name,i.name))}),n=!0);n&&(this.namesChanged=!0)}_reindexNames(s){const{engine:e}=this;if(!e||e.names.size===0)return;const i=[];let o=!1;for(const[r,t]of e.names){const n=r.indexOf("!"),l=n<0?0:s(Number(r.slice(0,n)));n>=0&&l!==Number(r.slice(0,n))&&(o=!0),n<0?i.push([r,t]):l>=0&&i.push([`${l}!${r.slice(n+1)}`,t])}if(o){e.names.clear();for(const[r,t]of i)e.names.set(r,t);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(s){const e=this.sheets[s];let o=`${e.name} (2)`,r=2;for(;this.sheets.some(h=>h.name.toLowerCase()===o.toLowerCase());)o=`${e.name} (${++r})`;const t=new V(o),n=this._copyTables(e,t),l=h=>Ne(h,n,e.name,t.name);for(const h of n.values())for(const u of h.totals??[])u?.formula&&(u.formula=l(u.formula));e.columns.forEach((h,u)=>{const p=[];h.forEach((d,m)=>{p[m]={kinds:d.kinds.slice(),values:d.values.slice(),styles:d.styles?d.styles.slice():null}}),t.columns[u]=p}),t.maxRow=e.maxRow,t.maxCol=e.maxCol,t.rows=e.rows.shifted(0,0),t.cols=e.cols.shifted(0,0);const c=new Map;e.formulas.forEachCell((h,u,p)=>{let d=c.get(p);d===void 0&&(d={...p,tpl:void 0},p.f!==void 0&&(d.f=l(p.f)),p.sf!==void 0&&(d.sf=l(p.sf)),c.set(p,d)),t.setFormula(h,u,d)}),t.merges=e.merges.map(h=>({...h})),t.rowStyles=e.rowStyles?new Map(e.rowStyles):null,t.colStyles=e.colStyles?new Map(e.colStyles):null,t.frozenRows=e.frozenRows,t.frozenCols=e.frozenCols,t.showGridlines=e.showGridlines,t.cellTypeRules=e.cellTypeRules,t.cellTypes=e.cellTypes?new Map(e.cellTypes):null,t.sparkRules=e.sparkRules,e.protectedRanges&&(t.protectedRanges=e.protectedRanges,t.protectedRangesChanged=!0),t.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,t.cellTags=e.cellTags?new Map(e.cellTags):null,t.cellButtons=e.cellButtons?new Map(e.cellButtons):null,t.cellStates=e.cellStates?e.cellStates.slice():null,t.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,t.background=e.background,t.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,t.frozenTrailingRows=e.frozenTrailingRows,t.frozenTrailingCols=e.frozenTrailingCols,t.hideZeros=e.hideZeros,t.hideHeadings=e.hideHeadings,t.isChartSheet=e.isChartSheet,t.hideOutline=e.hideOutline,t.gridColorId=e.gridColorId,t.areaOffset=e.areaOffset,t.selectionPolicy=e.selectionPolicy,t.selectionUnit=e.selectionUnit,t.gridlineAxes=e.gridlineAxes,t.gridColor=e.gridColor,t.tabStyles=e.tabStyles;const a=T;if(t.cf=a(e.cf),t.validations=a(e.validations),n.size){for(const h of t.cf??[])h.rules=h.rules.map(u=>I(u,l));for(const h of t.validations??[])h.formula1&&(h.formula1=l(h.formula1)),h.formula2&&(h.formula2=l(h.formula2))}t.comments=a(e.comments),t.threads=a(e.threads),t.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...a({...h,_ranges:void 0})})):e.hyperlinks,t.autoFilter=a(e.autoFilter),t.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,t.pageSetup=a(e.pageSetup),t.tabColor=e.tabColor,t.protection=a(e.protection),t.rtl=e.rtl,t.zoom=e.zoom,t.valueMeta=e.valueMeta?new Map(e.valueMeta):null,t.colsChanged=!0,t.viewChanged=!0,this.sheets.splice(s+1,0,t);for(const h of n.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=s+1,this._reindexNames(h=>h>s?h+1:h),this._copyScopedNames(s,e,t,l),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),t}sheetNameProblem(s,e){const i=e.trim().slice(0,31);return!i||/[\\/?*[\]:]/.test(i)||/^'|'$/.test(i)?"rules":i.toLowerCase()==="history"?"reserved":this.sheets.some((o,r)=>r!==s&&o.name.toLowerCase()===i.toLowerCase())?"taken":null}renameSheet(s,e){const i=e.trim().slice(0,31);if(this.sheetNameProblem(s,e)!==null)return!1;const o=this.sheets[s].name;this.sheets[s].name=i,this.engine?.sheetsChanged(),this._renameInFormulas(o,i);for(const r of this.sheets)Le(r,o,i);for(const r of Fe)r(this,o,i);return this._emit("sheets"),!0}_shrink3D(s){const e=this.sheets[s].name.toLowerCase(),i=l=>this.sheets.findIndex(c=>c.name.toLowerCase()===l.toLowerCase()),o=l=>l[0]==="'"?l.slice(1,-1).replace(/''/g,"'"):l,r=/((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*)):((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*))!/g,t=l=>l.replace(r,(c,a,h,u)=>{if(l[u-1]==="]")return c;const p=o(a),d=o(h);if(p.toLowerCase()!==e&&d.toLowerCase()!==e)return c;let m=i(p),g=i(d);if(m<0||g<0||(m>g&&([m,g]=[g,m]),m===s&&m++,g===s&&g--,m>g))return c;const y=w=>ee(this.sheets[w].name);return m===g?`${y(m)}!`:`${y(m)}:${y(g)}!`}),n=l=>l.includes(":")&&l.includes("!")?l.split(/("(?:[^"]|"")*")/).map((c,a)=>a%2?c:t(c)).join(""):l;for(const l of this.sheets){const c=new Map;l.formulas.forEachCell((a,h,u)=>{let p=c.get(u);if(p===void 0){const d=u.f??u.sf,m=typeof d=="string"?n(d):d;p=m===d?null:u.f!==void 0?{...u,f:m,tpl:void 0}:{...u,sf:m,tpl:void 0},c.set(u,p)}p!==null&&l.setFormula(a,h,p)})}for(const l of this.engine?.names.values()??[])typeof l.text=="string"&&(l.text=n(l.text));this.engine?.templates.clear()}_refErrorsFor(s){const e=te(this.sheets[s].name),i=t=>t.split(/("(?:[^"]|"")*")/).map((n,l)=>l%2?n:n.replace(e,"#REF!")).join(""),o=t=>typeof t=="string"&&t!==""?i(t):t,r=this.sheets[s];for(const t of this.sheets){if(t===r)continue;le(t,ae(o,I)),t.cf?.length>0&&(t.cf=t.cf.map(l=>({...l,rules:l.rules.map(c=>I(c,o))})),t.cfChanged=!0,t.cfEval?.invalidate()),t.validations?.length>0&&(t.validations=t.validations.map(l=>({...l,formula1:o(l.formula1),formula2:o(l.formula2)})),t.validationsChanged=!0);const n=new Map;t.formulas.forEachCell((l,c,a)=>{let h=n.get(a);if(h===void 0){const u=a.f??a.sf,p=typeof u=="string"?i(u):u;h=p===u?null:a.f!==void 0?{...a,f:p,tpl:void 0}:{...a,sf:p,tpl:void 0},n.set(a,h)}h!==null&&(t.setFormula(l,c,h),this.formulasEdited=!0)})}for(const t of this.engine?.names.values()??[])typeof t.text=="string"&&(t.text=i(t.text));this.engine?.templates.clear()}_renameInFormulas(s,e){const i=te(s);let o=!1;for(const t of this.sheets){const n=new Map;t.formulas.forEachCell((l,c,a)=>{let h=n.get(a);if(h===void 0){const u=a.f??a.sf;if(u===void 0||!i.test(u))i.lastIndex=0,h=null;else{i.lastIndex=0;const p=$(u,s,e);h=a.f!==void 0?{...a,f:p,tpl:void 0}:{...a,sf:p,tpl:void 0}}n.set(a,h)}h!==null&&(t.setFormula(l,c,h),o=!0)})}let r=!1;for(const t of this.engine?.names.values()??[]){if(typeof t.text!="string")continue;const n=$(t.text,s,e);n!==t.text&&(t.text=n,r=!0)}r&&(this.namesChanged=!0,this.engine.nameTemplates.clear()),(o||r)&&(o&&(this.formulasEdited=!0),this.engine?.templates.clear(),this.engine?.rebuild())}editText(s,e,i){const o=s.kind(e,i);if(this.engine?.dataTables.length){const n=this.engine.dataTableAt(s,e,i);if(n){const{info:l}=n,c=l.dt2D==="1",a=l.dtr==="1";return`{=TABLE(${c||a?l.r1:""},${c?l.r2:a?"":l.r1})}`}}if(o&ye&&this.engine){const n=this.engine.spillMaster(s,e,i);if(n)return this.editText(s,n.row,n.col)}if(o&F){const n=s.formula(e,i),l=n&&!n.typed&&n.t!=="array"&&n.tpl?.rangeResult?"=@":"=";if(n&&n.f!==void 0){const c=l+he(n.f);return n.t==="array"&&!n.cm?`{${c}}`:c}if(n&&n.sf!==void 0){const c=Math.floor(n.base/R),a=n.base-c*R;return l+he(ve(n.sf,e-c,i-a))}}const r=o&X;if(r===O)return"";const t=s.value(e,i);if(r===L&&s.valueMeta!==null&&!(o&F)){const n=this.richImages?.get(s.valueMeta.get(e*R+i));if(n!==void 0)return n.alt??"";const l=this.richValues?.indexOfVm(s.valueMeta.get(e*R+i))??-1,c=l>=0?this.richValues.view(l):null;if(c!==null)return c.text}return r===E?this.styles.get(s.style(e,i)).quotePrefix?`'${this.strings.get(t)}`:this.strings.get(t):r===P?t?"TRUE":"FALSE":r===L?ge[t]??"#N/A":String(t)}transact(s,e,i=null){if(this.guard&&!this.guard(s))return;const o=this.selectedSheets;!i&&o?.size>1&&ze.has(s)&&(i=this.sheets.filter(t=>o.has(t)&&(!t.protection||t===this.sheet)));const r=i?this._runGroup(s,e,i):this._runOn(this.sheet,s,e);r!==null&&this._pushUndo(r)}transactOn(s,e,i){const o=this._runOn(s,e,i);o!==null&&this._pushUndo(o)}_runOn(s,e,i){const o=new D,r={sheet:s,log:o,saveCell:(d,m)=>o.push(s,d,m)},{maxRow:t,maxCol:n}=s,l=this.recorder?.length,c=this.formulasEdited;let a;try{a=i(r)??null}catch(d){throw d instanceof N&&(ce(s,o),s.maxRow=t,s.maxCol=n,this.formulasEdited=c,l!==void 0&&(this.recorder.length=l),this.engine?.cellsChanged(s,o.rows,o.cols,o.count)),d}e!=="entry"&&this.engine?.presentationChanged(),s.changes!==null&&o.count>0&&re(this,s,o),o.vms!==null&&$e(s,o);const h=o.count>0&&this.engine?.tables.size>0?me(this,r,o):null,u=(d,m)=>g=>u(d(g),m(g)),p=a&&h?u(a,h):a??h;return o.count===0&&p===null?null:(s.revision++,this.engine?.cellsChanged(s,o.rows,o.cols,o.count),{sheetIndex:s===this.sheet?this.activeSheet:this.sheets.indexOf(s),sheet:s,log:o,label:e,extra:p})}_runGroup(s,e,i){const o=[],r=this.activeSheet,t=this.recorder?.length,n=this.formulasEdited,l=[];try{for(const c of i){const{maxRow:a,maxCol:h}=c,u=this._runOn(c,s,e);u!==null&&(o.push(u),l.push([c,a,h]))}}catch(c){if(c instanceof N){this.rollbackSlices(o);for(const[a,h,u]of l)a.maxRow=h,a.maxCol=u;this.activeSheet=r,this.formulasEdited=n,t!==void 0&&(this.recorder.length=t)}throw c}return o.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new D,label:s,extra:j(this,o)}}runSlice(s,e,i){const o=this._runOn(s,e,i);return o!==null&&this._emit("cells"),o}pushFolded(s,e,i){s.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(i),sheet:i,log:new D,label:e,extra:j(this,s)})}rollbackSlices(s){for(let e=s.length-1;e>=0;e--)this._restore(s[e]);this._emit("cells")}_pushUndo(s){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(s),this.undoStack.length>(this.historyLimit??Ie)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(s){const e=s.sheet??this.sheets[s.sheetIndex],{log:i}=s,o=new D;if(ce(e,i,o),i.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[n,l]of i.vms)e.valueMeta.set(i.rows[n]*R+i.cols[n],l)}let r=null;s.extra&&(r=s.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&i.count>0&&re(this,e,o),e.revision++,this.engine?.cellsChanged(e,i.rows,i.cols,i.count);const t=this.sheets.indexOf(e);return t>=0&&(this.activeSheet=t),{sheetIndex:t>=0?t:s.sheetIndex,sheet:e,log:o,label:s.label,extra:r}}undo(){const s=this.undoStack.pop();return s?(this.redoStack.push(this._restore(s)),this._emit("cells"),!0):!1}redo(){const s=this.redoStack.pop();return s?(this.undoStack.push(this._restore(s)),this._emit("cells"),!0):!1}setInput(s,e,i,o,{overLimitAsText:r=!1,typedQuote:t=!0}={}){const{sheet:n}=s,l=n.style(e,i),c=o!==""&&this.styles.get(l).numFmt==="@";let a=c?{kind:E,text:o[0]==="'"?o.slice(1):o}:oe(o,void 0,this.dateOffset);if(a.kind===F){const u=Te(a.formula);if(u){if(!r)throw new N(u);a={kind:E,text:o}}}if(this.recorder){const u=a.kind===E&&o.startsWith("=")&&!c?`'${o}`:o;this.recorder.push(`sheet.setValue(${JSON.stringify(Se(e,i))}, ${JSON.stringify(u)});`)}s.saveCell(e,i),n.setFormula(e,i,null);const h=t&&o[0]==="'"&&o.length>1;switch((h||this.styles.get(l).quotePrefix)&&n.setStyle(e,i,this.styles.derive(l,{quotePrefix:h})),a.kind){case O:n.setCell(e,i,O,0);break;case B:n.setCell(e,i,B,a.value),a.format&&this.styles.get(l).numFmt==="General"&&n.setStyle(e,i,this.styles.derive(n.style(e,i),{numFmt:a.format}));break;case P:n.setCell(e,i,P,a.value);break;case L:n.setCell(e,i,L,a.value);break;case F:n.setCell(e,i,F|O,0),n.setFormula(e,i,{f:Oe(this._expandTableRefs(de(a.formula,this.engine?.tables),n,e,i),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:n.setCell(e,i,E,this.strings.add(ie(a.text)))}}setRichInput(s,e,i,o,r){const{sheet:t}=s;s.saveCell(e,i),t.setFormula(e,i,null);const n=ie(o);t.setCell(e,i,E,this.strings.addRich(n,n===o?r:r?.filter(l=>l.at<n.length)))}_expandTableRefs(s,e,i,o){const r=this.engine;return!r||r.tables.size===0?s:Ee(s,()=>{for(const t of r.tables.values())if(t.sheet===e&&i>=t.r0&&i<=t.r1&&o>=t.c0&&o<=t.c1)return t;return null})}clearRange(s,e="contents",{visibleOnly:i=!1}={}){this.sheet.dataRanges?.cleared(s)||this.transact("clear",o=>{const{sheet:r}=o,t=[];if(e!=="contents")for(const{r0:l,c0:c,r1:a,c1:h}of s){const u=l===0&&a===Q-1,p=c===0&&h===R-1,d=(m,g,y,w)=>{for(const[C,x]of[...g])C<y||C>w||(t.push([m,C,x]),g.delete(C))};u&&r.colStyles!==null&&d("col",r.colStyles,c,h),p&&r.rowStyles!==null&&d("row",r.rowStyles,l,a)}const n=i&&r.filteredRows?.size>0?r.filteredRows:null;for(const{r0:l,c0:c,r1:a,c1:h}of s){const u=Math.min(h,r.maxCol),p=Math.min(a,r.maxRow);for(let d=c;d<=u;d++)if(r.columns[d]!==void 0)for(let m=l;m<=p;m++){if(r._chunk(m,d)===void 0){m|=1023;continue}if(n!==null&&n.has(m))continue;const y=r.kind(m,d)!==0,w=r.cellStyle(m,d)!==0;if(e==="formats"){if(!w)continue;o.saveCell(m,d),r.setStyle(m,d,0);continue}!y&&!(e==="all"&&w)||(o.saveCell(m,d),r.setCell(m,d,O,0),r.setFormula(m,d,null),e==="all"&&r.setStyle(m,d,0))}}return t.length>0?q([],t):void 0})}applyStyle(s,e,{measureRow:i,numberFit:o}={}){const r=JSON.stringify(e);if(this.recorder)for(const t of s)this.recorder.push(`sheet.setFormat(${JSON.stringify(Ce(t))}, ${r});`);this.transact("format",t=>{const{sheet:n}=t;this.strings.rich!==null&&Me(this,t,s,e);const l=[],c=new Set,a=[],h=[],u=(g,y,w)=>{const C=g*2048+y;c.has(C)||(c.add(C),l.push(g,y,w.styles===null?null:w.styles.slice()))},p=(g,y,w)=>{w===0&&(n.rowStyles?.has(g)||n.colStyles?.has(y))&&(w=this.styles.explicitDefault()),n.setStyle(g,y,w)};for(const{r0:g,c0:y,r1:w,c1:C}of s){const x=g===0&&w===Q-1,v=y===0&&C===R-1,k=x||v,b=k?Math.min(w,n.maxRow):w,ue=k?Math.min(C,n.maxCol):C;for(let S=y;S<=ue&&g<=b;S++){const _=n.columns[S];if(!(k&&!_))for(let M=g>>>U;M<=b>>>U;M++){const J=M<<U,K=Math.max(g,J),fe=Math.min(b,J+W),H=k?_[M]:n._ensure(K,S);if(!(k&&!H?.styles)){u(S,M,H);for(let A=K;A<=fe;A++)(!k||H.styles[A&W])&&p(A,S,this.styles.derive(n.style(A,S),e,r))}}}const z=S=>this.styles.derive(S,e,r),G=(S,_,M)=>{u(_,S>>>U,n._ensure(S,_)),n.setStyle(S,_,M||this.styles.explicitDefault())};if(v&&x){xe(n,z,a);for(const[S,_]of n.rowStyles??[])a.push(["row",S,_]),n.rowStyles.set(S,z(_))}else if(x)for(let S=y;S<=C;S++)ne(n,"col",S,z,a,G);else if(v)for(let S=g;S<=w;S++)ne(n,"row",S,z,a,G)}const d=(g,y,w)=>{const C=n[g];w!==C.sizeOf(y)&&(h.push([g,y,C.isCustom(y)?C.sizeOf(y):null,C.isAuto(y)]),C.setSize(y,w,!0),g==="cols"&&(n.colsChanged=!0))},m=e.fontSize!==void 0||e.wrap!==void 0||e.rotation!==void 0||["justify","distributed"].includes(e.hAlign)||["justify","distributed"].includes(e.vAlign);for(const{r0:g,r1:y,c0:w,c1:C}of s){const x=Math.min(y,n.maxRow);if(m&&x-g<=2e3)for(let v=g;v<=x;v++)d("rows",v,_e(n,this,v,i));if(o)for(const v of o.cols){if(v<w||v>C||!n.columns[v]||n.cols.isCustom(v)&&!n.cols.isAuto(v))continue;let k=n.cols.sizeOf(v);for(const b of o.rows)b>=g&&b<=x&&(n.kind(b,v)&X)===B&&(k=Math.max(k,o.measure(n,b,v)));d("cols",v,k)}}return q(l,a,h)})}}function ce(f,s,e){for(let i=s.count-1;i>=0;i--){const o=s.rows[i],r=s.cols[i];e?.push(f,o,r),f.setCell(o,r,s.kinds[i],s.values[i]),f.setStyle(o,r,s.styles[i]),f.setFormula(o,r,s.kinds[i]&F?s.formulas.get(i):null)}}function j(f,s){const e=()=>{const i=[];for(let o=s.length-1;o>=0;o--)i.push(f._restore(s[o]));return j(f,i)};return e.parts=s,e}function $e(f,s){let e=null;for(const i of s.vms.keys()){const o=s.rows[i],r=s.cols[i];(f.kind(o,r)&~(Z|Y))===s.kinds[i]&&f.value(o,r)===s.values[i]||(e??=new Map(f.valueMeta),e.delete(o*R+r))}e!==null&&(f.valueMeta=e.size>0?e:null)}function Ne(f,s,e,i){if(!s.size||typeof f!="string")return f;let o;try{o=Ae(f)}catch(n){if(n instanceof N)return f;throw n}let r="",t=0;for(let n=0;n<o.length;n++){const l=o[n],c=l.t==="name"?f.slice(l.s,l.e):l.t==="table"?l.v.name:null;if(!c)continue;const a=s.get(c.toUpperCase());if(!a)continue;let h=n-1;for(;o[h]?.t==="ws";)h--;const u=o[h];if(u?.t==="sheet"){const{book:p,sheet:d,sheet2:m}=u.v;if(p!==null||m!==null)continue;if(d.toUpperCase()===e.toUpperCase())r+=f.slice(t,u.s)+ee(i)+"!",t=u.e;else if(d.toUpperCase()!==i.toUpperCase())continue}r+=f.slice(t,l.s)+a.name,t=l.s+c.length}return t?r+f.slice(t):f}function T(f){if(f===null||typeof f!="object")return f;if(Array.isArray(f))return f.map(T);if(f instanceof Map)return new Map([...f].map(([e,i])=>[e,T(i)]));if(f instanceof Set)return new Set([...f].map(T));if(ArrayBuffer.isView(f))return f.slice();const s={};for(const[e,i]of Object.entries(f))!e.startsWith("_")&&typeof i!="function"&&(s[e]=T(i));return s}function q(f,s,e=[]){return i=>{const o=[];for(let n=0;n<f.length;n+=3){const l=f[n],c=f[n+1],a=i.columns[l]?.[c];a!==void 0&&(o.push(l,c,a.styles),a.styles=f[n+2])}const r=[];for(let n=s.length-1;n>=0;n--){const[l,c,a]=s[n];if(l==="columns"){r.push([l,c,i.colStyles]),i.colStyles=a,i.colsChanged=!0;continue}l==="col"&&(i.colsChanged=!0);const h=l==="col"?"colStyles":"rowStyles",u=i[h]??=new Map;r.push([l,c,u.get(c)]),a===void 0?u.delete(c):u.set(c,a)}const t=[];for(let n=e.length-1;n>=0;n--){const[l,c,a,h]=e[n],u=i[l];t.push([l,c,u.isCustom(c)?u.sizeOf(c):null,u.isAuto(c)]),u.setSize(c,a,h),l==="cols"&&(i.colsChanged=!0)}return q(o,r,t)}}export{D as CellLog,ze as GROUP_LABELS,nt as Workbook,j as foldEntries,oe as parseInput,Le as renameInRules,q as swapStyles};
1
+ import{withShared as me}from"./shared-view.js";import{expandBareTables as pe}from"../slicers/structured.js";import{syncTableHeaders as ge,tablesOf as ye}from"./tables.js";import{BOOL as j,CHUNK_BITS as T,CHUNK_MASK as Y,EMPTY as I,ERR as P,ERRORS as Se,FORMULA as F,DIRTY as X,EVALUATING as Z,KIND_MASK as Q,NUM as D,Sheet as G,SPILL as ee,STR as E}from"./sheet.js";import{cellRef as we,isValidName as Ce,mapSheetParts as te,MAX_COLS as R,MAX_ROWS as se,quoteSheetName as ke,rangeRef as ve,renameSheetInFormula as O,sheetPrefix as _e}from"./address.js";import{translateFormula as xe}from"./formula-refs.js";import{sheetStem as ne}from"./default-names.js";import{StringTable as Re}from"./strings.js";import{formatAxis as ie,formatSheetColumns as be}from"./axis-styles.js";import{autoRowHeight as Me}from"./row-fit.js";import{StyleTable as Ae}from"./styles.js";import{cellEntryText as oe,fractionEntry as Te,fractionFormat as Fe,parseInput as re,takesEntryFormat as Ee}from"./input.js";import{DATE_1904_OFFSET as Oe}from"./numfmt.js";import{logNumbers as Ie,roundLogged as ze}from"./precision.js";import{noteChanges as le}from"./changes.js";import{overrideRuns as Le}from"../cells/rich-runs.js";import{mapHostRules as ae,rewriteHostEntry as he}from"./host-rules.js";import{sheetRenameHooks as Ue}from"./sparse.js";import{shiftRuleFormulas as z}from"../cells/cf-file.js";import{expandStructured as Ne,formulaEntryLimit as $e,FormulaSyntaxError as B,tokenize as Pe,toDisplayFormula as ue,toFileFormula as De}from"../calc/parser.js";const Be=200,He=new Set(["entry","clear","format","borders","fill"]);class Ve{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(e,s){if(e>=this.ids.length){let n=this.ids.length*2;for(;n<=e;)n*=2;const l=new Int32Array(n);l.set(this.ids),this.ids=l}const i=this.list.length;(i===0||this.list[i-1]!==s)&&this.list.push(s),this.ids[e]=this.list.length}get(e){const s=e<this.ids.length?this.ids[e]:0;return s===0?void 0:this.list[s-1]}}class N{constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const e=this.capacity*2,s=(i,n)=>{const l=new i(e);return l.set(n),l};this.rows=s(Uint32Array,this.rows),this.cols=s(Uint16Array,this.cols),this.kinds=s(Uint8Array,this.kinds),this.styles=s(Uint16Array,this.styles),this.values=s(Float64Array,this.values),this.capacity=e}push(e,s,i){this.count===this.capacity&&this._grow();const n=this.count++,l=e.kind(s,i)&~(X|Z);if(this.rows[n]=s,this.cols[n]=i,this.kinds[n]=l,this.styles[n]=e.cellStyle(s,i),this.values[n]=e.value(s,i),l&F&&(this.formulas===null&&(this.formulas=new Ve),this.formulas.set(n,e.formula(s,i))),e.valueMeta!==null){const t=e.valueMeta.get(s*R+i);t!==void 0&&(this.vms??=new Map).set(n,t)}}}function je(f,e,s){const i=t=>typeof t=="string"&&t!==""?O(t,e,s):t;ae(f,he(i,z));const n=f.cf?.map(t=>{const o=t.rules.map(r=>z(r,i));return JSON.stringify(o)===JSON.stringify(t.rules)?t:{...t,rules:o}});n?.some((t,o)=>t!==f.cf[o])&&(f.cf=n,f.cfChanged=!0,f.cfEval?.invalidate()),f.printAreaFormula&&(f.printAreaFormula=i(f.printAreaFormula));const l=f.validations?.map(t=>{const o=i(t.formula1),r=i(t.formula2);return o===t.formula1&&r===t.formula2?t:{...t,formula1:o,formula2:r}});l?.some((t,o)=>t!==f.validations[o])&&(f.validations=l,f.validationsChanged=!0)}class mt{get namesChanged(){return this._namesChanged}set namesChanged(e){this._namesChanged=e,e&&(this.namesRevision=(this.namesRevision??0)+1)}constructor(){this.sheets=[new G(`${ne()}1`)],this.activeSheet=0,this.date1904=!1,this.strings=new Re,this.styles=new Ae,this.undoStack=[],this.redoStack=[],this.textChanges=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dateOffset(){return this.date1904?Oe:0}get dirty(){return this._dirty}set dirty(e){e&&this.edits++,this._dirty=!!e}onChange(e){this.listeners.add(e)}clearHistory(){if(this.historyCleared=(this.historyCleared??0)+1,!(this.undoStack.length===0&&this.redoStack.length===0)){this.undoStack.length=0,this.redoStack.length=0;for(const e of this.listeners)e("history")}}_emit(e){(e==="cells"||e==="bulk")&&(this.formatValueRevision=(this.formatValueRevision??0)+1),this.dirty=!0;for(const s of this.listeners)s(e)}addSheet(e){const s=ne();let i=1,n=e??`${s}${i}`;const l=o=>this.sheets.some(r=>r.name.toLowerCase()===o.toLowerCase());for(;l(n);)n=`${s}${++i}`;const t=new G(n);return this.sheets.push(t),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),t}deleteSheet(e){if(this.sheets.filter(n=>!n.hidden).length<=1)return!1;const s=this._shrink3D(e),i=this._refErrorsFor(e);return this.textChanges.push(n=>i(s(n))),this._removeSheet(e)}_removeSheet(e){if(this.sheets.length<=1)return!1;const[s]=this.sheets.splice(e,1);if(this.selectedSheets?.delete(s),this._forgetSheet(s,e),this.engine)for(const[n,l]of this.engine.tables)l.sheet===s&&this.engine.tables.delete(n);this._reindexNames(n=>n===e?-1:n>e?n-1:n),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);const i=this.activeSheet;for(;this.sheets[this.activeSheet].hidden&&(this.activeSheet=(this.activeSheet+1)%this.sheets.length,this.activeSheet!==i););return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(e,s){const i=l=>l.sheet===e||l.sheet===void 0&&l.sheetIndex===s||(l.extra?.parts??[]).some(i),n=l=>{l.sheetIndex>s&&l.sheetIndex--;for(const t of l.extra?.parts??[])n(t)};for(const l of[this.undoStack,this.redoStack]){const t=l.filter(o=>!i(o));t.forEach(n),l.splice(0,l.length,...t)}}moveSheet(e,s){if(e===s)return;const i=this.sheet,[n]=this.sheets.splice(e,1);this.sheets.splice(s,0,n),this.activeSheet=this.sheets.indexOf(i);const l=o=>o===e?s:e<s?o>e&&o<=s?o-1:o:o>=s&&o<e?o+1:o,t=o=>{o.sheetIndex=l(o.sheetIndex);for(const r of o.extra?.parts??[])t(r)};for(const o of this.undoStack)t(o);for(const o of this.redoStack)t(o);this.structureEdited=!0,this._reindexNames(l),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(e,s){const i=new Map,n=new Set;for(const l of ye(this,e))l.dataSheet||i.set(l.name.toUpperCase(),this.tableCopy(l,s,n));return i}tableCopy(e,s,i){const{sheet:n,part:l,id:t,source:o,sheetIndex:r,...a}=e;let u=this.engine.tables.size+i.size+2,h,c;do{const d=String(u++),m=e.name.slice(0,255-d.length);h=m+d,Ce(h)||(h=m.slice(0,254-d.length)+"_"+d),c=h.toUpperCase()}while(i.has(c)||this.engine.tables.has(c)||this.engine.names.has(c));return i.add(c),{...L(a),name:h,sheet:s,isNew:!0,dirty:!0}}_copyScopedNames(e,s,i,n){const{engine:l}=this;if(!l||l.names.size===0)return;const t=`${e}!`;let o=!1;for(const[r,a]of[...l.names])r.startsWith(t)&&(l.names.set(`${e+1}!${r.slice(t.length)}`,{...a,text:n(O(a.text,s.name,i.name))}),o=!0);o&&(this.namesChanged=!0)}_reindexNames(e){const{engine:s}=this;if(!s||s.names.size===0)return;const i=[];let n=!1;for(const[l,t]of s.names){const o=l.indexOf("!"),r=o<0?0:e(Number(l.slice(0,o)));o>=0&&r!==Number(l.slice(0,o))&&(n=!0),o<0?i.push([l,t]):r>=0&&i.push([`${r}!${l.slice(o+1)}`,t])}if(n){s.names.clear();for(const[l,t]of i)s.names.set(l,t);s.nameTemplates.clear(),this.namesChanged=!0,s.rebuild()}}duplicateSheet(e){const s=this.sheets[e];return me(this,()=>this._duplicateSheet(s),s)}_duplicateSheet(e){const s=this.sheets.indexOf(e);let n=`${e.name} (2)`,l=2;for(;this.sheets.some(h=>h.name.toLowerCase()===n.toLowerCase());)n=`${e.name} (${++l})`;const t=new G(n),o=this._copyTables(e,t),r=h=>Ke(h,o,e.name,t.name);for(const h of o.values())for(const c of h.totals??[])c?.formula&&(c.formula=r(c.formula));e.columns.forEach((h,c)=>{const d=[];h.forEach((m,p)=>{d[p]={kinds:m.kinds.slice(),values:m.values.slice(),styles:m.styles?m.styles.slice():null}}),t.columns[c]=d}),t.maxRow=e.maxRow,t.maxCol=e.maxCol,t.rows=e.rows.shifted(0,0),t.cols=e.cols.shifted(0,0);const a=new Map;e.formulas.forEachCell((h,c,d)=>{let m=a.get(d);m===void 0&&(m={...d,tpl:void 0},d.f!==void 0&&(m.f=r(d.f)),d.sf!==void 0&&(m.sf=r(d.sf)),a.set(d,m)),t.setFormula(h,c,m)}),t.merges=e.merges.map(h=>({...h})),t.rowStyles=e.rowStyles?new Map(e.rowStyles):null,t.colStyles=e.colStyles?new Map(e.colStyles):null,t.frozenRows=e.frozenRows,t.frozenCols=e.frozenCols,t.frozenTop=e.frozenTop,t.frozenLeft=e.frozenLeft,t.showGridlines=e.showGridlines,t.cellTypeRules=e.cellTypeRules,t.cellTypes=e.cellTypes?new Map(e.cellTypes):null,t.sparkRules=e.sparkRules,e.protectedRanges&&(t.protectedRanges=e.protectedRanges,t.protectedRangesChanged=!0),t.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,t.cellTags=e.cellTags?new Map(e.cellTags):null,t.cellButtons=e.cellButtons?new Map(e.cellButtons):null,t.cellStates=e.cellStates?e.cellStates.slice():null,t.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,t.background=e.background,t.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,t.frozenTrailingRows=e.frozenTrailingRows,t.frozenTrailingCols=e.frozenTrailingCols,t.hideZeros=e.hideZeros,t.hideHeadings=e.hideHeadings,t.isChartSheet=e.isChartSheet,t.hideOutline=e.hideOutline,t.gridColorId=e.gridColorId,t.areaOffset=e.areaOffset,t.selectionPolicy=e.selectionPolicy,t.selectionUnit=e.selectionUnit,t.gridlineAxes=e.gridlineAxes,t.gridColor=e.gridColor,t.tabStyles=e.tabStyles;const u=L;if(t.cf=u(e.cf),t.validations=u(e.validations),e.printAreaFormula&&(t.printAreaFormula=O(e.printAreaFormula,e.name,t.name)),o.size){for(const h of t.cf??[])h.rules=h.rules.map(c=>z(c,r));for(const h of t.validations??[])h.formula1&&(h.formula1=r(h.formula1)),h.formula2&&(h.formula2=r(h.formula2))}if(e.sparklines){const h=c=>c&&O(c,e.name,t.name);t.sparklines=e.sparklines.map(c=>({...c,dateRange:h(c.dateRange),items:c.items.map(d=>({...d,source:h(d.source)}))})),t.sparklinesChanged=!0}t.comments=u(e.comments),t.threads=u(e.threads),t.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...u({...h,_ranges:void 0})})):e.hyperlinks,t.autoFilter=u(e.autoFilter),t.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,t.pageSetup=u(e.pageSetup),t.tabColor=e.tabColor,t.protection=u(e.protection),t.rtl=e.rtl,t.zoom=e.zoom,t.valueMeta=e.valueMeta?new Map(e.valueMeta):null,t.colsChanged=!0,t.viewChanged=!0,this.sheets.splice(s+1,0,t);for(const h of o.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=s+1,this._reindexNames(h=>h>s?h+1:h),this._copyScopedNames(s,e,t,r),this.onSheetCopied?.(e,t,h=>r(O(h,e.name,t.name))),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),t}sheetNameProblem(e,s){const i=s.trim().slice(0,31);return!i||/[\\/?*[\]:]/.test(i)||/^'|'$/.test(i)?"rules":i.toLowerCase()==="history"?"reserved":this.sheets.some((n,l)=>l!==e&&n.name.toLowerCase()===i.toLowerCase())?"taken":null}renameSheet(e,s){const i=s.trim().slice(0,31);if(this.sheetNameProblem(e,s)!==null)return!1;const n=this.sheets[e].name;this.sheets[e].name=i,this.textChanges.push(l=>O(l,n,i)),this.engine?.sheetsChanged(),this._renameInFormulas(n,i);for(const l of this.sheets)je(l,n,i);for(const l of Ue)l(this,n,i);return this._emit("sheets"),!0}_shrink3D(e){const s=this.sheets[e].name.toLowerCase(),i=(o,r)=>{if(r===null||o.toLowerCase()!==s&&r.toLowerCase()!==s)return null;let a=l(o),u=l(r);return a<0||u<0||(a>u&&([a,u]=[u,a]),a===e&&a++,u===e&&u--,a>u)?null:_e(n[a],{last:a===u?null:n[u]})},n=this.sheets.map(o=>o.name),l=o=>n.findIndex(r=>r.toLowerCase()===o.toLowerCase()),t=o=>o.includes(":")&&o.includes("!")?te(o,i):o;return this._rewriteSheetParts(t),t}_rewriteSheetParts(e,s=null){for(const i of this.sheets){if(i===s)continue;const n=new Map;i.formulas.forEachCell((l,t,o)=>{let r=n.get(o);if(r===void 0){const a=o.f??o.sf,u=typeof a=="string"?e(a):a;r=u===a?null:o.f!==void 0?{...o,f:u,tpl:void 0}:{...o,sf:u,tpl:void 0},n.set(o,r)}r!==null&&(i.setFormula(l,t,r),this.formulasEdited=!0)})}for(const i of this.engine?.names.values()??[]){if(typeof i.text!="string")continue;const n=e(i.text);n!==i.text&&(i.text=n,this.namesChanged=!0)}this.engine?.nameTemplates.clear(),this.engine?.templates.clear()}_refErrorsFor(e){const s=this.sheets[e].name.toLowerCase(),i=t=>te(t,(o,r)=>o.toLowerCase()===s&&(r===null||r.toLowerCase()===s)?"#REF!":null),n=t=>typeof t=="string"&&t!==""?i(t):t,l=this.sheets[e];for(const t of this.sheets)t!==l&&(ae(t,he(n,z)),t.cf?.length>0&&(t.cf=t.cf.map(o=>({...o,rules:o.rules.map(r=>z(r,n))})),t.cfChanged=!0,t.cfEval?.invalidate()),t.printAreaFormula&&(t.printAreaFormula=n(t.printAreaFormula)),t.validations?.length>0&&(t.validations=t.validations.map(o=>({...o,formula1:n(o.formula1),formula2:n(o.formula2)})),t.validationsChanged=!0));return this._rewriteSheetParts(i,l),i}_renameInFormulas(e,s){const{engine:i}=this;let n=!1;this._rewriteSheetParts(l=>{const t=O(l,e,s);return t!==l&&(n=!0),t}),n&&i?.rebuild()}textSince(e,s){for(let i=e;i<this.textChanges.length;i++)s=this.textChanges[i](s);return s}_textInUse(){const e=new Set;for(const s of this.sheets){for(const i of s.formulas.descriptors())e.add(i);for(const i of["cf","validations","sparklines","sparkRules"])for(const n of s[i]??[])e.add(n)}return{held:e,names:new Map([...this.engine?.names.values()??[]].map(s=>[s,s.text]))}}_replayTextChanges(e,{held:s,names:i}){const n=t=>typeof t=="string"&&t!==""?this.textSince(e,t):t,l=(t,o)=>t.map(r=>s.has(r)?r:o(r));for(const t of this.sheets){const o=new Map;t.formulas.forEachCell((r,a,u)=>{if(s.has(u))return;let h=o.get(u);if(h===void 0){const c=u.f??u.sf,d=n(c);h=d===c?null:u.f!==void 0?{...u,f:d,tpl:void 0}:{...u,sf:d,tpl:void 0},o.set(u,h)}h!==null&&t.setFormula(r,a,h)}),t.cf&&(t.cf=l(t.cf,({_ranges:r,_base:a,...u})=>({...u,rules:u.rules.map(h=>z(h,n))}))),t.validations&&(t.validations=l(t.validations,({_ranges:r,...a})=>({...a,formula1:n(a.formula1),formula2:n(a.formula2)}))),t.sparklines&&(t.sparklines=l(t.sparklines,r=>({...r,...r.dateRange?{dateRange:n(r.dateRange)}:{},items:r.items.map(a=>({...a,source:n(a.source)}))}))),t.sparkRules&&(t.sparkRules=l(t.sparkRules,r=>Object.freeze({...r,formula:n(r.formula)}))),t.cfEval?.invalidate()}for(const t of this.engine?.names.values()??[])typeof t.text=="string"&&i.get(t)!==t.text&&(t.text=n(t.text));this.engine&&(this.engine.nameTemplates.clear(),this.engine.rebuild())}editText(e,s,i){const n=e.kind(s,i);if(this.engine?.dataTables.length){const o=this.engine.dataTableAt(e,s,i);if(o){const{info:r}=o,a=r.dt2D==="1",u=r.dtr==="1";return`{=TABLE(${a||u?r.r1:""},${a?r.r2:u?"":r.r1})}`}}if(n&ee&&this.engine){const o=this.engine.spillMaster(e,s,i);if(o)return this.editText(e,o.row,o.col)}if(n&F){const o=e.formula(s,i),r=o&&!o.typed&&o.t!=="array"&&o.tpl?.rangeResult?"=@":"=";if(o&&o.f!==void 0){const a=r+ue(o.f);return o.t==="array"&&!o.cm?`{${a}}`:a}if(o&&o.sf!==void 0){const a=Math.floor(o.base/R),u=o.base-a*R;return r+ue(xe(o.sf,s-a,i-u))}}const l=n&Q;if(l===I)return"";const t=e.value(s,i);if(l===P&&e.valueMeta!==null&&!(n&F)){const o=this.richImages?.get(e.valueMeta.get(s*R+i));if(o!==void 0)return o.alt??"";const r=this.richValues?.indexOfVm(e.valueMeta.get(s*R+i))??-1,a=r>=0?this.richValues.view(r):null;if(a!==null)return a.text}return l===E?this.styles.get(e.style(s,i)).quotePrefix?`'${this.strings.get(t)}`:this.strings.get(t):l===j?t?"TRUE":"FALSE":l===P?Se[t]??"#N/A":String(t)}transact(e,s,i=null){if(this.guard&&!this.guard(e))return;const n=this.selectedSheets;!i&&n?.size>1&&He.has(e)&&(i=this.sheets.filter(t=>n.has(t)&&(!t.protection||t===this.sheet)));const l=i?this._runGroup(e,s,i):this._runOn(this.sheet,e,s);l!==null&&this._pushUndo(l)}transactOn(e,s,i){const n=this._runOn(e,s,i);n!==null&&this._pushUndo(n)}_runOn(e,s,i){const n=new N,l={sheet:e,log:n,saveCell:(v,g)=>n.push(e,v,g)},{maxRow:t,maxCol:o,merges:r}=e,a=r.length,u=this.recorder?.length,h=this.formulasEdited;let c;try{c=i(l)??null}catch(v){throw v instanceof B&&(fe(e,n),e.maxRow=t,e.maxCol=o,this.formulasEdited=h,u!==void 0&&(this.recorder.length=u),this.engine?.cellsChanged(e,n.rows,n.cols,n.count)),v}s!=="entry"&&this.engine?.presentationChanged(),this.engine?.precise&&n.count>0&&ze(this,e,n),(e.merges!==r||r.length!==a)&&this.engine?.mergesChanged(e),e.changes!==null&&n.count>0&&le(this,e,n),n.vms!==null&&Je(e,n);const d=n.count>0&&this.engine?.tables.size>0?ge(this,l,n):null,m=(v,g)=>y=>m(v(y),g(y)),p=c&&d?m(c,d):c??d;return n.count===0&&p===null?null:(e.revision++,this.engine?.cellsChanged(e,n.rows,n.cols,n.count),{sheetIndex:e===this.sheet?this.activeSheet:this.sheets.indexOf(e),sheet:e,log:n,label:s,extra:p,mark:this.textChanges.length})}_runGroup(e,s,i){const n=[],l=this.activeSheet,t=this.recorder?.length,o=this.formulasEdited,r=[];try{for(const a of i){const{maxRow:u,maxCol:h}=a,c=this._runOn(a,e,s);c!==null&&(n.push(c),r.push([a,u,h]))}}catch(a){if(a instanceof B){this.rollbackSlices(n);for(const[u,h,c]of r)u.maxRow=h,u.maxCol=c;this.activeSheet=l,this.formulasEdited=o,t!==void 0&&(this.recorder.length=t)}throw a}return n.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new N,label:e,extra:H(this,n)}}runSlice(e,s,i){const n=this._runOn(e,s,i);return n!==null&&this._emit("cells"),n}pushFolded(e,s,i){e.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(i),sheet:i,log:new N,label:s,extra:H(this,e)})}rollbackSlices(e){for(let s=e.length-1;s>=0;s--)this._restore(e[s]);this._emit("cells")}_pushUndo(e){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(e),this.undoStack.length>(this.historyLimit??Be)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(e){const s=e.sheet??this.sheets[e.sheetIndex],{log:i}=e,n=new N,{merges:l}=s,t=l.length,o=e.mark<this.textChanges.length?this._textInUse():null;if(fe(s,i,n),i.formulas!==null&&this.engine?.arraysRestored(s,i),i.vms!==null){s.valueMeta=new Map(s.valueMeta??[]);for(const[u,h]of i.vms)s.valueMeta.set(i.rows[u]*R+i.cols[u],h)}let r=null;e.extra&&(r=e.extra(s)),o!==null&&this._replayTextChanges(e.mark,o),this.engine?.presentationChanged(),(s.merges!==l||l.length!==t)&&this.engine?.mergesChanged(s),s.changes!==null&&i.count>0&&le(this,s,n),s.revision++,this.engine?.cellsChanged(s,i.rows,i.cols,i.count);const a=this.sheets.indexOf(s);return a>=0&&(this.activeSheet=a),{sheetIndex:a>=0?a:e.sheetIndex,sheet:s,log:n,label:e.label,extra:r,mark:e.mark===void 0?void 0:this.textChanges.length}}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(this._restore(e)),this._emit("cells"),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(this._restore(e)),this._emit("cells"),!0):!1}setInput(e,s,i,n,{overLimitAsText:l=!1,typedQuote:t=!0,invalidAsText:o=!1}={}){const{sheet:r}=e,a=r.style(s,i),{numFmt:u}=this.styles.get(a),h=n!==""&&u==="@",c=Te(n,u);let d=c!==null?{kind:D,value:c,format:Fe(n)}:h?{kind:E,text:n[0]==="'"?n.slice(1):n}:re(n,void 0,this.dateOffset);if(d.kind===F){const p=$e(d.formula);if(p){if(!l)throw new B(p);d={kind:E,text:n}}else o&&this.engine&&!this._reads(d.formula)&&(d={kind:E,text:n})}if(this.recorder){const p=d.kind===E&&n.startsWith("=")&&!h?`'${n}`:n;this.recorder.push(`sheet.setValue(${JSON.stringify(we(s,i))}, ${JSON.stringify(p)});`)}e.saveCell(s,i),r.setFormula(s,i,null);const m=t&&n[0]==="'"&&n.length>1;switch((m||this.styles.get(a).quotePrefix)&&r.setStyle(s,i,this.styles.derive(a,{quotePrefix:m})),d.kind){case I:r.setCell(s,i,I,0);break;case D:r.setCell(s,i,D,d.value),d.format&&Ee(u,d.format)&&r.setStyle(s,i,this.styles.derive(r.style(s,i),{numFmt:d.format}));break;case j:r.setCell(s,i,j,d.value);break;case P:r.setCell(s,i,P,d.value);break;case F:r.setCell(s,i,F|I,0),r.setFormula(s,i,{f:De(this._expandTableRefs(pe(d.formula,this.engine?.tables),r,s,i),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:r.setCell(s,i,E,this.strings.add(oe(d.text)))}}_reads(e){try{return this.engine.validate(e),!0}catch{return!1}}setRichInput(e,s,i,n,l){const{sheet:t}=e;e.saveCell(s,i),t.setFormula(s,i,null);const o=oe(n);t.setCell(s,i,E,this.strings.addRich(o,o===n?l:l?.filter(r=>r.at<o.length)))}_expandTableRefs(e,s,i,n){const l=this.engine;return!l||l.tables.size===0?e:Ne(e,()=>{for(const t of l.tables.values())if(t.sheet===s&&i>=t.r0&&i<=t.r1&&n>=t.c0&&n<=t.c1)return t;return null})}clearRange(e,s="contents",{visibleOnly:i=!1}={}){this.sheet.dataRanges?.cleared(e)||this.transact("clear",n=>{const{sheet:l}=n,t=[];if(s!=="contents")for(const{r0:r,c0:a,r1:u,c1:h}of e){const c=r===0&&u===se-1,d=a===0&&h===R-1,m=(p,v,g,y)=>{for(const[w,k]of[...v])w<g||w>y||(t.push([p,w,k]),v.delete(w))};c&&l.colStyles!==null&&m("col",l.colStyles,a,h),d&&l.rowStyles!==null&&m("row",l.rowStyles,r,u)}const o=i&&l.filteredRows?.size>0?l.filteredRows:null;for(const{r0:r,c0:a,r1:u,c1:h}of e){const c=Math.min(h,l.maxCol),d=Math.min(u,l.maxRow);for(let m=a;m<=c;m++)if(l.columns[m]!==void 0)for(let p=r;p<=d;p++){if(l._chunk(p,m)===void 0){p|=1023;continue}if(o!==null&&o.has(p))continue;const g=l.kind(p,m)!==0,y=l.cellStyle(p,m)!==0;if(s==="formats"){if(!y)continue;n.saveCell(p,m),l.setStyle(p,m,0);continue}!g&&!(s==="all"&&y)||(n.saveCell(p,m),l.setCell(p,m,I,0),l.setFormula(p,m,null),s==="all"&&l.setStyle(p,m,0))}}return t.length>0?J([],t):void 0})}applyStyle(e,s,{measureRow:i,numberFit:n}={}){const l=JSON.stringify(s);if(this.recorder)for(const o of e)this.recorder.push(`sheet.setFormat(${JSON.stringify(ve(o))}, ${l});`);let t=!1;this.transact("format",o=>{const{sheet:r}=o;t=!0,this.strings.rich!==null&&Le(this,o,e,s);const a=[],u=new Set,h=[],c=[],d=(g,y,w)=>{const k=g*2048+y;u.has(k)||(u.add(k),a.push(g,y,w.styles===null?null:w.styles.slice()))},m=(g,y,w)=>{w===0&&(r.rowStyles?.has(g)||r.colStyles?.has(y))&&(w=this.styles.explicitDefault()),r.setStyle(g,y,w)};for(const{r0:g,c0:y,r1:w,c1:k}of e){const M=g===0&&w===se-1,C=y===0&&k===R-1,_=M||C,b=_?Math.min(w,r.maxRow):w,ce=_?Math.min(k,r.maxCol):k;for(let S=y;S<=ce&&g<=b;S++){const x=r.columns[S];if(!(_&&!x))for(let A=g>>>T;A<=b>>>T;A++){const q=A<<T,W=Math.max(g,q),de=Math.min(b,q+Y),V=_?x[A]:r._ensure(W,S);if(!(_&&!V?.styles)){d(S,A,V);for(let U=W;U<=de;U++)(!_||V.styles[U&Y])&&m(U,S,this.styles.derive(r.style(U,S),s,l))}}}const $=S=>this.styles.derive(S,s,l),K=(S,x,A)=>{d(x,S>>>T,r._ensure(S,x)),r.setStyle(S,x,A||this.styles.explicitDefault())};if(C&&M){be(r,$,h);for(const[S,x]of r.rowStyles??[])h.push(["row",S,x]),r.rowStyles.set(S,$(x))}else if(M)for(let S=y;S<=k;S++)ie(r,"col",S,$,h,K);else if(C)for(let S=g;S<=w;S++)ie(r,"row",S,$,h,K)}const p=(g,y,w)=>{const k=r[g];w!==k.sizeOf(y)&&(c.push([g,y,k.isCustom(y)?k.sizeOf(y):null,k.isAuto(y)]),k.setSize(y,w,!0),g==="cols"&&(r.colsChanged=!0))},v=s.fontSize!==void 0||s.wrap!==void 0||s.rotation!==void 0||["justify","distributed"].includes(s.hAlign)||["justify","distributed"].includes(s.vAlign);for(const{r0:g,r1:y,c0:w,c1:k}of e){const M=Math.min(y,r.maxRow);if(v&&M-g<=2e3)for(let C=g;C<=M;C++)p("rows",C,Me(r,this,C,i));if(n)for(const C of n.cols){if(C<w||C>k||!r.columns[C]||r.cols.isCustom(C)&&!r.cols.isAuto(C))continue;let _=r.cols.sizeOf(C);for(const b of n.rows)b>=g&&b<=M&&(r.kind(b,C)&Q)===D&&(_=Math.max(_,n.measure(r,b,C)));p("cols",C,_)}}return J(a,h,c)}),t&&this.engine?.precise&&s.numFmt!==void 0&&this._roundFormatted(e)}_roundFormatted(e){const i=(this.selectedSheets?.size>1?this.sheets.filter(l=>this.selectedSheets.has(l)&&(!l.protection||l===this.sheet)):[this.sheet]).map(l=>this._runOn(l,"precision",t=>{Ie(t,e)})).filter(Boolean),n=this.undoStack.at(-1);i.length===0||n===void 0||(this.undoStack.pop(),this._pushUndo({sheetIndex:this.activeSheet,sheet:this.sheet,log:new N,label:"format",extra:H(this,[n,...i])}))}}function fe(f,e,s){const i=Ge(f);for(let n=e.count-1;n>=0;n--){const l=e.rows[n],t=e.cols[n];s?.push(f,l,t),e.kinds[n]&ee&&!i(l,t)?f.setCell(l,t,I,0):f.setCell(l,t,e.kinds[n],e.values[n]),f.setStyle(l,t,e.styles[n]),f.setFormula(l,t,e.kinds[n]&F?e.formulas.get(n):null)}}function Ge(f){let e=null;return(s,i)=>{if(e===null){e=new Map;for(const t of f.spills?.values()??[])if(!t.blocked)for(let o=t.r0>>>T;o<=t.r1>>>T;o++){let r=e.get(o);r||e.set(o,r=new Map);const a=t.r0===t.r1?[t.r0]:[-1];for(const u of a){const h=r.get(u);h?h.push(t):r.set(u,[t])}}}const n=e.get(s>>>T),l=t=>s>=t.r0&&s<=t.r1&&i>=t.c0&&i<=t.c1;return n!==void 0&&((n.get(s)?.some(l)??!1)||(n.get(-1)?.some(l)??!1))}}function H(f,e){const s=()=>{const i=[];for(let n=e.length-1;n>=0;n--)i.push(f._restore(e[n]));return H(f,i)};return s.parts=e,s}function Je(f,e){let s=null;for(const i of e.vms.keys()){const n=e.rows[i],l=e.cols[i];(f.kind(n,l)&~(X|Z))===e.kinds[i]&&f.value(n,l)===e.values[i]||(s??=new Map(f.valueMeta),s.delete(n*R+l))}s!==null&&(f.valueMeta=s.size>0?s:null)}function Ke(f,e,s,i){if(!e.size||typeof f!="string")return f;let n;try{n=Pe(f)}catch(o){if(o instanceof B)return f;throw o}let l="",t=0;for(let o=0;o<n.length;o++){const r=n[o],a=r.t==="name"?f.slice(r.s,r.e):r.t==="table"?r.v.name:null;if(!a)continue;const u=e.get(a.toUpperCase());if(!u)continue;let h=o-1;for(;n[h]?.t==="ws";)h--;const c=n[h];if(c?.t==="sheet"){const{book:d,sheet:m,sheet2:p}=c.v;if(d!==null||p!==null)continue;if(m.toUpperCase()===s.toUpperCase())l+=f.slice(t,c.s)+ke(i)+"!",t=c.e;else if(m.toUpperCase()!==i.toUpperCase())continue}l+=f.slice(t,r.s)+u.name,t=r.s+a.length}return t?l+f.slice(t):f}function L(f){if(f===null||typeof f!="object")return f;if(Array.isArray(f))return f.map(L);if(f instanceof Map)return new Map([...f].map(([s,i])=>[s,L(i)]));if(f instanceof Set)return new Set([...f].map(L));if(ArrayBuffer.isView(f))return f.slice();const e={};for(const[s,i]of Object.entries(f))!s.startsWith("_")&&typeof i!="function"&&(e[s]=L(i));return e}function J(f,e,s=[]){return i=>{const n=[];for(let o=0;o<f.length;o+=3){const r=f[o],a=f[o+1],u=i.columns[r]?.[a];u!==void 0&&(n.push(r,a,u.styles),u.styles=f[o+2])}const l=[];for(let o=e.length-1;o>=0;o--){const[r,a,u]=e[o];if(r==="columns"){l.push([r,a,i.colStyles]),i.colStyles=u,i.colsChanged=!0;continue}r==="col"&&(i.colsChanged=!0);const h=r==="col"?"colStyles":"rowStyles",c=i[h]??=new Map;l.push([r,a,c.get(a)]),u===void 0?c.delete(a):c.set(a,u)}const t=[];for(let o=s.length-1;o>=0;o--){const[r,a,u,h]=s[o],c=i[r];t.push([r,a,c.isCustom(a)?c.sizeOf(a):null,c.isAuto(a)]),c.setSize(a,u,h),r==="cols"&&(i.colsChanged=!0)}return J(n,l,t)}}export{N as CellLog,He as GROUP_LABELS,mt as Workbook,Ke as copyTableRefs,H as foldEntries,re as parseInput,je as renameInRules,J as swapStyles};
@@ -1 +1 @@
1
- import{CHUNK_BITS as C,CHUNK_MASK as b,CHUNK_SIZE as A,EMPTY as F,NUM as R,Sheet as L}from"../core/sheet.js";import{colName as M}from"../core/address.js";import{Engine as S}from"../calc/engine.js";import{toFileFormula as $}from"../calc/parser.js";import{Arr as D,ERR as _,Lambda as O,Ref as I,RefList as K,XlError as N}from"../calc/values.js";import{extractWindowCalls as T}from"./window.js";const v=()=>({kinds:new Uint8Array(A),values:new Float64Array(A),styles:null});function E(h,e,t){const s=h.table,{kinds:i,values:u}=e,n=Math.min(A,s.rowCount-t),{data:a,kinds:m,isString:r}=h,f=h.type==="boolean";if(n<=0){i.fill(0);return}if(r)for(let o=0;o<n;o++){const l=a[t+o];i[o]=l<0?0:2,u[o]=l}else if(m!==null)for(let o=0;o<n;o++)i[o]=m[t+o],u[o]=a[t+o];else{const o=f?3:R;for(let l=0;l<n;l++){const d=a[t+l];d!==d?i[l]=F:(i[l]=o,u[l]=d)}}if(n<A&&i.fill(0,n),s.deletedCount>0){const{alive:o}=s;for(let l=0;l<n;l++)o[t+l]===0&&(i[l]=F)}}function V(h,e){let t="",s="";for(let i=0;i<h.length;i++){const u=h[i];if(u==='"'){t+=e(s),s="";let n=i+1;for(;!(n>=h.length);)if(h[n]==='"')if(h[n+1]==='"')n+=2;else break;else n++;t+=h.slice(i,n+1),i=n}else s+=u}return t+e(s)}const H=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,B=/\[(@?)\[?([^[\]]+?)\]?\]/g;class Z{constructor(e){this.manager=e,this.engine=null,this.sheets=new Map}_engineFor(){return this.engine===null&&(this.engine=new S({sheets:[],strings:this.manager.strings}),this.engine.legacy=!0),this.engine}_sheet(e){let t=this.sheets.get(e);return t===void 0&&(t=new L(`__data_${e.name}`),this.sheets.set(e,t)),t.maxRow=e.rowCount-1,t.maxCol=e.columns.length-1,t}bind(e){const t=e.table,s=new Set;let i=!1,u=!1;const n=T(String(e.formula).replace(/^=/,""),t,m=>{s.add(m.name),i=!0}),a=V(n,m=>m.replace(H,(r,f,o)=>{const l=o.trim();if(!l.includes("."))return r;const d=t.rollupColumn(f.toUpperCase(),l);return d?(s.add(d.name),`$${M(d.index)}1`):r}).replace(B,(r,f,o)=>{const l=o.trim(),d=t.column(l);if(!d)return u=!0,"#NAME?";s.add(d.name);const y=M(d.index);return f==="@"?`$${y}1`:(i=!0,`$${y}:$${y}`)}));if(e.deps=[...s],e.rangeDep=i,e.stale=!0,e.compiled=null,u){e.compiled={fn:()=>_.NAME,ok:!1};return}try{const r=this._engineFor().template($(a),0,e.index);e.compiled={fn:r.fn,ok:!r.external}}catch{e.compiled={fn:()=>_.NAME,ok:!1}}this._hasCycle(e)&&(e.compiled={fn:()=>_.REF,ok:!1},e.deps=[])}_hasCycle(e){const t=e.table,s=new Set,i=u=>{if(u===e.name)return!0;if(s.has(u))return!1;s.add(u);const n=t.column(u);return n?n.deps.some(i):!1};return e.deps.some(i)}_evaluate(e,t,s,i,u){let n;try{n=e(t,s,i)}catch(a){return a instanceof N?a:_.VALUE}if(n instanceof I||n instanceof K)try{n=u.refAuto(n,t,s)}catch(a){return a instanceof N?a:_.VALUE}return n instanceof D&&(n=n.data[0]),n instanceof O?_.CALC:typeof n=="number"&&!Number.isFinite(n)?_.NUM:n===void 0?null:n}computeAll(e){const t=e.table;e.compiled===null&&this.bind(e);const s=e.deps.map(p=>t.column(p));for(const p of s)t.ensure(p);const i=this._engineFor(),u=this._sheet(t),n=t.rowCount,{fn:a}=e.compiled,m=e.index,r=n+b>>>C,f=u.columns;f.length=0;const o=s.map(()=>v());for(const p of s)f[p.index]=[];if(e.rangeDep)for(const p of s){const x=f[p.index];for(let k=0;k<r;k++){const c=v();E(p,c,k<<C),x[k]=c}}const l=t.alive,d=t.deletedCount>0;e.kinds=null;const y=e.data,w=!e.isString;for(let p=0;p<r;p++){const x=p<<C;if(!e.rangeDep)for(let c=0;c<s.length;c++){const g=f[s[c].index];E(s[c],o[c],x),p>0&&(g[p-1]=void 0),g[p]=o[c]}const k=Math.min(n,x+A);for(let c=x;c<k;c++){if(d&&l[c]===0){e.put(c,null);continue}const g=this._evaluate(a,c,m,u,i);w&&e.kinds===null&&typeof g=="number"?y[c]=g:e.type==="any"||g===null||typeof g=="number"?e.put(c,g):e.put(c,e.type==="any"?g:U(e,g))}}f.length=0}computeRow(e,t){const s=e.table;e.compiled===null&&this.bind(e);const i=e.deps.map(r=>s.column(r));for(const r of i)r.stale&&s.ensure(r);const u=this._engineFor(),n=this._sheet(s),a=n.columns;a.length=0;const m=t>>>C;for(const r of i){const f=v();E(r,f,m<<C),a[r.index]=[],a[r.index][m]=f}if(s.alive[t]===0)e.put(t,null);else{const r=this._evaluate(e.compiled.fn,t,e.index,n,u);e.put(t,typeof r=="number"||r===null||e.type==="any"?r:U(e,r))}e.revision++,a.length=0}evaluateOnce(e,t,s){const i={table:e,index:e.columns.length,formula:s,deps:[],name:"\0temp",compiled:null};this.bind(i);const u=i.deps.map(f=>e.column(f));for(const f of u)e.ensure(f);const n=this._sheet(e),a=n.columns;a.length=0;const m=t>>>C;for(const f of u)if(a[f.index]=[],i.rangeDep){const o=e.rowCount+b>>>C;for(let l=0;l<o;l++){const d=v();E(f,d,l<<C),a[f.index][l]=d}}else{const o=v();E(f,o,m<<C),a[f.index][m]=o}const r=this._evaluate(i.compiled.fn,t,i.index,n,this._engineFor());return a.length=0,r}}function U(h,e){try{return h.coerce(e)}catch{return null}}export{Z as FormulaColumns,E as fillRawChunk};
1
+ import{CHUNK_BITS as C,CHUNK_MASK as b,CHUNK_SIZE as A,EMPTY as F,NUM as R,Sheet as L}from"../core/sheet.js";import{colName as M}from"../core/address.js";import{Engine as S}from"../calc/engine.js";import{toFileFormula as $}from"../calc/parser.js";import{Arr as D,ERR as _,Lambda as O,Ref as I,RefList as K,XlError as N}from"../calc/values.js";import{extractWindowCalls as T}from"./window.js";const v=()=>({kinds:new Uint8Array(A),values:new Float64Array(A),styles:null});function E(h,e,t){const s=h.table,{kinds:i,values:u}=e,n=Math.min(A,s.rowCount-t),{data:f,kinds:m,isString:r}=h,a=h.type==="boolean";if(n<=0){i.fill(0);return}if(r)for(let o=0;o<n;o++){const l=f[t+o];i[o]=l<0?0:2,u[o]=l}else if(m!==null)for(let o=0;o<n;o++)i[o]=m[t+o],u[o]=f[t+o];else{const o=a?3:R;for(let l=0;l<n;l++){const d=f[t+l];d!==d?i[l]=F:(i[l]=o,u[l]=d)}}if(n<A&&i.fill(0,n),s.deletedCount>0){const{alive:o}=s;for(let l=0;l<n;l++)o[t+l]===0&&(i[l]=F)}}function V(h,e){let t="",s="";for(let i=0;i<h.length;i++){const u=h[i];if(u==='"'){t+=e(s),s="";let n=i+1;for(;!(n>=h.length);)if(h[n]==='"')if(h[n+1]==='"')n+=2;else break;else n++;t+=h.slice(i,n+1),i=n}else s+=u}return t+e(s)}const H=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,B=/\[(@?)\[?([^[\]]+?)\]?\]/g;class Z{constructor(e){this.manager=e,this.engine=null,this.sheets=new Map}_engineFor(){return this.engine===null&&(this.engine=new S({sheets:[],strings:this.manager.strings,dateOffset:0}),this.engine.legacy=!0),this.engine}_sheet(e){let t=this.sheets.get(e);return t===void 0&&(t=new L(`__data_${e.name}`),this.sheets.set(e,t)),t.maxRow=e.rowCount-1,t.maxCol=e.columns.length-1,t}bind(e){const t=e.table,s=new Set;let i=!1,u=!1;const n=T(String(e.formula).replace(/^=/,""),t,m=>{s.add(m.name),i=!0}),f=V(n,m=>m.replace(H,(r,a,o)=>{const l=o.trim();if(!l.includes("."))return r;const d=t.rollupColumn(a.toUpperCase(),l);return d?(s.add(d.name),`$${M(d.index)}1`):r}).replace(B,(r,a,o)=>{const l=o.trim(),d=t.column(l);if(!d)return u=!0,"#NAME?";s.add(d.name);const y=M(d.index);return a==="@"?`$${y}1`:(i=!0,`$${y}:$${y}`)}));if(e.deps=[...s],e.rangeDep=i,e.stale=!0,e.compiled=null,u){e.compiled={fn:()=>_.NAME,ok:!1};return}try{const r=this._engineFor().template($(f),0,e.index);e.compiled={fn:r.fn,ok:!r.external}}catch{e.compiled={fn:()=>_.NAME,ok:!1}}this._hasCycle(e)&&(e.compiled={fn:()=>_.REF,ok:!1},e.deps=[])}_hasCycle(e){const t=e.table,s=new Set,i=u=>{if(u===e.name)return!0;if(s.has(u))return!1;s.add(u);const n=t.column(u);return n?n.deps.some(i):!1};return e.deps.some(i)}_evaluate(e,t,s,i,u){let n;try{n=e(t,s,i)}catch(f){return f instanceof N?f:_.VALUE}if(n instanceof I||n instanceof K)try{n=u.refAuto(n,t,s)}catch(f){return f instanceof N?f:_.VALUE}return n instanceof D&&(n=n.data[0]),n instanceof O?_.CALC:typeof n=="number"&&!Number.isFinite(n)?_.NUM:n===void 0?null:n}computeAll(e){const t=e.table;e.compiled===null&&this.bind(e);const s=e.deps.map(p=>t.column(p));for(const p of s)t.ensure(p);const i=this._engineFor(),u=this._sheet(t),n=t.rowCount,{fn:f}=e.compiled,m=e.index,r=n+b>>>C,a=u.columns;a.length=0;const o=s.map(()=>v());for(const p of s)a[p.index]=[];if(e.rangeDep)for(const p of s){const x=a[p.index];for(let k=0;k<r;k++){const c=v();E(p,c,k<<C),x[k]=c}}const l=t.alive,d=t.deletedCount>0;e.kinds=null;const y=e.data,w=!e.isString;for(let p=0;p<r;p++){const x=p<<C;if(!e.rangeDep)for(let c=0;c<s.length;c++){const g=a[s[c].index];E(s[c],o[c],x),p>0&&(g[p-1]=void 0),g[p]=o[c]}const k=Math.min(n,x+A);for(let c=x;c<k;c++){if(d&&l[c]===0){e.put(c,null);continue}const g=this._evaluate(f,c,m,u,i);w&&e.kinds===null&&typeof g=="number"?y[c]=g:e.type==="any"||g===null||typeof g=="number"?e.put(c,g):e.put(c,e.type==="any"?g:U(e,g))}}a.length=0}computeRow(e,t){const s=e.table;e.compiled===null&&this.bind(e);const i=e.deps.map(r=>s.column(r));for(const r of i)r.stale&&s.ensure(r);const u=this._engineFor(),n=this._sheet(s),f=n.columns;f.length=0;const m=t>>>C;for(const r of i){const a=v();E(r,a,m<<C),f[r.index]=[],f[r.index][m]=a}if(s.alive[t]===0)e.put(t,null);else{const r=this._evaluate(e.compiled.fn,t,e.index,n,u);e.put(t,typeof r=="number"||r===null||e.type==="any"?r:U(e,r))}e.revision++,f.length=0}evaluateOnce(e,t,s){const i={table:e,index:e.columns.length,formula:s,deps:[],name:"\0temp",compiled:null};this.bind(i);const u=i.deps.map(a=>e.column(a));for(const a of u)e.ensure(a);const n=this._sheet(e),f=n.columns;f.length=0;const m=t>>>C;for(const a of u)if(f[a.index]=[],i.rangeDep){const o=e.rowCount+b>>>C;for(let l=0;l<o;l++){const d=v();E(a,d,l<<C),f[a.index][l]=d}}else{const o=v();E(a,o,m<<C),f[a.index][m]=o}const r=this._evaluate(i.compiled.fn,t,i.index,n,this._engineFor());return f.length=0,r}}function U(h,e){try{return h.coerce(e)}catch{return null}}export{Z as FormulaColumns,E as fillRawChunk};
@@ -1,2 +1,2 @@
1
1
  import{FORMULA as k,STR as q}from"../core/sheet.js";import{cellRef as B,colName as F,MAX_COLS as m}from"../core/address.js";import{translateFormula as T}from"../core/formula-refs.js";import{createTable as R,resizeTable as v}from"../core/tables.js";import{hookSheet as U,rawCells as p,TableBinding as $,unhookSheet as E,valueOfWrite as L,writeRaw as O}from"./bind.js";import{DataError as S}from"./data.js";import{getPath as y,setPath as w}from"./remote.js";const g=(i,t)=>i*m+t;function _(i){const t=i.book.dataSheets;t&&(t.bindings=t.bindings.filter(e=>e!==i)),i.unbind()}function C(i,t){const e=i.usedRange(),{captions:s,rows:r}=i.exportRows();switch(t){case"json":return JSON.stringify(r,null,2);case"csv":{const o=n=>{const h=n==null?"":String(n);return/[",\n]/.test(h)?`"${h.replace(/"/g,'""')}"`:h};return[s.map(o).join(","),...r.map(n=>s.map(h=>o(n[h])).join(","))].join(`\r
2
- `)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class A{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},U(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,L(this.book.strings,s,r))}}class H extends A{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,M(n),{overLimitAsText:!0})}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const M=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class N extends A{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??z(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((a,l)=>{const f=s.col+l;a.width&&t.cols.setSize(f,a.width),this.headerRows&&p.setCell.call(t,s.row,f,q,e.strings.add(a.caption??M(a.path??`Column${l+1}`)));const b=this._styleOf(a.format);if(a.formula){const d=String(a.formula).replace(/^=/,"");for(let u=0;u<r.length;u++)p.setCell.call(t,n+u,f,k,0),p.setFormula.call(t,n+u,f,{f:T(d,u,0),typed:!0}),b&&p.setStyle.call(t,n+u,f,b);return}for(let d=0;d<r.length;d++){const u=y(r[d],a.path);O(t,e.strings,n+d,f,u===void 0?null:u),b&&t.cellStyle(n+d,f)===0&&p.setStyle.call(t,n+d,f,b)}});for(let a=r.length;a<this.lastRows;a++)for(let l=0;l<o.length;l++)p.setCell.call(t,n+a,s.col+l,0,0),p.setFormula.call(t,n+a,s.col+l,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((a,l)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+l,s.col+l)}),this._notify(c,x),this.table&&this.book.engine){const a=this.anchor,l={r0:a.row,c0:a.col,r1:a.row+Math.max(1,r.length),c1:a.col+o.length-1};this.table.r1!==l.r1&&v(this.book,this.table,l)}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function z(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}N.prototype.exportAs=function(t){return C(this,t)},$.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function I(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=I(e);return t}return null}export{H as CellPathBinding,N as RowsBinding,B as cellRef,F as colName,C as exportBinding,I as sampleOf,j as schemaOf};
2
+ `)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class A{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},U(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,L(this.book.strings,s,r))}}class H extends A{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,M(n),{overLimitAsText:!0})}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const M=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class N extends A{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??z(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((l,a)=>{const u=s.col+a;l.width&&t.cols.setSize(u,l.width),this.headerRows&&p.setCell.call(t,s.row,u,q,e.strings.add(l.caption??M(l.path??`Column${a+1}`)));const b=this._styleOf(l.format);if(l.formula){const d=String(l.formula).replace(/^=/,"");for(let f=0;f<r.length;f++)p.setCell.call(t,n+f,u,k,0),p.setFormula.call(t,n+f,u,{f:T(d,f,0),typed:!0}),b&&p.setStyle.call(t,n+f,u,b);return}for(let d=0;d<r.length;d++){const f=y(r[d],l.path);O(t,e.strings,n+d,u,f===void 0?null:f),b&&t.cellStyle(n+d,u)===0&&p.setStyle.call(t,n+d,u,b)}});for(let l=r.length;l<this.lastRows;l++)for(let a=0;a<o.length;a++)p.setCell.call(t,n+l,s.col+a,0,0),p.setFormula.call(t,n+l,s.col+a,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((l,a)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+a,s.col+a)}),this._notify(c,x),this.table&&this.book.engine){const l=this.anchor,a={r0:l.row,c0:l.col,r1:l.row+Math.max(1,r.length),c1:l.col+o.length-1};this.table.r1!==a.r1&&v(this.book,this.table,a,{cells:!1})}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function z(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}N.prototype.exportAs=function(t){return C(this,t)},$.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function I(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=I(e);return t}return null}export{H as CellPathBinding,N as RowsBinding,B as cellRef,F as colName,C as exportBinding,I as sampleOf,j as schemaOf};
@@ -1,2 +1,2 @@
1
- const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>",`${e}</Types>`)}function L(a,o){let t=a.replace(new RegExp(`<Relationship\\b[^>]*Type="${h(w)}"[^>]*/>`,"g"),"").replace(/<Relationship\b[^>]*Target="\/?(?:\.\.\/)?customXml\/ds8c[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[]){const r=s.replace(/^customXml\//,"");t=t.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*customXml/${h(r)}"[^>]*/>`),"")}const e=(o?.parts??[]).map((s,r)=>`<Relationship Id="rId8cDs${r+1}" Type="${b}" Target="/${s.file}"/>`).join("");return t.replace("</Relationships>",`${e}</Relationships>`)}async function T(a,o){const t=new Uint8Array(262144);let e=0,s=0,r=0,i=0;const f=async()=>{e>0&&(await o(t.slice(0,e)),e=0)};for await(const p of a){let l=0;const d=p.length;if(i>0)if(i===1&&d>=2){const c=s<<16|p[0]<<8|p[1];l=2,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else if(i===2&&d>=1){const c=s<<16|r<<8|p[0];l=1,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else{i===1&&d===1&&(r=p[0],i=2);continue}for(;l+2<d;){e+4>t.length&&await f();const c=p[l]<<16|p[l+1]<<8|p[l+2];t[e]=n[c>>18],t[e+1]=n[c>>12&63],t[e+2]=n[c>>6&63],t[e+3]=n[c&63],e+=4,l+=3}l<d&&(s=p[l],i=1,l+1<d&&(r=p[l+1],i=2)),e+8>t.length&&await f()}i===1?(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4],t[e++]=61,t[e++]=61):i===2&&(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4|r>>4],t[e++]=n[(r&15)<<2],t[e++]=61),await f()}async function*E(a){const o=a.stream().getReader();for(;;){const{done:t,value:e}=await o.read();if(t)return;yield e}}async function N(a,o,t){for(const e of o?.parts??[]){t?.add(e.file);const s=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1
+ const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>",()=>`${e}</Types>`)}function L(a,o){let t=a.replace(new RegExp(`<Relationship\\b[^>]*Type="${h(w)}"[^>]*/>`,"g"),"").replace(/<Relationship\b[^>]*Target="\/?(?:\.\.\/)?customXml\/ds8c[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[]){const r=s.replace(/^customXml\//,"");t=t.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*customXml/${h(r)}"[^>]*/>`),"")}const e=(o?.parts??[]).map((s,r)=>`<Relationship Id="rId8cDs${r+1}" Type="${b}" Target="/${s.file}"/>`).join("");return t.replace("</Relationships>",()=>`${e}</Relationships>`)}async function T(a,o){const t=new Uint8Array(262144);let e=0,s=0,r=0,i=0;const f=async()=>{e>0&&(await o(t.slice(0,e)),e=0)};for await(const p of a){let l=0;const d=p.length;if(i>0)if(i===1&&d>=2){const c=s<<16|p[0]<<8|p[1];l=2,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else if(i===2&&d>=1){const c=s<<16|r<<8|p[0];l=1,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else{i===1&&d===1&&(r=p[0],i=2);continue}for(;l+2<d;){e+4>t.length&&await f();const c=p[l]<<16|p[l+1]<<8|p[l+2];t[e]=n[c>>18],t[e+1]=n[c>>12&63],t[e+2]=n[c>>6&63],t[e+3]=n[c&63],e+=4,l+=3}l<d&&(s=p[l],i=1,l+1<d&&(r=p[l+1],i=2)),e+8>t.length&&await f()}i===1?(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4],t[e++]=61,t[e++]=61):i===2&&(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4|r>>4],t[e++]=n[(r&15)<<2],t[e++]=61),await f()}async function*E(a){const o=a.stream().getReader();for(;;){const{done:t,value:e}=await o.read();if(t)return;yield e}}async function N(a,o,t){for(const e of o?.parts??[]){t?.add(e.file);const s=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
2
  <d xmlns="${x}" n="${e.name}" b="${e.bytes}">`;await a.add(e.file,async r=>{await r(m.encode(s)),await T(E(e.blob),r),await r(m.encode("</d>"))},{large:e.blob.size>2952790016})}}export{y as CUSTOM_XML_TYPE,S as MANIFEST_NAME,x as NS,X as partFileName,D as patchDataSheetContentTypes,L as patchDataSheetWorkbookRels,C as skipOldDataSheetParts,N as writeDataSheetParts};