@8sheets/data-grid 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) 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/calcx/lang/convert.js +1 -1
  28. package/cells/axis-ops.js +1 -1
  29. package/cells/book-css.js +7 -2
  30. package/cells/cell-styles-xml.js +1 -1
  31. package/cells/cf-engine.js +1 -1
  32. package/cells/cf-file.js +1 -1
  33. package/cells/docprops-xml.js +2 -2
  34. package/cells/filter-eval.js +1 -0
  35. package/cells/filter-file.js +1 -1
  36. package/cells/find-engine.js +2 -2
  37. package/cells/find.js +1 -1
  38. package/cells/goto.js +1 -1
  39. package/cells/link-model.js +1 -0
  40. package/cells/name-box.js +1 -1
  41. package/cells/note-box.js +3 -0
  42. package/cells/options.js +1 -1
  43. package/cells/outline-column.js +1 -1
  44. package/cells/protected-menu.js +1 -0
  45. package/cells/rich-data-xml.js +1 -1
  46. package/cells/selection-modes.js +1 -1
  47. package/cells/sheet-views-file.js +2 -0
  48. package/cells/shift-check.js +1 -1
  49. package/cells/sort-compare.js +1 -0
  50. package/cells/ui-kit.js +1 -1
  51. package/cells/undo-group.js +1 -1
  52. package/celltypes/dropdowns.js +2 -2
  53. package/core/address.js +1 -1
  54. package/core/autofill.js +1 -1
  55. package/core/axis.js +1 -1
  56. package/core/cond-format.js +1 -1
  57. package/core/culture.js +5 -1
  58. package/core/custom-views.js +1 -1
  59. package/core/data-tools.js +1 -0
  60. package/core/date-codes.js +1 -0
  61. package/core/default-names.js +1 -1
  62. package/core/edit-ranges.js +1 -0
  63. package/core/formula-refs.js +1 -1
  64. package/core/host-rules.js +1 -0
  65. package/core/input.js +1 -1
  66. package/core/numfmt.js +1 -1
  67. package/core/precision.js +1 -0
  68. package/core/protection.js +1 -1
  69. package/core/region-input.js +1 -1
  70. package/core/rule-refs.js +1 -0
  71. package/core/shared-view.js +1 -0
  72. package/core/sheet.js +1 -1
  73. package/core/sparklines.js +1 -1
  74. package/core/sparse.js +1 -1
  75. package/core/spills.js +1 -0
  76. package/core/strings.js +1 -1
  77. package/core/structure.js +1 -1
  78. package/core/table-columns.js +1 -0
  79. package/core/tables.js +2 -2
  80. package/core/validation-ranges.js +1 -1
  81. package/core/whatif.js +1 -1
  82. package/core/workbook.js +1 -1
  83. package/datasheets/formula.js +1 -1
  84. package/datasheets/manager.js +1 -1
  85. package/datasheets/path-binding.js +1 -1
  86. package/datasheets/persist-writer.js +1 -1
  87. package/datasheets/persist.js +1 -1
  88. package/datasheets/report.js +1 -1
  89. package/extras/getdata/persist.js +2 -2
  90. package/extras/getdata/rows.js +1 -1
  91. package/extras/getdata/shared-steps.js +1 -0
  92. package/extras/getdata/steps-formula.js +1 -0
  93. package/extras/getdata/steps-more.js +1 -0
  94. package/extras/getdata/steps-tables.js +1 -0
  95. package/extras/getdata/steps.js +1 -1
  96. package/i18n/de/a11y.js +1 -0
  97. package/i18n/de/cells.js +2 -0
  98. package/i18n/de/charts.js +1 -0
  99. package/i18n/de/common.js +1 -0
  100. package/i18n/de/datasheets.js +1 -0
  101. package/i18n/de/format.js +1 -0
  102. package/i18n/de/misc.js +1 -0
  103. package/i18n/de/pivot.js +1 -0
  104. package/i18n/de/proofing.js +1 -0
  105. package/i18n/de/ribbon.js +1 -0
  106. package/i18n/de/shapes.js +1 -0
  107. package/i18n/de/shell.js +3 -0
  108. package/i18n/de/touch.js +1 -0
  109. package/i18n/de.js +1 -0
  110. package/i18n/en/cells.js +2 -1
  111. package/i18n/en/charts.js +1 -1
  112. package/i18n/en/format.js +1 -1
  113. package/i18n/en/misc.js +1 -1
  114. package/i18n/en/pivot.js +1 -1
  115. package/i18n/en/proofing.js +1 -1
  116. package/i18n/en/ribbon.js +1 -1
  117. package/i18n/en/shapes.js +1 -1
  118. package/i18n/en/shell.js +3 -2
  119. package/i18n/en/touch.js +1 -1
  120. package/i18n/es/a11y.js +1 -0
  121. package/i18n/es/cells.js +2 -0
  122. package/i18n/es/charts.js +1 -0
  123. package/i18n/es/common.js +1 -0
  124. package/i18n/es/datasheets.js +1 -0
  125. package/i18n/es/format.js +1 -0
  126. package/i18n/es/misc.js +1 -0
  127. package/i18n/es/pivot.js +1 -0
  128. package/i18n/es/proofing.js +1 -0
  129. package/i18n/es/ribbon.js +1 -0
  130. package/i18n/es/shapes.js +1 -0
  131. package/i18n/es/shell.js +3 -0
  132. package/i18n/es/touch.js +1 -0
  133. package/i18n/es.js +1 -0
  134. package/i18n/fr/a11y.js +1 -0
  135. package/i18n/fr/cells.js +2 -0
  136. package/i18n/fr/charts.js +1 -0
  137. package/i18n/fr/common.js +1 -0
  138. package/i18n/fr/datasheets.js +1 -0
  139. package/i18n/fr/format.js +1 -0
  140. package/i18n/fr/misc.js +1 -0
  141. package/i18n/fr/pivot.js +1 -0
  142. package/i18n/fr/proofing.js +1 -0
  143. package/i18n/fr/ribbon.js +1 -0
  144. package/i18n/fr/shapes.js +1 -0
  145. package/i18n/fr/shell.js +3 -0
  146. package/i18n/fr/touch.js +1 -0
  147. package/i18n/fr.js +1 -0
  148. package/i18n/index.js +1 -1
  149. package/i18n/languages.js +1 -1
  150. package/i18n/pl/cells.js +2 -1
  151. package/i18n/pl/charts.js +1 -1
  152. package/i18n/pl/format.js +1 -1
  153. package/i18n/pl/misc.js +1 -1
  154. package/i18n/pl/pivot.js +1 -1
  155. package/i18n/pl/proofing.js +1 -1
  156. package/i18n/pl/ribbon.js +1 -1
  157. package/i18n/pl/shapes.js +1 -1
  158. package/i18n/pl/shell.js +3 -2
  159. package/i18n/pl/touch.js +1 -1
  160. package/io/blob-sink.js +1 -0
  161. package/io/canonical-xml.js +1 -0
  162. package/io/client.js +1 -1
  163. package/io/crypto/cfb-build.js +1 -0
  164. package/io/crypto/cfb-read.js +1 -1
  165. package/io/crypto/cfb-write.js +1 -1
  166. package/io/crypto/errors.js +1 -1
  167. package/io/csv.js +8 -8
  168. package/io/encoding.js +1 -0
  169. package/io/foreign-sheets.js +2 -2
  170. package/io/io.worker.js +1 -1
  171. package/io/open-package.js +1 -0
  172. package/io/package-paths.js +1 -1
  173. package/io/plan.js +1 -1
  174. package/io/text-split.js +3 -3
  175. package/io/xls/chart-sheet.js +1 -0
  176. package/io/xls/chart.js +1 -0
  177. package/io/xls/crypt.js +1 -0
  178. package/io/xls/dml-color.js +1 -0
  179. package/io/xls/drawing.js +1 -0
  180. package/io/xls/formula.js +1 -0
  181. package/io/xls/geometry.js +1 -0
  182. package/io/xls/index.js +1 -0
  183. package/io/xls/pictures.js +1 -0
  184. package/io/xls/pivot.js +1 -0
  185. package/io/xls/props.js +1 -0
  186. package/io/xls/records.js +1 -0
  187. package/io/xls/shapes.js +1 -0
  188. package/io/xls/sheet-ext.js +1 -0
  189. package/io/xls/sheet.js +1 -0
  190. package/io/xls/styles.js +1 -0
  191. package/io/xls/vba.js +1 -0
  192. package/io/xls/workbook.js +1 -0
  193. package/io/xlsb/filter.js +1 -0
  194. package/io/xlsb/formula.js +2 -0
  195. package/io/xlsb/functions.js +1 -0
  196. package/io/xlsb/index.js +1 -0
  197. package/io/xlsb/parts.js +1 -0
  198. package/io/xlsb/pivot.js +1 -0
  199. package/io/xlsb/records.js +1 -0
  200. package/io/xlsb/sheet-ext.js +1 -0
  201. package/io/xlsb/sheet.js +1 -0
  202. package/io/xlsb/slicer.js +1 -0
  203. package/io/xlsb/styles.js +1 -0
  204. package/io/xlsb/workbook.js +1 -0
  205. package/io/xlsb/xml.js +2 -0
  206. package/io/xlsx-read.js +1 -1
  207. package/io/xlsx-styles.js +2 -2
  208. package/io/xlsx-tail.js +1 -1
  209. package/io/xlsx-write.js +2 -2
  210. package/io/xml-escape.js +1 -1
  211. package/io/xml-scan.js +2 -2
  212. package/io/zip-reader.js +1 -1
  213. package/objects/chart-model.js +1 -1
  214. package/objects/drawing-xml.js +1 -1
  215. package/package.json +1 -1
  216. package/pivot/calc-items.js +1 -0
  217. package/pivot/engine.js +1 -1
  218. package/pivot/xml.js +2 -2
  219. package/print/note-pages.js +2 -0
  220. package/print/page-setup.js +1 -1
  221. package/print/paginate.js +1 -1
  222. package/print/pdf-crypt.js +1 -0
  223. package/print/pdf-links.js +1 -0
  224. package/print/pdf-tags.js +1 -0
  225. package/print/pdf.js +24 -13
  226. package/print/render-page.js +3 -3
  227. package/print/shown-notes.js +1 -0
  228. package/shapes/form-xml.js +1 -1
  229. package/slicers/custom-styles.js +1 -1
  230. package/slicers/format.js +1 -1
  231. package/slicers/structured.js +1 -1
  232. package/slicers/write.js +1 -1
  233. package/table-view/files.js +1 -1
  234. package/table-view/mount.js +1 -1
  235. package/table-view/version.js +1 -1
  236. package/ui/dialogs.js +3 -3
  237. package/ui/icons.js +1 -1
  238. package/ui/menu-base.js +1 -1
  239. package/ui/protection-ui.js +1 -1
package/core/sheet.js CHANGED
@@ -1 +1 @@
1
- import{Axis as w}from"./axis.js";import{MAX_COLS as I,MAX_ROWS as A}from"./address.js";import{FormulaStore as S}from"./formula-store.js";const u=10,M=1<<u,g=M-1,H=0,O=1,V=2,Y=3,j=4,W=8,X=16,Z=32,b=64,K=7,N=15,q=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#GETTING_DATA","#SPILL!","#CALC!","#BUSY!","#CONNECT!","#BLOCKED!","#FIELD!","#UNKNOWN!"];class z{constructor(){this.kinds=new Uint8Array(M),this.values=new Float64Array(M),this.styles=null}}function E(m,t,e,s,n,l){const i=(f,d)=>{if(!s||f<0||f>=e||s.sizeOf(f)>0)return f;const x=s.offsetOf(f)-(d<0?1:0);return x<0?-1:x>=s.total?e:s.indexAt(x)},r=i(t>0?e-1:0,-t);if((r-m)*t<=0)return m;let o=i(m+t,t);if(n(m)&&n(o)){for(;o!==r;){const f=i(o+t,t);if(!n(f))break;o=f}return o}for(;(r-o)*t>=0;){if(n(o))return o;o=i(l(o),t)}return r}let D=1;class J{constructor(t){this.uid=D++,this.name=t,this.rowExtras=null,this.colExtras=null,this.valueMeta=null,this.columns=[],this.maxRow=-1,this.maxCol=-1,this.rows=new w(A,16),this.cols=new w(I,65),this._formulas=new S,this.spills=null,this.rowStyles=null,this.colStyles=null,this.merges=[],this.cellTypeRules=null,this.cellTypes=null,this.sparkRules=null,this.cellDropdowns=null,this.cellTags=null,this.cellPicOpts=null,this.cellButtons=null,this.cellStates=null,this.changes=null,this.autoMerges=null,this.background=null,this.outlineColumn=null,this.split=null,this.frozenTrailingRows=0,this.frozenTrailingCols=0,this.axisSizing=null,this.hideZeros=!1,this.mergeIndex=null,this.frozenRows=0,this.frozenCols=0,this.showGridlines=!0,this.zoom=1,this.sourceId=null,this.revision=0}_chunk(t,e){const s=this.columns[e];return s===void 0?void 0:s[t>>>u]}_ensure(t,e){let s=this.columns[e];s===void 0&&(s=[],this.columns[e]=s);const n=t>>>u;let l=s[n];return l===void 0&&(l=new z,s[n]=l),l}kind(t,e){const s=this._chunk(t,e);return s===void 0?0:s.kinds[t&g]}value(t,e){const s=this._chunk(t,e);return s===void 0?0:s.values[t&g]}style(t,e){const s=this._chunk(t,e);if(s!==void 0&&s.styles!==null){const n=s.styles[t&g];if(n!==0)return n}if(this.rowStyles!==null){const n=this.rowStyles.get(t);if(n!==void 0)return n}if(this.colStyles!==null){const n=this.colStyles.get(e);if(n!==void 0)return n}return 0}cellStyle(t,e){const s=this._chunk(t,e);return s===void 0||s.styles===null?0:s.styles[t&g]}get formulas(){return this._formulas}set formulas(t){this._formulas=t instanceof S?t:S.from(t)}formula(t,e){return this._formulas.at(t,e)}setCell(t,e,s,n){const l=this._ensure(t,e),i=t&g;if(this.valueListeners&&(l.kinds[i]!==s||l.values[i]!==n))for(const r of this.valueListeners)r(t,e,t,e);l.kinds[i]=s,l.values[i]=n,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setStyle(t,e,s){const n=this._ensure(t,e);if(n.styles===null){if(s===0)return;n.styles=new Uint16Array(M)}n.styles[t&g]=s,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setFormula(t,e,s){s?this._formulas.put(t,e,s):this._formulas.remove(t,e)}applyBatch(t){const{rows:e,cols:s,kinds:n,values:l,styles:i,count:r}=t;let o=-1,f=-1,d=null,x=this.maxRow,p=this.maxCol;for(let h=0;h<r;h++){const c=e[h],a=s[h],k=c>>>u;(a!==o||k!==f)&&(d=this._ensure(c,a),o=a,f=k);const y=c&g;d.kinds[y]=n[h],d.values[y]=l[h];const _=i[h];_!==0&&(d.styles===null&&(d.styles=new Uint16Array(M)),d.styles[y]=_),a>p&&(p=a)}if(this.valueListeners)for(const h of this.valueListeners)for(let c=0;c<r;c++)h(e[c],s[c],e[c],s[c]);if(r>0&&e[r-1]>x&&(x=e[r-1]),this.maxRow=x,this.maxCol=p,t.formulas){const h=this._formulas;for(const[c,a]of t.formulas)h.set(c,a)}if(t.valueMeta){this.valueMeta===null&&(this.valueMeta=new Map);for(const[h,c]of t.valueMeta)this.valueMeta.set(h,c)}this.revision++}addMerge(t){this.merges.push(t),this.mergeIndex=null}removeMergesIn(t){const e=this.merges.length;this.merges=this.merges.filter(s=>!B(s,t)),this.merges.length!==e&&(this.mergeIndex=null)}_buildMergeIndex(){const t=new Map;for(const e of this.merges)for(let s=e.r0>>>u;s<=e.r1>>>u;s++){const n=t.get(s);n?n.push(e):t.set(s,[e])}this.mergeIndex=t}mergeAt(t,e){if(this.merges.length===0)return null;this.mergeIndex===null&&this._buildMergeIndex();const s=this.mergeIndex.get(t>>>u);if(s===void 0)return null;for(let n=0;n<s.length;n++){const l=s[n];if(t>=l.r0&&t<=l.r1&&e>=l.c0&&e<=l.c1)return l}return null}mergesInRows(t,e){if(this.merges.length===0)return[];this.mergeIndex===null&&this._buildMergeIndex();const s=new Set;for(let n=t>>>u;n<=e>>>u;n++){const l=this.mergeIndex.get(n);if(l)for(const i of l)i.r1>=t&&i.r0<=e&&s.add(i)}return[...s]}jumpRow(t,e,s,n=!1){const l=this.columns[e],i=o=>{const f=l?.[o>>>u];return f!==void 0&&(f.kinds[o&g]&N)!==0},r=o=>l?.[o>>>u]!==void 0?o+s:s>0?(o>>>u)+1<<u:(o>>>u<<u)-1;return E(t,s,n?this.rows.count:A,n&&this.rows,i,r)}jumpCol(t,e,s,n=!1){const l=r=>(this.kind(t,r)&N)!==0,i=r=>s>0&&r>=this.maxCol?I:r+s;return E(e,s,n?this.cols.count:I,n&&this.cols,l,i)}aggregate(t){let e=0,s=0,n=0,l=1/0,i=-1/0;for(const{r0:r,c0:o,r1:f,c1:d}of t){const x=Math.min(d,this.maxCol),p=Math.min(f,this.maxRow);for(let h=o;h<=x;h++){const c=this.columns[h];if(c!==void 0)for(let a=r>>>u;a<=p>>>u;a++){const k=c[a];if(k===void 0)continue;const y=a<<u,_=Math.max(r-y,0),L=Math.min(p-y,g),{kinds:T,values:U}=k;for(let R=_;R<=L;R++){const v=T[R]&K;if(v!==0&&(n++,v===O)){const C=U[R];e+=C,s++,C<l&&(l=C),C>i&&(i=C)}}}}}return{sum:e,numeric:s,filled:n,min:l,max:i}}}function B(m,t){return m.r0<=t.r1&&m.r1>=t.r0&&m.c0<=t.c1&&m.c1>=t.c0}export{Y as BOOL,u as CHUNK_BITS,g as CHUNK_MASK,M as CHUNK_SIZE,N as CONTENT_MASK,Z as DIRTY,H as EMPTY,j as ERR,q as ERRORS,b as EVALUATING,W as FORMULA,K as KIND_MASK,O as NUM,X as SPILL,V as STR,J as Sheet,B as rangesTouch};
1
+ import{Axis as w}from"./axis.js";import{MAX_COLS as I,MAX_ROWS as A}from"./address.js";import{FormulaStore as S}from"./formula-store.js";const u=10,M=1<<u,g=M-1,H=0,O=1,V=2,Y=3,j=4,W=8,X=16,Z=32,b=64,z=7,L=15,q=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#GETTING_DATA","#SPILL!","#CALC!","#BUSY!","#CONNECT!","#BLOCKED!","#FIELD!","#UNKNOWN!"];class K{constructor(){this.kinds=new Uint8Array(M),this.values=new Float64Array(M),this.styles=null}}function N(m,t,e,s,n,l){const i=(f,d)=>{if(!s||f<0||f>=e||s.sizeOf(f)>0)return f;const x=s.offsetOf(f)-(d<0?1:0);return x<0?-1:x>=s.total?e:s.indexAt(x)},r=i(t>0?e-1:0,-t);if((r-m)*t<=0)return m;let o=i(m+t,t);if(n(m)&&n(o)){for(;o!==r;){const f=i(o+t,t);if(!n(f))break;o=f}return o}for(;(r-o)*t>=0;){if(n(o))return o;o=i(l(o),t)}return r}let D=1;class J{constructor(t){this.uid=D++,this.name=t,this.rowExtras=null,this.colExtras=null,this.valueMeta=null,this.columns=[],this.maxRow=-1,this.maxCol=-1,this.rows=new w(A,16),this.cols=new w(I,65),this._formulas=new S,this.spills=null,this.rowStyles=null,this.colStyles=null,this.merges=[],this.cellTypeRules=null,this.cellTypes=null,this.sparkRules=null,this.cellDropdowns=null,this.cellTags=null,this.cellPicOpts=null,this.cellButtons=null,this.cellStates=null,this.hostRules=null,this.changes=null,this.autoMerges=null,this.background=null,this.outlineColumn=null,this.split=null,this.frozenTrailingRows=0,this.frozenTrailingCols=0,this.axisSizing=null,this.hideZeros=!1,this.mergeIndex=null,this.frozenRows=0,this.frozenCols=0,this.frozenTop=0,this.frozenLeft=0,this.showGridlines=!0,this.zoom=1,this.sourceId=null,this.revision=0}_chunk(t,e){const s=this.columns[e];return s===void 0?void 0:s[t>>>u]}_ensure(t,e){let s=this.columns[e];s===void 0&&(s=[],this.columns[e]=s);const n=t>>>u;let l=s[n];return l===void 0&&(l=new K,s[n]=l),l}kind(t,e){const s=this._chunk(t,e);return s===void 0?0:s.kinds[t&g]}value(t,e){const s=this._chunk(t,e);return s===void 0?0:s.values[t&g]}style(t,e){const s=this._chunk(t,e);if(s!==void 0&&s.styles!==null){const n=s.styles[t&g];if(n!==0)return n}if(this.rowStyles!==null){const n=this.rowStyles.get(t);if(n!==void 0)return n}if(this.colStyles!==null){const n=this.colStyles.get(e);if(n!==void 0)return n}return 0}cellStyle(t,e){const s=this._chunk(t,e);return s===void 0||s.styles===null?0:s.styles[t&g]}get formulas(){return this._formulas}set formulas(t){this._formulas=t instanceof S?t:S.from(t)}formula(t,e){return this._formulas.at(t,e)}setCell(t,e,s,n){const l=this._ensure(t,e),i=t&g;if(this.valueListeners&&(l.kinds[i]!==s||l.values[i]!==n))for(const r of this.valueListeners)r(t,e,t,e);l.kinds[i]=s,l.values[i]=n,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setStyle(t,e,s){const n=this._ensure(t,e);if(n.styles===null){if(s===0)return;n.styles=new Uint16Array(M)}n.styles[t&g]=s,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setFormula(t,e,s){s?this._formulas.put(t,e,s):this._formulas.remove(t,e)}applyBatch(t){const{rows:e,cols:s,kinds:n,values:l,styles:i,count:r}=t;let o=-1,f=-1,d=null,x=this.maxRow,p=this.maxCol;for(let h=0;h<r;h++){const c=e[h],a=s[h],k=c>>>u;(a!==o||k!==f)&&(d=this._ensure(c,a),o=a,f=k);const y=c&g;d.kinds[y]=n[h],d.values[y]=l[h];const R=i[h];R!==0&&(d.styles===null&&(d.styles=new Uint16Array(M)),d.styles[y]=R),a>p&&(p=a)}if(this.valueListeners)for(const h of this.valueListeners)for(let c=0;c<r;c++)h(e[c],s[c],e[c],s[c]);if(r>0&&e[r-1]>x&&(x=e[r-1]),this.maxRow=x,this.maxCol=p,t.formulas){const h=this._formulas;for(const[c,a]of t.formulas)h.set(c,a)}if(t.valueMeta){this.valueMeta===null&&(this.valueMeta=new Map);for(const[h,c]of t.valueMeta)this.valueMeta.set(h,c)}this.revision++}addMerge(t){this.merges.push(t),this.mergeIndex=null}removeMergesIn(t){const e=this.merges.length;this.merges=this.merges.filter(s=>!B(s,t)),this.merges.length!==e&&(this.mergeIndex=null)}_buildMergeIndex(){const t=new Map;for(const e of this.merges)for(let s=e.r0>>>u;s<=e.r1>>>u;s++){const n=t.get(s);n?n.push(e):t.set(s,[e])}this.mergeIndex=t}mergeAt(t,e){if(this.merges.length===0)return null;this.mergeIndex===null&&this._buildMergeIndex();const s=this.mergeIndex.get(t>>>u);if(s===void 0)return null;for(let n=0;n<s.length;n++){const l=s[n];if(t>=l.r0&&t<=l.r1&&e>=l.c0&&e<=l.c1)return l}return null}mergesInRows(t,e){if(this.merges.length===0)return[];this.mergeIndex===null&&this._buildMergeIndex();const s=new Set;for(let n=t>>>u;n<=e>>>u;n++){const l=this.mergeIndex.get(n);if(l)for(const i of l)i.r1>=t&&i.r0<=e&&s.add(i)}return[...s]}jumpRow(t,e,s,n=!1){const l=this.columns[e],i=o=>{const f=l?.[o>>>u];return f!==void 0&&(f.kinds[o&g]&L)!==0},r=o=>l?.[o>>>u]!==void 0?o+s:s>0?(o>>>u)+1<<u:(o>>>u<<u)-1;return N(t,s,n?this.rows.count:A,n&&this.rows,i,r)}jumpCol(t,e,s,n=!1){const l=r=>(this.kind(t,r)&L)!==0,i=r=>s>0&&r>=this.maxCol?I:r+s;return N(e,s,n?this.cols.count:I,n&&this.cols,l,i)}aggregate(t){let e=0,s=0,n=0,l=1/0,i=-1/0;for(const{r0:r,c0:o,r1:f,c1:d}of t){const x=Math.min(d,this.maxCol),p=Math.min(f,this.maxRow);for(let h=o;h<=x;h++){const c=this.columns[h];if(c!==void 0)for(let a=r>>>u;a<=p>>>u;a++){const k=c[a];if(k===void 0)continue;const y=a<<u,R=Math.max(r-y,0),E=Math.min(p-y,g),{kinds:T,values:U}=k;for(let _=R;_<=E;_++){const v=T[_]&z;if(v!==0&&(n++,v===O)){const C=U[_];e+=C,s++,C<l&&(l=C),C>i&&(i=C)}}}}}return{sum:e,numeric:s,filled:n,min:l,max:i}}}function B(m,t){return m.r0<=t.r1&&m.r1>=t.r0&&m.c0<=t.c1&&m.c1>=t.c0}export{Y as BOOL,u as CHUNK_BITS,g as CHUNK_MASK,M as CHUNK_SIZE,L as CONTENT_MASK,Z as DIRTY,H as EMPTY,j as ERR,q as ERRORS,b as EVALUATING,W as FORMULA,z as KIND_MASK,O as NUM,X as SPILL,V as STR,J as Sheet,B as rangesTouch};
@@ -1 +1 @@
1
- import{cellRef as C,parseCellRef as E,parseRangeRef as G,sheetPrefix as O}from"./address.js";import{child as y,children as T,parseTree as R}from"../io/xml-scan.js";import{escapeMarkup as d}from"../io/xml-escape.js";const b=new TextEncoder,u=e=>e==="1"||e==="true";function _(e,i){const r=e.indexOf("sparklineGroups");if(r<0)return[];const o=e.lastIndexOf("<",r),l=e.indexOf("sparklineGroups>",r+16);if(o<0||l<0)return[];const s=e.slice(o,l+16);let t;try{t=R(b.encode(`<r xmlns:x14="x" xmlns:xm="m">${s}</r>`))}catch{return[]}const h=y(t,"sparklineGroups");return T(h,"sparklineGroup").map(a=>{const n=a.a,p={},c=(f,L)=>{const A=y(a,f),w=i(A)??L;return A&&w&&(p[f]={hex:w,attrs:Object.entries(A.a??{}).map(([M,v])=>`${M}="${d(v)}"`).join(" ")}),w},m=f=>f===void 0||f===""||!Number.isFinite(Number(f))?void 0:Number(f),k=c("colorSeries","#376092"),$=c("colorNegative","#D00000"),x=c("colorMarkers","#D00000");return{type:n.type??"line",markers:u(n.markers),high:u(n.high),low:u(n.low),first:u(n.first),last:u(n.last),negative:u(n.negative),lineWeight:Number(n.lineWeight??.75),seriesColor:k,negativeColor:$,markerColor:x,axisColor:c("colorAxis","#000000"),firstColor:c("colorFirst",x),lastColor:c("colorLast",x),highColor:c("colorHigh",x),lowColor:c("colorLow",x),displayXAxis:u(n.displayXAxis),displayHidden:u(n.displayHidden),rightToLeft:u(n.rightToLeft),displayEmptyCellsAs:n.displayEmptyCellsAs??"zero",dateAxis:u(n.dateAxis),dateRange:y(a,"f")?.t??null,minAxisType:n.minAxisType??"individual",maxAxisType:n.maxAxisType??"individual",manualMin:m(n.manualMin),manualMax:m(n.manualMax),rawColors:p,items:T(y(a,"sparklines"),"sparkline").map(f=>({source:y(f,"f")?.t??"",cell:y(f,"sqref")?.t??""}))}})}const F=[["colorSeries","seriesColor"],["colorNegative","negativeColor"],["colorAxis","axisColor"],["colorMarkers","markerColor"],["colorFirst","firstColor"],["colorLast","lastColor"],["colorHigh","highColor"],["colorLow","lowColor"]],I=e=>`FF${String(e).slice(1,7).toUpperCase()}`;function S(e){const i=[];e.manualMax!==void 0&&e.maxAxisType==="custom"&&i.push(`manualMax="${e.manualMax}"`),e.manualMin!==void 0&&e.minAxisType==="custom"&&i.push(`manualMin="${e.manualMin}"`),e.lineWeight!==void 0&&e.lineWeight!==.75&&i.push(`lineWeight="${e.lineWeight}"`),e.type!=="line"&&i.push(`type="${d(e.type)}"`),e.dateAxis&&e.dateRange&&i.push('dateAxis="1"'),i.push(`displayEmptyCellsAs="${d(e.displayEmptyCellsAs??"gap")}"`);for(const s of["markers","high","low","first","last","negative","displayXAxis","displayHidden"])e[s]&&i.push(`${s}="1"`);e.minAxisType&&e.minAxisType!=="individual"&&i.push(`minAxisType="${d(e.minAxisType)}"`),e.maxAxisType&&e.maxAxisType!=="individual"&&i.push(`maxAxisType="${d(e.maxAxisType)}"`),e.rightToLeft&&i.push('rightToLeft="1"');const r=F.map(([s,t])=>{const h=e[t]??(t==="axisColor"?"#000000":e.markerColor),a=e.rawColors?.[s];return`<x14:${s} ${a&&a.hex===h&&a.attrs?a.attrs:`rgb="${I(h)}"`}/>`}).join(""),o=e.dateAxis&&e.dateRange?`<xm:f>${d(e.dateRange)}</xm:f>`:"",l=e.items.map(s=>`<x14:sparkline><xm:f>${d(s.source)}</xm:f><xm:sqref>${d(s.cell)}</xm:sqref></x14:sparkline>`).join("");return`<x14:sparklineGroup ${i.join(" ")}>${r}${o}<x14:sparklines>${l}</x14:sparklines></x14:sparklineGroup>`}function N(e){return e.length===0?"":`<ext xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" uri="{05C60535-1F16-4fd2-B633-F4F36F0B64E0}"><x14:sparklineGroups xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">${e.map(S).join("")}</x14:sparklineGroups></ext>`}function H(e,i){const r=e.replace(/<ext\b[^>]*>\s*<x14:sparklineGroups[\s\S]*?<\/x14:sparklineGroups>\s*<\/ext>/,""),o=N(i),l=/<\/extLst>\s*(?:<\/worksheet>\s*)?$/.exec(r);if(!o)return l?r.replace(/<extLst>\s*<\/extLst>(\s*(?:<\/worksheet>\s*)?)$/,"$1"):r;if(l)return`${r.slice(0,l.index)}${o}${r.slice(l.index)}`;const s=r.lastIndexOf("</worksheet>"),t=`<extLst>${o}</extLst>`;return s>=0?r.slice(0,s)+t+r.slice(s):r+t}function X(e){if(e._sparkIndex&&e._sparkIndexOf===e.sparklines)return e._sparkIndex;const i=new Map;for(const r of e.sparklines??[])for(const o of r.items){const l=E(o.cell);l&&i.set(l.row*16384+l.col,{group:r,source:o.source})}return e._sparkIndex=i,e._sparkIndexOf=e.sparklines,i}function q(e,i,r,o){const l=[],s=G(r.replace(/^.*!/,"").replace(/\$/g,""));if(s===null)return!1;const t=s.r1-s.r0+1,h=s.c1-s.c0+1,a=r.includes("!")?r.slice(0,r.lastIndexOf("!")+1):O(e.name);if(o.r0!==o.r1&&o.c0!==o.c1)return!1;const n=[];for(let m=o.r0;m<=o.r1;m++)for(let k=o.c0;k<=o.c1;k++)n.push([m,k]);const p=n.length,c=p===1||(o.r1>o.r0?t===p:h!==p);return p>1&&t!==p&&h!==p?!1:(n.forEach(([m,k],$)=>{let x;p===1?x=`${C(s.r0,s.c0)}:${C(s.r1,s.c1)}`:c?x=`${C(s.r0+$,s.c0)}:${C(s.r0+$,s.c1)}`:x=`${C(s.r0,s.c0+$)}:${C(s.r1,s.c0+$)}`,l.push({source:`${a}${x}`,cell:C(m,k)})}),e.sparklines=[...e.sparklines??[],{type:i,markers:!1,high:!1,low:!1,first:!1,last:!1,negative:i==="stacked",lineWeight:.75,seriesColor:"#156082",negativeColor:"#C00000",markerColor:"#C00000",axisColor:"#000000",firstColor:"#C00000",lastColor:"#C00000",highColor:"#C00000",lowColor:"#C00000",displayEmptyCellsAs:"gap",minAxisType:"individual",maxAxisType:"individual",items:l}],e.sparklinesChanged=!0,!0)}export{q as addSparkline,_ as parseSparklines,H as patchSparklines,X as sparklineIndex,N as sparklinesXml};
1
+ import{cellRef as C,parseCellRef as E,parseRangeRef as G,sheetPrefix as O}from"./address.js";import{child as y,children as T,parseTree as R}from"../io/xml-scan.js";import{escapeMarkup as d}from"../io/xml-escape.js";const b=new TextEncoder,u=e=>e==="1"||e==="true";function _(e,o){const r=e.indexOf("sparklineGroups");if(r<0)return[];const i=e.lastIndexOf("<",r),l=e.indexOf("sparklineGroups>",r+16);if(i<0||l<0)return[];const s=e.slice(i,l+16);let t;try{t=R(b.encode(`<r xmlns:x14="x" xmlns:xm="m">${s}</r>`))}catch{return[]}const h=y(t,"sparklineGroups");return T(h,"sparklineGroup").map(a=>{const n=a.a,c={},p=(f,L)=>{const A=y(a,f),w=o(A)??L;return A&&w&&(c[f]={hex:w,attrs:Object.entries(A.a??{}).map(([M,v])=>`${M}="${d(v)}"`).join(" ")}),w},m=f=>f===void 0||f===""||!Number.isFinite(Number(f))?void 0:Number(f),k=p("colorSeries","#376092"),$=p("colorNegative","#D00000"),x=p("colorMarkers","#D00000");return{type:n.type??"line",markers:u(n.markers),high:u(n.high),low:u(n.low),first:u(n.first),last:u(n.last),negative:u(n.negative),lineWeight:Number(n.lineWeight??.75),seriesColor:k,negativeColor:$,markerColor:x,axisColor:p("colorAxis","#000000"),firstColor:p("colorFirst",x),lastColor:p("colorLast",x),highColor:p("colorHigh",x),lowColor:p("colorLow",x),displayXAxis:u(n.displayXAxis),displayHidden:u(n.displayHidden),rightToLeft:u(n.rightToLeft),displayEmptyCellsAs:n.displayEmptyCellsAs??"zero",dateAxis:u(n.dateAxis),dateRange:y(a,"f")?.t??null,minAxisType:n.minAxisType??"individual",maxAxisType:n.maxAxisType??"individual",manualMin:m(n.manualMin),manualMax:m(n.manualMax),rawColors:c,items:T(y(a,"sparklines"),"sparkline").map(f=>({source:y(f,"f")?.t??"",cell:y(f,"sqref")?.t??""}))}})}const F=[["colorSeries","seriesColor"],["colorNegative","negativeColor"],["colorAxis","axisColor"],["colorMarkers","markerColor"],["colorFirst","firstColor"],["colorLast","lastColor"],["colorHigh","highColor"],["colorLow","lowColor"]],I=e=>`FF${String(e).slice(1,7).toUpperCase()}`;function S(e){const o=[];e.manualMax!==void 0&&e.maxAxisType==="custom"&&o.push(`manualMax="${e.manualMax}"`),e.manualMin!==void 0&&e.minAxisType==="custom"&&o.push(`manualMin="${e.manualMin}"`),e.lineWeight!==void 0&&e.lineWeight!==.75&&o.push(`lineWeight="${e.lineWeight}"`),e.type!=="line"&&o.push(`type="${d(e.type)}"`),e.dateAxis&&e.dateRange&&o.push('dateAxis="1"'),o.push(`displayEmptyCellsAs="${d(e.displayEmptyCellsAs??"gap")}"`);for(const s of["markers","high","low","first","last","negative","displayXAxis","displayHidden"])e[s]&&o.push(`${s}="1"`);e.minAxisType&&e.minAxisType!=="individual"&&o.push(`minAxisType="${d(e.minAxisType)}"`),e.maxAxisType&&e.maxAxisType!=="individual"&&o.push(`maxAxisType="${d(e.maxAxisType)}"`),e.rightToLeft&&o.push('rightToLeft="1"');const r=F.map(([s,t])=>{const h=e[t]??(t==="axisColor"?"#000000":e.markerColor),a=e.rawColors?.[s];return`<x14:${s} ${a&&a.hex===h&&a.attrs?a.attrs:`rgb="${I(h)}"`}/>`}).join(""),i=e.dateAxis&&e.dateRange?`<xm:f>${d(e.dateRange)}</xm:f>`:"",l=e.items.map(s=>`<x14:sparkline>${s.source?`<xm:f>${d(s.source)}</xm:f>`:""}<xm:sqref>${d(s.cell)}</xm:sqref></x14:sparkline>`).join("");return`<x14:sparklineGroup ${o.join(" ")}>${r}${i}<x14:sparklines>${l}</x14:sparklines></x14:sparklineGroup>`}function N(e){return e.length===0?"":`<ext xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" uri="{05C60535-1F16-4fd2-B633-F4F36F0B64E0}"><x14:sparklineGroups xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">${e.map(S).join("")}</x14:sparklineGroups></ext>`}function H(e,o){const r=e.replace(/<ext\b[^>]*>\s*<x14:sparklineGroups[\s\S]*?<\/x14:sparklineGroups>\s*<\/ext>/,""),i=N(o),l=/<\/extLst>\s*(?:<\/worksheet>\s*)?$/.exec(r);if(!i)return l?r.replace(/<extLst>\s*<\/extLst>(\s*(?:<\/worksheet>\s*)?)$/,"$1"):r;if(l)return`${r.slice(0,l.index)}${i}${r.slice(l.index)}`;const s=r.lastIndexOf("</worksheet>"),t=`<extLst>${i}</extLst>`;return s>=0?r.slice(0,s)+t+r.slice(s):r+t}function X(e){if(e._sparkIndex&&e._sparkIndexOf===e.sparklines)return e._sparkIndex;const o=new Map;for(const r of e.sparklines??[])for(const i of r.items){const l=E(i.cell);l&&o.set(l.row*16384+l.col,{group:r,source:i.source})}return e._sparkIndex=o,e._sparkIndexOf=e.sparklines,o}function q(e,o,r,i){const l=[],s=G(r.replace(/^.*!/,"").replace(/\$/g,""));if(s===null)return!1;const t=s.r1-s.r0+1,h=s.c1-s.c0+1,a=r.includes("!")?r.slice(0,r.lastIndexOf("!")+1):O(e.name);if(i.r0!==i.r1&&i.c0!==i.c1)return!1;const n=[];for(let m=i.r0;m<=i.r1;m++)for(let k=i.c0;k<=i.c1;k++)n.push([m,k]);const c=n.length,p=c===1||(i.r1>i.r0?t===c:h!==c);return c>1&&t!==c&&h!==c?!1:(n.forEach(([m,k],$)=>{let x;c===1?x=`${C(s.r0,s.c0)}:${C(s.r1,s.c1)}`:p?x=`${C(s.r0+$,s.c0)}:${C(s.r0+$,s.c1)}`:x=`${C(s.r0,s.c0+$)}:${C(s.r1,s.c0+$)}`,l.push({source:`${a}${x}`,cell:C(m,k)})}),e.sparklines=[...e.sparklines??[],{type:o,markers:!1,high:!1,low:!1,first:!1,last:!1,negative:o==="stacked",lineWeight:.75,seriesColor:"#156082",negativeColor:"#C00000",markerColor:"#C00000",axisColor:"#000000",firstColor:"#C00000",lastColor:"#C00000",highColor:"#C00000",lowColor:"#C00000",displayEmptyCellsAs:"gap",minAxisType:"individual",maxAxisType:"individual",items:l}],e.sparklinesChanged=!0,!0)}export{q as addSparkline,_ as parseSparklines,H as patchSparklines,X as sparklineIndex,N as sparklinesXml};
package/core/sparse.js CHANGED
@@ -1 +1 @@
1
- import{copyTypeRules as h,shiftedTypeRules as O,sortedTypeRules as U}from"./cell-type-rules.js";const t=16384,v=["cellTypes","cellDropdowns","cellTags","cellButtons"],D=new Set,L=(n,o)=>n*t+o,N=[];function V(n,{moved:o=!0}={}){v.includes(n)||v.push(n),o||D.add(n)}const z=n=>{for(const o of v)if(n[o])return!0;return!!n.cellTypeRules};function S(n){const o={cellTypeRules:n.cellTypeRules??null};for(const c of v)o[c]=n[c]??null;return o}const E=n=>o=>{const c=E(S(o));return Object.assign(o,n),o.cellTypesChanged=!0,c},B=()=>B,W=n=>E(S(n)),X=n=>S(n);function q(n,o,c,e,i=2e6){const u=E(S(n)),f=new Map(n[o]??[]);let d=0;for(const{r0:p,c0:l,r1:s,c1:T}of c){const M=Math.min(s,Math.max(n.maxRow,p)),a=Math.min(T,Math.max(n.maxCol,l));for(let y=p;y<=M&&d<i;y++)for(let R=l;R<=a&&d<i;R++,d++)e===void 0?f.delete(y*t+R):f.set(y*t+R,e)}return n[o]=f.size>0?f:null,n.cellTypesChanged=!0,u}function Y(n,o,c){return c>0?n>=o?n+c:n:n>=o-c?n+c:n>=o?-1:n}function F(n,o){if(!z(n))return B;const c=E(S(n));n.cellTypeRules=O(n.cellTypeRules,o);const e=o.axis==="row";for(const i of v){if(D.has(i))continue;const u=n[i];if(!u)continue;const f=new Map;for(const[d,p]of u){const l=Math.floor(d/t),s=d-l*t,T=e?s:l;if(o.span&&(T<o.span[0]||T>o.span[1])){f.set(d,p);continue}const M=Y(e?l:s,o.at,o.n);M<0||f.set(e?M*t+s:l*t+M,p)}n[i]=f.size>0?f:null}return n.cellTypesChanged=!0,c}function G(n,o,c,e,i,u,f="row"){if(!z(n))return B;const d=E(S(n));n.cellTypeRules=U(n.cellTypeRules,{r0:o,r1:c,c0:e,c1:i},u,f);for(const p of v){if(D.has(p))continue;const l=n[p];if(!l)continue;const s=new Map;for(const[T,M]of l){const a=Math.floor(T/t),y=T-a*t;a>=o&&a<=c&&y>=e&&y<=i?s.set(f==="row"?(o+u[a-o])*t+y:a*t+e+u[y-e],M):s.set(T,M)}n[p]=s}return n.cellTypesChanged=!0,d}function I(n,o,c,e,{cut:i=!1,transpose:u=!1}={}){if(!z(n)&&!z(o))return B;const f=E(S(o)),d=n===o?null:E(S(n)),p=c.r1-c.r0+1,l=c.c1-c.c0+1;h(n,o,c,e,{cut:i,transpose:u});const s=e.r1-e.r0+1,T=e.c1-e.c0+1;for(const a of v){const y=n[a],R=o[a];if(!y&&!R)continue;const m=[];if(y)for(const[r,x]of y){const w=Math.floor(r/t),k=r-w*t;w>=c.r0&&w<=c.r1&&k>=c.c0&&k<=c.c1&&m.push([w-c.r0,k-c.c0,x])}const C=new Map(R??[]);if(i&&n===o)for(const[r,x]of m)C.delete((c.r0+r)*t+c.c0+x);if(C.size<s*T)for(const r of C.keys()){const x=Math.floor(r/t),w=r%t;x>=e.r0&&x<=e.r1&&w>=e.c0&&w<=e.c1&&C.delete(r)}else for(let r=e.r0;r<=e.r1;r++)for(let x=e.c0;x<=e.c1;x++)C.delete(r*t+x);if(m.length>0){const r=u?l:p,x=u?p:l;for(let w=0;w+r<=s||w===0;w+=r)for(let k=0;k+x<=T||k===0;k+=x)for(const[_,b,A]of m){const H=e.r0+w+(u?b:_),K=e.c0+k+(u?_:b);C.set(H*t+K,A)}}if(o[a]=C.size>0?C:null,i&&n!==o&&y){const r=new Map(y);for(const[x,w]of m)r.delete((c.r0+x)*t+c.c0+w);n[a]=r.size>0?r:null}}if(o.cellTypesChanged=!0,n.cellTypesChanged=!0,d===null)return f;const M=(a,y)=>R=>M(a(o),y(n))??R;return M(f,d)}function J(n,o,c){if(!z(n))return B;const e=E(S(n));h(n,n,o,c,{fill:!0});const i=o.r1-o.r0+1,u=o.c1-o.c0+1;for(const f of v){const d=n[f];if(!d)continue;const p=new Map(d);for(let l=c.r0;l<=c.r1;l++)for(let s=c.c0;s<=c.c1;s++){if(l>=o.r0&&l<=o.r1&&s>=o.c0&&s<=o.c1)continue;const T=o.r0+((l-o.r0)%i+i)%i,M=o.c0+((s-o.c0)%u+u)%u,a=d.get(T*t+M);a===void 0?p.delete(l*t+s):p.set(l*t+s,a)}n[f]=p.size>0?p:null}return n.cellTypesChanged=!0,e}export{I as copySparseBlock,J as fillSparse,B as noUndo,G as permuteSparse,V as registerSparseMap,q as setSparse,N as sheetRenameHooks,F as shiftSparse,L as sparseKey,X as sparseState,W as sparseUndo};
1
+ import{copyTypeRules as B,shiftedTypeRules as H,sortedTypeRules as K}from"./cell-type-rules.js";const t=16384,S=["cellTypes","cellDropdowns","cellTags","cellButtons","valueMeta","cellDefaults","cellPicOpts","cellLists","cellAltText","invalidFormulas"],P=new Set(S),D=new Set(["valueMeta"]),j=(n,o)=>n*t+o,F=[];function N(n,{moved:o=!0}={}){P.add(n),S.includes(n)||S.push(n),o||D.add(n)}const z=n=>{for(const o of S)if(n[o])return!0;return!!n.cellTypeRules};function v(n){const o={cellTypeRules:n.cellTypeRules??null};for(const e of S)o[e]=n[e]??null;return o}const k=n=>o=>{const e=k(v(o));return Object.assign(o,n),o.cellTypesChanged=!0,e},A=()=>A,V=n=>k(v(n)),W=n=>v(n);function X(n,o,e,c,i=2e6){const u=k(v(n)),f=new Map(n[o]??[]);let d=0;for(const{r0:p,c0:l,r1:s,c1:M}of e){const T=Math.min(s,Math.max(n.maxRow,p)),a=Math.min(M,Math.max(n.maxCol,l));for(let y=p;y<=T&&d<i;y++)for(let R=l;R<=a&&d<i;R++,d++)c===void 0?f.delete(y*t+R):f.set(y*t+R,c)}return n[o]=f.size>0?f:null,n.cellTypesChanged=!0,u}function U(n,o,e){return e>0?n>=o?n+e:n:n>=o-e?n+e:n>=o?-1:n}function q(n,o){if(!z(n))return A;const e=k(v(n));n.cellTypeRules=H(n.cellTypeRules,o);const c=o.axis==="row";for(const i of S){if(D.has(i))continue;const u=n[i];if(!u)continue;const f=new Map;for(const[d,p]of u){const l=Math.floor(d/t),s=d-l*t,M=c?s:l;if(o.span&&(M<o.span[0]||M>o.span[1])){f.set(d,p);continue}const T=U(c?l:s,o.at,o.n);T<0||f.set(c?T*t+s:l*t+T,p)}n[i]=f.size>0?f:null}return n.cellTypesChanged=!0,e}function G(n,o,e,c,i,u,f="row"){if(!z(n))return A;const d=k(v(n));n.cellTypeRules=K(n.cellTypeRules,{r0:o,r1:e,c0:c,c1:i},u,f);for(const p of S){if(D.has(p))continue;const l=n[p];if(!l)continue;const s=new Map;for(const[M,T]of l){const a=Math.floor(M/t),y=M-a*t;a>=o&&a<=e&&y>=c&&y<=i?s.set(f==="row"?(o+u[a-o])*t+y:a*t+c+u[y-c],T):s.set(M,T)}n[p]=s}return n.cellTypesChanged=!0,d}function I(n,o,e,c,{cut:i=!1,transpose:u=!1}={}){if(!z(n)&&!z(o))return A;const f=k(v(o)),d=n===o?null:k(v(n)),p=e.r1-e.r0+1,l=e.c1-e.c0+1;B(n,o,e,c,{cut:i,transpose:u});const s=c.r1-c.r0+1,M=c.c1-c.c0+1;for(const a of S){const y=n[a],R=o[a];if(!y&&!R)continue;const m=[];if(y)for(const[r,x]of y){const w=Math.floor(r/t),E=r-w*t;w>=e.r0&&w<=e.r1&&E>=e.c0&&E<=e.c1&&m.push([w-e.r0,E-e.c0,x])}const C=new Map(R??[]);if(i&&n===o)for(const[r,x]of m)C.delete((e.r0+r)*t+e.c0+x);if(C.size<s*M)for(const r of C.keys()){const x=Math.floor(r/t),w=r%t;x>=c.r0&&x<=c.r1&&w>=c.c0&&w<=c.c1&&C.delete(r)}else for(let r=c.r0;r<=c.r1;r++)for(let x=c.c0;x<=c.c1;x++)C.delete(r*t+x);if(m.length>0){const r=u?l:p,x=u?p:l;for(let w=0;w+r<=s||w===0;w+=r)for(let E=0;E+x<=M||E===0;E+=x)for(const[L,_,O]of m){const b=c.r0+w+(u?_:L),h=c.c0+E+(u?L:_);C.set(b*t+h,O)}}if(o[a]=C.size>0?C:null,i&&n!==o&&y){const r=new Map(y);for(const[x,w]of m)r.delete((e.r0+x)*t+e.c0+w);n[a]=r.size>0?r:null}}if(o.cellTypesChanged=!0,n.cellTypesChanged=!0,d===null)return f;const T=(a,y)=>R=>T(a(o),y(n))??R;return T(f,d)}function J(n,o,e){if(!z(n))return A;const c=k(v(n));B(n,n,o,e,{fill:!0});const i=o.r1-o.r0+1,u=o.c1-o.c0+1;for(const f of S){const d=n[f];if(!d)continue;const p=new Map(d);for(let l=e.r0;l<=e.r1;l++)for(let s=e.c0;s<=e.c1;s++){if(l>=o.r0&&l<=o.r1&&s>=o.c0&&s<=o.c1)continue;const M=o.r0+((l-o.r0)%i+i)%i,T=o.c0+((s-o.c0)%u+u)%u,a=d.get(M*t+T);a===void 0?p.delete(l*t+s):p.set(l*t+s,a)}n[f]=p.size>0?p:null}return n.cellTypesChanged=!0,c}export{P as CELL_MAPS,I as copySparseBlock,J as fillSparse,A as noUndo,G as permuteSparse,N as registerSparseMap,X as setSparse,F as sheetRenameHooks,q as shiftSparse,j as sparseKey,W as sparseState,V as sparseUndo};
package/core/spills.js ADDED
@@ -0,0 +1 @@
1
+ import{CHUNK_BITS as f,CHUNK_MASK as d,EMPTY as a,SPILL as k}from"./sheet.js";import{MAX_COLS as m}from"./address.js";function p(o,i,t=null){for(let s=i.c0;s<=i.c1;s++){const r=o.columns[s];if(r!==void 0)for(let c=i.r0>>>f;c<=i.r1>>>f;c++){if(r[c]===void 0)continue;const n=c<<f,l=t===null?r[c]:t(s,c),e=Math.min(i.r1-n,d);for(let u=Math.max(i.r0-n,0);u<=e;u++)(l.kinds[u]&k)===0||n+u===i.r0&&s===i.c0||(l.kinds[u]=a,l.values[u]=0)}}}function S(o,i){if(!o.spills)return;const t=[];for(const[n,l]of o.spills)!l.fixed&&i(l)&&t.push([n,l]);if(t.length===0)return;o.spills=new Map(o.spills);const s=o.columns.slice();o.columns=s;const r=new Set,c=(n,l)=>{r.has(n)||(r.add(n),s[n]=s[n].slice());const e=s[n][l];if(r.has(e))return e;const u={kinds:e.kinds.slice(),values:e.values.slice(),styles:e.styles&&e.styles.slice()};return r.add(u),s[n][l]=u,u};for(const[n,l]of t)o.spills.delete(n),l.blocked||p(o,l,c)}function x(o,i,t=o.columns){let s=o.spills;if(s){s=new Map(s);const r=c=>{for(let n=c.c0;n<=c.c1;n++)for(let l=c.r0>>>f;l<=c.r1>>>f;l++)if(o.columns[n]?.[l]!==t[n]?.[l])return!1;return!0};for(const[c,n]of o.spills){if(n.fixed)continue;const l=i?.get(c);l&&!l.blocked&&l.r1===n.r1&&l.c1===n.c1&&r(n)||(s.delete(c),n.blocked||p(o,n))}}return o.spills=i,s}function b(o,i,t){const s=o.spills?.get(i*m+t);return s&&!s.blocked?s:{r0:i,c0:t,r1:i,c1:t}}export{S as dropSpills,b as spillArea,x as swapSpills};
package/core/strings.js CHANGED
@@ -1 +1 @@
1
- const o=new TextDecoder,n=16384,l=n-1;class c{constructor(){this.pages=[],this.importedCount=0,this.rich=null,this.extras=[],this.extraIndex=null,this.cacheKeys=new Int32Array(n).fill(-1),this.cacheValues=new Array(n),this.lastPage=null}get size(){return this.importedCount+this.extras.length}addPage(e,t){const s=t.length-1;this.pages.push({start:this.importedCount,count:s,bytes:e,offsets:t}),this.importedCount+=s}_pageOf(e){const t=this.lastPage;if(t!==null&&e>=t.start&&e<t.start+t.count)return t;const s=this.pages;let i=0,r=s.length-1;for(;i<r;){const a=i+r+1>>>1;s[a].start<=e?i=a:r=a-1}return this.lastPage=s[i],s[i]}get(e){if(e>=this.importedCount)return this.extras[e-this.importedCount]??"";const t=e&l;if(this.cacheKeys[t]===e)return this.cacheValues[t];const s=this._pageOf(e),i=e-s.start,r=u(s.bytes,s.offsets[i],s.offsets[i+1]);return this.cacheKeys[t]=e,this.cacheValues[t]=r,r}add(e){this.extraIndex===null&&(this.extraIndex=new Map);let t=this.extraIndex.get(e);return t===void 0&&(t=this.extras.length,this.extras.push(e),this.extraIndex.set(e,t)),this.importedCount+t}addRich(e,t){if(!t||t.length===0)return this.add(e);this.extraIndex===null&&(this.extraIndex=new Map);const s=`\0rich${JSON.stringify(t)}\0${e}`;let i=this.extraIndex.get(s);return i===void 0&&(i=this.extras.length,this.extras.push(e),this.extraIndex.set(s,i),this.rich??=new Map,this.rich.set(this.importedCount+i,t)),this.importedCount+i}}function u(h,e,t){const s=t-e;if(s===0)return"";if(s<=48){let i=!0;for(let r=e;r<t;r++)if(h[r]>=128){i=!1;break}if(i)return String.fromCharCode.apply(null,h.subarray(e,t))}return o.decode(h.subarray(e,t))}export{c as StringTable,u as decodeBytes};
1
+ const h=new TextDecoder,c=16384,d=c-1;class x{constructor(){this.pages=[],this.importedCount=0,this.rich=null,this.extras=[],this.extraIndex=null,this.cacheKeys=new Int32Array(c).fill(-1),this.cacheValues=new Array(c),this.lastPage=null}get size(){return this.importedCount+this.extras.length}addPage(s,t){const e=t.length-1;this.pages.push({start:this.importedCount,count:e,bytes:s,offsets:t}),this.importedCount+=e}_pageOf(s){const t=this.lastPage;if(t!==null&&s>=t.start&&s<t.start+t.count)return t;const e=this.pages;let r=0,n=e.length-1;for(;r<n;){const o=r+n+1>>>1;e[o].start<=s?r=o:n=o-1}return this.lastPage=e[r],e[r]}get(s){if(s>=this.importedCount)return this.extras[s-this.importedCount]??"";const t=s&d;if(this.cacheKeys[t]===s)return this.cacheValues[t];const e=this._pageOf(s),r=s-e.start,n=p(e.bytes,e.offsets[r],e.offsets[r+1]);return this.cacheKeys[t]=s,this.cacheValues[t]=n,n}add(s){this.extraIndex===null&&(this.extraIndex=new Map);let t=this.extraIndex.get(s);return t===void 0&&(t=this.extras.length,this.extras.push(s),this.extraIndex.set(s,t)),this.importedCount+t}addRich(s,t){if(!t||t.length===0)return this.add(s);this.extraIndex===null&&(this.extraIndex=new Map);const e=`\0rich${JSON.stringify(t)}\0${s}`;let r=this.extraIndex.get(e);return r===void 0&&(r=this.extras.length,this.extras.push(s),this.extraIndex.set(e,r),this.rich??=new Map,this.rich.set(this.importedCount+r,t)),this.importedCount+r}}const u=new TextEncoder,f=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;function g(i){if(!f.test(i))return u.encode(i);const s=[];for(const t of i){const e=t.codePointAt(0);e>=55296&&e<=57343?s.push(224|e>>12,128|e>>6&63,128|e&63):s.push(...u.encode(t))}return Uint8Array.from(s)}function l(i){let s="",t=0;for(let e=0;e+2<i.length;e++)i[e]!==237||i[e+1]<160||(s+=h.decode(i.subarray(t,e))+String.fromCharCode(53248|(i[e+1]&63)<<6|i[e+2]&63),e+=2,t=e+1);return s+h.decode(i.subarray(t))}function p(i,s,t){const e=t-s;if(e===0)return"";if(e<=48){let o=!0;for(let a=s;a<t;a++)if(i[a]>=128){o=!1;break}if(o)return String.fromCharCode.apply(null,i.subarray(s,t))}const r=i.subarray(s,t),n=h.decode(r);return n.includes("�")?l(r):n}export{x as StringTable,p as decodeBytes,g as encodeText};
package/core/structure.js CHANGED
@@ -1 +1 @@
1
- import{CHUNK_BITS as v,CHUNK_MASK as A,CHUNK_SIZE as q,FORMULA as ln,STR as sn}from"./sheet.js";import{FormulaStore as X}from"./formula-store.js";import{cellRef as B,MAX_COLS as w,MAX_ROWS as k,parseCellRef as L,parseRangeRef as b,rangeRef as H}from"./address.js";import{translateFormula as on}from"./formula-refs.js";import{adjustFormula as T,adjustRange as O}from"../calc/adjust.js";import{clonePageSetup as en,shiftPageSetup as an}from"../print/page-setup.js";import{shiftSparse as cn}from"./sparse.js";import{shiftRuleFormulas as un}from"../cells/cf-file.js";import{noteStructure as fn}from"./changes.js";import{shiftHeaderColors as mn}from"../cells/header-colors.js";function V(t){return{kinds:new Uint8Array(q),values:new Float64Array(q),styles:t.styles===null?null:new Uint16Array(q)}}function W(t,n,r){if(!t||n===0)return;const s=/outlineLevel="\d+"/.exec(t.get(n-1)??"");if(s)for(let o=n;o<n+r;o++)t.set(o,s[0])}function Z(t,n,r,s,o,c){let l=s,e=r,u=c;for(;l>0;){const a=u>>>v,i=u&A,m=Math.min(l,q-i);let y=o[a];y===void 0&&(y=V(t),o[a]=y);const d=e-n;y.kinds.set(t.kinds.subarray(d,d+m),i),y.values.set(t.values.subarray(d,d+m),i),t.styles!==null&&(y.styles===null&&(y.styles=new Uint16Array(q)),y.styles.set(t.styles.subarray(d,d+m),i)),l-=m,e+=m,u+=m}}function G(t,n,r){const s=n>>>v,o=t.slice(0,s),c=t[s];c!==void 0&&(n&A)>0&&Z(c,s<<v,s<<v,n&A,o,s<<v);const l=r<0?n-r:n;for(let e=s;e<t.length;e++){const u=t[e];if(u===void 0)continue;const a=e<<v,i=Math.max(a,l),m=a+q;if(i>=m)continue;const y=i+r;if(y>=k)continue;const d=Math.min(m-i,k-y);Z(u,a,i,d,o,y)}return o}function dn(t,n,r){const s=[];for(let o=0;o<t.length;o++){const c=t[o];c!==void 0&&(o<n?s[o]=c:r>0?o+r<w&&(s[o+r]=c):o>=n-r&&(s[o+r]=c))}return s}function gn(t,n,r,s){const o=r-1,c=Math.min(s,(n?k:w)-r);if(c<=0)return;if(n){const u=c*t.columns.filter(Boolean).length<=4194304;for(let i=0;u&&i<t.columns.length;i++){if(t.columns[i]===void 0)continue;const m=t.cellStyle(o,i);if(m!==0)for(let y=0;y<c;y++)t.setStyle(r+y,i,m)}const a=t.rowStyles?.get(o);if(a!==void 0)for(let i=0;i<c;i++)t.rowStyles.set(r+i,a);return}const l=t.columns[o];if(l!==void 0&&l.some(u=>u?.styles)){for(let u=0;u<c;u++){const a=[];l.forEach((i,m)=>{if(i===void 0||i.styles===null)return;const y=V(i);y.styles.set(i.styles),a[m]=y}),t.columns[r+u]=a}r+c-1>t.maxCol&&(t.maxCol=r+c-1)}const e=t.colStyles?.get(o);if(e!==void 0)for(let u=0;u<c;u++)t.colStyles.set(r+u,e)}function N(t,n,r){if(t===null)return null;const s=new Map;for(const[o,c]of t)o<n?s.set(o,c):(r>0||o>=n-r)&&s.set(o+r,c);return s}const U=(t,n,r)=>r.axis==="row"?t<r.at?[t,n]:r.n>0?t+r.n<k?[t+r.n,n]:null:t>=r.at-r.n?[t+r.n,n]:null:n<r.at?[t,n]:r.n>0?n+r.n<w?[t,n+r.n]:null:n>=r.at-r.n?[t,n+r.n]:null;function J(t,n,r){if(t.f!==void 0)return t.f;if(t.sf!==void 0){const s=Math.floor(t.base/w);return on(t.sf,n-s,r-(t.base-s*w))}return null}const P=(t,n)=>(t.f??t.sf)?.toUpperCase().includes(n)===!0;function Q(t,n){for(const r of t.descriptors())if(P(r,n))return!0;return!1}function _(t,n){const r=b(t),s=r&&O(r,n);return s?H(s):t}function Y(t,n,r,s,o){if(t.t==="dataTable"){if(!s)return t;const l={...t,ref:_(t.ref,r),tpl:void 0};return t.r1&&(l.r1=_(t.r1,r)),t.r2&&(l.r2=_(t.r2,r)),l}const c={f:T(n,r,s,o)};return t.typed&&(c.typed=!0),t.ca&&(c.ca=t.ca),t.cm&&(c.cm=t.cm),t.t==="array"&&(c.t="array",c.ref=s&&t.ref?_(t.ref,r):t.ref),c}function Un(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,c=r.axis==="row",l=$(t,n),e=fn(n,r);if(c){const d=[];n.columns.forEach((p,R)=>{d[R]=G(p,s,o)}),n.columns=d,n.rows=n.rows.shifted(s,o),n.rowStyles=N(n.rowStyles,s,o),n.rowExtras=N(n.rowExtras,s,o),o>0&&W(n.rowExtras,s,o),n.maxRow=n.maxRow>=s?Math.max(s-1,n.maxRow+o):n.maxRow,n.maxRow>=k&&(n.maxRow=k-1),n.frozenRows>s&&(n.frozenRows=Math.max(s,n.frozenRows+o))}else n.columns=dn(n.columns,s,o),n.cols=n.cols.shifted(s,o),n.colStyles=N(n.colStyles,s,o),n.colExtras=N(n.colExtras,s,o),o>0&&W(n.colExtras,s,o),n.colsChanged=!0,n.maxCol=n.maxCol>=s?Math.max(s-1,n.maxCol+o):n.maxCol,n.maxCol>=w&&(n.maxCol=w-1),n.frozenCols>s&&(n.frozenCols=Math.max(s,n.frozenCols+o));if(o>0&&s>0&&!r.noFormat&&gn(n,c,s,o),n.merges=n.merges.map(d=>O(d,r)).filter(d=>d!==null&&(d.r0!==d.r1||d.c0!==d.c1)),n.mergeIndex=null,n.spills){const d=new Map;for(const[p,R]of n.spills){const f=Math.floor(p/w),x=U(f,p-f*w,r),g=O(R,r);x&&g&&d.set(x[0]*w+x[1],{...R,...g})}n.spills=d}if(n.valueMeta){const d=new Map;for(const[p,R]of n.valueMeta){const f=Math.floor(p/w),x=U(f,p-f*w,r);x&&d.set(x[0]*w+x[1],R)}n.valueMeta=d}const u=n.name.toUpperCase();for(const d of t.sheets){const p=d===n;if(!p&&!Q(d.formulas,u))continue;const R=new X;d.formulas.forEachCell((f,x,g)=>{const C=p?U(f,x,r):[f,x];if(C===null)return;if(!p&&!P(g,u)){R.put(C[0],C[1],g);return}const S=J(g,f,x);if(S===null||!p&&!S.toUpperCase().includes(u)){R.put(C[0],C[1],g);return}const M=Y(g,S,r,p,n.name);if(M.t==="array"&&M.ref&&p){const z=d.spills?.get(C[0]*w+C[1]);z&&(M.ref=H(z))}R.put(C[0],C[1],M)}),d.formulas=R}const a=tn(t,n,r),i=t.engine;if(i){for(const d of i.names.values())d.text=T(d.text,r,!1,n.name);i.names.size>0&&(t.namesChanged=!0),i.nameTemplates.clear(),i.rebuild()}n.structureOps=[...n.structureOps??[],r],n.pageSetup&&(an(n.pageSetup,r),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const m=(d,p)=>()=>m(d(),p()),y=m(a,D(t,n,l));return e===null?y:m(y,e)}const E=(t,n)=>{if(n.span){const[r,s]=n.span;if(!(n.axis==="row"?t.c0>=r&&t.c1<=s:t.r0>=r&&t.r1<=s))return t}return O(t,n)};function j(t,n){return t.split(/\s+/).map(b).filter(Boolean).map(r=>E(r,n)).filter(Boolean).map(H).join(" ")}function F(t,n,r){if(r.span){const[s,o]=r.span,c=r.axis==="row"?n:t;if(c<s||c>o)return[t,n]}return U(t,n,r)}function h(t,n){if(!t)return t;const r=E(t,n);if(r===null)return null;let{columns:s}=t;if(n.axis==="col"&&s?.size>0){s=new Map;for(const[c,l]of t.columns){const e=F(t.r0,c,n);e&&s.set(e[1],l)}}let{buttons:o}=t;if(n.axis==="col"&&o?.size>0){o=new Map;for(const[c,l]of t.buttons){const e=F(t.r0,c,n);e&&o.set(e[1],l)}}return{...t,...r,columns:s,buttons:o,sortState:nn(t.sortState,n)}}function nn(t,n){if(!t)return t??null;const r=E(t,n);if(r===null)return null;const s=[];for(const o of t.conditions){const c=E(o,n);c!==null&&s.push({...o,...c})}return s.length>0?{...t,...r,conditions:s}:null}const I=t=>({sheets:t.sheets.map(n=>[n,{cf:n.cf,cellStates:n.cellStates,headerColors:n.headerColors,validations:n.validations,hyperlinks:n.hyperlinks,ignoredErrors:n.ignoredErrors,comments:n.comments,sparklines:n.sparklines,sparkRules:n.sparkRules,autoFilter:n.autoFilter,advancedFilter:n.advancedFilter,outlineColumn:n.outlineColumn,outlineVersion:(n.outlineVersion??0)+1,sortState:n.sortState,filteredRows:n.filteredRows,scenarios:n.scenarios,threads:n.threads}]),tables:t.engine?[...t.engine.tables.values()].map(n=>[n,{r0:n.r0,c0:n.c0,r1:n.r1,c1:n.c1,columns:n.columns,filter:n.filter,totals:n.totals,dirty:n.dirty,columnsChanged:n.columnsChanged}]):[]}),rn=t=>{for(const[n,r]of t.sheets)Object.assign(n,r),n.cfEval?.invalidate();for(const[n,r]of t.tables)Object.assign(n,r)};function tn(t,n,r){const s=I(t),o=n.name;for(const l of t.sheets){const e=l===n,u=a=>typeof a=="string"&&a!==""?T(a,r,e,o):a;if(l.cf?.length>0&&(l.cf=l.cf.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,rules:i.rules.map(m=>un(m,u))})).filter(a=>a.sqref!==""),l.cfChanged=!0,l.cfEval?.invalidate()),e&&l.headerColors&&!r.span&&(l.headerColors=mn(l.headerColors,r)),e&&l.cellStates?.length>0){const a=l.cellStates.map(i=>({...i,ranges:i.ranges.map(m=>E(m,r)).filter(Boolean)})).filter(i=>i.ranges.length>0);l.cellStates=a.length>0?a:null}l.validations?.length>0&&(l.validations=l.validations.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,formula1:u(i.formula1),formula2:u(i.formula2)})).filter(a=>a.sqref!==""),l.validationsChanged=!0),e&&l.ignoredErrors?.length>0&&(l.ignoredErrors=l.ignoredErrors.map(a=>({...a,sqref:j(a.sqref,r)})).filter(a=>a.sqref!==""),l.ignoredErrorsChanged=!0),l.hyperlinks?.length>0&&(l.hyperlinks=l.hyperlinks.map(({_ranges:a,...i})=>{const m=e?j(i.ref,r):i.ref;return{...i,ref:m,...i.location?{location:u(i.location)}:{}}}).filter(a=>a.ref!==""),l.hyperlinksChanged=!0),l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(a=>({...a,sqref:e?j(a.sqref,r):a.sqref,formula:u(a.formula)})).filter(a=>a.sqref!=="")),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(a=>({...a,items:a.items.map(i=>{const m=L(i.cell),y=e&&m?F(m.row,m.col,r):m?[m.row,m.col]:null;return y?{...i,cell:B(y[0],y[1]),source:u(i.source)}:null}).filter(Boolean)})).filter(a=>a.items.length>0),l.sparklinesChanged=!0)}if(n.comments?.size>0){const l=new Map;for(const[e,u]of n.comments){const a=Math.floor(e/w),i=F(a,e-a*w,r);i&&l.set(i[0]*w+i[1],{...u,ref:B(i[0],i[1])})}n.comments=l,n.commentsChanged=!0}if(n.scenarios?.items.length>0&&(n.scenarios={...n.scenarios,items:n.scenarios.items.map(l=>({...l,cells:l.cells.map(e=>{const u=L(e.r),a=u&&F(u.row,u.col,r);return a?{...e,r:B(a[0],a[1])}:null}).filter(Boolean)}))},n.scenariosChanged=!0),n.threads?.length>0&&(n.threads=n.threads.map(l=>{const e=L(l.ref),u=e&&F(e.row,e.col,r);return u?{...l,ref:B(u[0],u[1])}:null}).filter(Boolean),n.threadsChanged=!0),n.outlineColumn){const l=n.outlineColumn;if(r.axis==="col"&&!r.span){const e=U(0,l.col,r);n.outlineColumn=e?{...l,col:e[1]}:null}else if(r.axis==="row"&&!r.span&&l.checks){const e={};for(const u of Object.keys(l.checks)){const a=U(Number(u),0,r);a&&(e[a[0]]=l.checks[u])}n.outlineColumn={...l,checks:e}}}if(n.outlineVersion=(n.outlineVersion??0)+1,n.sortState&&(n.sortState=nn(n.sortState,r),n.filterChanged=!0),n.autoFilter&&(n.autoFilter=h(n.autoFilter,r),n.filterChanged=!0),n.advancedFilter){const l=n.advancedFilter,e=l.listSheet===n?E(l,r):l;n.advancedFilter=e===null?null:{...l,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1,criteria:l.criteria&&l.criteriaSheet===n?E(l.criteria,r):l.criteria,extract:l.extract?E(l.extract,r):null},n.filterChanged=!0}if(n.filteredRows&&r.axis==="row"&&!r.span){const l=new Set;for(const e of n.filteredRows){const u=U(e,0,r);u&&l.add(u[0])}n.filteredRows=l}if(t.engine)for(const l of[...t.engine.tables.values()]){if(l.sheet!==n)continue;const e=E(l,r);if(e===null)continue;const u=!r.span||r.span[0]<=l.r0&&r.span[1]>=l.r1;r.axis==="col"&&u&&e.c1-e.c0!==l.c1-l.c0&&Cn(t,l,r),Object.assign(l,{r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1}),l.filter=h(l.filter,r),l.dirty=!0}const c=l=>()=>{const e=I(t);return rn(l),c(e)};return c(s)}function On(t){const n=r=>()=>{const s=I(t);return rn(r),n(s)};return n(I(t))}function xn(t,n){return D(t,n,$(t,n))}function yn(t,n,r,s){if(t===void 0&&n===void 0)return;const o=t===void 0?[]:t.slice();for(let c=r>>>v;c<=s>>>v;c++){const l=t?.[c],e=n?.[c];if(l===void 0&&e===void 0)continue;const u=c<<v,a=Math.max(r,u)-u,i=Math.min(s,u+A)-u+1,m=l===void 0?V({styles:null}):{kinds:l.kinds.slice(),values:l.values.slice(),styles:l.styles?l.styles.slice():null};e===void 0?(m.kinds.fill(0,a,i),m.values.fill(0,a,i),m.styles!==null&&m.styles.fill(0,a,i)):(m.kinds.set(e.kinds.subarray(a,i),a),m.values.set(e.values.subarray(a,i),a),e.styles!==null?(m.styles===null&&(m.styles=new Uint16Array(q)),m.styles.set(e.styles.subarray(a,i),a)):m.styles!==null&&m.styles.fill(0,a,i)),o[c]=m}return o}function wn(t){if(t===void 0)return-1;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r!==void 0){for(let s=A;s>=0;s--)if(r.kinds[s]!==0||r.styles!==null&&r.styles[s]!==0)return(n<<v)+s}}return-1}function An(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,[c,l]=r.span,e=r.axis==="row",u=xn(t,n),a=n.columns.slice();if(e)for(let f=c;f<=Math.min(l,n.columns.length-1);f++)n.columns[f]!==void 0&&(a[f]=G(n.columns[f],s,o),o>0&&(n.maxRow=Math.min(k-1,Math.max(n.maxRow,wn(a[f])))));else{const f=n.columns.length-1,x=o>0?Math.min(f+o,w-1):f;for(let g=s;g<=x;g++){const C=g-o,S=o>0&&g<s+o?void 0:n.columns[C],M=yn(n.columns[g],S,c,l);M!==void 0&&(a[g]=M)}o>0&&(n.maxCol=Math.min(w-1,Math.max(n.maxCol,Math.min(n.maxCol+o,x))))}if(n.columns=a,o>0&&s>0&&!r.noFormat){const f=Math.min(o,(e?k:w)-s),x=Math.min(l,e?n.maxCol:n.maxRow);if(f>0&&f*(x-c+1)<=1<<22)for(let g=c;g<=x;g++){const C=e?n.cellStyle(s-1,g):n.cellStyle(g,s-1);if(C!==0)for(let S=0;S<f;S++)e?n.setStyle(s+S,g,C):n.setStyle(g,s+S,C)}}const i=f=>e?f.c0>=c&&f.c1<=l:f.r0>=c&&f.r1<=l;if(n.merges=n.merges.map(f=>i(f)?O(f,r):f).filter(f=>f!==null&&(f.r0!==f.r1||f.c0!==f.c1)),n.mergeIndex=null,n.spills){const f=new Map;for(const[x,g]of n.spills){const C=Math.floor(x/w),S=F(C,x-C*w,r),M=i(g)?O(g,r):g;S&&M&&f.set(S[0]*w+S[1],{...g,...M})}n.spills=f}if(n.valueMeta){const f=new Map;for(const[x,g]of n.valueMeta){const C=Math.floor(x/w),S=F(C,x-C*w,r);S&&f.set(S[0]*w+S[1],g)}n.valueMeta=f}const m=n.name.toUpperCase();for(const f of t.sheets){const x=f===n;if(!x&&!Q(f.formulas,m))continue;const g=new X;f.formulas.forEachCell((C,S,M)=>{const z=x?F(C,S,r):[C,S];if(z===null)return;const K=x||P(M,m)?J(M,C,S):null;K===null||!x&&!K.toUpperCase().includes(m)?g.put(z[0],z[1],M):g.put(z[0],z[1],Y(M,K,r,x,n.name))}),f.formulas=g}const y=tn(t,n,r),d=cn(n,r),p=t.engine;if(p){for(const f of p.names.values())f.text=T(f.text,r,!1,n.name);p.names.size>0&&(t.namesChanged=!0),p.nameTemplates.clear(),p.rebuild()}n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const R=(f,x,g)=>()=>R(f(n),x(n),g(n));return R(d,y,u)}function Cn(t,n,r){const s=r.at-n.c0,o=n.columns.slice(),c=n.totals?.slice()??null;if(r.n>0){const l=new Set(o.map(u=>u.toLowerCase())),e=[];for(let u=0,a=1;u<r.n;u++){for(;l.has(`column${a}`);)a++;l.add(`column${a}`),e.push(`Column${a}`)}o.splice(s,0,...e),c?.splice(s,0,...e.map(()=>null)),n.headerRows>0&&e.forEach((u,a)=>n.sheet.setCell(n.r0,r.at+a,sn,t.strings.add(u)))}else{const l=Math.max(s,0),e=Math.min(-r.n-Math.max(0,n.c0-r.at),o.length-l);o.splice(l,e),c?.splice(l,e)}n.columns=o,n.totals=c,n.columnsChanged=!0}function $(t,n){const r=t.engine;return{columns:n.columns,rows:n.rows,cols:n.cols,rowStyles:n.rowStyles,colStyles:n.colStyles,rowExtras:n.rowExtras,colExtras:n.colExtras,valueMeta:n.valueMeta,merges:n.merges,spills:n.spills,maxRow:n.maxRow,maxCol:n.maxCol,frozenRows:n.frozenRows,frozenCols:n.frozenCols,colsChanged:n.colsChanged,structureOps:n.structureOps,pageSetup:n.pageSetup?en(n.pageSetup):null,formulas:t.sheets.map(s=>[s,s.formulas]),names:r?[...r.names].map(([s,o])=>[s,{...o}]):null}}function D(t,n,r){return()=>{const s=$(t,n);n.columns=r.columns,n.rows=r.rows,n.cols=r.cols,n.rowStyles=r.rowStyles,n.colStyles=r.colStyles,n.rowExtras=r.rowExtras,n.colExtras=r.colExtras,n.valueMeta=r.valueMeta,n.merges=r.merges,n.mergeIndex=null,n.spills=r.spills,n.maxRow=r.maxRow,n.maxCol=r.maxCol,n.frozenRows=r.frozenRows,n.frozenCols=r.frozenCols,n.colsChanged=r.colsChanged,n.structureOps=r.structureOps,r.pageSetup&&(n.pageSetup=r.pageSetup);for(const[c,l]of r.formulas)c.formulas=l;const o=t.engine;return o&&((o.names.size||r.names.length)&&(t.namesChanged=!0),o.names=new Map(r.names),o.nameTemplates.clear(),o.rebuild()),n.revision++,D(t,n,s)}}export{ln as FORMULA,I as captureFeatures,On as featuresUndo,rn as restoreFeatures,An as shiftBand,tn as shiftFeatures,Un as shiftStructure,xn as structureUndo};
1
+ import{addColumnIds as tn,columnIdsOf as Fn}from"./table-columns.js";import{CHUNK_BITS as z,CHUNK_MASK as B,CHUNK_SIZE as A,FORMULA as En,STR as Tn}from"./sheet.js";import{FormulaStore as H}from"./formula-store.js";import{cellRef as I,MAX_COLS as C,MAX_ROWS as T,parseCellRef as K,parseRangeRef as V,rangeRef as k}from"./address.js";import{translateFormula as Ln}from"./formula-refs.js";import{adjustFormula as U,adjustRange as b,moveIndex as qn}from"../calc/adjust.js";import{cornerOf as D,ruleRewriter as An,splitBlocks as Un,splitValidation as bn}from"./rule-refs.js";import{clonePageSetup as On,shiftPageSetup as en}from"../print/page-setup.js";import{mapHostRules as Bn,restoreHostRules as In}from"./host-rules.js";import{shiftSparse as Vn}from"./sparse.js";import{dropSpills as kn,spillArea as _n,swapSpills as Nn}from"./spills.js";import{captureViews as jn,foldViews as Hn,restoreViews as Kn,settleViews as sn,shiftViewColumns as ln,viewTableKey as Dn}from"./shared-view.js";import{shiftRuleFormulas as on}from"../cells/cf-file.js";import{noteStructure as $n}from"./changes.js";import{shiftHeaderColors as Pn}from"../cells/header-colors.js";function $(r){return{kinds:new Uint8Array(A),values:new Float64Array(A),styles:r.styles===null?null:new Uint16Array(A)}}function an(r,n,t){if(!r||n===0)return;const e=/outlineLevel="\d+"/.exec(r.get(n-1)??"");if(e)for(let s=n;s<n+t;s++)r.set(s,e[0])}function cn(r,n,t,e,s,o){let i=e,f=t,g=o;for(;i>0;){const u=g>>>z,m=g&B,l=Math.min(i,A-m);let a=s[u];a===void 0&&(a=$(r),s[u]=a);const p=f-n;a.kinds.set(r.kinds.subarray(p,p+l),m),a.values.set(r.values.subarray(p,p+l),m),r.styles!==null&&(a.styles===null&&(a.styles=new Uint16Array(A)),a.styles.set(r.styles.subarray(p,p+l),m)),i-=l,f+=l,g+=l}}function un(r,n,t){const e=n>>>z,s=r.slice(0,e),o=r[e];o!==void 0&&(n&B)>0&&cn(o,e<<z,e<<z,n&B,s,e<<z);const i=t<0?n-t:n;for(let f=e;f<r.length;f++){const g=r[f];if(g===void 0)continue;const u=f<<z,m=Math.max(u,i),l=u+A;if(m>=l)continue;const a=m+t;if(a>=T)continue;const p=Math.min(l-m,T-a);cn(g,u,m,p,s,a)}return s}function Wn(r,n,t){const e=[];for(let s=0;s<r.length;s++){const o=r[s];o!==void 0&&(s<n?e[s]=o:t>0?s+t<C&&(e[s+t]=o):s>=n-t&&(e[s+t]=o))}return e}function Xn(r,n,t,e){const s=t-1,o=Math.min(e,(n?T:C)-t);if(o<=0)return;if(n){const g=o*r.columns.filter(Boolean).length<=4194304;for(let m=0;g&&m<r.columns.length;m++){if(r.columns[m]===void 0)continue;const l=r.cellStyle(s,m);if(l!==0)for(let a=0;a<o;a++)r.setStyle(t+a,m,l)}const u=r.rowStyles?.get(s);if(u!==void 0)for(let m=0;m<o;m++)r.rowStyles.set(t+m,u);return}const i=r.columns[s];if(i!==void 0&&i.some(g=>g?.styles)){for(let g=0;g<o;g++){const u=[];i.forEach((m,l)=>{if(m===void 0||m.styles===null)return;const a=$(m);a.styles.set(m.styles),u[l]=a}),r.columns[t+g]=u}t+o-1>r.maxCol&&(r.maxCol=t+o-1)}const f=r.colStyles?.get(s);if(f!==void 0)for(let g=0;g<o;g++)r.colStyles.set(t+g,f)}function _(r,n,t){if(r===null)return null;const e=new Map;for(const[s,o]of r)s<n?e.set(s,o):(t>0||s>=n-t)&&e.set(s+t,o);return e}const q=(r,n,t)=>t.axis==="row"?r<t.at?[r,n]:t.n>0?r+t.n<T?[r+t.n,n]:null:r>=t.at-t.n?[r+t.n,n]:null:n<t.at?[r,n]:t.n>0?n+t.n<C?[r,n+t.n]:null:n>=t.at-t.n?[r,n+t.n]:null;function fn(r,n,t){if(r.f!==void 0)return r.f;if(r.sf!==void 0){const e=Math.floor(r.base/C);return Ln(r.sf,n-e,t-(r.base-e*C))}return null}const P=(r,n)=>(r.f??r.sf)?.toUpperCase().includes(n)===!0,mn=r=>r.name.toUpperCase().replace(/'/g,"''");function dn(r,n){for(const t of r.descriptors())if(P(t,n))return!0;return!1}function Zn(r,n){const t=V(r),e=t&&b(t,n);return e?k(e):r}function gn(r,n){const t=F(V(r.ref),n),e={...r,ref:t?k(t):r.ref,tpl:void 0};for(const[s,o]of[["r1","del1"],["r2","del2"]]){const i=r[s]?V(r[s]):null;if(!i)continue;const f=E(i.r0,i.c0,n);f?e[s]=I(f[0],f[1]):e[o]="1"}return e}function wn(r,n,t,e,s){const o={f:U(n,t,e,s)};return r.typed&&(o.typed=!0),r.ca&&(o.ca=r.ca),r.cm&&(o.cm=r.cm),r.t==="array"&&(o.t="array",o.ref=e&&r.ref?Zn(r.ref,t):r.ref),o}function pn(r,[n,t],e){if(e.t!=="array"||!e.ref)return;const s=r.spills?.get(n*C+t);e.cm?e.ref=k(_n(r,n,t)):s&&(e.ref=k(s))}function xn(r,n){const t=n.n<0?n.at-n.n:n.at;kn(r,e=>{const[s,o]=n.axis==="row"?[e.r0,e.r1]:[e.c0,e.c1];if(o<n.at)return!1;if(n.span){const[i,f]=n.axis==="row"?[e.c0,e.c1]:[e.r0,e.r1];if(f<n.span[0]||i>n.span[1])return!1;if(i<n.span[0]||f>n.span[1])return!0}return s<t||o+n.n>=(n.axis==="row"?T:C)})}function Rr(r,n,t){r.collab?.structure(n,t);const{at:e,n:s}=t,o=t.axis==="row",i=h(r,n),f=$n(n,t);if(xn(n,t),o){const c=[];n.columns.forEach((w,S)=>{c[S]=un(w,e,s)}),n.columns=c,n.rows=n.rows.shifted(e,s),n.rowStyles=_(n.rowStyles,e,s),n.rowExtras=_(n.rowExtras,e,s),s>0&&an(n.rowExtras,e,s),n.maxRow=n.maxRow>=e?Math.max(e-1,n.maxRow+s):n.maxRow,n.maxRow>=T&&(n.maxRow=T-1),n.frozenRows>e&&(n.frozenRows=Math.max(e,n.frozenRows+s)),n.frozenTop>e&&(n.frozenTop=Math.max(e,n.frozenTop+s)),n.frozenTop>0&&n.frozenTop>=n.frozenRows&&(n.frozenRows=n.frozenTop=0)}else n.columns=Wn(n.columns,e,s),n.cols=n.cols.shifted(e,s),n.colStyles=_(n.colStyles,e,s),n.colExtras=_(n.colExtras,e,s),s>0&&an(n.colExtras,e,s),n.colsChanged=!0,n.maxCol=n.maxCol>=e?Math.max(e-1,n.maxCol+s):n.maxCol,n.maxCol>=C&&(n.maxCol=C-1),n.frozenCols>e&&(n.frozenCols=Math.max(e,n.frozenCols+s)),n.frozenLeft>e&&(n.frozenLeft=Math.max(e,n.frozenLeft+s)),n.frozenLeft>0&&n.frozenLeft>=n.frozenCols&&(n.frozenCols=n.frozenLeft=0);if(s>0&&e>0&&!t.noFormat&&Xn(n,o,e,s),n.merges=n.merges.map(c=>b(c,t)).filter(c=>c!==null&&(c.r0!==c.r1||c.c0!==c.c1)),n.mergeIndex=null,n.spills){const c=new Map;for(const[w,S]of n.spills){const d=Math.floor(w/C),y=q(d,w-d*C,t),x=b(S,t);y&&x&&c.set(y[0]*C+y[1],{...S,...x})}n.spills=c}if(n.valueMeta){const c=new Map;for(const[w,S]of n.valueMeta){const d=Math.floor(w/C),y=q(d,w-d*C,t);y&&c.set(y[0]*C+y[1],S)}n.valueMeta=c}const g=mn(n);for(const c of r.sheets){const w=c===n;if(!w&&!dn(c.formulas,g))continue;const S=new H;c.formulas.forEachCell((d,y,x)=>{const R=w?q(d,y,t):[d,y];if(R===null)return;if(x.t==="dataTable"){S.put(R[0],R[1],w?gn(x,t):x);return}if(!w&&!P(x,g)){S.put(R[0],R[1],x);return}const M=fn(x,d,y);if(M===null||!w&&!M.toUpperCase().includes(g)){S.put(R[0],R[1],x);return}const v=wn(x,M,t,w,n.name);w&&pn(c,R,v),S.put(R[0],R[1],v)}),c.formulas=S}const u=Mn(r,n,t),m=Rn(r,n,t);vn(r,u);const l=r.engine;if(l){for(const c of l.names.values())c.text=U(c.text,t,!1,n.name);l.names.size>0&&(r.namesChanged=!0),l.nameTemplates.clear(),l.rebuild()}n.structureOps=[...n.structureOps??[],t],n.pageSetup&&(en(n.pageSetup,t),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,r.collab?.structureDone(n);const a=(c,w)=>()=>a(c(),w()),p=a(m,nn(r,n,i,zn(n,t)));return f===null?p:a(p,f)}const W=(r,n)=>!n.span||(n.axis==="row"?r.c0>=n.span[0]&&r.c1<=n.span[1]:r.r0>=n.span[0]&&r.r1<=n.span[1]),F=(r,n)=>W(r,n)?b(r,n):r,Mr=r=>r.split(/\s+/).map(V).filter(Boolean);function O(r,n){return Q(r).map(t=>F(t,n)).filter(Boolean).map(k).join(" ")}function E(r,n,t){if(t.span){const[e,s]=t.span,o=t.axis==="row"?n:r;if(o<e||o>s)return[r,n]}return q(r,n,t)}function Gn(r,{c0:n,c1:t,buttons:e}){if(!r.buttons||r.buttons.size<=r.c1-r.c0)return e;for(const o of r.buttons.values())if(!o.hidden)return e;const s=new Map(e);for(let o=n;o<=t;o++)s.has(o)||s.set(o,{hidden:!0,noShow:!1});return s}function X(r,n){if(!r)return r;const t=F(r,n);if(t===null)return null;let{columns:e}=r;if(n.axis==="col"&&e?.size>0){e=new Map;for(const[o,i]of r.columns){const f=E(r.r0,o,n);f&&e.set(f[1],i)}}let{buttons:s}=r;if(n.axis==="col"&&s?.size>0){s=new Map;for(const[o,i]of r.buttons){const f=E(r.r0,o,n);f&&s.set(f[1],i)}}return n.axis==="col"&&(s=Gn(r,{...t,buttons:s})),{...r,...t,columns:e,buttons:s,sortState:Z(r.sortState,n)}}function Z(r,n){if(!r)return r??null;const t=F(r,n);if(t===null)return null;const e=[];for(const s of r.conditions){const o=F(s,n);o!==null&&e.push({...s,...o})}return e.length>0?{...r,...t,conditions:e}:null}function N(r){return Hn(r),{book:r,sheets:r.sheets.map(n=>[n,{cf:n.cf,cellStates:n.cellStates,headerColors:n.headerColors,validations:n.validations,printAreaFormula:n.printAreaFormula,hyperlinks:n.hyperlinks,ignoredErrors:n.ignoredErrors,protectedRanges:n.protectedRanges,comments:n.comments,sparklines:n.sparklines,sparkRules:n.sparkRules,autoFilter:n.autoFilter,advancedFilter:n.advancedFilter,outlineColumn:n.outlineColumn,outlineVersion:(n.outlineVersion??0)+1,sortState:n.sortState,filteredRows:n.filteredRows,scenarios:n.scenarios,threads:n.threads,...n.namedViews?{namedViews:n.namedViews}:{}},n.hostRules]),views:jn(r),engine:r.engine??null,removedTables:r.removedTables,tables:r.engine?[...r.engine.tables.values()].map(n=>[n,{r0:n.r0,c0:n.c0,r1:n.r1,c1:n.c1,columns:n.columns,columnIds:n.columnIds,filter:n.filter,totals:n.totals,dirty:n.dirty,columnsChanged:n.columnsChanged}]):[]}}function Jn({book:r,engine:n,tables:t,removedTables:e}){if(n===null)return;const s=[...n.tables.values()];if(!(s.length===t.length&&t.every(([o],i)=>o===s[i]))){n.tables.clear();for(const[o]of t)n.tables.set(o.name.toUpperCase(),o);r.removedTables=e}}const yn=(r,n=null)=>{for(const[t,e,s]of r.sheets)Object.assign(t,e),In(t,s,n?.(t)),t.cfEval?.invalidate();for(const[t,e]of r.tables)Object.assign(t,e);Jn(r),Kn(r.views),sn(r.book)};function G(r,n,t,e,s=D){const o=An(J(r,n,t,e,s));return n?o:i=>typeof i=="string"&&i.includes("!")?o(i):i}function J(r,n,t,e,s){const o=u=>U(u,r,n,t);if(!n)return{...Cn(r),...Qn(e,s),rewrite:o,sqref:e};const i=Q(e),f=r.axis==="row",g=f?T:C;return{...Cn(r),ranges:i,sqref:O(e,r),grow:(u,m)=>{const[l,a]=f?[u.r1,m.r1]:[u.c1,m.c1];if(r.n<0||!W(m,r))return u;const p=l===r.at-1&&a>=r.at?r.n:0,c=Math.max(0,(l>=r.at?l+r.n:l+p)-(g-1));return f?{...u,r1:u.r1+p-c}:{...u,c1:u.c1+p-c}},base:s(i),next:s(i.map(u=>F(u,r)).filter(Boolean)),rewrite:o,place:(u,m,l)=>{if(!W(l,r))return[u,m];const a=qn(f?u:m,r.at,r.n);return a===null||a>=g?null:f?[a,m]:[u,a]}}}const Q=r=>r.split(/\s+/).map(V).filter(Boolean),Y=r=>D(r.slice(0,1));function Qn(r,n){const t=Q(r),e=n(t);return{ranges:t,base:e,next:e,place:(s,o)=>[s,o]}}function Cn(r){const n=r.n<0?[r.at,r.at-r.n]:[r.at],t=r.span?[r.span[0],r.span[1]+1]:[];return r.axis==="row"?{rows:n,cols:t}:{rows:t,cols:n}}function Sn(r,n,t){const e=({_ranges:s,_base:o,...i})=>({...i,sqref:n?O(i.sqref,r):i.sqref});return({validation:s,block:o})=>{const{_ranges:i,_base:f,...g}=o,u=e(o,!0);if(u.sqref==="")return null;const m=G(r,n,t,o.sqref),l=s&&G(r,n,t,s.sqref,Y);return{validation:s&&{...e(s),formula1:l(s.formula1),formula2:l(s.formula2)},block:{...u,rules:o.rules.map(a=>on(a,m))}}}}function Rn(r,n,t){const e=N(r),s=n.name;for(const l of r.sheets){const a=l===n,p=c=>typeof c=="string"&&c!==""?U(c,t,a,s):c;if(Bn(l,Sn(t,a,s)),l.cf?.length>0&&(l.cf=Un(l.cf,c=>J(t,a,s,c.sqref,D),on),l.cfChanged=!0,l.cfEval?.invalidate()),a&&l.headerColors&&!t.span&&(l.headerColors=Pn(l.headerColors,t)),a&&l.cellStates?.length>0){const c=l.cellStates.map(w=>({...w,ranges:w.ranges.map(S=>F(S,t)).filter(Boolean)})).filter(w=>w.ranges.length>0);l.cellStates=c.length>0?c:null}l.printAreaFormula&&(l.printAreaFormula=p(l.printAreaFormula)),l.validations?.length>0&&(l.validations=l.validations.flatMap(c=>bn(c,J(t,a,s,c.sqref,Y))),l.validationsChanged=!0),a&&l.protectedRanges?.length>0&&(l.protectedRanges=l.protectedRanges.map(c=>({...c,sqref:O(c.sqref,t)})).filter(c=>c.sqref!==""),l.protectedRangesChanged=!0),a&&l.ignoredErrors?.length>0&&(l.ignoredErrors=l.ignoredErrors.map(c=>({...c,sqref:O(c.sqref,t)})).filter(c=>c.sqref!==""),l.ignoredErrorsChanged=!0),l.hyperlinks?.length>0&&(l.hyperlinks=l.hyperlinks.map(({_ranges:c,...w})=>{const S=a?O(w.ref,t):w.ref;return{...w,ref:S,...w.location?{location:p(w.location)}:{}}}).filter(c=>c.ref!==""),l.hyperlinksChanged=!0),l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(c=>({...c,sqref:a?O(c.sqref,t):c.sqref,formula:G(t,a,s,c.sqref,Y)(c.formula)})).filter(c=>c.sqref!=="")),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(c=>({...c,...c.dateRange?{dateRange:p(c.dateRange)}:{},items:c.items.map(w=>{const S=K(w.cell),d=a&&S?E(S.row,S.col,t):S?[S.row,S.col]:null;return d?{...w,cell:I(d[0],d[1]),source:p(w.source)}:null}).filter(Boolean)})).filter(c=>c.items.length>0),l.sparklinesChanged=!0)}if(n.comments?.size>0){const l=new Map;for(const[a,p]of n.comments){const c=Math.floor(a/C),w=E(c,a-c*C,t);w&&l.set(w[0]*C+w[1],{...p,ref:I(w[0],w[1])})}n.comments=l,n.commentsChanged=!0}if(n.scenarios?.items.length>0&&(n.scenarios={...n.scenarios,items:n.scenarios.items.map(l=>({...l,cells:l.cells.map(a=>{const p=K(a.r),c=p&&E(p.row,p.col,t);return c?{...a,r:I(c[0],c[1])}:null}).filter(Boolean)}))},n.scenariosChanged=!0),n.threads?.length>0&&(n.threads=n.threads.map(l=>{const a=K(l.ref),p=a&&E(a.row,a.col,t);return p?{...l,ref:I(p[0],p[1])}:null}).filter(Boolean),n.threadsChanged=!0),n.outlineColumn){const l=n.outlineColumn;if(t.axis==="col"&&!t.span){const a=q(0,l.col,t);n.outlineColumn=a?{...l,col:a[1]}:null}else if(t.axis==="row"&&!t.span&&l.checks){const a={};for(const p of Object.keys(l.checks)){const c=q(Number(p),0,t);c&&(a[c[0]]=l.checks[p])}n.outlineColumn={...l,checks:a}}}n.outlineVersion=(n.outlineVersion??0)+1,n.sortState&&(n.sortState=Z(n.sortState,t),n.filterChanged=!0);const o=[],i=(l,a)=>{t.axis==="col"&&l?.columns?.size>0&&(a?.columns?.size??0)===0&&o.push([l.r0+1,l.r1])},f=l=>a=>t.axis==="col"?E(l.r0,a,t)?.[1]??null:a;if(n.autoFilter){const l=n.autoFilter;n.autoFilter=X(l,t),n.filterChanged=!0,i(l,n.autoFilter),ln(n,void 0,l,n.autoFilter,f(l))}if(n._view?.api.shiftBase(n,t,{filter:l=>X(l,t)??null,sortState:l=>Z(l,t),row:l=>q(l,0,t)?.[0]??null}),n.advancedFilter){const l=n.advancedFilter,a=l.listSheet===n?F(l,t):l;n.advancedFilter=a===null?null:{...l,r0:a.r0,c0:a.c0,r1:a.r1,c1:a.c1,criteria:l.criteria&&l.criteriaSheet===n?F(l.criteria,t):l.criteria,extract:l.extract?F(l.extract,t):null},n.filterChanged=!0}if(n.filteredRows&&t.axis==="row"&&!t.span){const l=new Set;for(const a of n.filteredRows){const p=q(a,0,t);p&&l.add(p[0])}n.filteredRows=l}if(r.engine)for(const l of[...r.engine.tables.values()]){if(l.sheet!==n)continue;const a=F(l,t);if(a===null){i(l.filter,null),r.engine.tables.delete(l.name.toUpperCase()),l.source===!0&&l.part&&(r.removedTables=[...r.removedTables??[],{part:l.part,sheetIndex:r.sheets.indexOf(n)}]);continue}const p=!t.span||t.span[0]<=l.r0&&t.span[1]>=l.r1;t.axis==="col"&&p&&a.c1-a.c0!==l.c1-l.c0&&er(r,l,t),Object.assign(l,{r0:a.r0,c0:a.c0,r1:a.r1,c1:a.c1});const c=l.filter;l.filter=X(c,t),i(c,l.filter),ln(n,Dn(l),c,l.filter,c?f(c):null),l.dirty=!0}const g=[];if(o.length>0&&n.filteredRows?.size>0){const l=new Set;for(const a of n.filteredRows)o.some(([p,c])=>a>=p&&a<=c)?g.push(a):l.add(a);n.filteredRows=l;for(const a of g)n.rows.setHidden(a,!1)}sn(r);let u=!0;const m=(l,a)=>()=>{const p=N(r),c={...a,n:-a.n};for(const w of g)n.rows.setHidden(w,u);return u=!u,yn(l,w=>Sn(c,w===n,n.name)),m(p,c)};return m(e,t)}function vr(r,n=null){const t=(e,s)=>()=>{const o=N(r);return yn(e,s?.back),t(o,s&&{back:s.forth,forth:s.back})};return t(N(r),n)}function Yn(r,n,t=null){return nn(r,n,h(r,n),t)}function hn(r,n,t,e){if(r===void 0&&n===void 0)return;const s=r===void 0?[]:r.slice();for(let o=t>>>z;o<=e>>>z;o++){const i=r?.[o],f=n?.[o];if(i===void 0&&f===void 0)continue;const g=o<<z,u=Math.max(t,g)-g,m=Math.min(e,g+B)-g+1,l=i===void 0?$({styles:null}):{kinds:i.kinds.slice(),values:i.values.slice(),styles:i.styles?i.styles.slice():null};f===void 0?(l.kinds.fill(0,u,m),l.values.fill(0,u,m),l.styles!==null&&l.styles.fill(0,u,m)):(l.kinds.set(f.kinds.subarray(u,m),u),l.values.set(f.values.subarray(u,m),u),f.styles!==null?(l.styles===null&&(l.styles=new Uint16Array(A)),l.styles.set(f.styles.subarray(u,m),u)):l.styles!==null&&l.styles.fill(0,u,m)),s[o]=l}return s}function nr(r){if(r===void 0)return-1;for(let n=r.length-1;n>=0;n--){const t=r[n];if(t!==void 0){for(let e=B;e>=0;e--)if(t.kinds[e]!==0||t.styles!==null&&t.styles[e]!==0)return(n<<z)+e}}return-1}function zr(r,n,t){r.collab?.structure(n,t);const{at:e,n:s}=t,[o,i]=t.span,f=t.axis==="row",g=Yn(r,n,zn(n,t));xn(n,t);const u=n.columns.slice();if(f)for(let d=o;d<=Math.min(i,n.columns.length-1);d++)n.columns[d]!==void 0&&(u[d]=un(n.columns[d],e,s),s>0&&(n.maxRow=Math.min(T-1,Math.max(n.maxRow,nr(u[d])))));else{const d=n.columns.length-1,y=s>0?Math.min(d+s,C-1):d;for(let x=e;x<=y;x++){const R=x-s,M=s>0&&x<e+s?void 0:n.columns[R],v=hn(n.columns[x],M,o,i);v!==void 0&&(u[x]=v)}s>0&&(n.maxCol=Math.min(C-1,Math.max(n.maxCol,Math.min(n.maxCol+s,y))))}if(n.columns=u,s>0&&e>0&&!t.noFormat){const d=Math.min(s,(f?T:C)-e),y=Math.min(i,f?n.columns.length-1:((n.columns[e-1]?.length??0)<<z)-1);if(d>0&&d*(y-o+1)<=1<<22)for(let x=o;x<=y;x++){const R=f?n.cellStyle(e-1,x):n.cellStyle(x,e-1);if(R!==0)for(let M=0;M<d;M++)f?n.setStyle(e+M,x,R):n.setStyle(x,e+M,R)}}const m=d=>f?d.c0>=o&&d.c1<=i:d.r0>=o&&d.r1<=i;if(n.merges=n.merges.map(d=>m(d)?b(d,t):d).filter(d=>d!==null&&(d.r0!==d.r1||d.c0!==d.c1)),n.mergeIndex=null,n.spills){const d=new Map;for(const[y,x]of n.spills){const R=Math.floor(y/C),M=E(R,y-R*C,t),v=m(x)?b(x,t):x;M&&v&&d.set(M[0]*C+M[1],{...x,...v})}n.spills=d}if(n.valueMeta){const d=new Map;for(const[y,x]of n.valueMeta){const R=Math.floor(y/C),M=E(R,y-R*C,t);M&&d.set(M[0]*C+M[1],x)}n.valueMeta=d}const l=mn(n);for(const d of r.sheets){const y=d===n;if(!y&&!dn(d.formulas,l))continue;const x=new H;d.formulas.forEachCell((R,M,v)=>{const L=y?E(R,M,t):[R,M];if(L===null)return;if(v.t==="dataTable"){x.put(L[0],L[1],y?gn(v,t):v);return}const j=y||P(v,l)?fn(v,R,M):null;if(j===null||!y&&!j.toUpperCase().includes(l))x.put(L[0],L[1],v);else{const rn=wn(v,j,t,y,n.name);y&&pn(d,L,rn),x.put(L[0],L[1],rn)}}),d.formulas=x}const a=Mn(r,n,t),p=Rn(r,n,t);vn(r,a);const c=Vn(n,t),w=r.engine;if(w){for(const d of w.names.values())d.text=U(d.text,t,!1,n.name);w.names.size>0&&(r.namesChanged=!0),w.nameTemplates.clear(),w.rebuild()}n.pageSetup?.printAreas?.length&&(en(n.pageSetup,t),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,r.collab?.structureDone(n);const S=(d,y,x)=>()=>S(d(n),y(n),x(n));return S(c,p,g)}function Mn(r,n,t){const e=[];if(t.axis!=="col"||t.n>=0)return e;for(const s of r.engine?.tables.values()??[]){const o=!t.span||t.span[0]<=s.r0&&t.span[1]>=s.r1;if(s.sheet!==n||!o)continue;const i=s.columns.filter((f,g)=>s.c0+g>=t.at&&s.c0+g<t.at-t.n);if(i.length<s.columns.length)for(const f of i)e.push([s,f])}return e}const rr=/"(?:[^"]|"")*"|'(?:[^']|'')*'!|([^\s()+\-*/^&=<>,;:{}"'![\]#@%]+)(\[(?:[^[\]']|'.|\[(?:[^[\]']|'.)*\])*\])/g;function tr(r){const n=r.slice(1,-1);return(/^\s*\[/.test(n)?[...n.matchAll(/\[((?:[^[\]']|'.)*)\]/g)].map(e=>e[1]):[n]).filter(e=>!e.startsWith("#")).map(e=>e.replace(/'(.)/g,"$1").toLowerCase())}function vn(r,n){if(n.length===0)return;const t=new Map;for(const[s,o]of n){const i=s.name.toLowerCase();t.has(i)||t.set(i,[]),t.get(i).push(o.toLowerCase())}const e=s=>s.includes("[")?s.replace(rr,(o,i,f,g)=>{if(i===void 0||s[g-1]==="!")return o;const u=t.get(i.toLowerCase());return u&&tr(f).some(m=>u.includes(m))?"#REF!":o}):s;for(const s of r.sheets){let o=null;const i=new Map;s.formulas.forEachCell((f,g,u)=>{const m=u.f??u.sf;if(typeof m!="string")return;if(!i.has(u)){const a=e(m);i.set(u,a===m?null:u.f!==void 0?{...u,f:a,tpl:void 0}:{...u,sf:a,tpl:void 0})}const l=i.get(u);l!==null&&(o??=H.from(s.formulas),o.put(f,g,l))}),o!==null&&(s.formulas=o)}r.formulasEdited=!0;for(const s of r.engine.names.values())typeof s.text=="string"&&(s.text=e(s.text));for(const s of r.engine.tables.values()){const o=s.totals?.map(i=>i?.fn==="custom"&&i.formula?{...i,formula:e(i.formula)}:i);o?.some((i,f)=>i?.formula!==s.totals[f]?.formula)&&(s.totals=o,s.dirty=!0)}}function er(r,n,t){const e=t.at-n.c0,s=n.columns.slice(),o=n.totals?.slice()??null,i=Fn(n).slice();if(t.n>0){const f=new Set(s.map(u=>u.toLowerCase())),g=[];for(let u=0,m=1;u<t.n;u++){for(;f.has(`column${m}`);)m++;f.add(`column${m}`),g.push(`Column${m}`)}s.splice(e,0,...g),tn(n,i,e,t.n),o?.splice(e,0,...g.map(()=>null)),n.headerRows>0&&g.forEach((u,m)=>n.sheet.setCell(n.r0,t.at+m,Tn,r.strings.add(u)))}else{const f=Math.max(e,0),g=Math.min(-t.n-Math.max(0,n.c0-t.at),s.length-f);s.splice(f,g),tn(n,i,0,0),i.splice(f,g),o?.splice(f,g)}n.columns=s,n.columnIds=i,n.totals=o,n.columnsChanged=!0}const sr=r=>new Map([...r.names.values()].map(n=>[n,n.text]));function lr(r,n,t){for(const e of r.names.values())n.has(e)?e.text=n.get(e):t&&typeof e.text=="string"&&(e.text=t(e.text))}const zn=(r,n)=>{const t=e=>s=>U(s,e,!1,r.name);return{back:t({...n,n:-n.n}),forth:t(n)}};function h(r,n){const t=r.engine,e=o=>o&&new Map(o),s=o=>r.collab?o.copy():o;return{columns:n.columns,rows:s(n.rows),cols:s(n.cols),rowStyles:e(n.rowStyles),colStyles:e(n.colStyles),rowExtras:e(n.rowExtras),colExtras:e(n.colExtras),valueMeta:n.valueMeta,merges:n.merges,spills:n.spills,maxRow:n.maxRow,maxCol:n.maxCol,frozenRows:n.frozenRows,frozenCols:n.frozenCols,frozenTop:n.frozenTop,frozenLeft:n.frozenLeft,colsChanged:n.colsChanged,structureOps:n.structureOps,pageSetup:n.pageSetup?On(n.pageSetup):null,formulas:r.sheets.map(o=>[o,o.formulas]),names:t?sr(t):null}}function nn(r,n,t,e=null){return()=>{const s=h(r,n);s.spills=Nn(n,t.spills,t.columns),n.columns=t.columns,n.rows=t.rows,n.cols=t.cols,n.rowStyles=t.rowStyles,n.colStyles=t.colStyles,n.rowExtras=t.rowExtras,n.colExtras=t.colExtras,n.valueMeta=t.valueMeta,n.merges=t.merges,n.mergeIndex=null,n.maxRow=t.maxRow,n.maxCol=t.maxCol,n.frozenRows=t.frozenRows,n.frozenCols=t.frozenCols,n.frozenTop=t.frozenTop,n.frozenLeft=t.frozenLeft,n.colsChanged=t.colsChanged,n.structureOps=t.structureOps,t.pageSetup&&(n.pageSetup=t.pageSetup);for(const[i,f]of t.formulas)i.formulas=f;const o=r.engine;return o&&(o.names.size&&(r.namesChanged=!0),lr(o,t.names,e?.back),o.nameTemplates.clear(),o.rebuild()),n.revision++,nn(r,n,s,e&&{back:e.forth,forth:e.back})}}export{En as FORMULA,Gn as buttonsFor,N as captureFeatures,vr as featuresUndo,X as moveFilter,yn as restoreFeatures,zr as shiftBand,Rn as shiftFeatures,Rr as shiftStructure,Yn as structureUndo};
@@ -0,0 +1 @@
1
+ function l(n){const o=n.columns.length,c=n.columnIds;if(c?.length===o)return c;const s=c?c.slice(0,o):[];for(c&&c.length>o&&(n.columnsLeft=[...c.slice(o),...n.columnsLeft??[]]);s.length<o&&n.columnsLeft?.length;){const t=n.columnsLeft[0];n.columnsLeft=n.columnsLeft.slice(1),s.includes(t)||s.push(t)}return n.columnIds=s,e(n,s,o,o-s.length),s}function e(n,o,c,s){let t=n.columnNext??1;for(const u of[...o,...n.columnsLeft??[]])t=Math.max(t,u+1);o.splice(Math.min(c,o.length),0,...Array.from({length:s},()=>t++)),n.columnNext=t}export{e as addColumnIds,l as columnIdsOf};
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 ue}from"../slicers/structured.js";import{syncTableHeaders as fe,tablesOf as de}from"./tables.js";import{BOOL as D,CHUNK_BITS as z,CHUNK_MASK as W,EMPTY as I,ERR as U,ERRORS as me,FORMULA as F,DIRTY as J,EVALUATING as Z,KIND_MASK as Y,NUM as P,Sheet as B,SPILL as pe,STR as T}from"./sheet.js";import{cellRef as ge,isValidName as ye,MAX_COLS as R,MAX_ROWS as X,quoteSheetName as Q,rangeRef as Se,renameSheetInFormula as V,sheetReferencePattern as ee}from"./address.js";import{translateFormula as we}from"./formula-refs.js";import{sheetStem as te}from"./default-names.js";import{StringTable as Ce}from"./strings.js";import{formatAxis as se,formatSheetColumns as ve}from"./axis-styles.js";import{autoRowHeight as ke}from"./row-fit.js";import{StyleTable as xe}from"./styles.js";import{cellEntryText as ne,parseInput as ie}from"./input.js";import{DATE_1904_OFFSET as _e}from"./numfmt.js";import{noteChanges as oe}from"./changes.js";import{overrideRuns as Re}from"../cells/rich-runs.js";import{sheetRenameHooks as be}from"./sparse.js";import{shiftRuleFormulas as re}from"../cells/cf-file.js";import{expandStructured as Me,formulaEntryLimit as Fe,FormulaSyntaxError as L,tokenize as Te,toDisplayFormula as le,toFileFormula as Ae}from"../calc/parser.js";const Ee=200,Ie=new Set(["entry","clear","format","borders","fill"]);class Oe{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let o=this.ids.length*2;for(;o<=t;)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[t]=this.list.length}get(t){const e=t<this.ids.length?this.ids[t]:0;return e===0?void 0:this.list[e-1]}}class ${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 t=this.capacity*2,e=(i,o)=>{const r=new i(t);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=t}push(t,e,i){this.count===this.capacity&&this._grow();const o=this.count++,r=t.kind(e,i)&~(J|Z);if(this.rows[o]=e,this.cols[o]=i,this.kinds[o]=r,this.styles[o]=t.cellStyle(e,i),this.values[o]=t.value(e,i),r&F&&(this.formulas===null&&(this.formulas=new Oe),this.formulas.set(o,t.formula(e,i))),t.valueMeta!==null){const s=t.valueMeta.get(e*R+i);s!==void 0&&(this.vms??=new Map).set(o,s)}}}class Qe{get namesChanged(){return this._namesChanged}set namesChanged(t){this._namesChanged=t,t&&(this.namesRevision=(this.namesRevision??0)+1)}constructor(){this.sheets=[new B(`${te()}1`)],this.activeSheet=0,this.date1904=!1,this.strings=new Ce,this.styles=new xe,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?_e:0}get dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}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 t of this.listeners)t("history")}}_emit(t){(t==="cells"||t==="bulk")&&(this.formatValueRevision=(this.formatValueRevision??0)+1),this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=te();let i=1,o=t??`${e}${i}`;const r=n=>this.sheets.some(l=>l.name.toLowerCase()===n.toLowerCase());for(;r(o);)o=`${e}${++i}`;const s=new B(o);return this.sheets.push(s),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),s}deleteSheet(t){return this.sheets.filter(e=>!e.hidden).length<=1?!1:(this._shrink3D(t),this._refErrorsFor(t),this._removeSheet(t))}_removeSheet(t){if(this.sheets.length<=1)return!1;const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[o,r]of this.engine.tables)r.sheet===e&&this.engine.tables.delete(o);this._reindexNames(o=>o===t?-1:o>t?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(t,e){const i=r=>r.sheet===t||r.sheet===void 0&&r.sheetIndex===e||(r.extra?.parts??[]).some(i),o=r=>{r.sheetIndex>e&&r.sheetIndex--;for(const s of r.extra?.parts??[])o(s)};for(const r of[this.undoStack,this.redoStack]){const s=r.filter(n=>!i(n));s.forEach(o),r.splice(0,r.length,...s)}}moveSheet(t,e){if(t===e)return;const i=this.sheet,[o]=this.sheets.splice(t,1);this.sheets.splice(e,0,o),this.activeSheet=this.sheets.indexOf(i);const r=n=>n===t?e:t<e?n>t&&n<=e?n-1:n:n>=e&&n<t?n+1:n,s=n=>{n.sheetIndex=r(n.sheetIndex);for(const l of n.extra?.parts??[])s(l)};for(const n of this.undoStack)s(n);for(const n of this.redoStack)s(n);this.structureEdited=!0,this._reindexNames(r),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(t,e){const i=new Map,o=new Set;for(const r of de(this,t)){const{sheet:s,part:n,id:l,source:c,sheetIndex:a,...h}=r;let u=this.engine.tables.size+i.size+2,p,f;do{const d=String(u++),g=r.name.slice(0,255-d.length);p=g+d,ye(p)||(p=g.slice(0,254-d.length)+"_"+d),f=p.toUpperCase()}while(o.has(f)||this.engine.tables.has(f)||this.engine.names.has(f));o.add(f),i.set(r.name.toUpperCase(),{...A(h),name:p,sheet:e,isNew:!0,dirty:!0})}return i}_copyScopedNames(t,e,i,o){const{engine:r}=this;if(!r||r.names.size===0)return;const s=`${t}!`;let n=!1;for(const[l,c]of[...r.names])l.startsWith(s)&&(r.names.set(`${t+1}!${l.slice(s.length)}`,{...c,text:o(V(c.text,e.name,i.name))}),n=!0);n&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const i=[];let o=!1;for(const[r,s]of e.names){const n=r.indexOf("!"),l=n<0?0:t(Number(r.slice(0,n)));n>=0&&l!==Number(r.slice(0,n))&&(o=!0),n<0?i.push([r,s]):l>=0&&i.push([`${l}!${r.slice(n+1)}`,s])}if(o){e.names.clear();for(const[r,s]of i)e.names.set(r,s);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let o=`${e.name} (2)`,r=2;for(;this.sheets.some(h=>h.name.toLowerCase()===o.toLowerCase());)o=`${e.name} (${++r})`;const s=new B(o),n=this._copyTables(e,s),l=h=>Ue(h,n,e.name,s.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((f,d)=>{p[d]={kinds:f.kinds.slice(),values:f.values.slice(),styles:f.styles?f.styles.slice():null}}),s.columns[u]=p}),s.maxRow=e.maxRow,s.maxCol=e.maxCol,s.rows=e.rows.shifted(0,0),s.cols=e.cols.shifted(0,0);const c=new Map;e.formulas.forEachCell((h,u,p)=>{let f=c.get(p);f===void 0&&(f={...p,tpl:void 0},p.f!==void 0&&(f.f=l(p.f)),p.sf!==void 0&&(f.sf=l(p.sf)),c.set(p,f)),s.setFormula(h,u,f)}),s.merges=e.merges.map(h=>({...h})),s.rowStyles=e.rowStyles?new Map(e.rowStyles):null,s.colStyles=e.colStyles?new Map(e.colStyles):null,s.frozenRows=e.frozenRows,s.frozenCols=e.frozenCols,s.showGridlines=e.showGridlines,s.cellTypeRules=e.cellTypeRules,s.cellTypes=e.cellTypes?new Map(e.cellTypes):null,s.sparkRules=e.sparkRules,s.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,s.cellTags=e.cellTags?new Map(e.cellTags):null,s.cellButtons=e.cellButtons?new Map(e.cellButtons):null,s.cellStates=e.cellStates?e.cellStates.slice():null,s.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,s.background=e.background,s.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,s.frozenTrailingRows=e.frozenTrailingRows,s.frozenTrailingCols=e.frozenTrailingCols,s.hideZeros=e.hideZeros,s.hideHeadings=e.hideHeadings,s.isChartSheet=e.isChartSheet,s.hideOutline=e.hideOutline,s.gridColorId=e.gridColorId,s.areaOffset=e.areaOffset,s.selectionPolicy=e.selectionPolicy,s.selectionUnit=e.selectionUnit,s.gridlineAxes=e.gridlineAxes,s.gridColor=e.gridColor,s.tabStyles=e.tabStyles;const a=A;if(s.cf=a(e.cf),s.validations=a(e.validations),n.size){for(const h of s.cf??[])h.rules=h.rules.map(u=>re(u,l));for(const h of s.validations??[])h.formula1&&(h.formula1=l(h.formula1)),h.formula2&&(h.formula2=l(h.formula2))}s.comments=a(e.comments),s.threads=a(e.threads),s.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...a({...h,_ranges:void 0})})):e.hyperlinks,s.autoFilter=a(e.autoFilter),s.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,s.pageSetup=a(e.pageSetup),s.tabColor=e.tabColor,s.protection=a(e.protection),s.rtl=e.rtl,s.zoom=e.zoom,s.valueMeta=e.valueMeta?new Map(e.valueMeta):null,s.colsChanged=!0,s.viewChanged=!0,this.sheets.splice(t+1,0,s);for(const h of n.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=t+1,this._reindexNames(h=>h>t?h+1:h),this._copyScopedNames(t,e,s,l),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),s}sheetNameProblem(t,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!==t&&o.name.toLowerCase()===i.toLowerCase())?"taken":null}renameSheet(t,e){const i=e.trim().slice(0,31);if(this.sheetNameProblem(t,e)!==null)return!1;const o=this.sheets[t].name;this.sheets[t].name=i,this.engine?.sheetsChanged(),this._renameInFormulas(o,i);for(const r of be)r(this,o,i);return this._emit("sheets"),!0}_shrink3D(t){const e=this.sheets[t].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,s=l=>l.replace(r,(c,a,h,u)=>{if(l[u-1]==="]")return c;const p=o(a),f=o(h);if(p.toLowerCase()!==e&&f.toLowerCase()!==e)return c;let d=i(p),g=i(f);if(d<0||g<0||(d>g&&([d,g]=[g,d]),d===t&&d++,g===t&&g--,d>g))return c;const y=w=>Q(this.sheets[w].name);return d===g?`${y(d)}!`:`${y(d)}:${y(g)}!`}),n=l=>l.includes(":")&&l.includes("!")?l.split(/("(?:[^"]|"")*")/).map((c,a)=>a%2?c:s(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 f=u.f??u.sf,d=typeof f=="string"?n(f):f;p=d===f?null:u.f!==void 0?{...u,f:d,tpl:void 0}:{...u,sf:d,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(t){const e=ee(this.sheets[t].name),i=s=>s.split(/("(?:[^"]|"")*")/).map((n,l)=>l%2?n:n.replace(e,"#REF!")).join(""),o=s=>typeof s=="string"&&s!==""?i(s):s,r=this.sheets[t];for(const s of this.sheets){if(s===r)continue;s.cf?.length>0&&(s.cf=s.cf.map(l=>({...l,rules:l.rules.map(c=>re(c,o))})),s.cfChanged=!0,s.cfEval?.invalidate()),s.validations?.length>0&&(s.validations=s.validations.map(l=>({...l,formula1:o(l.formula1),formula2:o(l.formula2)})),s.validationsChanged=!0);const n=new Map;s.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&&(s.setFormula(l,c,h),this.formulasEdited=!0)})}for(const s of this.engine?.names.values()??[])typeof s.text=="string"&&(s.text=i(s.text));this.engine?.templates.clear()}_renameInFormulas(t,e){const i=ee(t);let o=!1;for(const s of this.sheets){const n=new Map;s.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=V(u,t,e);h=a.f!==void 0?{...a,f:p,tpl:void 0}:{...a,sf:p,tpl:void 0}}n.set(a,h)}h!==null&&(s.setFormula(l,c,h),o=!0)})}let r=!1;for(const s of this.engine?.names.values()??[]){if(typeof s.text!="string")continue;const n=V(s.text,t,e);n!==s.text&&(s.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(t,e,i){const o=t.kind(e,i);if(this.engine?.dataTables.length){const n=this.engine.dataTableAt(t,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&pe&&this.engine){const n=this.engine.spillMaster(t,e,i);if(n)return this.editText(t,n.row,n.col)}if(o&F){const n=t.formula(e,i),l=n&&!n.typed&&n.t!=="array"&&n.tpl?.rangeResult?"=@":"=";if(n&&n.f!==void 0){const c=l+le(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+le(we(n.sf,e-c,i-a))}}const r=o&Y;if(r===I)return"";const s=t.value(e,i);if(r===U&&t.valueMeta!==null&&!(o&F)){const n=this.richImages?.get(t.valueMeta.get(e*R+i));if(n!==void 0)return n.alt??"";const l=this.richValues?.indexOfVm(t.valueMeta.get(e*R+i))??-1,c=l>=0?this.richValues.view(l):null;if(c!==null)return c.text}return r===T?this.styles.get(t.style(e,i)).quotePrefix?`'${this.strings.get(s)}`:this.strings.get(s):r===D?s?"TRUE":"FALSE":r===U?me[s]??"#N/A":String(s)}transact(t,e,i=null){if(this.guard&&!this.guard(t))return;const o=this.selectedSheets;!i&&o?.size>1&&Ie.has(t)&&(i=this.sheets.filter(s=>o.has(s)&&(!s.protection||s===this.sheet)));const r=i?this._runGroup(t,e,i):this._runOn(this.sheet,t,e);r!==null&&this._pushUndo(r)}transactOn(t,e,i){const o=this._runOn(t,e,i);o!==null&&this._pushUndo(o)}_runOn(t,e,i){const o=new $,r={sheet:t,log:o,saveCell:(f,d)=>o.push(t,f,d)},{maxRow:s,maxCol:n}=t,l=this.recorder?.length,c=this.formulasEdited;let a;try{a=i(r)??null}catch(f){throw f instanceof L&&(ae(t,o),t.maxRow=s,t.maxCol=n,this.formulasEdited=c,l!==void 0&&(this.recorder.length=l),this.engine?.cellsChanged(t,o.rows,o.cols,o.count)),f}e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&o.count>0&&oe(this,t,o),o.vms!==null&&ze(t,o);const h=o.count>0&&this.engine?.tables.size>0?fe(this,r,o):null,u=(f,d)=>g=>u(f(g),d(g)),p=a&&h?u(a,h):a??h;return o.count===0&&p===null?null:(t.revision++,this.engine?.cellsChanged(t,o.rows,o.cols,o.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:o,label:e,extra:p})}_runGroup(t,e,i){const o=[],r=this.activeSheet,s=this.recorder?.length,n=this.formulasEdited,l=[];try{for(const c of i){const{maxRow:a,maxCol:h}=c,u=this._runOn(c,t,e);u!==null&&(o.push(u),l.push([c,a,h]))}}catch(c){if(c instanceof L){this.rollbackSlices(o);for(const[a,h,u]of l)a.maxRow=h,a.maxCol=u;this.activeSheet=r,this.formulasEdited=n,s!==void 0&&(this.recorder.length=s)}throw c}return o.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new $,label:t,extra:H(this,o)}}runSlice(t,e,i){const o=this._runOn(t,e,i);return o!==null&&this._emit("cells"),o}pushFolded(t,e,i){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(i),sheet:i,log:new $,label:e,extra:H(this,t)})}rollbackSlices(t){for(let e=t.length-1;e>=0;e--)this._restore(t[e]);this._emit("cells")}_pushUndo(t){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(t),this.undoStack.length>(this.historyLimit??Ee)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:i}=t,o=new $;if(ae(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;t.extra&&(r=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&i.count>0&&oe(this,e,o),e.revision++,this.engine?.cellsChanged(e,i.rows,i.cols,i.count);const s=this.sheets.indexOf(e);return s>=0&&(this.activeSheet=s),{sheetIndex:s>=0?s:t.sheetIndex,sheet:e,log:o,label:t.label,extra:r}}undo(){const t=this.undoStack.pop();return t?(this.redoStack.push(this._restore(t)),this._emit("cells"),!0):!1}redo(){const t=this.redoStack.pop();return t?(this.undoStack.push(this._restore(t)),this._emit("cells"),!0):!1}setInput(t,e,i,o,{overLimitAsText:r=!1,typedQuote:s=!0}={}){const{sheet:n}=t,l=n.style(e,i),c=o!==""&&this.styles.get(l).numFmt==="@";let a=c?{kind:T,text:o[0]==="'"?o.slice(1):o}:ie(o,void 0,this.dateOffset);if(a.kind===F){const u=Fe(a.formula);if(u){if(!r)throw new L(u);a={kind:T,text:o}}}if(this.recorder){const u=a.kind===T&&o.startsWith("=")&&!c?`'${o}`:o;this.recorder.push(`sheet.setValue(${JSON.stringify(ge(e,i))}, ${JSON.stringify(u)});`)}t.saveCell(e,i),n.setFormula(e,i,null);const h=s&&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 I:n.setCell(e,i,I,0);break;case P:n.setCell(e,i,P,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 D:n.setCell(e,i,D,a.value);break;case U:n.setCell(e,i,U,a.value);break;case F:n.setCell(e,i,F|I,0),n.setFormula(e,i,{f:Ae(this._expandTableRefs(ue(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,T,this.strings.add(ne(a.text)))}}setRichInput(t,e,i,o,r){const{sheet:s}=t;t.saveCell(e,i),s.setFormula(e,i,null);const n=ne(o);s.setCell(e,i,T,this.strings.addRich(n,n===o?r:r?.filter(l=>l.at<n.length)))}_expandTableRefs(t,e,i,o){const r=this.engine;return!r||r.tables.size===0?t:Me(t,()=>{for(const s of r.tables.values())if(s.sheet===e&&i>=s.r0&&i<=s.r1&&o>=s.c0&&o<=s.c1)return s;return null})}clearRange(t,e="contents",{visibleOnly:i=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",o=>{const{sheet:r}=o,s=[];if(e!=="contents")for(const{r0:l,c0:c,r1:a,c1:h}of t){const u=l===0&&a===X-1,p=c===0&&h===R-1,f=(d,g,y,w)=>{for(const[C,x]of[...g])C<y||C>w||(s.push([d,C,x]),g.delete(C))};u&&r.colStyles!==null&&f("col",r.colStyles,c,h),p&&r.rowStyles!==null&&f("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 t){const u=Math.min(h,r.maxCol),p=Math.min(a,r.maxRow);for(let f=c;f<=u;f++)if(r.columns[f]!==void 0)for(let d=l;d<=p;d++){if(r._chunk(d,f)===void 0){d|=1023;continue}if(n!==null&&n.has(d))continue;const y=r.kind(d,f)!==0,w=r.cellStyle(d,f)!==0;if(e==="formats"){if(!w)continue;o.saveCell(d,f),r.setStyle(d,f,0);continue}!y&&!(e==="all"&&w)||(o.saveCell(d,f),r.setCell(d,f,I,0),r.setFormula(d,f,null),e==="all"&&r.setStyle(d,f,0))}}return s.length>0?j([],s):void 0})}applyStyle(t,e,{measureRow:i,numberFit:o}={}){const r=JSON.stringify(e);if(this.recorder)for(const s of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(Se(s))}, ${r});`);this.transact("format",s=>{const{sheet:n}=s;this.strings.rich!==null&&Re(this,s,t,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 t){const x=g===0&&w===X-1,v=y===0&&C===R-1,k=x||v,b=k?Math.min(w,n.maxRow):w,he=k?Math.min(C,n.maxCol):C;for(let S=y;S<=he&&g<=b;S++){const _=n.columns[S];if(!(k&&!_))for(let M=g>>>z;M<=b>>>z;M++){const G=M<<z,K=Math.max(g,G),ce=Math.min(b,G+W),N=k?_[M]:n._ensure(K,S);if(!(k&&!N?.styles)){u(S,M,N);for(let E=K;E<=ce;E++)(!k||N.styles[E&W])&&p(E,S,this.styles.derive(n.style(E,S),e,r))}}}const O=S=>this.styles.derive(S,e,r),q=(S,_,M)=>{u(_,S>>>z,n._ensure(S,_)),n.setStyle(S,_,M||this.styles.explicitDefault())};if(v&&x){ve(n,O,a);for(const[S,_]of n.rowStyles??[])a.push(["row",S,_]),n.rowStyles.set(S,O(_))}else if(x)for(let S=y;S<=C;S++)se(n,"col",S,O,a,q);else if(v)for(let S=g;S<=w;S++)se(n,"row",S,O,a,q)}const f=(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))},d=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 t){const x=Math.min(y,n.maxRow);if(d&&x-g<=2e3)for(let v=g;v<=x;v++)f("rows",v,ke(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)&Y)===P&&(k=Math.max(k,o.measure(n,b,v)));f("cols",v,k)}}return j(l,a,h)})}}function ae(m,t,e){for(let i=t.count-1;i>=0;i--){const o=t.rows[i],r=t.cols[i];e?.push(m,o,r),m.setCell(o,r,t.kinds[i],t.values[i]),m.setStyle(o,r,t.styles[i]),m.setFormula(o,r,t.kinds[i]&F?t.formulas.get(i):null)}}function H(m,t){const e=()=>{const i=[];for(let o=t.length-1;o>=0;o--)i.push(m._restore(t[o]));return H(m,i)};return e.parts=t,e}function ze(m,t){let e=null;for(const i of t.vms.keys()){const o=t.rows[i],r=t.cols[i];(m.kind(o,r)&~(J|Z))===t.kinds[i]&&m.value(o,r)===t.values[i]||(e??=new Map(m.valueMeta),e.delete(o*R+r))}e!==null&&(m.valueMeta=e.size>0?e:null)}function Ue(m,t,e,i){if(!t.size||typeof m!="string")return m;let o;try{o=Te(m)}catch(n){if(n instanceof L)return m;throw n}let r="",s=0;for(let n=0;n<o.length;n++){const l=o[n],c=l.t==="name"?m.slice(l.s,l.e):l.t==="table"?l.v.name:null;if(!c)continue;const a=t.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:f,sheet2:d}=u.v;if(p!==null||d!==null)continue;if(f.toUpperCase()===e.toUpperCase())r+=m.slice(s,u.s)+Q(i)+"!",s=u.e;else if(f.toUpperCase()!==i.toUpperCase())continue}r+=m.slice(s,l.s)+a.name,s=l.s+c.length}return s?r+m.slice(s):m}function A(m){if(m===null||typeof m!="object")return m;if(Array.isArray(m))return m.map(A);if(m instanceof Map)return new Map([...m].map(([e,i])=>[e,A(i)]));if(m instanceof Set)return new Set([...m].map(A));if(ArrayBuffer.isView(m))return m.slice();const t={};for(const[e,i]of Object.entries(m))!e.startsWith("_")&&typeof i!="function"&&(t[e]=A(i));return t}function j(m,t,e=[]){return i=>{const o=[];for(let n=0;n<m.length;n+=3){const l=m[n],c=m[n+1],a=i.columns[l]?.[c];a!==void 0&&(o.push(l,c,a.styles),a.styles=m[n+2])}const r=[];for(let n=t.length-1;n>=0;n--){const[l,c,a]=t[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 s=[];for(let n=e.length-1;n>=0;n--){const[l,c,a,h]=e[n],u=i[l];s.push([l,c,u.isCustom(c)?u.sizeOf(c):null,u.isAuto(c)]),u.setSize(c,a,h),l==="cols"&&(i.colsChanged=!0)}return j(o,r,s)}}export{$ as CellLog,Ie as GROUP_LABELS,Qe as Workbook,H as foldEntries,ie as parseInput,j 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};