@8sheets/data-grid 0.0.0-stage → 1.0.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 (290) hide show
  1. package/LICENSE.md +36 -0
  2. package/README.md +52 -2
  3. package/a11y/cell-alt-text.js +1 -0
  4. package/api/overlay.js +1 -0
  5. package/api/serialize.js +1 -0
  6. package/api/skins.js +1 -0
  7. package/api/style-refs.js +1 -0
  8. package/api/watermark-xml.js +2 -0
  9. package/calc/adjust.js +1 -0
  10. package/calc/cell-set.js +1 -0
  11. package/calc/compile.js +1 -0
  12. package/calc/engine.js +1 -0
  13. package/calc/fill-shape.js +2 -0
  14. package/calc/functions/array.js +1 -0
  15. package/calc/functions/database.js +1 -0
  16. package/calc/functions/date.js +1 -0
  17. package/calc/functions/engineering.js +1 -0
  18. package/calc/functions/financial.js +1 -0
  19. package/calc/functions/helpers.js +1 -0
  20. package/calc/functions/index.js +1 -0
  21. package/calc/functions/info.js +1 -0
  22. package/calc/functions/logical.js +1 -0
  23. package/calc/functions/lookup.js +1 -0
  24. package/calc/functions/math.js +1 -0
  25. package/calc/functions/registry.js +1 -0
  26. package/calc/functions/stat.js +1 -0
  27. package/calc/functions/text.js +1 -0
  28. package/calc/parser.js +3 -0
  29. package/calc/values.js +1 -0
  30. package/calcx/ai/client.js +1 -0
  31. package/calcx/ai/functions.js +15 -0
  32. package/calcx/ai/settings.js +1 -0
  33. package/calcx/async.js +1 -0
  34. package/calcx/culture/format-locale.js +1 -0
  35. package/calcx/culture/lcid.js +1 -0
  36. package/calcx/external-read.js +1 -0
  37. package/calcx/external-write.js +3 -0
  38. package/calcx/external.js +1 -0
  39. package/calcx/functions/dynamic.js +1 -0
  40. package/calcx/functions/ets.js +1 -0
  41. package/calcx/functions/index.js +1 -0
  42. package/calcx/functions/misc.js +1 -0
  43. package/calcx/functions/text.js +1 -0
  44. package/calcx/functions/xml.js +1 -0
  45. package/calcx/refresh.js +1 -0
  46. package/cells/auto-merge.js +1 -0
  47. package/cells/axis-limits.js +1 -0
  48. package/cells/axis-ops.js +1 -0
  49. package/cells/background-xml.js +1 -0
  50. package/cells/background.js +1 -0
  51. package/cells/book-css.js +206 -0
  52. package/cells/book-read.js +1 -0
  53. package/cells/book-view.js +1 -0
  54. package/cells/cell-defaults.js +1 -0
  55. package/cells/cell-extras.js +1 -0
  56. package/cells/cell-options-ui.js +1 -0
  57. package/cells/cell-styles-xml.js +1 -0
  58. package/cells/cf-engine.js +1 -0
  59. package/cells/cf-file.js +1 -0
  60. package/cells/cf-paint.js +1 -0
  61. package/cells/consolidate-links.js +1 -0
  62. package/cells/docprops-xml.js +2 -0
  63. package/cells/filter-file.js +1 -0
  64. package/cells/find-engine.js +2 -0
  65. package/cells/find.js +1 -0
  66. package/cells/format-code.js +1 -0
  67. package/cells/format-panes.js +3 -0
  68. package/cells/format-tabs.js +102 -0
  69. package/cells/goto.js +1 -0
  70. package/cells/header-colors.js +1 -0
  71. package/cells/mask.js +1 -0
  72. package/cells/menu-extras.js +1 -0
  73. package/cells/name-box.js +1 -0
  74. package/cells/note-xml.js +1 -0
  75. package/cells/options.js +1 -0
  76. package/cells/outline-column.js +1 -0
  77. package/cells/paint.js +1 -0
  78. package/cells/panes.js +1 -0
  79. package/cells/rich-data-xml.js +2 -0
  80. package/cells/rich-data.js +1 -0
  81. package/cells/rich-runs.js +2 -0
  82. package/cells/rich-values.js +1 -0
  83. package/cells/rich-xml.js +1 -0
  84. package/cells/rounded.js +1 -0
  85. package/cells/sections.js +2 -0
  86. package/cells/selection-modes.js +1 -0
  87. package/cells/style-xml.js +1 -0
  88. package/cells/text-layout.js +8 -0
  89. package/cells/undo-group.js +1 -0
  90. package/cells/validation-alert.js +2 -0
  91. package/cells/view-options.js +1 -0
  92. package/cells/view-xml.js +1 -0
  93. package/celltypes/barcode-tables.js +31 -0
  94. package/celltypes/barcode.js +2 -0
  95. package/celltypes/base.js +1 -0
  96. package/celltypes/cell-buttons.js +1 -0
  97. package/celltypes/cell-types.js +2 -0
  98. package/celltypes/data-object.js +1 -0
  99. package/celltypes/diagonal.js +1 -0
  100. package/celltypes/dropdowns-more.js +13 -0
  101. package/celltypes/dropdowns.js +42 -0
  102. package/celltypes/file-cell.js +2 -0
  103. package/celltypes/glyphs.js +1 -0
  104. package/celltypes/persist.js +2 -0
  105. package/celltypes/range-template.js +2 -0
  106. package/charts/chartex.js +3 -0
  107. package/charts/geo/geo-xml.js +1 -0
  108. package/charts/geo/map-state.js +1 -0
  109. package/charts/patterns.js +1 -0
  110. package/core/address.js +1 -0
  111. package/core/axis.js +1 -0
  112. package/core/base64.js +1 -0
  113. package/core/changes.js +1 -0
  114. package/core/color.js +1 -0
  115. package/core/cond-format.js +1 -0
  116. package/core/custom-views.js +1 -0
  117. package/core/default-names.js +1 -0
  118. package/core/formula-refs.js +1 -0
  119. package/core/formula-store.js +1 -0
  120. package/core/input.js +1 -0
  121. package/core/math.js +1 -0
  122. package/core/numfmt.js +1 -0
  123. package/core/online.js +1 -0
  124. package/core/protection.js +1 -0
  125. package/core/regexp.js +1 -0
  126. package/core/sheet.js +1 -0
  127. package/core/sparklines.js +1 -0
  128. package/core/sparse.js +1 -0
  129. package/core/strings.js +1 -0
  130. package/core/styles.js +1 -0
  131. package/core/table-presets.js +7 -0
  132. package/core/tables.js +2 -0
  133. package/core/tsv.js +4 -0
  134. package/core/whatif.js +1 -0
  135. package/core/workbook.js +1 -0
  136. package/datasheets/bind.js +1 -0
  137. package/datasheets/calendar.js +1 -0
  138. package/datasheets/cross.js +1 -0
  139. package/datasheets/data-core.js +1 -0
  140. package/datasheets/data.js +1 -0
  141. package/datasheets/formula.js +1 -0
  142. package/datasheets/gantt-paint.js +1 -0
  143. package/datasheets/gantt-resources.js +1 -0
  144. package/datasheets/gantt-shapes.js +1 -0
  145. package/datasheets/gantt.js +1 -0
  146. package/datasheets/manager.js +1 -0
  147. package/datasheets/path-binding.js +2 -0
  148. package/datasheets/persist-writer.js +2 -0
  149. package/datasheets/persist.js +1 -0
  150. package/datasheets/query-function.js +1 -0
  151. package/datasheets/remote.js +3 -0
  152. package/datasheets/report-entry.js +1 -0
  153. package/datasheets/report.js +1 -0
  154. package/datasheets/rules.js +1 -0
  155. package/datasheets/sort.js +1 -0
  156. package/datasheets/table-sheet.js +1 -0
  157. package/datasheets/view.js +3 -0
  158. package/datasheets/virtual-sheet.js +1 -0
  159. package/datasheets/window.js +1 -0
  160. package/extras/getdata/persist.js +2 -0
  161. package/extras/getdata/rows.js +1 -0
  162. package/extras/getdata/steps.js +1 -0
  163. package/i18n/dom.js +1 -0
  164. package/i18n/en/a11y.js +1 -0
  165. package/i18n/en/cells.js +1 -0
  166. package/i18n/en/charts.js +1 -0
  167. package/i18n/en/common.js +1 -0
  168. package/i18n/en/datasheets.js +1 -0
  169. package/i18n/en/format.js +1 -0
  170. package/i18n/en/misc.js +1 -0
  171. package/i18n/en/pivot.js +1 -0
  172. package/i18n/en/proofing.js +1 -0
  173. package/i18n/en/ribbon.js +1 -0
  174. package/i18n/en/shapes.js +1 -0
  175. package/i18n/en/shell.js +1 -0
  176. package/i18n/en/touch.js +1 -0
  177. package/i18n/en.js +1 -0
  178. package/i18n/index.js +1 -0
  179. package/i18n/key-text.js +1 -0
  180. package/i18n/languages.js +1 -0
  181. package/i18n/pl/a11y.js +1 -0
  182. package/i18n/pl/cells.js +1 -0
  183. package/i18n/pl/charts.js +1 -0
  184. package/i18n/pl/common.js +1 -0
  185. package/i18n/pl/datasheets.js +1 -0
  186. package/i18n/pl/format.js +1 -0
  187. package/i18n/pl/misc.js +1 -0
  188. package/i18n/pl/pivot.js +1 -0
  189. package/i18n/pl/proofing.js +1 -0
  190. package/i18n/pl/ribbon.js +1 -0
  191. package/i18n/pl/shapes.js +1 -0
  192. package/i18n/pl/shell.js +1 -0
  193. package/i18n/pl/touch.js +1 -0
  194. package/i18n/pl.js +1 -0
  195. package/io/client.js +1 -0
  196. package/io/crc32.js +1 -0
  197. package/io/crypto/aes.js +1 -0
  198. package/io/crypto/agile.js +2 -0
  199. package/io/crypto/cfb-read.js +1 -0
  200. package/io/crypto/cfb-write.js +1 -0
  201. package/io/crypto/dataspaces.js +1 -0
  202. package/io/crypto/errors.js +1 -0
  203. package/io/crypto/hash.js +1 -0
  204. package/io/crypto/index.js +1 -0
  205. package/io/crypto/package-read.js +1 -0
  206. package/io/crypto/package-write.js +1 -0
  207. package/io/crypto/spool.js +1 -0
  208. package/io/crypto/standard.js +1 -0
  209. package/io/csv.js +5 -0
  210. package/io/export-blocks.js +1 -0
  211. package/io/foreign-parts.js +1 -0
  212. package/io/foreign-sheets.js +2 -0
  213. package/io/io.worker.js +1 -0
  214. package/io/package-paths.js +1 -0
  215. package/io/plan.js +1 -0
  216. package/io/xlsx-read.js +1 -0
  217. package/io/xlsx-styles.js +2 -0
  218. package/io/xlsx-tail.js +1 -0
  219. package/io/xlsx-write.js +2 -0
  220. package/io/xml-escape.js +1 -0
  221. package/io/xml-scan.js +1 -0
  222. package/io/zip-reader.js +1 -0
  223. package/io/zip-writer.js +1 -0
  224. package/objects/chart-model.js +1 -0
  225. package/objects/dml.js +5 -0
  226. package/objects/drawing-xml.js +1 -0
  227. package/objects/picture-url.js +1 -0
  228. package/package.json +57 -4
  229. package/pivot/engine.js +1 -0
  230. package/pivot/xml.js +2 -0
  231. package/print/page-setup.js +1 -0
  232. package/print/paginate.js +1 -0
  233. package/print/pdf.js +35 -0
  234. package/print/render-page.js +3 -0
  235. package/render/patterns.js +1 -0
  236. package/shapes/form-xml.js +1 -0
  237. package/shapes/watermark.js +1 -0
  238. package/slicers/custom-styles.js +1 -0
  239. package/slicers/date-filters.js +1 -0
  240. package/slicers/format.js +2 -0
  241. package/slicers/pivot-file.js +1 -0
  242. package/slicers/structured.js +1 -0
  243. package/slicers/table-file.js +1 -0
  244. package/slicers/write.js +1 -0
  245. package/sparklines/colors.js +1 -0
  246. package/sparklines/data.js +1 -0
  247. package/sparklines/descriptor.js +1 -0
  248. package/sparklines/excel-paint.js +1 -0
  249. package/sparklines/functions.js +1 -0
  250. package/sparklines/paint-core.js +1 -0
  251. package/sparklines/paint-measure.js +1 -0
  252. package/sparklines/paint-other.js +2 -0
  253. package/sparklines/paint-series.js +1 -0
  254. package/sparklines/paint.js +1 -0
  255. package/sparklines/print.js +1 -0
  256. package/sparklines/rule.js +1 -0
  257. package/table-view/api.js +1 -0
  258. package/table-view/cell-editor.js +1 -0
  259. package/table-view/cell-format.js +1 -0
  260. package/table-view/chrome.js +1 -0
  261. package/table-view/client.js +1 -0
  262. package/table-view/column-drag.js +1 -0
  263. package/table-view/column-input.js +1 -0
  264. package/table-view/column-window.js +1 -0
  265. package/table-view/events.js +1 -0
  266. package/table-view/files.js +1 -0
  267. package/table-view/grid-keys.js +2 -0
  268. package/table-view/index.d.ts +4 -0
  269. package/table-view/index.js +1 -0
  270. package/table-view/labels.js +1 -0
  271. package/table-view/model.js +1 -0
  272. package/table-view/mount.js +1 -0
  273. package/table-view/panel.js +1 -0
  274. package/table-view/pivot.js +1 -0
  275. package/table-view/public.d.ts +841 -0
  276. package/table-view/quick-filter.js +1 -0
  277. package/table-view/reader.worker.js +1 -0
  278. package/table-view/remote.js +1 -0
  279. package/table-view/row-cache.js +1 -0
  280. package/table-view/row-selection.js +1 -0
  281. package/table-view/table-css.js +1207 -0
  282. package/table-view/totals.js +1 -0
  283. package/table-view/version.js +1 -0
  284. package/table-view/worksheet-table.js +1 -0
  285. package/ui/dialogs.js +3 -0
  286. package/ui/dom.js +1 -0
  287. package/ui/icons.js +1 -0
  288. package/ui/menu-base.js +1 -0
  289. package/ui/protection-ui.js +1 -0
  290. package/ui/ui-scale.js +1 -0
package/core/tables.js ADDED
@@ -0,0 +1,2 @@
1
+ import{patchTableColumns as Y,totalsChildXml as N}from"../slicers/table-file.js";import{colName as q,MAX_COLS as G,rangeRef as F,sheetPrefix as J}from"./address.js";import{columnStem as y,nextName as Q,tableStem as V,totalLabel as k}from"./default-names.js";import{FORMULA as D,KIND_MASK as L,STR as T}from"./sheet.js";import{translateFormula as ee}from"./formula-refs.js";import{autoFilterXml as te,sortStateXml as re}from"../cells/filter-file.js";import{PRESET_DXFS as ne,PRESET_STYLES as K}from"./table-presets.js";import{resolveColor as se}from"../io/xlsx-styles.js";import{elementTableColors as le}from"../slicers/custom-styles.js";import{undoGroup as oe}from"../cells/undo-group.js";import{escapeMarkup as E,xmlAttr as M}from"../io/xml-escape.js";const ae=["FFFFFF","000000","E8E8E8","0E2841","156082","E97132","196B24","0F9ED5","A02B93","4EA72E"],B=new Set;function Le(t){B.add(t)}function ce(t,e){const r=K[t];if(!r)return null;const s=e&&e.length>=10?e:ae,n=l=>typeof l=="string"?`#${l}`:se({a:{theme:String(l[0]),tint:l[1]?String(l[1]):void 0}},s),o={},a={};for(const[l,f,u]of r){const c=ne[f],i={};c.bold&&(i.bold=!0),c.italic&&(i.italic=!0),c.c&&(i.color=n(c.c)),c.f&&(i.fill=n(c.f));for(const d of["l","r","t","b","v","h"])c[d]&&(i.borders??={},i.borders[d]={style:c[d][0],color:n(c[d][1])});o[l]=i,u&&(a[l]=u)}return{el:o,sizes:a}}const P=new WeakMap,ie={};function ue(t,e){if(t&&K[t]&&t.startsWith("TableStyle")){const r=e&&e.length>=10?e:ie;let s=P.get(r);s||P.set(r,s=new Map);let n=s.get(t);if(!n){const{el:o,sizes:a}=ce(t,e),l=f=>a[f]??1;n=le(o,[l("firstRowStripe"),l("secondRowStripe")],[l("firstColumnStripe"),l("secondColumnStripe")]),s.set(t,n)}return n}for(const r of B){const s=r(t,e);if(s)return s}return null}function Me(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 l=[];for(const f of s.hiddenSizes.keys())f>=r&&f<=t.r1&&l.push(f);l.sort((f,u)=>f-u),n={version:s.version,top:r,r1:t.r1,rows:s,list:l},t._bandRows=n}let o=0,a=n.list.length;for(;o<a;){const l=o+a>>1;n.list[l]<e?o=l+1:a=l}return e-r-o}function fe(t){const e=t.engine;return Q(V(),r=>e.tables.has(r.toUpperCase()))}function _e(t,e,r,s,n="TableStyleMedium2"){const o=t.engine,a=[];let l={...r};return t.transact("table",f=>{if(!s){l.r0>0&&!_(e,l.r0-1,l.c0,l.c1)&&(l={...l,r0:l.r0-1});for(let i=l.c0;i<=l.c1;i++)t.setInput(f,l.r0,i,`${y()}${i-l.c0+1}`)}const u=new Set;for(let i=l.c0;i<=l.c1;i++){let d=t.editText(e,l.r0,i).trim()||`${y()}${i-l.c0+1}`,m=d;for(let p=2;u.has(m.toLowerCase());p++)m=`${d}${p}`;u.add(m.toLowerCase()),a.push(m),(m!==d||(e.kind(l.r0,i)&L)!==T)&&(d=m,f.saveCell(l.r0,i),e.setCell(l.r0,i,T,t.strings.add(m)))}const c={name:fe(t),sheet:e,...l,headerRows:1,totalsRows:0,columns:a,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};return o.tables.set(c.name.toUpperCase(),c),()=>(o.tables.delete(c.name.toUpperCase()),o.rebuild(),()=>(o.tables.set(c.name.toUpperCase(),c),o.rebuild(),()=>null))}),o.tables.get(`${[...o.tables.keys()].pop()}`)}function _(t,e,r,s){for(let n=r;n<=s;n++)if(t.kind(e,n)!==0)return!0;return!1}function g(t,e){const r=[];if(t.engine)for(const s of t.engine.tables.values())s.sheet===e&&r.push(s);return r}function Ie(t,e,r,s){for(const n of g(t,e)){const o=r===n.r1+1-0&&n.totalsRows===0&&s>=n.c0&&s<=n.c1,a=s===n.c1+1&&r>=n.r0&&r<=n.r1;if(o)return n.r1=r,n.filter&&(n.filter.r1=r),n.dirty=!0,r-1>=n.r0+n.headerRows&&t.transact("table-row",l=>{for(let f=n.c0;f<=n.c1;f++)f===s||(e.kind(r-1,f)&D)===0||e.kind(r,f)!==0||t.setInput(l,r,f,`=${ee(t.editText(e,r-1,f).slice(1),1,0)}`)}),t.engine.rebuild(),n;if(a){n.c1=s;const l=t.editText(e,n.r0,s).trim()||`${y()}${n.columns.length+1}`;return n.columns.push(l),n.filter&&(n.filter.c1=s),e.kind(n.r0,s)===0&&e.setCell(n.r0,s,T,t.strings.add(l)),n.dirty=!0,n.columnsChanged=!0,t.engine.rebuild(),n}}return null}function Ue(t,e,r){for(const s of g(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(g(t,e).some(a=>a!==s&&a.r0<=n&&a.r1>=r.r0&&a.c0<=s.c1&&a.c1>=s.c0))return null;const o={r1:s.r1,filter:s.filter?{...s.filter}:null};return t.transact("table-expand",()=>{const a=u=>{s.r1=u.r1,s.filter=u.filter?{...u.filter}:null,s.dirty=!0,t.engine.rebuild()},l={r1:n,filter:s.filter?{...s.filter,r1:n}:null};a(l);const f=(u,c)=>()=>(a(u),f(c,u));return f(o,l)}),s}return null}function ze(t,e,r,s,n,o){if(!n.startsWith("="))return!1;for(const a of g(t,e)){if(s<a.c0||s>a.c1||r<=a.r0||r>a.r1-a.totalsRows)continue;const l=a.r0+a.headerRows,f=a.r1-a.totalsRows;for(let u=l;u<=f;u++)if(u!==r&&e.kind(u,s)!==0)return!1;return f===l?!1:(t.transact("calculated-column",u=>{for(let c=l;c<=f;c++)c!==r&&t.setInput(u,c,s,`=${o(n.slice(1),c-r,0)}`)}),!0)}return!1}const Z=(t,e)=>{const r=t.totals?.[e];return r?r.label!==void 0?` totalsRowLabel="${M(r.label)}"`:` totalsRowFunction="${r.fn}"`:""},j=t=>`<tableStyleInfo name="${M(t.styleName??"TableStyleMedium2")}" showFirstColumn="${t.showFirstColumn?1:0}" showLastColumn="${t.showLastColumn?1:0}" showRowStripes="${t.showRowStripes===!1?0:1}" showColumnStripes="${t.showColumnStripes?1:0}"/>`,de=t=>F({r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1}),H=t=>t.filter&&t.headerRows>0?te({...t.filter,r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1},!1)+re(t.filter.sortState):"",W=t=>`${t.headerRows===0?' headerRowCount="0"':""}${t.totalsRows?` totalsRowCount="${t.totalsRows}"`:' totalsRowShown="0"'}`;function Oe(t,e){const r=t.columns.map((n,o)=>{const a=N(t,o),l=`<tableColumn id="${t.columnIds?.[o]??o+1}" name="${M(n)}"${Z(t,o)}`;return a?`${l}>${a}</tableColumn>`:`${l}/>`}).join(""),s=H(t);return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="${e}" name="${E(t.name)}" displayName="${E(t.name)}" ref="${F(t)}"${W(t)}>${s}<tableColumns count="${t.columns.length}">${r}</tableColumns>${j(t)}</table>`}function Xe(t){return{name:t.name,ref:F(t),filterRef:t.filter&&t.headerRows>0?de(t):null,filterXml:H(t),counts:W(t),styleInfo:j(t),totals:t.totals?t.columns.map((e,r)=>Z(t,r)):null,totalsChild:t.totals?t.columns.map((e,r)=>N(t,r)):null}}function Ne(t,e){let r=t.replace(/<table\b[^>]*>/,s=>s.replace(/\bname="[^"]*"/,`name="${E(e.name)}"`).replace(/\bdisplayName="[^"]*"/,`displayName="${E(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=Y(r,e)),r}const me=/[[\]#']/g,I=t=>t.replace(me,"'$&"),pe=/^[A-Za-z_\\][A-Za-z0-9_.\\]*$/;function U(t,e){const r=[];for(const s of t.sheets){const n=new Map;for(const[o,a]of s.formulas){const l=a.f??a.sf;if(typeof l!="string")continue;const f=a.f===void 0&&a.base!==void 0;let u=f?n.get(a):void 0;if(u===void 0){const c=e(l,s,Math.floor((f?a.base:o)/G));u=c===l?null:a.f!==void 0?{...a,f:c,tpl:void 0}:{...a,sf:c,tpl:void 0},f&&n.set(a,u)}u!==null&&r.push([s.formulas,o,a,u])}}for(const[s,n]of t.engine.names){const o=e(n.text,null,0);o!==n.text&&r.push([t.engine.names,s,n,{...n,text:o}])}return t.formulasEdited=!0,r.some(s=>s[0]===t.engine.names)&&(t.namesChanged=!0),x(r,3),r}const x=(t,e)=>{for(const r of t)r[0].set(r[1],r[e])};function C(t,e,r,s,{rebuild:n=!1}={}){const o=t.engine;t.transact(r,a=>{const l={...e},f=s(a),u={...e};e.dirty=!0,n&&o.rebuild();const c=(i,d,m)=>()=>(Object.assign(e,i),e.dirty=!0,m?.(),n&&o.rebuild(),c(d,i,m));return c(l,u,f)})}function De(t,e,r,s){C(t,e,"table-option",()=>{e[r]=s})}function Ke(t,e,r){r&&e.headerRows===0||C(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 Be(t,e,r){const s=t.engine;if(!pe.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 o=e.name;return t.transact("table-name",()=>{const a=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${o.replace(/[.\\]/g,"\\$&")}(?=\\[)`,"gi"),l=U(t,i=>i.replace(a,`$1${r}`)),f=(i,d,m)=>{s.tables.delete(i.toUpperCase()),e.name=d,s.tables.set(d.toUpperCase(),e),e.dirty=!0,x(l,m),s.rebuild()};f(o,r,3);const u=()=>(f(o,r,3),c),c=()=>(f(r,o,2),u);return c}),null}function Pe(t,e,r){const{sheet:s}=e;if(r===e.totalsRows>0)return null;if(r){const o=e.r1+1;return _(s,o,e.c0,e.c1)?"Clear the row under the table to add a total row.":(C(t,e,"table-totals",a=>{const l=e.c1-e.c0;e.totals=e.columns.map(()=>null);const f=k();if(e.totals[0]={label:f},t.setInput(a,o,e.c0,f),l>0){let u=!1;for(let i=e.r0+e.headerRows;i<=e.r1&&!u;i++)u=(s.kind(i,e.c1)&L)===1;const c=u?109:103;e.totals[l]={fn:u?"sum":"count"},t.setInput(a,o,e.c1,`=SUBTOTAL(${c},${e.name}[${I(e.columns[l])}])`)}e.totalsRows=1,e.r1=o,e.columnsChanged=e.source!==!0},{rebuild:!0}),null)}const n=e.r1;return C(t,e,"table-totals",o=>{for(let a=e.c0;a<=e.c1;a++)t.setInput(o,n,a,"");e.totalsRows=0,e.totals=null,e.r1=n-1},{rebuild:!0}),null}function Ze(t,e,r){if(r===e.headerRows>0)return null;const{sheet:s}=e;return r?e.r0===0||_(s,e.r0-1,e.c0,e.c1)?"Clear the row above the table to show its headers.":(C(t,e,"table-header",n=>{e.r0-=1,e.headerRows=1,e.columns.forEach((o,a)=>t.setInput(n,e.r0,e.c0+a,o)),e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}},{rebuild:!0}),null):(C(t,e,"table-header",n=>{for(let o=e.c0;o<=e.c1;o++)t.setInput(n,e.r0,o,"");e.r0+=1,e.headerRows=0,e.filter=null},{rebuild:!0}),null)}function je(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 g(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 C(t,e,"table-resize",()=>{const n=r.c1-r.c0+1,o=e.columns.slice(0,n);for(let a=o.length;a<n;a++){const l=e.c0+a;let f=e.headerRows?t.editText(s,e.r0,l).trim():"";f||(f=`${y()}${a+1}`),o.push(f)}e.columns=o,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 he(t,e,r){const{sheet:s}=e,n=e.r1-e.r0+1,o=e.c1-e.c0+1,a=new Map,l=(u,c,i,d)=>{const m=(u-e.r0)*o+(c-e.c0);let p=a.get(m);p||a.set(m,p={}),p[i]=d};for(const u of r.areas(e,e.r0,e.r1,e.c0,e.c1)){const c=u.borders;for(let i=Math.max(u.r0,e.r0);i<=Math.min(u.r1,e.r1);i++)for(let d=Math.max(u.c0,e.c0);d<=Math.min(u.c1,e.c1);d++)c.t&&i===u.r0&&l(i,d,"t",c.t),c.b&&i===u.r1&&l(i,d,"b",c.b),c.l&&d===u.c0&&l(i,d,"l",c.l),c.r&&d===u.c1&&l(i,d,"r",c.r),c.h&&i<u.r1&&l(i,d,"b",c.h),c.v&&d<u.c1&&l(i,d,"r",c.v)}const f=new Map;t.transact("format",u=>{for(let c=0;c<n;c++){const i=e.r0+c;for(let d=0;d<o;d++){const m=e.c0+d,p=r.format(e,i,m),w=a.get(c*o+d),h=s.style(i,m),$=t.styles.get(h),b={};if(p.fill&&!$.fill&&(b.fill=p.fill),p.color&&!$.color&&(b.color=p.color),p.bold&&!$.bold&&(b.bold=!0),p.italic&&!$.italic&&(b.italic=!0),w){const R=$.borders??{},O={l:R.l??null,r:R.r??null,t:R.t??null,b:R.b??null};let X=!1;for(const S of["l","r","t","b"])w[S]&&!R[S]&&(O[S]={style:w[S].style,color:w[S].color},X=!0);X&&(b.borders=O)}const A=JSON.stringify(b);if(A==="{}")continue;const z=`${h}|${A}`;let v=f.get(z);v===void 0&&f.set(z,v=t.styles.derive(h,b,A)),v!==h&&(u.saveCell(i,m),s.setStyle(i,m,v))}}})}function He(t,e){oe(t,"Convert to Range",()=>we(t,e))}function we(t,e){const r=t.engine,{sheet:s}=e,n=ue(e.styleName,t.theme),o=t.activeSheet;t.activeSheet=t.sheets.indexOf(s),n?.format&&he(t,e,n),t.activeSheet=o;const a=e.name.toUpperCase(),l=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${e.name.replace(/[.\\]/g,"\\$&")}(\\[(?:[^\\[\\]']|'.|\\[(?:[^\\[\\]']|'.)*\\])*\\])`,"gi");t.transact("table-convert",()=>{const f=U(t,(d,m,p)=>d.replace(l,(w,h,$)=>{const b=r.tableSpecToA1(e,$,p);return b===null?w:`${h}${m===s?"":J(s.name)}${b}`})),u=e.source===!0&&e.part?{part:e.part,sheetIndex:t.sheets.indexOf(s)}:null,c=()=>{r.tables.delete(a),u&&(t.removedTables??=[]).push(u),x(f,3),r.rebuild()},i=()=>(r.tables.set(a,e),u&&(t.removedTables=t.removedTables.filter(d=>d!==u)),x(f,2),r.rebuild(),()=>(c(),i));return c(),i})}function be(t,e,r,s){const n=t.toLowerCase(),o=`${e.toLowerCase()}[`;let a="",l=0;for(let f=n.indexOf(o);f>=0;f=n.indexOf(o,f+1)){const u=f+o.length-1;let c=0,i=u;for(;i<t.length;i++){const p=t[i];if(p==="'")i++;else if(p==="[")c++;else if(p==="]"&&--c===0)break}const d=t.slice(u,i+1),m=d.split(`[${r}]`).join(`[${s}]`);m!==d&&(a+=t.slice(l,u)+m,l=i+1)}return l===0?t:a+t.slice(l)}function $e(t,e,r,s){const n=e.columns[r],o=I(n),a=I(s),l=U(t,i=>i.includes("[")?be(i,e.name,o,a):i),f=(i,d)=>{e.columns=e.columns.map((m,p)=>p===r?i:m),e.columnsChanged=!0,e.dirty=!0,x(l,d),t.engine?.rebuild()};f(s,3);const u=()=>(f(s,3),c),c=()=>(f(n,2),u);return c}function We(t,e,r){let s=null;const{sheet:n}=e;for(const o of g(t,n))if(!(o.headerRows===0||o.dataSheet))for(let a=0;a<r.count;a++){if(r.rows[a]!==o.r0||r.cols[a]<o.c0||r.cols[a]>o.c1)continue;const l=r.cols[a],f=l-o.c0,u=n.kind(o.r0,l);let c=u===0?"":String(t.engine.read(n,o.r0,l)??"").trim();const i=new Set(o.columns.filter((w,h)=>h!==f).map(w=>w.toLowerCase()));if(c===""){const w=y();let h=f+1;for(;i.has(`${w}${h}`.toLowerCase());)h++;c=`${w}${h}`}else if(i.has(c.toLowerCase())){const w=c;let h=2;for(;i.has(`${w}${h}`.toLowerCase());)h++;c=`${w}${h}`}if(((u&L)!==T||(u&D)!==0||t.strings.get(n.value(o.r0,l))!==c)&&(e.saveCell(o.r0,l),n.setFormula(o.r0,l,null),n.setCell(o.r0,l,T,t.strings.add(c))),o.columns[f]===c)continue;const d=$e(t,o,f,c),m=s,p=(w,h)=>h?()=>p(w(),h()):w;s=p(d,m)}return s}const Ye=[...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{Ye as TABLE_STYLE_NAMES,Me as bandRow,q as colName,He as convertTableToRange,_e as createTable,ze as fillCalculatedColumn,Ue as growTableOver,Ie as maybeExpandTable,fe as nextTableName,Ne as patchTableXml,ce as presetElements,Be as renameTable,$e as renameTableColumn,je as resizeTable,Le as setCustomTableResolver,Ke as setTableFilterButton,Ze as setTableHeaderRow,De as setTableOption,Pe as setTableTotals,I as structuredColumn,We as syncTableHeaders,ue as tableColors,Xe as tablePatch,Oe as tableXml,g as tablesOf};
package/core/tsv.js ADDED
@@ -0,0 +1,4 @@
1
+ function f(l){return/[\t\n\r]|^"/.test(l)?`"${l.replace(/"/g,'""')}"`:l}function i(l){const r=[];let s=[],e="",c=!1;const o=l.replace(/\r\n?/g,`
2
+ `),u=o.endsWith(`
3
+ `)?o.slice(0,-1):o;for(let n=0;n<u.length;n++){const t=u[n];c?t==='"'?u[n+1]==='"'?(e+='"',n++):c=!1:e+=t:t==='"'&&e===""?c=!0:t===" "?(s.push(e),e=""):t===`
4
+ `?(s.push(e),r.push(s),s=[],e=""):e+=t}return s.push(e),r.push(s),r}export{i as parseTsv,f as quoteTsv};
package/core/whatif.js ADDED
@@ -0,0 +1 @@
1
+ import{FORMULA as k,KIND_MASK as F,NUM as b,STR as V}from"./sheet.js";import{cellRef as T,MAX_COLS as G,parseRangeRef as $,rangeRef as H}from"./address.js";async function Q(t,n,r,e,a,{maxIter:o=200,tolerance:i=.001}={}){const l=t.engine,g=async d=>{t.transact("goal-seek",M=>{M.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,d)}),await l.whenIdle();const x=l.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,u=await g(p),v=f===0?1:f*1.01,S=await g(v),E={x:p,f:u},L=null,h=null;for(let d=0;d<o&&((Math.abs(S)<Math.abs(E.f)||Number.isNaN(E.f))&&(E={x:v,f:S}),!(Math.abs(S)<=i));d++){u*S<0&&(L=u<0?p:v,h=u<0?v:p);let x=S===u?v*1.5+1:v-S*(v-p)/(S-u);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,u=S,v=x,S=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 l.whenIdle(),{value:E.x,found:Math.abs(E.f)<=i,result:l.read(n,r.row,r.col)}}const R=t=>{if(t===void 0)return 0;const n=t.indexOf('outlineLevel="');return n<0?0:t.charCodeAt(n+14)-48},K=(t,n)=>t.rowExtras===null?0:R(t.rowExtras.get(n));function W(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 P=(t,n)=>t.colExtras===null?0:R(t.colExtras.get(n));function X(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 Y(t,n,r,e,a){for(let o=r;o<=e;o++)n==="row"?W(t,o,Math.max(0,Math.min(7,K(t,o)+a))):X(t,o,Math.max(0,Math.min(7,P(t,o)+a)));t.outlineVersion=(t.outlineVersion??0)+1,n==="col"&&(t.colsChanged=!0),t.revision++}function Z(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 C(t,n,r){return n==="row"?K(t,r):P(t,r)}function tt(t,n,r){const e=n==="row"?t.rowExtras:t.colExtras,a=n==="row"?t.rows:t.cols;if(e){for(const[o,i]of e){const l=/outlineLevel="(\d+)"/.exec(i);l&&a.setHidden(o,Number(l[1])>=r)}n==="col"&&(t.colsChanged=!0),t.revision++}}function nt(t,n,r,e,a,o){const i=[],l={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)&F)===V?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))&&(i.push({afterRow:c-1,from:s,to:c-1,title:`${g(s)} ${l}`}),s=c);return{groups:i,functionNum:a,sumCols:o,groupCol:e,grandTitle:`Grand ${l}`}}function rt(t,n,r,e,a){const o={r0:r.r0+1,c0:r.c0+1,r1:r.r1,c1:r.c1},i=e&&a,l={t:"dataTable",ref:H(o),dt2D:i?"1":"0",dtr:e?"1":"0",r1:T((e??a).row,(e??a).col)};i&&(l.r2=T(a.row,a.col));const g=t.engine,s={sheet:n,row:o.r0,col:o.c0,info:l};t.transact("data-table",c=>{for(let u=o.r0;u<=o.r1;u++)for(let v=o.c0;v<=o.c1;v++)c.saveCell(u,v),n.setFormula(u,v,null),n.setCell(u,v,b,0);n.setFormula(o.r0,o.c0,l),n.setCell(o.r0,o.c0,k|b,0),t.formulasEdited=!0,g.dataTables.push(s),g.tablesDirty=!0;const f=()=>(g.dataTables=g.dataTables.filter(u=>u!==s),p),p=()=>(g.dataTables.push(s),g.tablesDirty=!0,f);return f})}const U=(t,n,r,e)=>{const a=n.kind(r,e)&F;return a===0?"":a===V?t.strings.get(n.value(r,e)):String(n.value(r,e))};function et(t,n,r,e){const a=[],o=new Set;for(const i of r.split(/[\s,;]+/)){const l=$(i.replace(/\$/g,""));if(l)for(let g=l.r0;g<=l.r1&&a.length<32;g++)for(let s=l.c0;s<=l.c1&&a.length<32;s++){const c=T(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:U(t,n,g,s)})}}return a}function ot(t,n,r){t.transact("scenario",e=>{for(const{r:a,val:o}of r.cells){const i=$(a);i&&t.setInput(e,i.r0,i.c0,o)}})}function at(t,n,r,e){const a=t.engine,o=[["Scenario Summary","Current Values",...r.map(s=>s.name)]],i=[];for(const s of r)for(const c of s.cells)i.includes(c.r)||i.push(c.r);const l=s=>{const c=$(s);return{row:c.r0,col:c.c0}};o.push(["Changing Cells:"]);for(const s of i){const{row:c,col:f}=l(s);o.push([s,U(t,n,c,f),...r.map(p=>p.cells.find(u=>u.r===s)?.val??"")])}if(e.length>0){o.push(["Result Cells:"]);const s=r.map(c=>a.evaluateWith(n,c.cells.map(f=>({...l(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([T(c,f),String(a.read(n,c,f)??""),...s.map(u=>String(u[p]??""))])})}const g=t.addSheet();return t.transact("scenario-summary",s=>{o.forEach((c,f)=>c.forEach((p,u)=>{p!==""&&t.setInput(s,f,u,String(p))}))}),g}const w=t=>t.filter(n=>typeof n=="number"),A=t=>t.reduce((n,r)=>n+r,0),_=t=>A(t)/t.length,D=(t,n)=>{const r=_(t);return A(t.map(e=>(e-r)**2))/n},j={Sum:t=>A(w(t)),Count:t=>t.filter(n=>n!==null&&n!=="").length,Average:t=>w(t).length?_(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(D(w(t),w(t).length-1)):null,StdDevp:t=>w(t).length?Math.sqrt(D(w(t),w(t).length)):null,Var:t=>w(t).length>1?D(w(t),w(t).length-1):null,Varp:t=>w(t).length?D(w(t),w(t).length):null};function ct(t,n,r,e,a,{topRow:o=!1,leftCol:i=!1}={}){const l=t.engine,g=j[a],s=[],c=[],f=new Map,p=new Map,u=new Map,v=(h,m,d)=>{const x=String(d).toLowerCase();let M=h.get(x);return M===void 0&&(M=m.length,h.set(x,M),m.push(d)),M};for(const{sheet:h,range:m}of e){const d=m.r0+(o?1:0),x=m.c0+(i?1:0);for(let M=d;M<=m.r1;M++){const y=i?l.read(h,M,m.c0):M-d;if(i&&(y===null||y===""))continue;const q=v(f,s,y);for(let N=x;N<=m.c1;N++){const I=o?l.read(h,m.r0,N):N-x;if(o&&(I===null||I===""))continue;const B=v(p,c,I),O=q*16384+B;u.has(O)||u.set(O,[]),u.get(O).push(l.read(h,M,N))}}}const S=r.row+(o?1:0),E=r.col+(i?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,V,t.strings.add(String(x)))};return t.transact("consolidate",h=>{o&&c.forEach((m,d)=>L(h,r.row,E+d,m)),i&&s.forEach((m,d)=>L(h,S+d,r.col,m));for(const[m,d]of u){const x=Math.floor(m/16384),M=m-x*16384,y=g(d);y!==null&&L(h,S+x,E+M,y)}}),{rows:s.length,cols:c.length}}export{j as CONSOLIDATE_FUNCTIONS,G as MAX_COLS,Y as changeOutline,ct as consolidate,rt as createDataTable,Q as goalSeek,Z as maxOutlineLevel,C as outlineLevel,at as scenarioSummary,et as scenarioValues,tt as showOutlineLevel,ot as showScenario,nt as subtotalPlan};
@@ -0,0 +1 @@
1
+ import{expandBareTables as q}from"../slicers/structured.js";import{syncTableHeaders as J}from"./tables.js";import{BOOL as b,CHUNK_BITS as I,CHUNK_MASK as W,EMPTY as x,ERR as E,ERRORS as Y,FORMULA as C,DIRTY as z,EVALUATING as N,KIND_MASK as j,NUM as B,Sheet as A,SPILL as X,STR as T}from"./sheet.js";import{cellRef as Z,MAX_COLS as y,MAX_ROWS as P,rangeRef as Q,renameSheetInFormula as D,sheetReferencePattern as ee}from"./address.js";import{translateFormula as te}from"./formula-refs.js";import{sheetStem as G}from"./default-names.js";import{StringTable as se}from"./strings.js";import{StyleTable as ne}from"./styles.js";import{parseInput as H}from"./input.js";import{noteChanges as V}from"./changes.js";import{overrideRuns as ie}from"../cells/rich-runs.js";import{sheetRenameHooks as le}from"./sparse.js";import{expandStructured as re,toDisplayFormula as K,toFileFormula as oe}from"../calc/parser.js";const ae=200,he=new Set(["entry","clear","format","borders","fill"]);class ce{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let l=this.ids.length*2;for(;l<=t;)l*=2;const n=new Int32Array(l);n.set(this.ids),this.ids=n}const s=this.list.length;(s===0||this.list[s-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 R{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=(s,l)=>{const n=new s(t);return n.set(l),n};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,s){this.count===this.capacity&&this._grow();const l=this.count++,n=t.kind(e,s)&~(z|N);if(this.rows[l]=e,this.cols[l]=s,this.kinds[l]=n,this.styles[l]=t.cellStyle(e,s),this.values[l]=t.value(e,s),n&C&&(this.formulas===null&&(this.formulas=new ce),this.formulas.set(l,t.formula(e,s))),t.valueMeta!==null){const i=t.valueMeta.get(e*y+s);i!==void 0&&(this.vms??=new Map).set(l,i)}}}class Me{constructor(){this.sheets=[new A(`${G()}1`)],this.activeSheet=0,this.strings=new se,this.styles=new ne,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 dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}_emit(t){this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=G();let s=1,l=t??`${e}${s}`;const n=r=>this.sheets.some(o=>o.name.toLowerCase()===r.toLowerCase());for(;n(l);)l=`${e}${++s}`;const i=new A(l);return this.sheets.push(i),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),i}deleteSheet(t){if(this.sheets.filter(s=>!s.hidden).length<=1)return!1;const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[s,l]of this.engine.tables)l.sheet===e&&this.engine.tables.delete(s);for(this._reindexNames(s=>s===t?-1:s>t?s-1:s),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);this.sheets[this.activeSheet].hidden;)this.activeSheet=(this.activeSheet+1)%this.sheets.length;return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(t,e){const s=n=>n.sheet===t||n.sheet===void 0&&n.sheetIndex===e||(n.extra?.parts??[]).some(s),l=n=>{n.sheetIndex>e&&n.sheetIndex--;for(const i of n.extra?.parts??[])l(i)};for(const n of[this.undoStack,this.redoStack]){const i=n.filter(r=>!s(r));i.forEach(l),n.splice(0,n.length,...i)}}moveSheet(t,e){if(t===e)return;const s=this.sheet,[l]=this.sheets.splice(t,1);this.sheets.splice(e,0,l),this.activeSheet=this.sheets.indexOf(s);const n=r=>r===t?e:t<e?r>t&&r<=e?r-1:r:r>=e&&r<t?r+1:r,i=r=>{r.sheetIndex=n(r.sheetIndex);for(const o of r.extra?.parts??[])i(o)};for(const r of this.undoStack)i(r);for(const r of this.redoStack)i(r);this.structureEdited=!0,this.engine?.sheetsChanged(),this._reindexNames(n),this._emit("sheets")}_copyScopedNames(t,e,s){const{engine:l}=this;if(!l||l.names.size===0)return;const n=`${t}!`;let i=!1;for(const[r,o]of[...l.names])r.startsWith(n)&&(l.names.set(`${t+1}!${r.slice(n.length)}`,{...o,text:D(o.text,e.name,s.name)}),i=!0);i&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const s=[];let l=!1;for(const[n,i]of e.names){const r=n.indexOf("!"),o=r<0?0:t(Number(n.slice(0,r)));r>=0&&o!==Number(n.slice(0,r))&&(l=!0),r<0?s.push([n,i]):o>=0&&s.push([`${o}!${n.slice(r+1)}`,i])}if(l){e.names.clear();for(const[n,i]of s)e.names.set(n,i);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let l=`${e.name} (2)`,n=2;for(;this.sheets.some(a=>a.name.toLowerCase()===l.toLowerCase());)l=`${e.name} (${++n})`;const i=new A(l);e.columns.forEach((a,c)=>{const f=[];a.forEach((d,S)=>{f[S]={kinds:d.kinds.slice(),values:d.values.slice(),styles:d.styles?d.styles.slice():null}}),i.columns[c]=f}),i.maxRow=e.maxRow,i.maxCol=e.maxCol,i.rows=e.rows.shifted(0,0),i.cols=e.cols.shifted(0,0);const r=new Map;e.formulas.forEachCell((a,c,f)=>{let d=r.get(f);d===void 0&&(d={...f,tpl:void 0},r.set(f,d)),i.setFormula(a,c,d)}),i.merges=e.merges.map(a=>({...a})),i.rowStyles=e.rowStyles?new Map(e.rowStyles):null,i.colStyles=e.colStyles?new Map(e.colStyles):null,i.frozenRows=e.frozenRows,i.frozenCols=e.frozenCols,i.showGridlines=e.showGridlines,i.cellTypes=e.cellTypes?new Map(e.cellTypes):null,i.sparkRules=e.sparkRules,i.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,i.cellTags=e.cellTags?new Map(e.cellTags):null,i.cellButtons=e.cellButtons?new Map(e.cellButtons):null,i.cellStates=e.cellStates?e.cellStates.slice():null,i.autoMerges=e.autoMerges?e.autoMerges.map(a=>({...a})):null,i.background=e.background,i.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,i.frozenTrailingRows=e.frozenTrailingRows,i.frozenTrailingCols=e.frozenTrailingCols,i.hideZeros=e.hideZeros,i.hideHeadings=e.hideHeadings,i.isChartSheet=e.isChartSheet,i.hideOutline=e.hideOutline,i.gridColorId=e.gridColorId,i.areaOffset=e.areaOffset,i.selectionPolicy=e.selectionPolicy,i.selectionUnit=e.selectionUnit,i.gridlineAxes=e.gridlineAxes,i.gridColor=e.gridColor,i.tabStyles=e.tabStyles;const o=_;return i.cf=o(e.cf),i.validations=o(e.validations),i.comments=o(e.comments),i.threads=o(e.threads),i.hyperlinks=e.hyperlinks?e.hyperlinks.map(a=>({...o({...a,_ranges:void 0})})):e.hyperlinks,i.autoFilter=o(e.autoFilter),i.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,i.pageSetup=o(e.pageSetup),i.tabColor=e.tabColor,i.protection=o(e.protection),i.rtl=e.rtl,i.zoom=e.zoom,i.valueMeta=e.valueMeta?new Map(e.valueMeta):null,i.colsChanged=!0,i.viewChanged=!0,this.sheets.splice(t+1,0,i),this.activeSheet=t+1,this._reindexNames(a=>a>t?a+1:a),this._copyScopedNames(t,e,i),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),i}renameSheet(t,e){const s=e.trim().slice(0,31);if(!s||/[\\/?*[\]:]/.test(s)||/^'|'$/.test(s)||s.toLowerCase()==="history"||this.sheets.some((n,i)=>i!==t&&n.name.toLowerCase()===s.toLowerCase()))return!1;const l=this.sheets[t].name;this.sheets[t].name=s,this._renameInFormulas(l,s);for(const n of le)n(this,l,s);return this.engine?.sheetsChanged(),this._emit("sheets"),!0}_renameInFormulas(t,e){const s=ee(t);let l=!1;for(const n of this.sheets){const i=new Map;n.formulas.forEachCell((r,o,a)=>{let c=i.get(a);if(c===void 0){const f=a.f??a.sf;if(f===void 0||!s.test(f))s.lastIndex=0,c=null;else{s.lastIndex=0;const d=D(f,t,e);c=a.f!==void 0?{...a,f:d,tpl:void 0}:{...a,sf:d,tpl:void 0}}i.set(a,c)}c!==null&&(n.setFormula(r,o,c),l=!0)})}l&&(this.formulasEdited=!0,this.engine?.templates.clear(),this.engine?.rebuild())}editText(t,e,s){const l=t.kind(e,s);if(this.engine?.dataTables.length){const r=this.engine.dataTableAt(t,e,s);if(r){const{info:o}=r,a=o.dt2D==="1",c=o.dtr==="1";return`{=TABLE(${a||c?o.r1:""},${a?o.r2:c?"":o.r1})}`}}if(l&X&&this.engine){const r=this.engine.spillMaster(t,e,s);if(r)return this.editText(t,r.row,r.col)}if(l&C){const r=t.formula(e,s);if(r&&r.f!==void 0){const o="="+K(r.f);return r.t==="array"&&!r.cm?`{${o}}`:o}if(r&&r.sf!==void 0){const o=Math.floor(r.base/y),a=r.base-o*y;return"="+K(te(r.sf,e-o,s-a))}}const n=l&j;if(n===x)return"";const i=t.value(e,s);if(n===E&&t.valueMeta!==null&&!(l&C)){const r=this.richImages?.get(t.valueMeta.get(e*y+s));if(r!==void 0)return r.alt??"";const o=this.richValues?.indexOfVm(t.valueMeta.get(e*y+s))??-1,a=o>=0?this.richValues.view(o):null;if(a!==null)return a.text}return n===T?this.styles.get(t.style(e,s)).quotePrefix?`'${this.strings.get(i)}`:this.strings.get(i):n===b?i?"TRUE":"FALSE":n===E?Y[i]??"#N/A":String(i)}transact(t,e){if(this.guard&&!this.guard(t))return;const s=this.selectedSheets,l=s!==null&&s.size>1&&he.has(t)?this._runGroup(t,e,s):this._runOn(this.sheet,t,e);l!==null&&this._pushUndo(l)}transactOn(t,e,s){const l=this._runOn(t,e,s);l!==null&&this._pushUndo(l)}_runOn(t,e,s){const l=new R,n={sheet:t,log:l,saveCell:(c,f)=>l.push(t,c,f)},i=s(n)??null;e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&l.count>0&&V(this,t,l),l.vms!==null&&ue(t,l);const r=l.count>0&&this.engine?.tables.size>0?J(this,n,l):null,o=(c,f)=>d=>o(c(d),f(d)),a=i&&r?o(i,r):i??r;return l.count===0&&a===null?null:(t.revision++,this.engine?.cellsChanged(t,l.rows,l.cols,l.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:l,label:e,extra:a})}_runGroup(t,e,s){const l=[];for(const n of this.sheets){if(!s.has(n)||n.protection&&n!==this.sheet)continue;const i=this._runOn(n,t,e);i!==null&&l.push(i)}return l.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new R,label:t,extra:O(this,l)}}runSlice(t,e,s){const l=this._runOn(t,e,s);return l!==null&&this._emit("cells"),l}pushFolded(t,e,s){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(s),sheet:s,log:new R,label:e,extra:O(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??ae)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:s}=t,l=new R;for(let r=s.count-1;r>=0;r--){const o=s.rows[r],a=s.cols[r];l.push(e,o,a),e.setCell(o,a,s.kinds[r],s.values[r]),e.setStyle(o,a,s.styles[r]),e.setFormula(o,a,s.kinds[r]&C?s.formulas.get(r):null)}if(s.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[r,o]of s.vms)e.valueMeta.set(s.rows[r]*y+s.cols[r],o)}let n=null;t.extra&&(n=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&s.count>0&&V(this,e,l),e.revision++,this.engine?.cellsChanged(e,s.rows,s.cols,s.count);const i=this.sheets.indexOf(e);return i>=0&&(this.activeSheet=i),{sheetIndex:i>=0?i:t.sheetIndex,sheet:e,log:l,label:t.label,extra:n}}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,s,l){const{sheet:n}=t;this.recorder?.push(`sheet.setValue(${JSON.stringify(Z(e,s))}, ${JSON.stringify(l)});`),t.saveCell(e,s),n.setFormula(e,s,null);const i=H(l),r=l[0]==="'"&&l.length>1,o=n.cellStyle(e,s);switch((r||o!==0&&this.styles.get(o).quotePrefix)&&n.setStyle(e,s,this.styles.derive(o,{quotePrefix:r})),i.kind){case x:n.setCell(e,s,x,0);break;case B:n.setCell(e,s,B,i.value),i.format&&(n.cellStyle(e,s)===0||this.styles.get(n.cellStyle(e,s)).numFmt==="General")&&n.setStyle(e,s,this.styles.derive(n.cellStyle(e,s),{numFmt:i.format}));break;case b:n.setCell(e,s,b,i.value);break;case C:n.setCell(e,s,C|x,0),n.setFormula(e,s,{f:oe(this._expandTableRefs(q(i.formula,this.engine?.tables),n,e,s)),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:n.setCell(e,s,T,this.strings.add(i.text))}}setRichInput(t,e,s,l,n){const{sheet:i}=t;t.saveCell(e,s),i.setFormula(e,s,null),i.setCell(e,s,T,this.strings.addRich(l,n))}_expandTableRefs(t,e,s,l){const n=this.engine;return!n||n.tables.size===0?t:re(t,()=>{for(const i of n.tables.values())if(i.sheet===e&&s>=i.r0&&s<=i.r1&&l>=i.c0&&l<=i.c1)return i;return null})}clearRange(t,e="contents",{visibleOnly:s=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",l=>{const{sheet:n}=l,i=[];if(e!=="contents")for(const{r0:o,c0:a,r1:c,c1:f}of t){const d=o===0&&c===P-1,S=a===0&&f===y-1,m=(g,v,u,p)=>{for(const[w,k]of[...v])w<u||w>p||(i.push([g,w,k]),v.delete(w))};d&&n.colStyles!==null&&m("col",n.colStyles,a,f),S&&n.rowStyles!==null&&m("row",n.rowStyles,o,c)}const r=s&&n.filteredRows?.size>0?n.filteredRows:null;for(const{r0:o,c0:a,r1:c,c1:f}of t){const d=Math.min(f,n.maxCol),S=Math.min(c,n.maxRow);for(let m=a;m<=d;m++)if(n.columns[m]!==void 0)for(let g=o;g<=S;g++){if(n._chunk(g,m)===void 0){g|=1023;continue}if(r!==null&&r.has(g))continue;const u=n.kind(g,m)!==0,p=n.cellStyle(g,m)!==0;if(e==="formats"){if(!p)continue;l.saveCell(g,m),n.setStyle(g,m,0);continue}!u&&!(e==="all"&&p)||(l.saveCell(g,m),n.setCell(g,m,x,0),n.setFormula(g,m,null),e==="all"&&n.setStyle(g,m,0))}}return i.length>0?F([],i):void 0})}applyStyle(t,e){const s=JSON.stringify(e);if(this.recorder)for(const l of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(Q(l))}, ${s});`);this.transact("format",l=>{const{sheet:n}=l;this.strings.rich!==null&&ie(this,l,t,e);const i=[],r=new Set,o=[];for(const{r0:a,c0:c,r1:f,c1:d}of t){const S=a===0&&f===P-1,m=c===0&&d===y-1;if(S){n.colStyles===null&&(n.colStyles=new Map);for(let u=c;u<=d;u++){const p=n.colStyles.get(u);o.push(["col",u,p]),n.colStyles.set(u,this.styles.derive(p??0,e,s))}if(m&&n.rowStyles!==null)for(const[u,p]of n.rowStyles)o.push(["row",u,p]),n.rowStyles.set(u,this.styles.derive(p,e,s))}else if(m){n.rowStyles===null&&(n.rowStyles=new Map);for(let u=a;u<=f;u++){const p=n.rowStyles.get(u);o.push(["row",u,p]),n.rowStyles.set(u,this.styles.derive(p??0,e,s))}}const g=S?n.maxRow:f,v=m?n.maxCol:d;for(let u=c;u<=v;u++)for(let p=a>>>I;p<=g>>>I;p++){const w=p<<I,k=Math.max(a,w),U=Math.min(g,w+W);if(k>U)continue;const $=n._ensure(k,u),L=u*2048+p;r.has(L)||(r.add(L),i.push(u,p,$.styles===null?null:$.styles.slice()));for(let M=k;M<=U;M++)n.setStyle(M,u,this.styles.derive(n.style(M,u),e,s))}}return F(i,o)})}}function O(h,t){const e=()=>{const s=[];for(let l=t.length-1;l>=0;l--)s.push(h._restore(t[l]));return O(h,s)};return e.parts=t,e}function ue(h,t){let e=null;for(const s of t.vms.keys()){const l=t.rows[s],n=t.cols[s];(h.kind(l,n)&~(z|N))===t.kinds[s]&&h.value(l,n)===t.values[s]||(e??=new Map(h.valueMeta),e.delete(l*y+n))}e!==null&&(h.valueMeta=e.size>0?e:null)}function _(h){if(h===null||typeof h!="object")return h;if(Array.isArray(h))return h.map(_);if(h instanceof Map)return new Map([...h].map(([e,s])=>[e,_(s)]));if(h instanceof Set)return new Set([...h].map(_));if(ArrayBuffer.isView(h))return h.slice();const t={};for(const[e,s]of Object.entries(h))!e.startsWith("_")&&typeof s!="function"&&(t[e]=_(s));return t}function F(h,t){return e=>{const s=[];for(let n=0;n<h.length;n+=3){const i=h[n],r=h[n+1],o=e.columns[i]?.[r];o!==void 0&&(s.push(i,r,o.styles),o.styles=h[n+2])}const l=[];for(const[n,i,r]of t){const o=n==="col"?"colStyles":"rowStyles",a=e[o]??=new Map;l.push([n,i,a.get(i)]),r===void 0?a.delete(i):a.set(i,r)}return F(s,l)}}export{R as CellLog,he as GROUP_LABELS,Me as Workbook,O as foldEntries,H as parseInput,F as swapStyles};
@@ -0,0 +1 @@
1
+ import{BOOL as v,CHUNK_BITS as L,CHUNK_MASK as j,EMPTY as S,ERR as B,FORMULA as G,KIND_MASK as F,NUM as b,Sheet as x,STR as f}from"../core/sheet.js";import{MAX_COLS as X,MAX_ROWS as O}from"../core/address.js";import{ERR_BY_INDEX as U,XlError as N}from"../calc/values.js";import{partsToSerial as V}from"../core/numfmt.js";import{DataError as Y}from"./data.js";import{STAGE as $}from"./view.js";import{t as H}from"../i18n/index.js";const c=x.prototype.setCell,D=x.prototype.setStyle,T=x.prototype.setFormula,ot={setCell:c,setStyle:D,setFormula:T};function rt(h,e,t,i,s){s==null||s===""?c.call(h,t,i,S,0):typeof s=="number"?c.call(h,t,i,b,s):typeof s=="boolean"?c.call(h,t,i,v,s?1:0):s instanceof N?c.call(h,t,i,B,s.index):s instanceof Date?c.call(h,t,i,b,V(s.getUTCFullYear(),s.getUTCMonth()+1,s.getUTCDate())):c.call(h,t,i,f,e.add(typeof s=="object"?JSON.stringify(s):String(s)))}function at(h,e,t){switch(e&F){case b:return t;case f:return h.get(t);case v:return t!==0;case B:return U[t]??null;default:return null}}function J(h){h.dataBindings||(h.dataBindings=[],h.routeInput=function(t,i,s,o){for(const n of this.dataBindings)if(n.routeInput&&n.contains(i,s))return n.routeInput(t,i,s,o);return!1},h.setCell=function(t,i,s,o){c.call(this,t,i,s,o);for(const n of this.dataBindings)if(n.contains(t,i)){n.cellWritten(t,i,s,o);break}},h.setFormula=function(t,i,s){if(T.call(this,t,i,s),!!s){for(const o of this.dataBindings)if(o.contains(t,i)){o.formulaWritten(t,i,s);break}}})}function P(h){h.dataBindings&&h.dataBindings.length===0&&(delete h.dataBindings,delete h.setCell,delete h.setFormula,delete h.routeInput)}class z{constructor(e,t,i,s,o={}){this.book=e,this.sheet=t,this.view=s,this.table=s.table,this.range={...i},this.options={header:!0,editable:!0,grow:i.r0===i.r1,...o},this.quiet=0,this.lastRows=0,this._pendingFlush=!1,this.formatStyles=new Map,J(t),t.dataBindings.push(this),this._unsubscribe=s.onChange(n=>this._viewChanged(n)),this.render()}unbind(){this._unsubscribe();const e=this.sheet.dataBindings;e.splice(e.indexOf(this),1),P(this.sheet)}get columnCount(){const{c0:e,c1:t}=this.range;return Math.min(this.view.columns.length,e===t&&this.options.grow?this.view.columns.length:t-e+1)}get headerRows(){return this.options.header?1:0}get dataRows(){const{r0:e,r1:t}=this.range,i=this.options.grow?O-e-this.headerRows:t-e+1-this.headerRows;return Math.max(0,Math.min(i,this.view.count))}contains(e,t){const{r0:i,c0:s}=this.range,o=this.options.grow&&this.options.editable?1:0;return e>=i&&t>=s&&t<s+this.columnCount&&e<i+this.headerRows+Math.max(this.dataRows,this.lastRows)+o}routeInput(e,t,i,s){if(!this.options.editable)return!1;const o=i-this.range.c0,n=this.view.columns[o];if(!n||n.col.type!=="string"||s[0]==="="||this.options.header&&t===this.range.r0)return!1;e.saveCell(t,i);const r=s[0]==="'"?s.slice(1):s,a=r===""?0:this.book.strings.add(r);return e.sheet.setCell(t,i,r===""?S:f,a),!0}_styleFor(e,t=!1){const i=`${t?"b":""}|${e}`;let s=this.formatStyles.get(i);if(s===void 0){const o={};e&&e!=="General"&&(o.numFmt=e),t&&(o.bold=!0),s=Object.keys(o).length>0?this.book.styles.derive(0,o):0,this.formatStyles.set(i,s)}return s}render(){this.quiet++;const{sheet:e,view:t,book:i}=this,{r0:s,c0:o}=this.range,n=this.columnCount;if(this.options.header)for(let l=0;l<n;l++)c.call(e,s,o+l,f,i.strings.add(t.columns[l].caption)),e.cellStyle(s,o+l)===0&&D.call(e,s,o+l,this._styleFor("General",!0));const r=s+this.headerRows,a=this.dataRows;for(let l=0;l<n;l++)this._renderColumn(l,r,0,a);for(let l=a;l<this.lastRows;l++)for(let y=0;y<n;y++)c.call(e,r+l,o+y,S,0);const R=Math.max(a,this.lastRows);this.lastRows=a,this.quiet--,this._notifyEngine(r-this.headerRows,r+R-1,n)}_renderColumn(e,t,i,s){const{sheet:o,view:n}=this,r=n.columns[e],a=r.col;a.stale&&this.table.ensure(a);const R=this.range.c0+e,l=r.format&&r.format!=="General"?this._styleFor(r.format):0,{map:y}=n,{data:M,isString:K}=a,A=a.kinds,W=a.type==="boolean";let u=null,I=-1;for(let g=i;g<i+s;g++){const q=t+g,E=q>>>L;E!==I&&(u=o._ensure(q,R),I=E);const _=q&j,m=y[g];let p=S,w=0;if(m>=0)if(K){const d=M[m];d>=0&&(p=f,w=d)}else if(A!==null)p=A[m],w=M[m];else{const d=M[m];d===d&&(p=W?v:b,w=d)}else{const d=-m-1,k=d>>>1;if(e===0)p=f,w=this.book.strings.add((d&1)===1?n.nodeLevel[k]<0?"Total":`${n.groupCaption(k)} total`:n.groupCaption(k));else{const C=n.summaryFor(k,r.field);C!==void 0&&C===C&&(p=b,w=C)}}u.kinds[_]=p,u.values[_]=w,l!==0&&(u.styles===null||u.styles[_]===0)&&(u.styles===null&&(u.styles=new Uint16Array(u.kinds.length)),u.styles[_]=l)}if(s>0){const g=t+i+s-1;g>o.maxRow&&(o.maxRow=g),R>o.maxCol&&(o.maxCol=R)}}_notifyEngine(e,t,i){const s=this.book.engine;if(this.sheet.revision++,!s||s.deps.get(this.sheet)===void 0||t<e)return;const o=i*2,n=new Uint32Array(o),r=new Uint16Array(o);for(let a=0;a<i;a++)n[a*2]=e,n[a*2+1]=t,r[a*2]=this.range.c0+a,r[a*2+1]=this.range.c0+a;s.cellsChanged(this.sheet,n,r,o)}_viewChanged(e){if(e.type==="cell"){this._renderRecord(e.row),this._notify();return}this.quiet>0||(this._forgetUndo(),this.render(),this._notify())}_forgetUndo(){const{book:e}=this,t=e.sheets.indexOf(this.sheet),i=s=>s.sheetIndex!==t;e.undoStack=e.undoStack.filter(i),e.redoStack=e.redoStack.filter(i)}_notify(){this._pendingFlush||(this._pendingFlush=!0,queueMicrotask(()=>{this._pendingFlush=!1,this.view.summariesStale&&(this.view.refresh(),this.render()),this.options.onRefresh?.()}))}_renderRecord(e){const t=this.view.rowOfRecord(e);if(t<0||t>=this.dataRows)return;const i=this.range.r0+this.headerRows,s=this.columnCount;this.quiet++;for(let o=0;o<s;o++)this._renderColumn(o,i,t,1);this.quiet--,this._notifyEngine(i+t,i+t,s)}cellWritten(e,t,i,s){if(this.quiet>0||!this.options.editable||i&G||this.options.header&&e===this.range.r0&&t-this.range.c0>=this.view.columns.length)return;const o=t-this.range.c0;if(this.options.header&&e===this.range.r0){(i&F)===f&&this.view.columns[o]&&this._rename(this.view.columns[o],this.book.strings.get(s));return}let n;switch(i&F){case b:n=s;break;case f:n=this.book.strings.get(s);break;case v:n=s!==0;break;case B:n=U[s]??null;break;default:n=null}this._pushValue(e,o,n)}formulaWritten(e,t,i){if(this.quiet>0||!this.options.editable)return;const s=i.f??i.sf;if(s===void 0||!this.book.engine)return;const o=t-this.range.c0;let n;try{n=this.book.engine.template(s,e,t).fn(e,t,this.sheet),n&&n.isCell&&(n=this.book.engine.read(n.sheet,n.r0,n.c0))}catch(r){n=r instanceof N?r:null}T.call(this.sheet,e,t,null),this._pushValue(e,o,n)}_rename(e,t){this.quiet++,this.view.setColumn(e.field,{caption:t}),this.quiet--}_pushValue(e,t,i){const s=e-this.range.r0-this.headerRows,o=this.view.columns[t];let n=this.view.recordAt(s);if(o!==void 0&&s===this.view.count&&this.options.grow&&i!==null){this.quiet++;try{n=this.table.addRow({})}finally{this.quiet--}this.lastRows=this.view.count}if(n<0||o===void 0){queueMicrotask(()=>this.render());return}if(o.readOnly){this.options.onRejected?.(H(o.col.computed?"The {field} field is calculated, so it can't be edited.":"The {field} field is read-only, so it can't be edited.",{field:o.caption})),queueMicrotask(()=>this.render());return}this.quiet++;try{this.table.set(n,o.col,i)}catch(r){if(!(r instanceof Y))throw r;this.options.onRejected?.(r.message),queueMicrotask(()=>this.render())}finally{this.quiet--}}shiftRecords(e,t=!1){if(e.axis!=="row"||!this.options.grow)return;const i=this.range.r0+this.headerRows,s=e.at-i;if(!(s<0||s>this.view.count)){this.quiet++;try{const o=this.removedRecords??(this.removedRecords=[]);if(e.n>0&&t&&o.at(-1)?.length===e.n){for(const n of o.pop())this.table.restoreRow(n);this.view.invalidate($.FILTER),this.view.refresh()}else if(e.n>0){const n=this.view.recordAt(s),r=[];for(let a=0;a<e.n;a++)r.push(this.table.addRow({}));n>=0&&this.view.moveRecords(r,n)}else{const n=[];for(let r=s;r<Math.min(this.view.count,s-e.n);r++){const a=this.view.recordAt(r);a>=0&&n.push(a)}for(const r of n)this.table.removeRow(r);o.push(n)}}finally{this.quiet--}this.render()}}redraw(){this.view.refresh(),this.render()}usedRange(){const{r0:e,c0:t}=this.range;return{r0:e,c0:t,r1:e+this.headerRows+Math.max(this.dataRows,1)-1,c1:t+this.columnCount-1}}exportRows(){const e=this.view.columns.slice(0,this.columnCount),t=[];for(let i=0;i<this.view.count;i++){const s=this.view.map[i];if(s<0)continue;const o={};for(const n of e)o[n.caption]=n.col.get(s);t.push(o)}return{captions:e.map(i=>i.caption),rows:t}}shift(e){const t=this.range;e.axis==="row"?e.at<=t.r0?(t.r0+=e.n,t.r1+=e.n):e.at<=t.r1&&(t.r1+=e.n):e.at<=t.c0?(t.c0+=e.n,t.c1+=e.n):e.at<=t.c1&&(t.c1+=e.n),t.r0=Math.max(0,Math.min(t.r0,O-1)),t.c0=Math.max(0,Math.min(t.c0,X-1))}}function ht(h=x){h.prototype.bindTable=function(t,i,s){return new z(i.table.manager.book,this,t,i,s)},h.prototype.unbindTables=function(){for(const t of[...this.dataBindings??[]])t.unbind()}}export{z as TableBinding,J as hookSheet,ht as installSheetApi,ot as rawCells,P as unhookSheet,at as valueOfWrite,rt as writeRaw};
@@ -0,0 +1 @@
1
+ const p=131072,P=1440;function A(a){return a.map(([t,e])=>[Math.round(t*60),Math.round(e*60)]).filter(([t,e])=>e>t)}const y=a=>{if(typeof a=="number")return Math.floor(a);throw new Error("Calendar dates are serial numbers.")};class m{constructor(t={}){const{name:e="Standard",workDays:r=[!1,!0,!0,!0,!0,!0,!1],holidays:n=[],hours:s=null,weekHours:i=null,exceptions:o=[],weeks:u=[],hoursPerDay:h=null,hoursPerWeek:l=null,daysPerMonth:d=20,weekStart:c=1}=t;if(!r.some(Boolean))throw new Error("A calendar needs at least one working weekday.");this.name=e,this.workDays=r,this.hours=s,this.weekHours=i,this.holidays=new Set(n.map(D=>Math.floor(D))),this.exceptions=o,this.weeks=u,this.fullDays=s===null;const f=h??(s===null?8:s.reduce((D,[w,k])=>D+(k-w),0));this.hoursPerDay=f,this.hoursPerWeek=l??f*r.filter(Boolean).length,this.daysPerMonth=d,this.weekStart=c,this.cum=null,this.patternOf=null,this.patterns=null}unitsPer(t){if(this.fullDays)switch(t){case"min":return 1/(this.hoursPerDay*60);case"h":return 1/this.hoursPerDay;case"w":return this.hoursPerWeek/this.hoursPerDay;case"mo":return this.daysPerMonth;default:return 1}switch(t){case"min":return 1;case"h":return 60;case"w":return this.hoursPerWeek*60;case"mo":return this.daysPerMonth*this.hoursPerDay*60;default:return this.hoursPerDay*60}}_dayPatternKey(t,e){if(this.holidays.has(t))return null;for(const r of this.exceptions)if(t>=y(r.from)&&t<=y(r.to??r.from))return r.off||!r.hours?r.off===!1&&!r.hours?this._weekPattern(t,e):null:r.hours;return this._weekPattern(t,e)}_weekPattern(t,e){for(const r of this.weeks)if(t>=y(r.from)&&t<=y(r.to??r.from))return r.workDays&&!r.workDays[e]?null:r.hours??this.hours??"day";return this.workDays[e]?this.weekHours&&this.weekHours[e]?this.weekHours[e]:this.hours??"day":null}_build(){const t=new Int32Array(131074),e=new Uint16Array(131074),r=[null],n=new Map;let s=0;for(let i=1;i<=131072;i++){t[i]=s;const o=this._dayPatternKey(i,(i-1)%7);if(o===null)continue;if(this.fullDays){e[i]=1,s+=1;continue}const u=o==="day"?"day":JSON.stringify(o);let h=n.get(u);if(h===void 0){const l=o==="day"?[[0,1440]]:A(o);h=r.length,r.push({intervals:l,total:l.reduce((d,[c,f])=>d+f-c,0)}),n.set(u,h)}e[i]=h,s+=r[h].total}if(t[131073]=s,this.cum=t,this.patternOf=e,this.patterns=r,this.totalUnits=s,this.fullDays){const i=new Int32Array(s+1);for(let o=1;o<=131072;o++)e[o]!==0&&(i[t[o]]=o);this.toDate=i}}_ready(){this.cum===null&&this._build()}isWorkDay(t){this._ready();const e=Math.floor(t);return e>=1&&e<=131072&&this.patternOf[e]!==0}isWorkTime(t){this._ready();const e=Math.floor(t);if(e<1||e>131072||this.patternOf[e]===0)return!1;if(this.fullDays)return!0;const r=(t-e)*1440;return this.patterns[this.patternOf[e]].intervals.some(([n,s])=>r>=n&&r<s)}intervalsOf(t){this._ready();const e=this.patternOf[Math.floor(t)];return e===0?[]:this.fullDays?[[0,1440]]:this.patterns[e].intervals}indexOf(t){this._ready();const e=Math.floor(t),r=e<1?1:e>131072?131072:e,n=this.cum[r],s=this.patternOf[r],i=e===r?t-r:0;if(s===0||i<=0)return n;if(this.fullDays)return i>0?n+1:n;const o=Math.round(i*1440);let u=0;for(const[h,l]of this.patterns[s].intervals){if(o<=h)break;u+=Math.min(o,l)-h}return n+u}_dayOfUnit(t){const{cum:e}=this;let r=1,n=131072;for(;r<n;){const s=r+n+1>>>1;e[s]<=t?r=s:n=s-1}return r}momentStart(t){this._ready();const e=t<0?0:t>=this.totalUnits?this.totalUnits-1:t;if(this.fullDays)return this.toDate[e];let r=this._dayOfUnit(e);for(;this.patternOf[r]===0&&r>1;)r--;let n=e-this.cum[r];for(const[s,i]of this.patterns[this.patternOf[r]].intervals){if(n<i-s)return r+(s+n)/1440;n-=i-s}return r+1}momentEnd(t){return t<=0?this.momentStart(0):this.momentStart(t-1)+(this.fullDays?1:1/1440)}nextWork(t){return this.momentStart(this.indexOf(t))}prevEnd(t){return this.momentEnd(this.indexOf(t))}add(t,e){const r=this.indexOf(t);return e<=0?this.momentStart(r+e):this.momentEnd(r+e)}sub(t,e){return this.momentStart(this.indexOf(t)-e)}unitsBetween(t,e){return this.indexOf(e)-this.indexOf(t)}dateOf(t){return Math.floor(this.momentStart(t))}addWorkDays(t,e){if(this.fullDays)return this.momentStart(this.indexOf(t)+e);let r=Math.floor(t),n=e;const s=n<0?-1:1;for(;!this.isWorkDay(r);)r+=1;for(;n!==0;)r+=s,this.isWorkDay(r)&&(n-=s);return r}workDaysBetween(t,e){this._ready();const r=Math.floor(t),n=Math.floor(e);if(this.fullDays)return this.indexOf(n+1)-this.indexOf(r);let s=0;for(let i=r;i<=n;i++)this.isWorkDay(i)&&s++;return s}toJSON(){return{name:this.name,workDays:this.workDays,hours:this.hours,weekHours:this.weekHours,holidays:[...this.holidays],exceptions:this.exceptions,weeks:this.weeks,hoursPerDay:this.hoursPerDay,hoursPerWeek:this.hoursPerWeek,daysPerMonth:this.daysPerMonth,weekStart:this.weekStart}}}const S={days:{},standard:{name:"Standard",hours:[[8,12],[13,17]]},nightShift:{name:"Night Shift",workDays:[!1,!0,!0,!0,!0,!0,!0],hours:[[0,3],[4,8],[23,24]],hoursPerDay:8},allHours:{name:"24 Hours",workDays:[!0,!0,!0,!0,!0,!0,!0],hours:[[0,24]],hoursPerDay:24}};function E(a){if(a instanceof m)return a;if(typeof a=="string"){const t=S[a];if(!t)throw new Error(`No calendar named ${a}.`);return new m(t)}return new m(a??{})}export{S as CALENDAR_PRESETS,m as WorkCalendar,E as makeCalendar};
@@ -0,0 +1 @@
1
+ import{getFormatter as M}from"../core/numfmt.js";const E=500,O=64e6;function S(n){return Math.max(1,Math.floor(O/Math.max(1,n.table.capacity)))}const _=n=>{const l=typeof n.cross=="string"?{over:n.cross}:n.cross;return{...l,agg:l.agg??"sum"}};function x(n,l,u){const{table:s}=n,e=l.indexOf(".");if(e>0){const t=s.manager.relationshipTo(s,l.slice(0,e));if(t&&t.to===s&&t.from!==s){const r=l.slice(0,e+1);return{table:t.from,relation:t,over:l.slice(e+1),value:u?.startsWith(r)?u.slice(r.length):u}}}return{table:s,relation:null,over:l,value:u}}const k=(n,l)=>l==null?"(blank)":n.type==="date"&&typeof l=="number"?M(n.format).number(l):String(l);function v(n,l,u){const{table:s}=n,e=s.column(n.over);if(!e)return[];s.ensure(e);const t=l?u(s,l):null,r=new Map;for(let i=0;i<s.rowCount;i++){if(s.alive[i]===0)continue;if(t!==null){const g=t.get(i);if(g!==!0&&!(typeof g=="number"&&g!==0))continue}const a=e.get(i);if(r.has(a)||r.set(a,i),r.size>E)break}const c=[...r.entries()].map(([i,a])=>({value:i,row:a}));return c.sort((i,a)=>i.value===null?1:a.value===null?-1:typeof i.value=="number"&&typeof a.value=="number"?i.value-a.value:String(i.value).localeCompare(String(a.value))),c}function C(n,l,u,s){const{table:e}=n;let t=e.byName.get(l);if(!t){const r=s&&u?u.type:"number";t=e.addHelper({name:l,type:r==="any"?"any":r,format:u?.format??"General",hidden:!0})}return t}function A(n,l,u,s,e,t){return{def:n,col:l,field:l.name,caption:s,format:n.format??u?.format??"General",width:typeof n.width=="number"?n.width:null,pinned:!1,readOnly:!0,align:n.align??null,allowSort:!0,allowFilter:!0,showNullAs:n.showNullAs??null,showEmptyAs:n.showEmptyAs??null,display:null,style:n.style??null,headerStyle:n.headerStyle??null,headerFit:"normal",captionPath:e,cellType:null,validator:null,conditionalFormats:n.conditionalFormats??null,sparkline:n.sparkline??null,...t}}function G(n,l,u){const s=_(l),e=x(n,s.over,l.field),t=e.table.column(e.value),r=e.table.column(e.over);if(!r)return[];const c=e.relation===null,i=n.spec.options.showCrossValueHeader!==!1,a=s.caption??l.caption??t?.caption??l.field,g=(s.attributes??[]).map(p=>typeof p=="string"?{value:p}:p);n._useCrossSource(e.table);const w=v(e,s.filter,u),b=S(n);return w.length>b&&(n.truncatedColumns=w.length-b),w.slice(0,b).map(({value:p,row:m})=>{const f=k(r,p),o=C(n,`__cross:${s.over}|${l.field}|${s.agg}|${p}`,t,c),d=g.map(h=>{const $=e.table.column(h.value);return $?k($,$.get(m)):""}),y=[...i?[a]:[],...d,f];return A(l,o,t,f,y.length>1?y:null,{generated:"cross",fill:{source:e,value:p,agg:s.agg},summaryAgg:s.agg})})}function L(n,l){const u=[];return n.spec.groups.forEach((s,e)=>{for(const t of s.summaries??[]){if(!t.slice&&!t.own)continue;const r=typeof t.slice=="string"?t.slice:t.slice?.field??null,c=typeof t.slice=="object"&&t.slice!==null?t.slice:{},i=t.field?n.table.column(t.field):null,a=t.agg??"sum",g=t.caption??`${a.charAt(0).toUpperCase()}${a.slice(1)} of ${i?.caption??t.field}`,w={format:t.format,style:c.style??t.style,width:c.width??t.width};if(r===null){const o=C(n,`__cross:own|${e}|${t.field}|${a}`,i,!0);u.push(A(w,o,i,g,null,{generated:"summary",summaryOnly:!0,sliceLevel:e,summaryAgg:a,fill:{source:{table:n.table,relation:null,over:null,value:t.field},agg:a}}));continue}const b={table:n.table,relation:null,over:r,value:t.field},p=n.table.column(r);if(!p)continue;const m=v(b,c.filter,l),f=S(n);m.length>f&&(n.truncatedColumns=m.length-f);for(const{value:o}of m.slice(0,f)){const d=k(p,o),y=C(n,`__cross:slice|${e}|${r}|${t.field}|${a}|${o}`,i,!0);u.push(A(w,y,i,d,[g,d],{generated:"slice",summaryOnly:!0,sliceLevel:e,summaryAgg:a,fill:{source:b,value:o,agg:a}}))}}}),u}const F=n=>n.isString?-1:NaN;function N(n,l){if(l.kinds!==null)return{ofRow:t=>l.get(t),ofValue:t=>t};const{data:u}=l,s=l.isString?-1:null,{strings:e}=n.manager;return{ofRow:t=>{const r=u[t];return r!==r||r===s?null:r},ofValue:t=>t===null?null:typeof t=="string"?e.add(t):t===!0?1:t===!1?0:t}}function T(n,l){const{table:u}=n,s=new Map;for(const e of l){if(!e.fill)continue;const{source:t}=e.fill,r=`${t.table.name}|${t.relation?.name??""}|${t.over??""}|${t.value??""}|${e.fill.agg}`;s.has(r)||s.set(r,{source:t,agg:e.fill.agg,list:[]}),s.get(r).list.push(e);const c=e.col;c.data.fill(F(c),0,c.data.length),c.kinds=null,c.revision++,c.rankCache=null}for(const{source:e,agg:t,list:r}of s.values()){const c=e.value?e.table.column(e.value):null;c&&e.table.ensure(c);const i=e.over?e.table.column(e.over):null;i&&e.table.ensure(i);const a=i?N(e.table,i):null,g=new Map;for(const m of r)g.set(a?a.ofValue(m.fill.value):0,m.col);if(e.relation===null){const m=c!==null&&c.kinds===null;for(let f=0;f<u.rowCount;f++){if(u.alive[f]===0)continue;const o=g.get(a?a.ofRow(f):0);if(o!==void 0)if(m&&o.isString===c.isString&&o.kinds===null)o.data[f]=c.data[f];else{const d=c?c.get(f):1;d!=null&&o.put(f,o.coerce(d))}}continue}const w=e.relation.parents(),b=e.table,p=t==="average"?new Map:null;for(let m=0;m<b.rowCount;m++){if(b.alive[m]===0)continue;const f=g.get(a?a.ofRow(m):0);if(f===void 0)continue;const o=w[m];if(o<0||u.alive[o]===0)continue;const d=c?c.get(m):1,y=typeof d=="number"?d:d===!0?1:0,{data:h}=f,$=h[o]===h[o];switch(t){case"count":h[o]=($?h[o]:0)+1;break;case"min":h[o]=$?Math.min(h[o],y):y;break;case"max":h[o]=$?Math.max(h[o],y):y;break;default:h[o]=($?h[o]:0)+y}p&&(p.has(f)||p.set(f,new Int32Array(u.rowCount)),p.get(f)[o]++)}if(p)for(const[m,f]of p)for(let o=0;o<u.rowCount;o++)f[o]>0&&(m.data[o]/=f[o])}}export{G as crossColumnsOf,T as fillGenerated,L as sliceColumnsOf};
@@ -0,0 +1 @@
1
+ import{BOOL as E,EMPTY as b,ERR as D,ERRORS as P,KIND_MASK as T,NUM as k,STR as N}from"../core/sheet.js";import{partsToSerial as H}from"../core/numfmt.js";import{StringTable as L}from"../core/strings.js";import{ERR_BY_CODE as $,ERR_BY_INDEX as V,numberToText as z,textToNumber as j,XlError as x}from"../calc/values.js";import{parseInput as q}from"../core/input.js";import{rankStrings as B}from"./sort.js";import{computeWindow as K}from"./window.js";import{checkValidator as Y,flattenRecord as X,parseSource as W,readField as J,readRemote as Q,sendChanges as I}from"./remote.js";import{t as _}from"../i18n/index.js";const Z=["number","date","boolean","string","any"],tt=new Set(["number","date","boolean"]),u={UNCHANGED:0,INSERTED:1,UPDATED:2,PURGED:3},et=256;class m extends Error{}class O{constructor(t,e,i){if(this.table=t,this.index=i,this.name=e.name,this.caption=e.caption??e.name,this.type=e.type??"any",!Z.includes(this.type))throw new m(`Unknown field type: ${this.type}`);this.format=e.format??(this.type==="date"?"yyyy-mm-dd":"General"),this.readOnly=e.readOnly===!0,this.defaultValue=e.defaultValue??null,this.width=e.width??null,this.hidden=e.hidden===!0,this.formula=e.formula??null,this.lookup=e.lookup??null,this.rollup=e.rollup??null,this.window=e.window??null,this.required=e.required===!0,this.showNullAs=e.showNullAs??null,this.validator=e.validator??null,this.trigger=e.trigger??null,this.computed=this.formula!==null||this.lookup!==null||this.rollup!==null||this.window!==null,this.stale=this.computed,this.deps=[],this.rangeDep=!1,this.compiled=null,this.revision=0,this.rankCache=null,this.styles=null,this.kinds=null,this.data=this.type==="string"?new Int32Array(t.capacity).fill(-1):new Float64Array(t.capacity).fill(NaN)}get isString(){return this.type==="string"}get isNumeric(){return tt.has(this.type)||this.type==="any"&&this.kinds===null}_grow(t){const e=this.data,i=this.isString?new Int32Array(t).fill(-1):new Float64Array(t).fill(NaN);if(i.set(e),this.data=i,this.kinds!==null){const n=new Uint8Array(t);n.set(this.kinds),this.kinds=n}if(this.styles!==null){const n=new Uint16Array(t);n.set(this.styles),this.styles=n}}kind(t){if(this.isString)return this.data[t]<0?b:N;if(this.kinds!==null)return this.kinds[t];const e=this.data[t];return e!==e?b:this.type==="boolean"?E:k}raw(t){return this.data[t]}get(t){switch(this.stale&&this.table.ensure(this),this.kind(t)){case k:return this.data[t];case N:return this.table.manager.strings.get(this.data[t]);case E:return this.data[t]!==0;case D:return V[this.data[t]]??null;default:return null}}put(t,e){const{strings:i}=this.table.manager;if(this.isString){this.data[t]=e===null?-1:i.add(String(e));return}if(this.kinds===null){if(typeof e=="number"){this.data[t]=e;return}if(e===null){this.data[t]=NaN;return}if(this.type==="boolean"){this.data[t]=e?1:0;return}this.kinds=new Uint8Array(this.data.length);const n=this.table.rowCount,{data:s,kinds:r}=this;for(let o=0;o<n;o++)r[o]=s[o]!==s[o]?b:k}e===null?(this.kinds[t]=b,this.data[t]=0):typeof e=="number"?(this.kinds[t]=k,this.data[t]=e):typeof e=="string"?(this.kinds[t]=N,this.data[t]=i.add(e)):typeof e=="boolean"?(this.kinds[t]=E,this.data[t]=e?1:0):e instanceof x?(this.kinds[t]=D,this.data[t]=e.index):(this.kinds[t]=b,this.data[t]=0)}coerce(t){if(t==null)return null;if(t==="")return this.type==="string"?"":null;switch(t instanceof Date&&(t=H(t.getUTCFullYear(),t.getUTCMonth()+1,t.getUTCDate())+t.getTime()%864e5/864e5),this.type){case"string":return typeof t=="string"?t:typeof t=="number"?z(t):typeof t=="boolean"?t?"TRUE":"FALSE":t instanceof x?t.code:String(t);case"number":case"date":{if(typeof t=="number")return t;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const e=q(t);if(e.kind===k)return e.value;const i=j(t);if(i!=null&&!Number.isNaN(i))return i}throw new m(_(this.type==="date"?`"{value}" isn't a date, which the {field} field needs.`:`"{value}" isn't a number, which the {field} field needs.`,{value:t,field:this.caption}))}case"boolean":if(typeof t=="boolean")return t;if(t===1||t===0)return t===1;if(typeof t=="string"){const e=t.trim().toLowerCase();if(e==="true"||e==="yes")return!0;if(e==="false"||e==="no")return!1}throw new m(_(`"{value}" isn't TRUE or FALSE, which the {field} field needs.`,{value:t,field:this.caption}));default:return t}}ranks(){const{strings:t}=this.table.manager;if(this.rankCache!==null&&this.rankCache.revision===this.revision&&this.rankCache.size===t.size)return this.rankCache;const e=this.table.rowCount,i=new Uint8Array(t.size),{data:n,kinds:s}=this,r=[];if(this.isString)for(let l=0;l<e;l++){const a=n[l];a>=0&&i[a]===0&&(i[a]=1,r.push(a))}else if(s!==null){for(let l=0;l<e;l++)if(s[l]===N){const a=n[l];i[a]===0&&(i[a]=1,r.push(a))}}const{rank:o,count:h}=B(t,r,t.size);return this.rankCache={rank:o,count:h,revision:this.revision,size:t.size},this.rankCache}}class it{constructor(t,e){if(this.manager=t,this.from=t.table(e.from),this.to=t.table(e.to),this.fromField=e.fromField,this.toField=e.toField??e.to_field??this.to.key,this.name=e.name,this.inverse=e.inverse??null,!this.from.column(this.fromField))throw new m(_("No field {field} in {table}",{field:this.fromField,table:this.from.name}));if(!this.toField||!this.to.column(this.toField))throw new m(_("No key field in {table}",{table:this.to.name}));this._parents=null,this._children=null,this._stamp=-1}_currentStamp(){return this.from.structureRevision*4096+this.to.structureRevision}_check(){const t=this._currentStamp();t!==this._stamp&&(this._stamp=t,this._parents=null,this._children=null)}parents(){if(this._check(),this._parents!==null)return this._parents;const t=this.from.column(this.fromField),e=this.to.column(this.toField);this.from.ensure(t),this.to.ensure(e);const i=this.from.rowCount,n=new Int32Array(this.from.capacity).fill(-1);if(t.isString===e.isString&&t.kinds===null&&e.kinds===null){const s=st(e,this.to),{data:r}=t,o=t.isString?-1:NaN;for(let h=0;h<i;h++){const l=r[h];l===o||l!==l||(n[h]=s(l))}}else{const s=new Map;for(let r=this.to.rowCount-1;r>=0;r--)this.to.alive[r]&&s.set(String(e.get(r)),r);for(let r=0;r<i;r++){const o=t.get(r);o!==null&&(n[r]=s.get(String(o))??-1)}}return this._parents=n,n}children(){if(this._check(),this._children!==null)return this._children;const t=this.parents(),e=this.from.rowCount,i=this.to.rowCount,n=new Int32Array(i+2),{alive:s}=this.from;for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&n[h+2]++}for(let o=0;o<i;o++)n[o+2]+=n[o+1];const r=new Int32Array(n[i+1]);for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&(r[n[h+1]++]=o)}return this._children={starts:n,rows:r},this._children}childRows(t){const{starts:e,rows:i}=this.children();return i.subarray(e[t],e[t+1])}}function st(c,t){const{data:e}=c,i=t.rowCount;let n=1/0,s=-1/0,r=!0;for(let h=0;h<i;h++){const l=e[h];l!==l||!t.alive[h]||(l<n&&(n=l),l>s&&(s=l),l!==Math.floor(l)&&(r=!1))}if(r&&s-n<i*4+1024){const h=new Int32Array(s-n+1>0?s-n+1:0).fill(-1);for(let l=i-1;l>=0;l--){const a=e[l];a===a&&t.alive[l]&&(!c.isString||a>=0)&&(h[a-n]=l)}return l=>l>=n&&l<=s&&l===Math.floor(l)?h[l-n]:-1}const o=new Map;for(let h=i-1;h>=0;h--){const l=e[h];l===l&&t.alive[h]&&o.set(l,h)}return h=>o.get(h)??-1}function mt(c,t="children",e="level"){const i=[],n=[];for(let s=c.length-1;s>=0;s--)n.push([c[s],0]);for(;n.length>0;){const[s,r]=n.pop(),{[t]:o,...h}=s;if(i.push({...h,[e]:r}),Array.isArray(o))for(let l=o.length-1;l>=0;l--)n.push([o[l],r+1])}return i}const nt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max"};class M{constructor(t,e,i={}){this.manager=t,this.name=e,this.capacity=Math.max(et,i.capacity??0),this.rowCount=0,this.columns=[],this.byName=new Map,this.alive=new Uint8Array(this.capacity),this.state=new Uint8Array(this.capacity),this.deletedCount=0,this.originals=new Map,this.listeners=new Set,this.revision=0,this.structureRevision=0,this.key=i.key??null,this.tracking=i.tracking!==!1,this.provider=i.provider??null,this.batchDepth=0,this.batchChanged=!1,this.indexes=new Map,this.views=new Map,this.windowDefs=i.windows??{},this.schema=i.schema??null,this.remote=i.remote??null,this.autoSync=i.autoSync===!0,this.batchSync=i.batch===!0,this.rowErrors=new Map,this.fetched=!1,this.fetching=null,this.triggers=[],this.options=i;for(const n of i.fields??[])this.addField(n);i.indexes&&this.createIndexes(i.indexes),i.data&&this.load(i.data)}createIndexes(t){for(const e of t)this.column(e)&&this.indexes.set(e,null)}dropIndexes(t){for(const e of t)this.indexes.delete(e)}clearIndexes(){this.indexes.clear()}getIndexes(){return[...this.indexes.keys()]}searchRows(t,e){const i=this.column(e);if(!i)return[];if(this.ensure(i),this.indexes.has(e)){let r=this.indexes.get(e);if(r===null){r=new Map;const o=this.rowCount;for(let h=0;h<o;h++){if(this.alive[h]===0)continue;const l=i.get(h);if(l===null)continue;const a=r.get(l);a===void 0?r.set(l,[h]):a.push(h)}this.indexes.set(e,r)}return r.get(t)??[]}const n=[],s=this.rowCount;for(let r=0;r<s;r++)this.alive[r]===1&&i.get(r)===t&&n.push(r);return n}search(t,e){return this.searchRows(t,e).map(i=>this.record(i))}_dropIndexOf(t){this.indexes.has(t.name)&&this.indexes.set(t.name,null)}_dropAllIndexes(){for(const t of this.indexes.keys())this.indexes.set(t,null)}ensureOrderColumn(){let t=this.byName.get("__order");if(!t){t=this.addHelper({name:"__order",type:"number",hidden:!0});for(let e=0;e<this.rowCount;e++)t.data[e]=e}return t}column(t){const e=this.byName.get(t);if(e!==void 0)return e;if(typeof t=="string"&&t.includes("."))return this._pathColumn(t)}get fields(){return this.columns.filter(t=>t!==null&&!t.hidden)}addField(t){if(this.byName.has(t.name))throw new m(_("The field {field} already exists in {table}.",{field:t.name,table:this.name}));const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),e.formula!==null&&this.manager.formulas.bind(e),e.trigger&&this.triggers.push(e),this.computedOrder=null,this.revision++,this._emit({type:"schema"}),e}removeField(t){const e=this.byName.get(t);if(e){this.byName.delete(t),this.columns[e.index]=null,this.computedOrder=null,this.revision++;for(const i of this.columns)i&&i.computed&&(i.stale=!0);this._emit({type:"schema"})}}setFormula(t,e){const i=this.byName.get(t);if(!i)throw new m(`No field ${t} in ${this.name}`);i.formula=e,i.computed=!0,i.stale=!0,this.manager.formulas.bind(i),this.computedOrder=null,this._markDependentsStale(i),this.revision++,this._emit({type:"reload"})}_pathColumn(t){const e=t.indexOf("."),i=t.slice(0,e),n=t.slice(e+1),s=this.manager.relationshipFrom(this,i);if(!s)return;const r=s.to.column(n);if(r)return this.addHelper({name:t,type:r.type==="string"?"string":r.type,format:r.format,caption:r.caption,readOnly:!0,hidden:!0,lookup:{relation:s,field:n}})}addHelper(t){const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),this.computedOrder=null,e}rollupColumn(t,e){const i=`${t}(${e})`,n=this.byName.get(i);if(n)return n;const s=e.indexOf(".");if(s<0)return;const r=this.manager.relationshipTo(this,e.slice(0,s)),o=nt[t];if(!r||!o)return;const h=e.slice(s+1);if(r.from.column(h))return this.addHelper({name:i,type:"number",readOnly:!0,hidden:!0,rollup:{relation:r,field:h,agg:o}})}ensure(t){t.stale&&(t.stale=!1,t.window!==null?K(t):t.formula!==null?this.manager.formulas.computeAll(t):t.lookup!==null?this._computeLookup(t):t.rollup!==null&&this._computeRollup(t),t.revision++)}ensureAll(){for(const t of this.columns)t!==null&&t.stale&&this.ensure(t)}_computeLookup(t){const{relation:e,field:i}=t.lookup,n=e.parents(),s=e.to.column(i);e.to.ensure(s);const r=this.rowCount,{data:o}=t,h=s.data;if(t.isString&&s.isString)for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?-1:h[a]}else if(!t.isString&&!s.isString&&s.kinds===null){t.kinds=null;for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?NaN:h[a]}}else for(let l=0;l<r;l++){const a=n[l];t.put(l,a<0?null:s.get(a))}}_computeRollup(t){const{relation:e,field:i,agg:n}=t.rollup,s=e.from.column(i);e.from.ensure(s);const{starts:r,rows:o}=e.children(),h=this.rowCount,{data:l}=t,a=s.data,p=s.isNumeric;for(let f=0;f<h;f++){const d=r[f],w=r[f+1];let y=0,g=0,v=1/0,R=-1/0;for(let A=d;A<w;A++){const U=o[A];if(!p){s.kind(U)!==b&&g++;continue}const C=a[U];C===C&&(y+=C,g++,C<v&&(v=C),C>R&&(R=C))}switch(n){case"sum":l[f]=y;break;case"count":l[f]=g;break;case"average":l[f]=g>0?y/g:NaN;break;case"min":l[f]=g>0?v:NaN;break;default:l[f]=g>0?R:NaN}}}_order(){if(this.computedOrder)return this.computedOrder;const t=[],e=new Set,i=n=>{if(!e.has(n)){e.add(n);for(const s of n.deps){const r=this.column(s);r&&r.computed&&i(r)}t.push(n)}};for(const n of this.columns)n&&n.computed&&i(n);return this.computedOrder=t,t}_reserve(t){if(t<=this.capacity)return;let e=this.capacity;for(;e<t;)e*=2;for(const n of this.columns)n!==null&&n._grow(e);const i=n=>{const s=new Uint8Array(e);return s.set(n),s};this.alive=i(this.alive),this.state=i(this.state),this.capacity=e}get liveCount(){return this.rowCount-this.deletedCount}load(t){this.schema&&(t=W(t,this.schema)),Array.isArray(t)&&t.length>0&&this.schema?.spread&&(t=t.map(r=>X(r)));const e=Array.isArray(t)?t:null;if(e!==null&&this.columns.length===0&&e.length>0&&this._inferFields(e),e===null)return this._loadColumns(t);const i=e.length;this._reserve(i);const n=this.columns.filter(r=>r!==null&&!r.computed),s=i>0&&Array.isArray(e[0]);for(const r of n)r.rankCache=null,r.kinds=null,r.data.fill(r.isString?-1:NaN,0,this.capacity);this.rowCount=i;for(let r=0;r<n.length;r++){const o=n[r];for(let h=0;h<i;h++){const l=s?e[h][r]:J(e[h],o.name);l!=null&&o.put(h,o.coerce(l))}}return this._afterLoad(i),i}_loadColumns(t){let e=0;for(const i of Object.values(t))e=Math.max(e,i.length);this._reserve(e),this.rowCount=e;for(const[i,n]of Object.entries(t)){let s=this.byName.get(i);if(!s){const r=n.length>0?n[0]:null;s=this.addField({name:i,type:ArrayBuffer.isView(n)||typeof r=="number"?"number":typeof r=="boolean"?"boolean":"string"}),this._reserve(e)}if(s.rankCache=null,ArrayBuffer.isView(n)&&!s.isString)s.kinds=null,s.data.set(n),n.length<this.capacity&&s.data.fill(NaN,n.length);else if(s.isString&&n instanceof Int32Array)s.data.set(n);else for(let r=0;r<n.length;r++){const o=n[r];o!=null&&s.put(r,s.coerce(o))}}return this._afterLoad(e),e}_afterLoad(t){this._dropAllIndexes(),this.rowErrors.clear(),this.alive.fill(1,0,t),this.alive.fill(0,t),this.state.fill(0),this.originals.clear(),this.deletedCount=0,this.revision++,this.structureRevision++,this._markAllComputedStale(),this.manager._tableChanged(this),this._emit({type:"reload"})}_inferFields(t){const e=t[0];if(Array.isArray(e)){e.forEach((s,r)=>this.addField({name:`Field${r+1}`,type:S(t,r)}));return}const i=new Set,n=Math.min(t.length,200);for(let s=0;s<n;s++)for(const r of Object.keys(t[s]))i.add(r);for(const s of i)this.addField({name:s,type:S(t,s)})}loadSheet(t,e,i,{header:n=!0}={}){const s=[],{strings:r}=t;for(let a=i.c0;a<=i.c1;a++){const f=(e.kind(i.r0,a)&T)===N?r.get(e.value(i.r0,a)):"";s.push(n&&f?f:`Field${a-i.c0+1}`)}const o=n?i.r0+1:i.r0,h=Math.max(0,i.r1-o+1),l=(a,p)=>{const f=e.kind(a,p)&T,d=e.value(a,p);return f===k?d:f===N?r.get(d):f===E?d!==0:f===D?$.get(P[d])??null:null};return s.forEach((a,p)=>{if(this.byName.has(a))return;const f=[];for(let g=o;g<=Math.min(o+199,o+h-1);g++)f.push([l(g,i.c0+p)]);const d=t.styles?.get(e.style(o,i.c0+p)),w=d&&/[ymd]/i.test(String(d.numFmt??"").replace(/"[^"]*"/g,"")),y=S(f,0);this.addField({name:a,type:y==="number"&&w?"date":y,format:d?.numFmt!=="General"?d?.numFmt:void 0})}),this._reserve(h),this.rowCount=h,s.forEach((a,p)=>{const f=this.byName.get(a),d=i.c0+p;f.rankCache=null;for(let w=0;w<h;w++){const y=l(o+w,d);f.put(w,y instanceof x?null:f.coerce(y))}}),this._afterLoad(h),h}addRow(t={},{track:e=!0}={}){const i=this.rowCount;this._reserve(i+1),this.rowCount=i+1,this.alive[i]=1,this.state[i]=e&&this.tracking?u.INSERTED:u.UNCHANGED;for(const s of this.columns){if(s===null||s.computed)continue;let r=t[s.name]!==void 0?t[s.name]:s.defaultValue;typeof r=="string"&&r[0]==="="&&t[s.name]===void 0&&(r=this.manager.formulas.evaluateOnce(this,i,r)),s.put(i,r==null?null:s.coerce(r)),s.rankCache=null}const n=this.byName.get("__order");return n&&(n.data[i]=t.__order??this._nextOrder(n.data)),this._dropAllIndexes(),this._runTriggers(i,!0),this._rowsChanged(i),this._emit({type:"rows",row:i,added:!0}),i}_nextOrder(t){let e=-1;for(let i=0;i<this.rowCount;i++)t[i]>e&&(e=t[i]);return e+1}_runTriggers(t,e){for(const i of this.triggers){if(!e&&i.trigger.when!=="newAndUpdate")continue;const n=this.manager.formulas.evaluateOnce(this,t,i.trigger.formula);i.put(t,n instanceof x?null:i.coerce(n)),i.revision++}}removeRow(t){return this.alive[t]?(this.alive[t]=0,this.deletedCount++,this._dropAllIndexes(),this._rowsChanged(t),this._emit({type:"rows",row:t,removed:!0}),this._autoPush(),!0):!1}restoreRow(t){return this.alive[t]?!1:(this.alive[t]=1,this.deletedCount--,this.state[t]===u.PURGED&&(this.state[t]=u.UNCHANGED),this._rowsChanged(t),this._emit({type:"rows",row:t,added:!0}),!0)}_rowsChanged(t){this.revision++,this.structureRevision++;for(const e of this._order())this._recomputeRowOrAll(e,t);this.manager._tableChanged(this)}_recomputeRowOrAll(t,e){t.stale||(t.formula!==null&&!t.rangeDep&&e<this.rowCount?this.manager.formulas.computeRow(t,e):t.stale=!0)}_markAllComputedStale(){for(const t of this.columns)t!==null&&t.computed&&(t.stale=!0)}_markDependentsStale(t){for(const e of this._order())e!==t&&e.deps.includes(t.name)&&(e.stale=!0,this._markDependentsStale(e))}get(t,e){const i=this.column(e);if(!i)throw new m(`No field ${e} in ${this.name}`);return i.get(t)}set(t,e,i){const n=typeof e=="string"?this.column(e):e;if(!n)throw new m(`No field ${e} in ${this.name}`);if(n.computed)throw new m(_("The {field} field is calculated, so it can't be edited.",{field:n.caption}));if(n.readOnly)throw new m(_("The {field} field is read-only.",{field:n.caption}));const s=n.coerce(i),r=n.get(t);if(G(r,s))return!1;if(n.validator!==null){const o=Y(n,s,t);if(o)throw new m(o)}if(n.required&&(s===null||s===""))throw new m(_("The {field} field can't be blank.",{field:n.caption}));return this.tracking&&this.state[t]!==u.INSERTED&&this._track(t,n,r,s),n.put(t,s),n.revision++,this._dropIndexOf(n),this.triggers.length>0&&this._runTriggers(t,!1),this._afterEdit(t,n),this._autoPush(),!0}_track(t,e,i,n){let s=this.originals.get(t);s===void 0&&(s=new Map,this.originals.set(t,s)),s.has(e.index)?G(s.get(e.index),n)&&s.delete(e.index):s.set(e.index,i),s.size===0?(this.originals.delete(t),this.state[t]=u.UNCHANGED):this.state[t]=u.UPDATED}_afterEdit(t,e){this.revision++;const i=new Set([e.name]);let n=this.manager.isKeyField(this,e.name);for(const s of this._order())s.deps.some(r=>i.has(r))&&(i.add(s.name),s.rangeDep||s.formula===null?s.stale=!0:s.stale||this.manager.formulas.computeRow(s,t),this.manager.isKeyField(this,s.name)&&(n=!0));n&&this.structureRevision++,this.manager._fieldChanged(this,i),this._emit({type:"cell",row:t,col:e})}batch(t){this.batchDepth++;try{return t()}finally{this.batchDepth--,this.batchDepth===0&&this.batchChanged&&(this.batchChanged=!1,this._emit({type:"reload"}))}}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){if(this.batchDepth>0){this.batchChanged=!0;return}for(const e of this.listeners)e(t)}getChanges(){const t=[],e=[],i=[],n=this.rowCount,{state:s,alive:r}=this;for(let o=0;o<n;o++)if(s[o]!==u.PURGED){if(s[o]===u.INSERTED)r[o]&&t.push(Object.defineProperty(this.record(o),"__row",{value:o,enumerable:!1}));else if(!r[o])i.push({row:o,record:this.originalRecord(o)});else if(s[o]===u.UPDATED){const h=this.originals.get(o),l={},a={};for(const[p,f]of h){const d=this.columns[p];l[d.name]=d.get(o),a[d.name]=f}e.push({row:o,record:this.record(o),changes:l,original:a})}}return{inserted:t,updated:e,deleted:i}}get hasChanges(){if(this.originals.size>0)return!0;const{state:t,alive:e}=this;for(let i=0;i<this.rowCount;i++)if(t[i]===u.INSERTED?e[i]===1:t[i]!==u.PURGED&&e[i]===0)return!0;return!1}originalValue(t,e){return this.originals.get(t)?.get(e.index)}isCellEdited(t,e){return this.originals.get(t)?.has(e.index)===!0}record(t){const e={};for(const i of this.columns)i!==null&&!i.hidden&&(e[i.name]=i.get(t));return e}originalRecord(t){const e=this.record(t),i=this.originals.get(t);if(i)for(const[n,s]of i)e[this.columns[n].name]=s;return e}acceptChanges(){this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;for(let n=0;n<t;n++)e[n]=i[n]?u.UNCHANGED:u.PURGED;this.revision++,this._emit({type:"cells"})}rejectChanges(){this.batch(()=>{for(const[s,r]of this.originals)for(const[o,h]of r){const l=this.columns[o];l.put(s,h),l.revision++}this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;let n=0;for(let s=0;s<t;s++)e[s]===u.INSERTED?(i[s]=0,e[s]=u.PURGED):e[s]!==u.PURGED&&(i[s]=1,e[s]=u.UNCHANGED),i[s]===0&&n++;this.deletedCount=n,this.structureRevision++,this.revision++,this._markAllComputedStale(),this.manager._tableChanged(this),this.batchChanged=!0})}revertRow(t){const e=this.originals.get(t);if(e){for(const[i,n]of e){const s=this.columns[i];s.put(t,n),s.revision++,this._afterEdit(t,s)}this.originals.delete(t),this.state[t]=u.UNCHANGED}if(this.state[t]===u.INSERTED){this.state[t]=u.PURGED,this.removeRow(t);return}this.alive[t]||this.restoreRow(t),this._emit({type:"cell",row:t})}connect(t){this.remote=t,this.provider=null}fetch(t=!1){return this.fetched&&!t?Promise.resolve(this):this.fetching?this.fetching:!this.remote&&this.options.data===void 0&&!t?(this.fetched=!0,Promise.resolve(this)):this.remote?(this.fetching=Q(this.remote,this.schema).then(e=>(this.load(e),this.fetched=!0,this.fetching=null,this),e=>{throw this.fetching=null,e}),this.fetching):Promise.resolve(this)}pull(){return this.fetch(!0)}_autoPush(){!this.autoSync||!this.remote||this.batchDepth>0||this._pushing||(this._pushing=!0,queueMicrotask(()=>{this._pushing=!1,this.submitChanges().catch(()=>{})}))}async submitChanges(){if(!this.remote)throw new m(_("{table} has no data source to write to.",{table:this.name}));const t=this.getChanges(),e=await I(this,t);return this.rowErrors=e.errors,e.errors.size===0?this.acceptChanges():this._acceptExcept(e.errors),this._emit({type:"cells"}),e.counts}push(){return this.submitChanges()}cancelChanges(){this.rejectChanges()}_acceptExcept(t){const e=this.rowCount,{state:i,alive:n}=this;for(let s=0;s<e;s++)t.has(s)||(this.originals.delete(s),i[s]=n[s]?u.UNCHANGED:u.PURGED);this.revision++}async saveRow(t){if(!this.remote){this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED,this._emit({type:"cells"});return}const e=this.getChanges(),i={inserted:e.inserted.filter(s=>s.__row===t),updated:e.updated.filter(s=>s.row===t),deleted:e.deleted.filter(s=>s.row===t)},n=await I(this,i);n.errors.has(t)?this.rowErrors.set(t,n.errors.get(t)):(this.rowErrors.delete(t),this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED),this._emit({type:"cells"})}resetRow(t){this.rowErrors.delete(t),this.revertRow(t)}missingRequired(t){const e=[];for(const i of this.columns)i!==null&&i.required&&(i.kind(t)===b||i.get(t)==="")&&e.push(i.caption);return e}}const G=(c,t)=>c===t?!0:c===null||t===null||typeof c=="string"&&typeof t=="string"?!1:typeof c=="boolean"&&typeof t=="number"?(c?1:0)===t:typeof c=="number"&&typeof t=="boolean"?(t?1:0)===c:!1;function S(c,t){let e=null;const i=Math.min(c.length,500);for(let n=0;n<i;n++){const s=c[n][t];if(s==null||s==="")continue;const r=s instanceof Date?"date":typeof s=="number"?"number":typeof s=="boolean"?"boolean":typeof s=="string"?"string":"any";if(e===null)e=r;else if(e!==r)if(e==="date"&&r==="number"||e==="number"&&r==="date")e="number";else return"any"}return e??"string"}let F=null;function pt(c){F=c}class gt{constructor(t=null){this.book=t,this.strings=t?.strings??new L,this.tables=new Map,this.relationships=[],this._formulas=null}get formulas(){if(this._formulas===null){if(F===null)throw new Error("Formula support is not loaded. Import datasheets/data.js first.");this._formulas=new F(this)}return this._formulas}addTable(t,e={}){if(this.tables.has(t))throw new m(`The table ${t} already exists.`);const i=new M(this,t,e);return this.tables.set(t,i),i}table(t){if(t instanceof M)return t;const e=this.tables.get(t);if(!e)throw new m(`No table named ${t}.`);return e}removeTable(t){const e=this.table(t);this.tables.delete(e.name),this.relationships=this.relationships.filter(i=>i.from!==e&&i.to!==e)}addRelationship(t){const e=new it(this,t);return this.relationships.push(e),e}removeRelationship(t){this.relationships=this.relationships.filter(e=>e!==t)}relationshipFrom(t,e){return this.relationships.find(i=>i.from===t&&i.name===e)??null}relationshipTo(t,e){return this.relationships.find(i=>i.to===t&&i.inverse===e)??null}relationshipBetween(t,e){return this.relationships.find(i=>i.from===t&&i.to===e||i.from===e&&i.to===t)??null}isKeyField(t,e){return this.relationships.length===0?!1:this.relationships.some(i=>i.from===t&&i.fromField===e||i.to===t&&i.toField===e)}_tableChanged(t){for(const e of this.tables.values()){let i=!1;for(const n of e.columns)n!==null&&(n.lookup&&(n.lookup.relation.to===t||n.lookup.relation.from===t)||n.rollup&&(n.rollup.relation.from===t||n.rollup.relation.to===t))&&(n.stale||(n.stale=!0,i=!0,e._markDependentsStale(n)));i&&e!==t&&e._emit({type:"reload",derived:!0})}}_fieldChanged(t,e){if(this.relationships.length!==0)for(const i of this.tables.values()){let n=!1;for(const s of i.columns){if(s===null)continue;(s.window&&s.window.table===t&&s.deps.some(o=>e.has(o))||s.lookup&&s.lookup.relation.to===t&&e.has(s.lookup.field)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.field)||s.lookup&&s.lookup.relation.from===t&&e.has(s.lookup.relation.fromField)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.relation.fromField))&&!s.stale&&(s.stale=!0,n=!0,i._markDependentsStale(s))}n&&i!==t&&i._emit({type:"reload",derived:!0})}}}export{O as DataColumn,m as DataError,gt as DataManager,M as DataTable,Z as FIELD_TYPES,u as ROW,it as Relationship,mt as flattenTree,pt as installFormulas,st as keyIndex};
@@ -0,0 +1 @@
1
+ import{FormulaColumns as o}from"./formula.js";import{installFormulas as m}from"./data-core.js";m(o);export*from"./data-core.js";
@@ -0,0 +1 @@
1
+ import{CHUNK_BITS as C,CHUNK_MASK as b,CHUNK_SIZE as A,EMPTY as F,NUM as R,Sheet as L}from"../core/sheet.js";import{colName as M}from"../core/address.js";import{Engine as S}from"../calc/engine.js";import{toFileFormula as $}from"../calc/parser.js";import{Arr as D,ERR as _,Lambda as O,Ref as I,RefList as K,XlError as N}from"../calc/values.js";import{extractWindowCalls as T}from"./window.js";const v=()=>({kinds:new Uint8Array(A),values:new Float64Array(A),styles:null});function E(h,e,t){const s=h.table,{kinds:i,values:u}=e,n=Math.min(A,s.rowCount-t),{data:a,kinds:m,isString:r}=h,f=h.type==="boolean";if(n<=0){i.fill(0);return}if(r)for(let o=0;o<n;o++){const l=a[t+o];i[o]=l<0?0:2,u[o]=l}else if(m!==null)for(let o=0;o<n;o++)i[o]=m[t+o],u[o]=a[t+o];else{const o=f?3:R;for(let l=0;l<n;l++){const d=a[t+l];d!==d?i[l]=F:(i[l]=o,u[l]=d)}}if(n<A&&i.fill(0,n),s.deletedCount>0){const{alive:o}=s;for(let l=0;l<n;l++)o[t+l]===0&&(i[l]=F)}}function V(h,e){let t="",s="";for(let i=0;i<h.length;i++){const u=h[i];if(u==='"'){t+=e(s),s="";let n=i+1;for(;!(n>=h.length);)if(h[n]==='"')if(h[n+1]==='"')n+=2;else break;else n++;t+=h.slice(i,n+1),i=n}else s+=u}return t+e(s)}const H=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,B=/\[(@?)\[?([^[\]]+?)\]?\]/g;class Z{constructor(e){this.manager=e,this.engine=null,this.sheets=new Map}_engineFor(){return this.engine===null&&(this.engine=new S({sheets:[],strings:this.manager.strings}),this.engine.legacy=!0),this.engine}_sheet(e){let t=this.sheets.get(e);return t===void 0&&(t=new L(`__data_${e.name}`),this.sheets.set(e,t)),t.maxRow=e.rowCount-1,t.maxCol=e.columns.length-1,t}bind(e){const t=e.table,s=new Set;let i=!1,u=!1;const n=T(String(e.formula).replace(/^=/,""),t,m=>{s.add(m.name),i=!0}),a=V(n,m=>m.replace(H,(r,f,o)=>{const l=o.trim();if(!l.includes("."))return r;const d=t.rollupColumn(f.toUpperCase(),l);return d?(s.add(d.name),`$${M(d.index)}1`):r}).replace(B,(r,f,o)=>{const l=o.trim(),d=t.column(l);if(!d)return u=!0,"#NAME?";s.add(d.name);const y=M(d.index);return f==="@"?`$${y}1`:(i=!0,`$${y}:$${y}`)}));if(e.deps=[...s],e.rangeDep=i,e.stale=!0,e.compiled=null,u){e.compiled={fn:()=>_.NAME,ok:!1};return}try{const r=this._engineFor().template($(a),0,e.index);e.compiled={fn:r.fn,ok:!r.external}}catch{e.compiled={fn:()=>_.NAME,ok:!1}}this._hasCycle(e)&&(e.compiled={fn:()=>_.REF,ok:!1},e.deps=[])}_hasCycle(e){const t=e.table,s=new Set,i=u=>{if(u===e.name)return!0;if(s.has(u))return!1;s.add(u);const n=t.column(u);return n?n.deps.some(i):!1};return e.deps.some(i)}_evaluate(e,t,s,i,u){let n;try{n=e(t,s,i)}catch(a){return a instanceof N?a:_.VALUE}if(n instanceof I||n instanceof K)try{n=u.refAuto(n,t,s)}catch(a){return a instanceof N?a:_.VALUE}return n instanceof D&&(n=n.data[0]),n instanceof O?_.CALC:typeof n=="number"&&!Number.isFinite(n)?_.NUM:n===void 0?null:n}computeAll(e){const t=e.table;e.compiled===null&&this.bind(e);const s=e.deps.map(p=>t.column(p));for(const p of s)t.ensure(p);const i=this._engineFor(),u=this._sheet(t),n=t.rowCount,{fn:a}=e.compiled,m=e.index,r=n+b>>>C,f=u.columns;f.length=0;const o=s.map(()=>v());for(const p of s)f[p.index]=[];if(e.rangeDep)for(const p of s){const x=f[p.index];for(let k=0;k<r;k++){const c=v();E(p,c,k<<C),x[k]=c}}const l=t.alive,d=t.deletedCount>0;e.kinds=null;const y=e.data,w=!e.isString;for(let p=0;p<r;p++){const x=p<<C;if(!e.rangeDep)for(let c=0;c<s.length;c++){const g=f[s[c].index];E(s[c],o[c],x),p>0&&(g[p-1]=void 0),g[p]=o[c]}const k=Math.min(n,x+A);for(let c=x;c<k;c++){if(d&&l[c]===0){e.put(c,null);continue}const g=this._evaluate(a,c,m,u,i);w&&e.kinds===null&&typeof g=="number"?y[c]=g:e.type==="any"||g===null||typeof g=="number"?e.put(c,g):e.put(c,e.type==="any"?g:U(e,g))}}f.length=0}computeRow(e,t){const s=e.table;e.compiled===null&&this.bind(e);const i=e.deps.map(r=>s.column(r));for(const r of i)r.stale&&s.ensure(r);const u=this._engineFor(),n=this._sheet(s),a=n.columns;a.length=0;const m=t>>>C;for(const r of i){const f=v();E(r,f,m<<C),a[r.index]=[],a[r.index][m]=f}if(s.alive[t]===0)e.put(t,null);else{const r=this._evaluate(e.compiled.fn,t,e.index,n,u);e.put(t,typeof r=="number"||r===null||e.type==="any"?r:U(e,r))}e.revision++,a.length=0}evaluateOnce(e,t,s){const i={table:e,index:e.columns.length,formula:s,deps:[],name:"\0temp",compiled:null};this.bind(i);const u=i.deps.map(f=>e.column(f));for(const f of u)e.ensure(f);const n=this._sheet(e),a=n.columns;a.length=0;const m=t>>>C;for(const f of u)if(a[f.index]=[],i.rangeDep){const o=e.rowCount+b>>>C;for(let l=0;l<o;l++){const d=v();E(f,d,l<<C),a[f.index][l]=d}}else{const o=v();E(f,o,m<<C),a[f.index][m]=o}const r=this._evaluate(i.compiled.fn,t,i.index,n,this._engineFor());return a.length=0,r}}function U(h,e){try{return h.coerce(e)}catch{return null}}export{Z as FormulaColumns,E as fillRawChunk};
@@ -0,0 +1 @@
1
+ import{STR as on}from"../core/sheet.js";import{getFormatter as ln}from"../core/numfmt.js";import{formulaHelper as mn}from"./view.js";const B={bar:"#4a90d9",barDone:"#22598f",critical:"#d64545",criticalDone:"#932626",summary:"#404040",milestone:"#2b2b2b",baseline:"#a8a8a8",deadline:"#c42b1c",link:"#6b6b6b",linkCritical:"#c42b1c",today:"#107c41",tier:"#f3f3f3",tierLine:"#d0d0d0",tierInk:"#3b3b3b",label:"#3b3b3b"};function cn(n,i){if(i)return i._panes();const e=n.toScreen(0,0);return[{x:n.hx,y:n.hy,w:n.cssW-n.hx,h:n.cssH-n.hy,originX:n.hx-e.x,originY:n.hy-e.y,frozenC:!1,frozenR:!1,print:!0}]}function tn(n,i,e,l,o,t){const f=Math.min(t,l/2,o/2);n.beginPath(),n.moveTo(i+f,e),n.lineTo(i+l-f,e),n.quadraticCurveTo(i+l,e,i+l,e+f),n.lineTo(i+l,e+o-f),n.quadraticCurveTo(i+l,e+o,i+l-f,e+o),n.lineTo(i+f,e+o),n.quadraticCurveTo(i,e+o,i,e+o-f),n.lineTo(i,e+f),n.quadraticCurveTo(i,e,i+f,e),n.closePath()}function rn(n,i,e,l,o,t,f,r){if(!t||t==="solid")return;n.save(),n.beginPath(),n.rect(i,e,l,o),n.clip(),n.strokeStyle=f,n.fillStyle=f,n.lineWidth=Math.max(1,r*.75);const a=5*r;if(t==="dots")for(let s=i;s<i+l;s+=a)for(let m=e;m<e+o;m+=a)n.fillRect(s,m,Math.max(1,r),Math.max(1,r));else{n.beginPath();for(let s=-o;s<l;s+=a)n.moveTo(i+s,e+o),n.lineTo(i+s+o,e);n.stroke()}n.restore()}function dn(n,i,e,l){let t=n.taskbarStyles[e]??null;const f=n.taskbarRules;for(let r=0;r<f.length;r++){const a=f[r];if(a.type&&a.type!==e)continue;let s=!0;if(a.formula){let m=l[r];m===void 0&&(m=mn(n.table,a.formula),l[r]=m);const S=m.get(i);s=S===!0||typeof S=="number"&&S!==0}s&&(t=t===null?a.style:{...t,...a.style})}return t}function an(n,i,e,l,o,t,f,r){if(!i)return;const a=l+o/2,s=o*.75,m=r?1:-1;n.fillStyle=t,n.beginPath(),i==="diamond"?(n.moveTo(e,a-s),n.lineTo(e+s,a),n.lineTo(e,a+s),n.lineTo(e-s,a)):i==="triangle"?(n.moveTo(e,a-s),n.lineTo(e+m*s,a),n.lineTo(e,a+s)):i==="circle"?n.arc(e,a,s*.8,0,Math.PI*2):n.rect(e-f*1.5,l-f,3*f,o+2*f),n.closePath(),n.fill()}function Mn(n,i,e,l=null){const o=e.schedule;if(!o)return;const{dpr:t}=i,{zoom:f}=i;for(const r of cn(i,l)){n.save(),n.beginPath(),n.rect(r.x*t,r.y*t,r.w*t,r.h*t),n.clip();const a=y=>(r.x+(y-r.originX)*f)*t,s=y=>(r.y+(y-r.originY)*f)*t,m=f*t,{rows:S,cols:k}=e,w=r.originX,u=r.originX+r.w/f,g=r.originY,D=r.originY+r.h/f,h=k.offsetOf(e.timelineStart);if(u>h){const y=r.frozenR?0:Math.max(S.indexAt(g),e.frozenRows),c=r.frozenR?e.frozenRows-1:S.indexAt(D),b=Math.max(g,S.offsetOf(e.frozenRows));(!r.frozenR||r.print)&&fn(n,e,a,s,m,w,u,b,D,r),(!r.frozenR||r.print)&&un(n,e,o,a,s,m,w,u,b,D,y,c),y===0&&!r.print&&(r.frozenR||e.frozenRows===0)&&sn(n,e,a,s,m,w,u),r.print&&g<S.sizeOf(0)&&sn(n,e,a,s,m,w,u),(c>=e.bodyStart||r.frozenR)&&yn(n,e,o,a,s,m,Math.max(y,1),Math.min(c,e.bodyStart+e.view.count-1),w,u),e.nonWorking.mode==="front"&&!r.frozenR&&fn(n,e,a,s,m,w,u,b,D,r,!0),r.frozenR||bn(n,e,o,a,s,m,g,D),e.progressLine.visible&&!r.frozenR&&pn(n,e,o,a,s,m,Math.max(y,1),Math.min(c,e.bodyStart+e.view.count-1))}n.restore()}}function sn(n,i,e,l,o,t,f){const{scale:r,cols:a,colors:s}=i,m=a.offsetOf(i.timelineStart),S=r.tickWidth,k=i.rows.sizeOf(0),w=l(0),u=Math.max(m,t),g=s?.tier??B.tier,D=s?.tierInk??B.tierInk,h=s?.tierLine??B.tierLine;n.fillStyle=g,n.fillRect(e(u),w,(f-u)*o,k*o),n.textBaseline="middle";const y=Math.round(10.5*o);n.font=`${y}px -apple-system, "Helvetica Neue", Arial, sans-serif`;const c=Math.max(0,Math.floor((t-m)/S)),b=Math.min(r.count-1,Math.floor((f-m)/S)),C=r.tiers,O=k/Math.max(1,C.length),T=Math.max(1,Math.round(o*.75));C.forEach((v,W)=>{const P=W*O,{marks:F}=v;let I=0,d=F.length-1;for(;I<d;){const z=I+d+1>>>1;F[z].tick<=c?I=z:d=z-1}n.textAlign=v.bottom?"center":"left";for(let z=I;z<F.length;z++){const A=F[z];if(A.tick>b)break;const Z=z+1<F.length?F[z+1].tick:r.count,q=m+A.tick*S,R=m+Z*S;n.fillStyle=h,n.fillRect(Math.round(e(q)),l(P),T,O*o),n.fillStyle=D,v.bottom?n.fillText(A.label,e((q+R)/2),l(P+O/2)):(n.save(),n.beginPath(),n.rect(e(q),l(P),(R-q)*o,O*o),n.clip(),n.fillText(A.label,e(Math.max(q,t)+4),l(P+O/2)),n.restore())}n.fillStyle=h,n.fillRect(e(u),l(P+O)-T,(f-u)*o,T)})}function fn(n,i,e,l,o,t,f,r,a,s,m=!1){const{scale:S,cols:k,calendar:w,nonWorking:u}=i;if(s.frozenR||u.mode==="none"||u.mode==="front"!==m)return;const{unit:g}=S.bottomTier;if(g!=="day"&&g!=="hour"&&g!=="minute")return;const D=k.offsetOf(i.timelineStart),h=S.tickWidth,y=Math.max(0,Math.floor((t-D)/h)),c=Math.min(S.count-1,Math.floor((f-D)/h));n.fillStyle=u.color;const b=n.globalCompositeOperation;!m&&n.fillRect&&!s.print&&(n.globalCompositeOperation="multiply");for(let C=y;C<=c;C++){const O=S.ticks[C];(g==="day"?w.isWorkDay(O):w.isWorkTime(O+1e-6))||(n.fillRect(e(D+C*h),l(r),h*o,(a-r)*o),u.pattern&&u.pattern!=="solid"&&(n.globalCompositeOperation=b,rn(n,e(D+C*h),l(r),h*o,(a-r)*o,u.pattern,"#b8b8b8",o),!m&&!s.print&&(n.globalCompositeOperation="multiply"),n.fillStyle=u.color))}n.globalCompositeOperation=b}function un(n,i,e,l,o,t,f,r,a,s,m,S){const{scale:k,cols:w,gridlines:u,rows:g}=i,D=Math.max(1,Math.round(t*.75));if(u.interval>0){const h=w.offsetOf(i.timelineStart),y=k.tickWidth,c=Math.max(0,Math.floor((f-h)/y)),b=Math.min(k.count-1,Math.floor((r-h)/y));n.fillStyle=u.intervalColor;for(let C=c-c%u.interval;C<=b;C+=u.interval)n.fillRect(l(h+C*y),o(a),D,(s-a)*t)}if(u.rowInterval>0){n.fillStyle=u.rowColor;const h=Math.max(i.bodyStart,m);for(let y=h-(h-i.bodyStart)%u.rowInterval;y<=S;y+=u.rowInterval)n.fillRect(l(f),o(g.offsetOf(y)),(r-f)*t,D)}}function Y(n,i,e,l,o,t,f){n.strokeStyle=o,n.lineWidth=Math.max(1,t),n.setLineDash(f.map(r=>r*t)),n.beginPath(),n.moveTo(i,e),n.lineTo(i,l),n.stroke(),n.setLineDash([])}function bn(n,i,e,l,o,t,f,r){const{gridlines:a}=i,s=o(f),m=o(r);i.showToday&&a.current!==!1&&Y(n,l(i.xOfDate(i.today)),s,m,B.today,t,[4,3]),a.status&&i.statusDate!==null&&Y(n,l(i.xOfDate(i.statusDate)),s,m,"#7a4fb5",t,[2,2]),a.projectStart&&Y(n,l(i.xOfDate(e.projectStart)),s,m,"#2f6fb3",t,[6,3]),a.projectFinish&&Y(n,l(i.xOfDate(e.projectFinish)),s,m,"#2f6fb3",t,[6,3])}function pn(n,i,e,l,o,t,f,r){const{progressLine:a,rows:s,table:m,fields:S}=i,k=a.reference==="current"?i.today:i.statusDate??i.today,w=i.xOfDate(k),u=m.column(S.progress)?.data,g=[];for(let c=f;c<=r;c++){const b=i.recordAtRow(c);if(b<0||b>=e.rows||e.isSummary[b]===1||e.momentStart[b]===1/0)continue;const C=i.xOfDate(e.momentStart[b]),O=i.xOfDate(e.momentFinish[b]),T=u?u[b]:0,v=T===T?T:0,W=v>=1&&e.momentFinish[b]<=k||v<=0&&e.momentStart[b]>=k;g.push({x:W?w:C+(O-C)*v,y:s.offsetOf(c)+s.sizeOf(c)/2,row:c})}n.strokeStyle=a.color,n.fillStyle=a.color,n.lineWidth=Math.max(1,t*(a.width??1)),n.beginPath();let D=!1,h=null;const y=(c,b)=>{D?n.lineTo(l(c),o(b)):(n.moveTo(l(c),o(b)),D=!0)};for(const c of g){if(a.returnToAnchor){const b=c.y-s.sizeOf(c.row)/2;y(w,b),a.path==="square"&&y(c.x,b),y(c.x,c.y),a.path==="square"&&y(c.x,b+s.sizeOf(c.row)),y(w,b+s.sizeOf(c.row))}else h&&a.path==="square"&&y(h.x,c.y),y(c.x,c.y);h=c}n.stroke();for(const c of g)n.beginPath(),n.arc(l(c.x),o(c.y),2.2*t,0,Math.PI*2),n.fill();g.length>0&&a.showDate!==!1&&(n.font=`${Math.round(10*t)}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textAlign="center",n.textBaseline="bottom",n.fillText(ln("d-mmm").number(Math.floor(k)),l(w),o(g[0].y-s.sizeOf(g[0].row)/2)))}const V=(n,i,e,l)=>{if(!e)return"";const o=n.table.column(e);if(!o)return String(e);const t=o.get(i);if(t==null)return"";if(typeof t=="number"){const f=l??o.format;return f&&f!=="General"?ln(f).number(t):String(t)}return typeof t=="object"?t.code:String(t)};function yn(n,i,e,l,o,t,f,r,a,s){const{table:m,view:S,fields:k,rows:w,layoutOptions:u,colors:g}=i,D=m.column(k.progress)?.data,h=m.column(k.name),y=m.column(k.resource),c=i.showBaseline?m.column(k.deadline)?.data:null,b=i.showBaseline?m.column(k.baselineStart)?.data:null,C=i.showBaseline?m.column(k.baselineFinish)?.data:null,O=Math.round(11*t);n.font=`${O}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textBaseline="middle",n.textAlign="left";const T=i.bodyStart+S.count-1;i.showLinks&&u.linkMode!=="noLinks"&&Tn(n,i,e,l,o,t,f,Math.min(r,T));const v=[],W=u.roundToDays,P=g?.bar??B.bar,F=g?.barDone??B.barDone;for(let I=f;I<=r&&I<=T;I++){const d=i.recordAtRow(I);if(d<0||d>=e.rows||e.momentStart[d]===1/0)continue;const z=w.offsetOf(I),A=w.sizeOf(I),Z=W?Math.floor(e.momentStart[d]):e.momentStart[d],q=W?Math.ceil(e.momentFinish[d]):e.momentFinish[d],R=i.xOfDate(Z),H=i.xOfDate(q);if(H<a-300||R>s+40)continue;const E=e.isSummary[d]===1,j=!E&&e.duration[d]===0,$=i.showCritical&&e.critical[d]===1,K=m.column(k.manual)?.data[d]===1,p=dn(i,d,E?"summary":j?"milestone":K?"manual":$?"critical":"task",v),_=u.barHeight??A-8-(b?2:0),U=z+(A-_)/2-(b?1:0);if(b&&b[d]===b[d]&&!E){const L=i.xOfDate(b[d]),M=i.xOfDate(C[d]+(m.column(k.baselineFinish)&&e.calOf(d).fullDays?1:0));n.fillStyle=i.taskbarStyles.baseline?.fill??B.baseline,n.fillRect(l(L),o(z+A-4),Math.max(2,(M-L)*t),Math.max(2,2*t))}if(E){const L=p?.fill??($?B.criticalDone:g?.summary??B.summary);n.fillStyle=L;const M=U+1,N=Math.max(3,_*.45);n.fillRect(l(R),o(M),Math.max(2,(H-R)*t),N*t);const J=Math.min(5,Math.max(2,(H-R)/2)),G=N+3;n.beginPath(),n.moveTo(l(R),o(M)),n.lineTo(l(R+J),o(M)),n.lineTo(l(R),o(M+G)),n.closePath(),n.moveTo(l(H),o(M)),n.lineTo(l(H-J),o(M)),n.lineTo(l(H),o(M+G)),n.closePath(),n.fill()}else if(j){const L=z+A/2,M=Math.min(A/2-2,6);n.fillStyle=p?.fill??($?B.critical:B.milestone),n.beginPath(),n.moveTo(l(R),o(L-M)),n.lineTo(l(R+M),o(L)),n.lineTo(l(R),o(L+M)),n.lineTo(l(R-M),o(L)),n.closePath(),n.fill()}else{const L=Math.max(3/t,H-R),M=l(R),N=o(U),J=L*t,G=_*t,x=p?.fill??($?B.critical:K?"#7fa8d1":P);n.fillStyle=x,tn(n,M,N,J,G,2*t),n.fill(),p?.pattern&&rn(n,M,N,J,G,p.pattern,p.patternColor??"#ffffff",t),K&&!p&&(n.strokeStyle=F,n.lineWidth=Math.max(1,t*.75),n.strokeRect(M,N,J,G));const en=D?D[d]:0;en>0&&(n.fillStyle=p?.progressFill??($?B.criticalDone:F),tn(n,M,N,L*Math.min(1,en)*t,G,2*t),n.fill()),p?.startShape&&an(n,p.startShape,M,N,G,p.shapeColor??x,t,!1),p?.endShape&&an(n,p.endShape,M+J,N,G,p.shapeColor??x,t,!0)}if(c&&c[d]===c[d]){const L=i.xOfDate(c[d]+1),M=e.momentFinish[d]>c[d]+1;n.strokeStyle=B.deadline,n.lineWidth=Math.max(1,(M?2:1)*t),n.beginPath(),n.moveTo(l(L),o(z+2)),n.lineTo(l(L),o(z+A-2)),n.stroke(),n.fillStyle=B.deadline,n.beginPath(),n.moveTo(l(L-3),o(z+2)),n.lineTo(l(L+3),o(z+2)),n.lineTo(l(L),o(z+6)),n.closePath(),n.fill()}n.textBaseline="middle";const nn=p?.textColor??B.label,X=j?9:4;if(p&&(p.textRight!==void 0||p.textLeft!==void 0||p.textInside!==void 0||p.textTop!==void 0||p.textBottom!==void 0))n.fillStyle=nn,n.textAlign="left",p.textRight&&n.fillText(V(i,d,p.textRight,u.barDateFormat),l(H+X),o(z+A/2)),p.textInside&&(n.save(),n.beginPath(),n.rect(l(R),o(U),(H-R)*t,_*t),n.clip(),n.fillStyle=p.insideColor??"#ffffff",n.fillText(V(i,d,p.textInside,u.barDateFormat),l(R+3),o(z+A/2)),n.restore()),n.textAlign="right",p.textLeft&&n.fillText(V(i,d,p.textLeft,u.barDateFormat),l(R-X),o(z+A/2)),n.textAlign="center",p.textTop&&(n.textBaseline="bottom",n.fillText(V(i,d,p.textTop,u.barDateFormat),l((R+H)/2),o(U))),p.textBottom&&(n.textBaseline="top",n.fillText(V(i,d,p.textBottom,u.barDateFormat),l((R+H)/2),o(U+_))),n.textAlign="left",n.textBaseline="middle";else if(i.showLabels){const M=(y&&y.kind(d)===on?y.get(d):null)??((E||j)&&h.kind(d)===on?h.get(d):"");M&&(n.fillStyle=nn,n.fillText(M,l(H+X),o(z+A/2)))}}}function Tn(n,i,e,l,o,t,f,r){const{rows:a,layoutOptions:s}=i,m=i.linkIndex(),{outStart:S,outList:k,inStart:w,inList:u,from:g,to:D,type:h}=m,y=new Set;n.lineWidth=Math.max(1,t);const c=s.linkMode==="toEnd",b=O=>{const T=i.rowOfRecord(O);return T<0?null:a.offsetOf(T)+a.sizeOf(T)/2},C=O=>{if(y.has(O))return;y.add(O);const T=g[O],v=D[O],W=b(T),P=b(v);if(W===null||P===null)return;const F=h[O],I=i.xOfDate(F===0||F===2?e.momentFinish[T]:e.momentStart[T]),d=i.xOfDate(F===0||F===1?e.momentStart[v]:e.momentFinish[v]),A=i.showCritical&&e.critical[T]===1&&e.critical[v]===1&&e.isSummary[T]===0&&e.isSummary[v]===0?B.linkCritical:B.link;n.strokeStyle=A,n.fillStyle=A;const q=F===0||F===1?1:-1,R=F===0||F===2?1:-1,H=7;n.beginPath(),n.moveTo(l(I),o(W));const E=I+R*H,j=d-q*H,$=W+(P>W?1:-1)*(a.defaultSize/2);if(!c&&F===0&&d>=I+2){const K=(P>W?-1:1)*Math.min(4,a.defaultSize/2-2),Q=d+3;n.lineTo(l(Q),o(W)),n.lineTo(l(Q),o(P+K-(P>W?3:-3))),n.stroke();const p=P+K,_=P>W?1:-1;n.beginPath(),n.moveTo(l(Q),o(p)),n.lineTo(l(Q-3),o(p-_*4)),n.lineTo(l(Q+3),o(p-_*4)),n.closePath(),n.fill();return}q===1&&j>=E||q===-1&&j<=E?(n.lineTo(l(j),o(W)),n.lineTo(l(j),o(P))):(n.lineTo(l(E),o(W)),n.lineTo(l(E),o($)),n.lineTo(l(j),o($)),n.lineTo(l(j),o(P))),n.lineTo(l(d-q*3),o(P)),n.stroke(),n.beginPath(),n.moveTo(l(d),o(P)),n.lineTo(l(d-q*4),o(P-3)),n.lineTo(l(d-q*4),o(P+3)),n.closePath(),n.fill()};for(let O=f;O<=r;O++){const T=i.recordAtRow(O);if(!(T<0||T>=e.rows)){for(let v=w[T];v<w[T+1];v++)C(u[v]);for(let v=S[T];v<S[T+1];v++)C(k[v])}}}export{B as BAR_COLORS,dn as barStyleOf,Mn as paintGantt,cn as viewAreas};
@@ -0,0 +1 @@
1
+ function F(o){const i=[];if(o==null||o==="")return i;for(const c of String(o).split(/[,;]/)){const t=/^\s*(.+?)\s*(?:\[\s*(\d+(?:\.\d+)?)\s*%?\s*\])?\s*$/.exec(c);t&&t[1]&&i.push({name:t[1],units:t[2]!==void 0?Number(t[2])/100:1})}return i}const A=o=>o.map(i=>i.units===1?i.name:`${i.name}[${Math.round(i.units*100)}%]`).join(", ");function D(o,{resources:i=[],assignments:c=[]}={}){const{table:t}=o,{manager:u}=t,f=t.name;if(o.resourceTable)return o.resourceTable;const w=u.addTable(`${f} Resources`,{key:"id",fields:[{name:"id",caption:"ID",type:"number"},{name:"name",caption:"Resource",type:"string"},{name:"type",caption:"Type",type:"string",defaultValue:"work"},{name:"maxUnits",caption:"Max Units",type:"number",format:"0%",defaultValue:1},{name:"cost",caption:"Cost per Hour",type:"number",format:"#,##0.00"},{name:"costPerUse",caption:"Cost per Use",type:"number",format:"#,##0.00"}],tracking:!0}),l=u.addTable(`${f} Assignments`,{key:"id",fields:[{name:"id",caption:"ID",type:"number"},{name:"taskId",caption:"Task",type:"number"},{name:"resourceId",caption:"Resource",type:"number"},{name:"units",caption:"Units",type:"number",format:"0%",defaultValue:1}],tracking:!0});i.length>0&&w.load(i.map((s,n)=>({id:n+1,...typeof s=="string"?{name:s}:s}))),c.length>0&&l.load(c.map((s,n)=>({id:n+1,units:1,...s}))),u.addRelationship({from:l,fromField:"taskId",to:t,toField:o.fields.id,name:"task",inverse:"assignments"}),u.addRelationship({from:l,fromField:"resourceId",to:w,toField:"id",name:"resource",inverse:"assignments"}),o.resourceTable=w,o.assignmentTable=l;const p=t.column(o.fields.resource);if(c.length===0&&p){const s=[];for(let n=0;n<t.rowCount;n++){if(t.alive[n]===0)continue;const m=p.get(n);typeof m=="string"&&m!==""&&s.push([n,m])}for(const[n,m]of s)$(o,n,m)}return o.resourceNamesChanged?.(),w.onChange(s=>{s.type!=="schema"&&o.resourceNamesChanged?.()}),w}function U(o,i,c){const t=o.resourceTable,u=t.column("name"),f=i.toLowerCase();for(let l=0;l<t.rowCount;l++)if(t.alive[l]===1){const p=u.get(l);if(typeof p=="string"&&p.toLowerCase()===f)return t.get(l,"id")}if(!c)return null;let w=0;for(let l=0;l<t.rowCount;l++)w=Math.max(w,t.get(l,"id")??0);return t.addRow({id:w+1,name:i}),o.resourceNamesChanged?.(),w+1}function $(o,i,c){const t=o.assignmentTable;if(!t)return;const u=o.table.column(o.fields.id).data[i],f=F(c).map(s=>({...s,id:U(o,s.name,!0)})),w=[],l=t.column("taskId").data;for(let s=0;s<t.rowCount;s++)t.alive[s]===1&&l[s]===u&&w.push(s);for(const s of w){const n=t.get(s,"resourceId"),m=f.find(I=>I.id===n);m?(t.get(s,"units")!==m.units&&t.set(s,"units",m.units),m.done=!0):t.removeRow(s)}let p=0;for(let s=0;s<t.rowCount;s++)p=Math.max(p,t.get(s,"id")??0);for(const s of f)s.done||t.addRow({id:++p,taskId:u,resourceId:s.id,units:s.units})}function P(o,i){const c=o.assignmentTable;if(!c)return;const{table:t,fields:u}=o,f=o.resourceTable,w=t.column(u.id).data,l=new Map;for(let e=0;e<f.rowCount;e++)f.alive[e]===1&&l.set(f.get(e,"id"),f.get(e,"name"));const p=new Map;for(let e=0;e<c.rowCount;e++){if(c.alive[e]===0)continue;const a=c.get(e,"taskId");p.has(a)||p.set(a,[]);const d=c.get(e,"resourceId");p.get(a).push({name:l.get(d)??"?",units:c.get(e,"units")??1,resourceId:d})}const s=t.column(u.resource),n=t.column(u.work),m=t.column(u.cost),I=t.column(u.fixedCost),k=new Map;for(let e=0;e<f.rowCount;e++)f.alive[e]===1&&k.set(f.get(e,"id"),{hour:f.get(e,"cost")??0,use:f.get(e,"costPerUse")??0});for(let e=0;e<t.rowCount;e++){if(t.alive[e]===0)continue;const a=p.get(w[e]);if(s&&s.put(e,a?A(a):null),n){const d=i.calOf(e),v=i.duration[e]/d.unitsPer("h");n.data[e]=a&&i.isSummary[e]===0?v*a.reduce((y,g)=>y+g.units,0):NaN}if(m){const d=i.calOf(e),v=i.duration[e]/d.unitsPer("h"),y=I?I.data[e]:NaN;let g=y===y?y:NaN;if(a&&i.isSummary[e]===0)for(const C of a){const r=k.get(C.resourceId);r&&(g=(g===g?g:0)+v*C.units*r.hour+r.use)}m.data[e]=g}}if(n||m){const{parentRow:e,isSummary:a}=i,d=new Int32Array(t.rowCount),v=[];for(let y=0;y<t.rowCount;y++){let g=0;for(let C=e[y];C>=0&&g<=t.rowCount;C=e[C])g++;d[y]=g,(v[g]??=[]).push(y)}for(let y=v.length-1;y>0;y--)for(const g of v[y]??[]){const C=e[g];if(!(C<0||a[C]!==1))for(const r of[n,m]){if(!r)continue;const b=r.data[g];b===b&&(r.data[C]=(r.data[C]!==r.data[C]?0:r.data[C])+b)}}}}function L(o){const i=o.assignmentTable,c=o.resourceTable;if(!i||!c)return 0;const{table:t,fields:u}=o,f=t.column(u.levelStart),w=t.column(u.levelFrom),l=t.column(u.start),p=t.column(u.manual)?.data??null,s=t.column(u.priority)?.data??null,n=t.column(u.id).data,m=new Map;for(let a=0;a<c.rowCount;a++)c.alive[a]===1&&m.set(c.get(a,"id"),c.get(a,"maxUnits")??1);const I=new Map;for(let a=0;a<t.rowCount;a++)t.alive[a]===1&&I.set(n[a],a);const k=new Map;for(let a=0;a<i.rowCount;a++){if(i.alive[a]===0)continue;const d=I.get(i.get(a,"taskId"));d!==void 0&&(k.has(d)||k.set(d,[]),k.get(d).push({id:i.get(a,"resourceId"),units:i.get(a,"units")??1}))}const e=new Set;for(let a=0;a<500;a++){const d=o.schedule,v=[...k.keys()].filter(r=>d.isSummary[r]===0&&!(p&&p[r]===1)&&d.momentStart[r]!==1/0),y=r=>s&&s[r]===s[r]?s[r]:0;v.sort((r,b)=>d.momentStart[r]-d.momentStart[b]||y(b)-y(r)||d.slack[r]-d.slack[b]||n[r]-n[b]);const g=new Map;let C=!1;for(const r of v){const b=d.calOf(r),R=k.get(r);let N=d.momentStart[r];const h=T=>{const x=d.duration[r]===0?T:b.add(T,d.duration[r]),S=[];for(let M=Math.floor(T);M<Math.ceil(x);M++)b.isWorkDay(M)&&S.push(M);return S};for(let T=0;T<3660;T++){const x=h(N).find(S=>R.some(M=>{const O=g.get(M.id)?.get(S)??0;return O>0&&O+M.units>(m.get(M.id)??1)+1e-9}));if(x===void 0)break;N=b.nextWork(x+1)}N!==d.momentStart[r]&&(f.data[r]!==f.data[r]&&(w.data[r]=l.data[r]),f.data[r]=N,C=!0,e.add(r));for(const T of h(N))for(const x of R){g.has(x.id)||g.set(x.id,new Map);const S=g.get(x.id);S.set(T,(S.get(T)??0)+x.units)}}if(!C)break;o.reschedule()}return e.size}function V(o,i){const c=o.schedule,t=o.assignmentTable,u=U(o,i,!1);if(!t||u===null)return{days:new Map,over:[]};const f=new Map,w=o.table.column(o.fields.id).data;for(let n=0;n<o.table.rowCount;n++)o.table.alive[n]===1&&f.set(w[n],n);const l=new Map;for(let n=0;n<t.rowCount;n++){if(t.alive[n]===0||t.get(n,"resourceId")!==u)continue;const m=f.get(t.get(n,"taskId"));if(m===void 0||c.isSummary[m]===1)continue;const I=t.get(n,"units")??1,k=c.calOf(m);for(let e=Math.floor(c.momentStart[m]);e<Math.ceil(c.momentFinish[m]);e++)k.isWorkDay(e)&&l.set(e,(l.get(e)??0)+I)}const p=o.resourceTable;let s=1;for(let n=0;n<p.rowCount;n++)p.alive[n]===1&&p.get(n,"id")===u&&(s=p.get(n,"maxUnits")??1);return{days:l,over:[...l].filter(([,n])=>n>s+1e-9).map(([n])=>n)}}export{D as enableResources,A as formatAssignments,L as levelTasks,F as parseAssignments,V as resourceLoad,P as resourceNamesOf,$ as syncAssignments};
@@ -0,0 +1 @@
1
+ import{barStyleOf as N,BAR_COLORS as h}from"./gantt-paint.js";const D="Plan Bar ",$=3e3,z=t=>({rgb:String(t).replace("#","").toUpperCase()}),L=t=>({type:"solid",color:z(t)}),_={w:0,fill:{type:"none"}},T={lnRef:{idx:0},fillRef:{idx:0},effectRef:{idx:0},fontRef:{color:{scheme:"tx1",mods:[]}}};function V(t){const e=t.schedule,n=[];if(e===null)return n;const{rows:i,table:w,fields:y,layoutOptions:c}=t,l=w.column(y.progress)?.data??null,S=w.column(y.manual),R=w.column(y.resource),E=w.column(y.name),j=c.roundToDays,F=[],O=new Map,H=t.bodyStart+t.view.count-1;for(let o=t.bodyStart;o<=H;o++){const r=t.recordAtRow(o);r>=0&&r<e.rows&&O.set(r,o)}for(const[o,r]of O){if(e.momentStart[o]===1/0)continue;const k=i.offsetOf(r),u=i.sizeOf(r);if(u<=0)continue;const s=j?Math.floor(e.momentStart[o]):e.momentStart[o],I=j?Math.ceil(e.momentFinish[o]):e.momentFinish[o],a=t.xOfDate(s),m=t.xOfDate(I),x=e.isSummary[o]===1,g=!x&&e.duration[o]===0,d=t.showCritical&&e.critical[o]===1,M=S?.data[o]===1,b=N(t,o,x?"summary":g?"milestone":M?"manual":d?"critical":"task",F),p=c.barHeight??u-8,A=k+(u-p)/2;if(x)n.push({kind:"shape",prst:"rect",x:a,y:A+1,w:Math.max(2,m-a),h:Math.max(3,p*.45),fill:b?.fill??h.summary});else if(g){const f=Math.max(6,p);n.push({kind:"shape",prst:"diamond",x:a-f/2,y:k+(u-f)/2,w:f,h:f,fill:b?.fill??h.milestone})}else{const f=b?.fill??(d?h.critical:h.bar);n.push({kind:"shape",prst:"rect",x:a,y:A,w:Math.max(2,m-a),h:p,fill:f});const v=l&&l[o]===l[o]?Math.min(1,l[o]):0;v>0&&n.push({kind:"shape",prst:"rect",x:a,y:A+p*.25,w:Math.max(1,(m-a)*v),h:p*.5,fill:b?.progressFill??(d?h.criticalDone:h.barDone)})}if(t.showLabels!==!1){const f=R?.kind(o)===2?R.get(o):x||g?E?.get(o):null;f&&n.push({kind:"textbox",x:m+(g?8:3),y:k,w:Math.min(240,String(f).length*6.5+12),h:u,text:String(f)})}}if(t.showLinks&&c.linkMode!=="noLinks"){const{from:o,to:r,type:k}=e.links,u=s=>i.offsetOf(s)+i.sizeOf(s)/2;for(let s=0;s<o.length;s++){const I=O.get(o[s]),a=O.get(r[s]);if(I===void 0||a===void 0||e.momentStart[o[s]]===1/0||e.momentStart[r[s]]===1/0)continue;const m=k[s],x=t.xOfDate(m===0||m===2?e.momentFinish[o[s]]:e.momentStart[o[s]]),g=t.xOfDate(m===0||m===1?e.momentStart[r[s]]:e.momentFinish[r[s]]),d=u(I),M=u(a),C=M>d?M-i.sizeOf(a)/2+4:M+i.sizeOf(a)/2-4,b=t.showCritical&&e.critical[o[s]]===1&&e.critical[r[s]]===1?h.linkCritical:h.link,p=Math.max(g+3,x+4);n.push({kind:"connector",x,y:d,w:Math.max(1,p-x),h:0,color:b}),n.push({kind:"connector",x:p,y:Math.min(d,C),w:0,h:Math.abs(C-d),color:b,arrow:!0,flipV:C<d})}}return n}function B(t,e){const n={name:`${D}${e+1}`,id:1e5+e,geom:{prst:t.prst??"rect",av:{}},style:T,moved:!1};if(t.kind==="connector"){const i={w:.75,fill:L(t.color)};return t.arrow&&(i.tail={type:"triangle",w:"med",len:"med"}),{...n,kind:"connector",geom:{prst:"straightConnector1",av:{}},line:i,flipV:t.flipV===!0}}return t.kind==="textbox"?{...n,kind:"textbox",fill:{type:"none"},line:_,text:{bodyPr:{wrap:"none",anchor:"ctr",lIns:0,tIns:0,rIns:0,bIns:0},paras:[{align:"l",runs:[{text:t.text,size:9,color:z("#404040")}]}]}}:{...n,kind:"shape",fill:L(t.fill),line:_,text:{bodyPr:{},paras:[{runs:[]}]}}}function K(t,e){const n=e._state(t),i=n.objects,w=n.dirty,y=V(t);n.objects=i.filter(c=>!P(c));for(let c=0;c<y.length;c++){const l=y[c],S=B(l,c);S.anchor={type:"twoCell",editAs:"twoCell",from:null,to:null},e.setRect(S,{x:l.x,y:l.y,w:l.w,h:l.h},t),n.objects.push(S)}return n.dirty=!0,n.invalidateIndex(),()=>{n.objects=i,n.dirty=w,n.invalidateIndex()}}const P=t=>typeof t.name=="string"&&t.name.startsWith(D);function U(t,e){const n=e.states.get(t);!n||!n.objects.some(P)||(n.objects=n.objects.filter(i=>!P(i)),n.invalidateIndex())}export{$ as SHAPE_MAX_TASKS,D as SHAPE_NAME,K as addPlanShapes,U as dropPlanShapes,P as isPlanShape,V as planShapes};
@@ -0,0 +1 @@
1
+ import{EMPTY as te,STR as ee}from"../core/sheet.js";import{serialToParts as ft,partsToSerial as z}from"../core/numfmt.js";import{MAX_COLS as se}from"../core/address.js";import{getPageSetup as ne}from"../print/page-setup.js";import{sortByF64 as ie,sortColumn as re}from"./sort.js";import{CALENDAR_PRESETS as ae,makeCalendar as Pt,WorkCalendar as oe}from"./calendar.js";import{enableResources as le,levelTasks as ce,resourceNamesOf as jt,syncAssignments as he}from"./gantt-resources.js";import{addPlanShapes as ue,SHAPE_MAX_TASKS as de}from"./gantt-shapes.js";import{ROW as fe}from"./data.js";import{STAGE as zt,TableView as me,todaySerial as Ht}from"./view.js";import{TableSheet as pe}from"./table-sheet.js";import{language as ye,t as mt}from"../i18n/index.js";const Kt=["FS","SS","FF","SF"],we=/^\s*(\d+)\s*(FS|SS|FF|SF)?\s*(?:([+-])\s*(\d+(?:\.\d+)?)\s*(d|w|day|days|wk|wks)?)?\s*$/i;function rt(p){const s=[];if(p==null||p==="")return s;for(const e of String(p).split(/[,;]/)){if(e.trim()==="")continue;const n=we.exec(e);if(!n)return null;let t=n[4]?Number(n[4]):0;n[3]==="-"&&(t=-t),n[5]&&/^w/i.test(n[5])&&(t*=5),s.push({id:Number(n[1]),type:(n[2]??"FS").toUpperCase(),lag:Math.round(t)})}return s}function pt(p){return p.map(s=>`${s.id}${s.type==="FS"&&s.lag===0?"":s.type}${s.lag>0?`+${s.lag}d`:s.lag<0?`${s.lag}d`:""}`).join(",")}const $t={id:"id",parent:"parent",name:"name",start:"start",finish:"finish",duration:"duration",progress:"progress",predecessors:"predecessors",constraint:"constraint",manual:"manual",deadline:"deadline",baselineStart:"baselineStart",baselineFinish:"baselineFinish",order:"order",slack:"slack",critical:"critical",wbs:"wbs",resource:"resource",successors:"successors",work:"work",calendar:"calendar",cost:"cost",fixedCost:"fixedCost",levelStart:"levelStart",levelFrom:"levelFrom",priority:"priority"};function Ee(p,s,e=[],n=[]){const t=p.addTable(s,{key:"id",fields:[{name:"id",caption:"ID",type:"number",width:44},{name:"wbs",caption:"WBS",type:"string",width:58,readOnly:!0},{name:"name",caption:"Task",type:"string",width:200},{name:"start",caption:"Start",type:"date",format:"d-mmm-yy",width:76},{name:"finish",caption:"Finish",type:"date",format:"d-mmm-yy",width:76},{name:"duration",caption:"Days",type:"number",format:"0",width:42},{name:"progress",caption:"% Done",type:"number",format:"0%",width:52},{name:"predecessors",caption:"Predecessors",type:"string",width:84},{name:"resource",caption:"Resource",type:"string",width:90},{name:"slack",caption:"Slack",type:"number",format:"0",width:42,readOnly:!0},{name:"critical",caption:"Critical",type:"boolean",width:50,readOnly:!0},{name:"successors",caption:"Successors",type:"string",width:84,readOnly:!0},{name:"work",caption:"Work",type:"number",format:"0.0",width:50,readOnly:!0},{name:"cost",caption:"Cost",type:"number",format:"#,##0.00",width:70,readOnly:!0},{name:"fixedCost",caption:"Fixed Cost",type:"number",format:"#,##0.00",width:70,hidden:!0},{name:"priority",caption:"Priority",type:"number",format:"0",width:56,hidden:!0},{name:"levelStart",caption:"Leveled Start",type:"date",format:"d-mmm-yy",hidden:!0},{name:"levelFrom",caption:"Start Before Leveling",type:"date",format:"d-mmm-yy",hidden:!0},{name:"calendar",caption:"Calendar",type:"string",hidden:!0},{name:"parent",caption:"Parent",type:"number",hidden:!0},{name:"order",caption:"Order",type:"number",hidden:!0},{name:"constraint",caption:"Start No Earlier Than",type:"date",format:"d-mmm-yy",hidden:!0},{name:"manual",caption:"Manual",type:"boolean",hidden:!0},{name:"deadline",caption:"Deadline",type:"date",format:"d-mmm-yy",hidden:!0},{name:"baselineStart",caption:"Baseline Start",type:"date",format:"d-mmm-yy",hidden:!0},{name:"baselineFinish",caption:"Baseline Finish",type:"date",format:"d-mmm-yy",hidden:!0},...n]});return e.length>0&&t.load(ge(e)),t}function ge(p,s={}){const e=s.childrenKey??"children",n=[];if(p.some(r=>Array.isArray(r[e]))){let r=p.reduce(function o(l,u){const g=typeof u.id=="number"?u.id:0;return Math.max(l,g,Array.isArray(u[e])?u[e].reduce(o,0):0)},0)+1;const a=(o,l)=>{for(const u of o){const{[e]:g,...d}=u,m=typeof d.id=="number"?d.id:r++;n.push({...d,id:m,parent:l??null}),Array.isArray(g)&&a(g,m)}};a(p,null)}else if(p.length>0&&p.every(r=>typeof r.level=="number")&&!p.some(r=>r.parent!==void 0)){const r=[];let a=p.reduce((o,l)=>Math.max(o,typeof l.id=="number"?l.id:0),0)+1;for(const o of p){const l=typeof o.id=="number"?o.id:a++;r.length=Math.min(r.length,o.level),n.push({...o,id:l,parent:r.length>0?r[r.length-1]:null}),r[o.level]=l}}else if(p.length>0&&p.every(r=>typeof r.path=="string")){const r=new Map;let a=1;for(const o of p)r.set(o.path,typeof o.id=="number"?o.id:a++);for(const o of p){const l=o.path.lastIndexOf(".");n.push({...o,id:r.get(o.path),parent:l>0?r.get(o.path.slice(0,l))??null:null})}}else n.push(...p);return n.forEach((r,a)=>{r.order===void 0&&(r.order=a+1)}),n}function Tt(p,s,e,{projectStart:n=null,calendars:t=null,durationUnit:r="d"}={}){const a=p.rowCount,o={...$t,...s},{alive:l}=p,u=i=>p.column(o[i]),g=u("id").data,d=u("parent").data,m=u("start").data,f=u("finish").data,T=u("duration").data,O=u("predecessors"),y=u("constraint")?.data??null,k=u("manual")?.data??null,S=u("levelStart")?.data??null,_=u("progress")?.data??null,U=u("calendar")??null;let Y=0,G=1/0;for(let i=0;i<a;i++){if(l[i]===0)continue;const h=g[i];h>Y&&(Y=h);const c=m[i];c===c&&c<G&&(G=c)}G===1/0&&(G=n??Ht());const Q=n??G,Z=Y<=a*4+1024?new Int32Array(Y+1).fill(-1):null,vt=Z===null?new Map:null;for(let i=a-1;i>=0;i--){if(l[i]===0)continue;const h=g[i];h===h&&(Z!==null?Z[h]=i:vt.set(h,i))}const Mt=i=>Z!==null?i<=Y&&i>=0&&i===Math.floor(i)?Z[i]:-1:vt.get(i)??-1,q=new Int32Array(a).fill(-1),A=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0)continue;const h=d[i];if(h===h){const c=Mt(h);c>=0&&c!==i&&(q[i]=c,A[c]=1)}}const L=!t||!U||t.size===0?()=>e:i=>{const h=U.get(i);return h===null?e:t.get(h)??e},At=new Map,{strings:Yt}=p.manager,H=[],tt=[],K=[],X=[],Ft=[],Gt=O.data;for(let i=0;i<a;i++){if(l[i]===0)continue;const h=Gt[i];if(h<0)continue;let c=At.get(h);if(c===void 0&&(c=rt(Yt.get(h)),At.set(h,c)),c===null){Ft.push(i);continue}for(const w of c){const b=Mt(w.id);b<0||b===i||(H.push(b),tt.push(i),K.push(Kt.indexOf(w.type)),X.push(w.lag))}}const gt=H.length,C=new Float64Array(a);for(let i=0;i<a;i++){if(l[i]===0||A[i]===1)continue;const h=L(i),c=T[i],w=h.unitsPer(r);if(c===c)C[i]=Math.max(0,Math.round(c*w));else if(m[i]===m[i]&&f[i]===f[i]){const b=h.fullDays?Math.floor(f[i])+1:f[i];C[i]=Math.max(0,h.unitsBetween(m[i],b))}else C[i]=Math.round(w)}const P=2*a,B=new Int32Array(P+1),at=i=>{B[i+1]++};for(let i=0;i<a;i++){if(l[i]===0)continue;at(2*i);const h=q[i];h>=0&&(at(2*h),at(2*i+1))}for(let i=0;i<gt;i++){const h=K[i];at(h===0||h===2?2*H[i]+1:2*H[i])}for(let i=0;i<P;i++)B[i+1]+=B[i];const kt=B[P],ot=new Int32Array(kt),bt=new Int32Array(kt),Qt=B.slice(),lt=(i,h,c)=>{const w=Qt[i]++;ot[w]=h,bt[w]=c};for(let i=0;i<a;i++){if(l[i]===0)continue;lt(2*i,2*i+1,0);const h=q[i];h>=0&&(lt(2*h,2*i,1),lt(2*i+1,2*h+1,2))}for(let i=0;i<gt;i++){const h=K[i];lt(h===0||h===2?2*H[i]+1:2*H[i],2*tt[i],3+i)}const et=-1/0,x=new Float64Array(P).fill(et),ct=new Int32Array(P);for(let i=0;i<kt;i++)ct[ot[i]]++;const Lt=new Uint8Array(a);for(let i=0;i<gt;i++)Lt[tt[i]]=1;const ht=i=>k!==null&&k[i]===1,st=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0)continue;const h=L(i);let c=et;if(A[i]===0){const w=m[i];if(ht(i)){const b=f?f[i]:NaN;w===w?c=h.nextWork(w):b===b&&(c=h.sub(h.fullDays?b+1:b,C[i]))}else Lt[i]===0&&(c=h.nextWork(w===w?w:Q))}if(y!==null){const w=y[i];w===w&&(c=Math.max(c,h.nextWork(w)))}if(S!==null&&A[i]===0&&!ht(i)){const w=S[i];w===w&&(c=Math.max(c,h.nextWork(w)))}c===et&&A[i]===0&&ht(i)&&(st[i]=1),x[2*i]=c}const E=new Int32Array(P);let It=0,R=0;for(let i=0;i<a;i++)l[i]!==0&&(ct[2*i]===0&&(E[R++]=2*i),ct[2*i+1]===0&&(E[R++]=2*i+1));const Ot=(i,h)=>h*i.unitsPer("d"),Zt=(i,h,c)=>{const w=x[i];if(w===et)return;const b=h>>1;if(st[b]===1)return;let v;if(c===0)if(A[b]===1)v=w;else{const M=L(b);v=C[b]===0?M.nextWork(w):M.add(w,C[b])}else if(c===1||c===2)v=w;else{if(ht(b)&&A[b]===0)return;const M=c-3,F=L(b),j=X[M]===0?w:F.add(w,Ot(F,X[M])),J=K[M];J===0||J===1||A[b]===1?v=F.nextWork(j):v=F.sub(j,C[b])}v>x[h]&&(x[h]=v)};for(;It<R;){const i=E[It++];for(let h=B[i];h<B[i+1];h++){const c=ot[h];Zt(i,c,bt[h]),--ct[c]===0&&(E[R++]=c)}}const Rt=[];let Dt=0;for(let i=0;i<a;i++)l[i]===1&&(Dt+=2);if(R<Dt){const i=new Uint8Array(P);for(let h=0;h<R;h++)i[E[h]]=1;for(let h=0;h<a;h++)if(l[h]!==0&&(i[2*h]===0||i[2*h+1]===0)){Rt.push(h),i[2*h]===0&&(E[R++]=2*h),i[2*h+1]===0&&(E[R++]=2*h+1);const c=m[h],w=L(h);x[2*h]=w.nextWork(c===c?c:Q),x[2*h+1]=w.add(x[2*h],C[h])}}for(let i=0;i<a;i++){if(l[i]===0||A[i]===1||st[i]===1)continue;const h=L(i);x[2*i]===et&&(x[2*i]=h.nextWork(Q));const c=C[i]===0?x[2*i]:h.add(x[2*i],C[i]);c>x[2*i+1]&&(x[2*i+1]=c)}const Wt=new Float64Array(a).fill(NaN),Et=new Float64Array(a).fill(NaN),D=new Float64Array(a).fill(1/0),I=new Float64Array(a).fill(-1/0),nt=new Float64Array(a),ut=new Float64Array(a),St=new Float64Array(a);let $=-1/0,it=1/0;for(let i=0;i<R;i++){const h=E[i];if((h&1)===0)continue;const c=h>>1;if(st[c]!==1)if(A[c]===0){const b=x[2*c],v=C[c]===0?b:L(c).add(b,C[c]);D[c]=b,I[c]=v;const M=C[c],F=_!==null&&_[c]===_[c]?_[c]:0;nt[c]=M,ut[c]=M*F,St[c]=F}else nt[c]>0&&(St[c]=ut[c]/nt[c]);if(I[c]>$&&($=I[c]),D[c]<it&&(it=D[c]),D[c]!==1/0){Wt[c]=D[c];const b=L(c).fullDays;Et[c]=b&&I[c]>D[c]?Math.ceil(I[c])-1:I[c]}const w=q[c];w>=0&&(D[c]<D[w]&&(D[w]=D[c]),I[c]>I[w]&&(I[w]=I[c]),nt[w]+=nt[c],ut[w]+=ut[c])}$===-1/0&&($=e.nextWork(Q),it=$);const W=new Float64Array(P).fill(1/0);for(let i=0;i<a;i++)l[i]===1&&(W[2*i+1]=$);for(let i=R-1;i>=0;i--){const h=E[i],c=h>>1;let w=W[h];for(let b=B[h];b<B[h+1];b++){const v=ot[b],M=bt[b];let F;if(M===0)F=A[c]===1||C[c]===0?W[v]:L(c).sub(W[v],C[c]);else if(M===1||M===2)F=W[v];else{const j=M-3,J=tt[j],Ut=L(J),Bt=K[j]===2||K[j]===3?W[2*J+1]:W[2*J];F=X[j]===0?Bt:Ut.add(Bt,-Ot(Ut,X[j]))}F<w&&(w=F)}W[h]=w}const Nt=new Float64Array(a).fill(NaN),dt=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0||A[i]===1||st[i]===1)continue;const h=L(i),c=I[i],w=Math.max(h.unitsBetween(c,W[2*i+1]),0),b=h.unitsPer("d");Nt[i]=w/b,(W[2*i+1]<=c+1e-9||w===0)&&(dt[i]=1)}for(let i=0;i<R;i++){const h=E[i];if((h&1)===0)continue;const c=h>>1,w=q[c];w>=0&&dt[c]===1&&(dt[w]=1)}return{rows:a,start:Wt,finish:Et,momentStart:D,momentFinish:I,duration:C,parentRow:q,isSummary:A,progress:St,slack:Nt,critical:dt,links:{from:H,to:tt,type:K,lag:X},inCycle:Rt,badLinks:Ft,projectStart:it===1/0?Q:it,projectFinish:$,calendar:e,calOf:L,durationUnit:r}}const qt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ke=["S","M","T","W","T","F","S"],Xt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],_t={months:qt,weekdays:Xt,shown:!1};let yt=null;function be(){const p=ye();if(yt?.lang!==p)if(p==="en")yt={..._t,shown:!0,lang:p};else{const s=new Intl.DateTimeFormat(p,{month:"short",timeZone:"UTC"}),e=new Intl.DateTimeFormat(p,{weekday:"short",timeZone:"UTC"});yt={lang:p,shown:!0,months:qt.map((n,t)=>s.format(Date.UTC(2021,t,1))),weekdays:Xt.map((n,t)=>e.format(Date.UTC(2021,0,3+t)))}}return yt}const V=[{name:"minutes",unit:"minute",tickWidth:24,tiers:[{unit:"day"},{unit:"hour"},{unit:"minute",count:15}]},{name:"hours",unit:"hour",tickWidth:24,tiers:[{unit:"week"},{unit:"day"},{unit:"hour"}]},{name:"shifts",unit:"hour",tickWidth:28,tiers:[{unit:"day"},{unit:"hour",count:6}]},{name:"day-wide",unit:"day",tickWidth:28,tiers:[{unit:"week"},{unit:"day"}]},{name:"day",unit:"day",tickWidth:18,tiers:[{unit:"month"},{unit:"day"}]},{name:"week",unit:"week",tickWidth:44,tiers:[{unit:"month"},{unit:"week"}]},{name:"month",unit:"month",tickWidth:54,tiers:[{unit:"year"},{unit:"month"}]},{name:"quarter",unit:"quarter",tickWidth:64,tiers:[{unit:"year"},{unit:"quarter"}]},{name:"half",unit:"half",tickWidth:64,tiers:[{unit:"year"},{unit:"half"}]},{name:"year",unit:"year",tickWidth:72,tiers:[{unit:"decade"},{unit:"year"}]}],Ct=p=>V.findIndex(s=>s.name===p);function xt(p,s,e=1,n=1){const t=Math.floor(p),r=ft(t);switch(s){case"minute":{const a=e/1440;return Math.floor(p/a+1e-6)*a}case"hour":{const a=e/24;return t+Math.floor((p-t)/a+1e-6)*a}case"day":return t;case"week":return t-(r.weekday-n+7)%7;case"month":return z(r.year,r.month,1);case"quarter":return z(r.year,Math.floor((r.month-1)/3)*3+1,1);case"half":return z(r.year,r.month<=6?1:7,1);case"year":return z(r.year,1,1);default:return z(Math.floor(r.year/10)*10,1,1)}}function wt(p,s,e=1){const n=s==="minute"||s==="hour"||s==="day"||s==="week"?null:ft(p);switch(s){case"minute":return p+e/1440;case"hour":return p+e/24;case"day":return p+e;case"week":return p+7*e;case"month":{const t=n.month-1+e;return z(n.year+Math.floor(t/12),t%12+1,1)}case"quarter":return wt(p,"month",3*e);case"half":return wt(p,"month",6*e);case"year":return z(n.year+e,1,1);default:return z(n.year+10*e,1,1)}}const N=(p,s,e)=>p.shown?mt(s,e):s.replace(/\{(\w+)\}/g,(n,t)=>String(e[t]));function Jt(p,s,e=_t){const n=ft(Math.floor(p)),t=Math.round((p-Math.floor(p))*1440),r=e.months[n.month-1];switch(s){case"minute":return String(t%60).padStart(2,"0");case"hour":return String(Math.floor(t/60));case"day":return String(n.day);case"week":return N(e,"{day} {month}",{day:n.day,month:r});case"month":return r;case"quarter":return N(e,"Q{n}",{n:Math.floor((n.month-1)/3)+1});case"half":return N(e,"H{n}",{n:n.month<=6?1:2});case"year":return String(n.year);default:return N(e,"{decade}s",{decade:Math.floor(n.year/10)*10})}}function Se(p,s,e=_t){const n=ft(Math.floor(p)),t=e.months[n.month-1];switch(s){case"hour":return`${String(Math.round((p-Math.floor(p))*24)).padStart(2,"0")}:00`;case"day":return N(e,"{weekday} {day} {month}",{weekday:e.weekdays[(Math.floor(p)-1)%7],day:n.day,month:t});case"week":return N(e,"{month} {day}, {year}",{month:t,day:n.day,year:n.year});case"month":return N(e,"{month} {year}",{month:t,year:n.year});case"quarter":return N(e,"Q{n} {year}",{n:Math.floor((n.month-1)/3)+1,year:n.year});case"half":return N(e,"H{n} {year}",{n:n.month<=6?1:2,year:n.year});case"year":return String(n.year);default:return N(e,"{decade}s",{decade:Math.floor(n.year/10)*10})}}class Vt{constructor(s=Ct("day")){this.level=s,this.ticks=new Float64Array(0),this.tiers=[],this.tops=[],this.count=0,this.padBefore=3,this.padAfter=6,this.factor=1,this.customTiers=null,this.minDate=null,this.maxDate=null,this.autoFit="project",this.margin=null,this.weekStart=1}get spec(){return V[this.level]}get tierSpecs(){return this.customTiers??this.spec.tiers}get bottomTier(){const s=this.tierSpecs;return s[s.length-1]}get tickWidth(){return Math.max(4,Math.round((this.bottomTier.width??this.spec.tickWidth)*this.factor))}build(s,e,n=se-64){let t=s,r=e;this.minDate!==null&&(t=this.minDate),this.maxDate!==null&&(r=this.maxDate),this.autoFit==="none"&&this.ticks.length>0&&this.minDate===null&&this.builtFrom!==void 0&&(t=this.builtFrom,r=this.builtTo);const a=this.margin?.before??this.padBefore,o=this.margin?.after??this.padAfter;for(;;){const l=this.bottomTier,{unit:u}=l,g=l.count??1;let d=xt(t,u,g,this.weekStart);for(let f=0;f<a;f++)d=xt(d-1e-6,u,g,this.weekStart);const m=[];for(;(d<=r||m.length===0)&&(m.push(d),d=wt(d,u,g),!(m.length>n)););if(m.length>n&&this.level<V.length-1&&this.customTiers===null){this.level++;continue}for(let f=0;f<o&&m.length<=n;f++)m.push(d),d=wt(d,u,g);m.push(d),this.ticks=Float64Array.from(m),this.count=m.length-1,this.builtFrom=t,this.builtTo=r,this._buildTiers();return}}_buildTiers(){const s=this.tierSpecs,e=be();this.tiers=s.map((n,t)=>{const r=t===s.length-1,a=[];let o=NaN;for(let l=0;l<this.count;l++){const u=xt(this.ticks[l],n.unit,n.count??1,this.weekStart);u!==o&&(a.push({tick:l,label:n.label?n.label(this.ticks[l]):r?Jt(this.ticks[l],n.unit,e):Se(n.unit==="week"?this.ticks[l]:u,n.unit,e)}),o=u)}return{unit:n.unit,count:n.count??1,marks:a,bottom:r}}),this.tops=this.tiers.length>1?this.tiers[this.tiers.length-2].marks:[]}position(s){const{ticks:e,count:n}=this;if(n===0)return 0;if(s<=e[0])return(s-e[0])/(e[1]-e[0]);if(s>=e[n])return n+(s-e[n])/(e[n]-e[n-1]);let t=0,r=n;for(;r-t>1;){const a=t+r>>>1;e[a]<=s?t=a:r=a}return t+(s-e[t])/(e[t+1]-e[t])}dateAt(s){const{ticks:e,count:n}=this;if(n===0)return 0;const t=Math.max(0,Math.min(n-1,Math.floor(s))),r=e[t]+(s-t)*(e[t+1]-e[t]),{unit:a}=this.bottomTier;return a==="hour"||a==="minute"?Math.round(r*1440)/1440:Math.round(r)}label(s){return Jt(this.ticks[s],this.bottomTier.unit)}weekdayLetter(s){return ke[(Math.floor(this.ticks[s])-1)%7]}}const Te=2e4,_e=1200;class Ne extends pe{constructor(s,e,n,t={}){const r={...$t,...t.fields},a=t.columns??["id","wbs","name","start","finish","duration","progress","predecessors","resource"].filter(l=>n.column(r[l]??l)),o=t.view??new me(n,{columns:a,sort:[{field:r.order}],hierarchy:{key:r.id,parent:r.parent,column:r.name}});super(s,e,o,{banded:!1,rowHeight:20,allowAdd:!0,...t.sheet}),this.kindName="gantt",this.fields=r,this.calendar=Pt(t.calendar),this.calendars=new Map(Object.entries(t.calendars??{}).map(([l,u])=>[l,Pt(u)])),this.durationUnit=t.durationUnit??"d",this.scale=new Vt(t.scaleLevel??Ct("day")),Object.assign(this.scale,t.scale??{}),this.schedule=null,this.showCritical=t.showCritical!==!1,this.showBaseline=t.showBaseline!==!1,this.showLinks=t.showLinks!==!1,this.showLabels=t.showLabels!==!1,this.showToday=t.showToday!==!1,this.today=t.today??Ht(),this.statusDate=t.statusDate??null,this.taskbarRules=t.taskbarRules??[],this.taskbarStyles=t.taskbarStyles??{},this.layoutOptions={linkMode:"toTop",barHeight:null,roundToDays:!1,barDateFormat:null,...t.layout},this.gridlines={interval:0,intervalColor:"#e0e0e0",rowInterval:0,rowColor:"#e8e8e8",projectStart:!1,projectFinish:!1,status:!1,current:!0,...t.gridlines},this.nonWorking={color:"#f1f1f1",pattern:"solid",mode:"behind",...t.nonWorking},this.progressLine={visible:!1,reference:"status",path:"angled",returnToAnchor:!0,color:"#c42b1c",...t.progressLine},this.frozenLimit=t.frozenLimit??null,this.lastCycle=[],this.scheduleDirty=!0,this.reschedule({track:!1}),this.applyLayout(),t.resources&&le(this,t.resources)}shapeColumnCount(){return this.exporting&&this._exportBars()?this.view.columns.length+this.scale.count:this.view.columns.length}_useShapes(){return this.book.dataSheets?.objects?.takesExportObjects===!0&&this.options.barExport!=="cells"&&this.view.count<=de}addExportObjects(s){return!this.exporting||!this._useShapes()?null:ue(this,s)}supportsNewRow(){return this.options.allowAdd&&this.view.spec.filters.length===0&&!this.view.spec.search}clearSort(){this.viewOp("sort",s=>s.setSort([{field:this.fields.order}]))}_exportBars(){return this.view.count<=Te&&this.scale.count<=_e}applyLayout(s){if(this.scale===void 0){super.applyLayout(s);return}this.timelineStart=this.view.columns.length;const e=this.scale.tickWidth,t=Math.max(1,this.scale.tierSpecs.length)*16+2;this.rows.sizeOf(0)!==t&&this.rows.setSize(0,t),super.applyLayout(s);const r=this.timelineStart+this.scale.count;for(let u=this.timelineStart;u<r;u++)this.cols.sizeOf(u)!==e&&this.cols.setSize(u,e);if(this.lastTotal!==void 0&&this.lastTotal>r)for(let u=r;u<this.lastTotal;u++)this.cols.setSize(u,this.cols.defaultSize);this.lastTotal=r,this.maxCol=r-1,this._applyPrintArea(r);let a=0,o=0;const l=this.frozenLimit??640;for(let u=0;u<this.timelineStart;u++)a+=this.cols.sizeOf(u),a<=l&&(o=u+1);o!==this.frozenCols&&(this.frozenCols=o,this.viewChanged=!0)}setSplitter(s){this.frozenLimit=Math.max(0,s),this.applyLayout({keepCells:!0}),this.onRefresh?.()}_applyPrintArea(s){const e=ne(this),n={r0:0,c0:0,r1:Math.max(0,this.bodyStart+this.view.count-1),c1:s-1},t=this._printArea;(e.printAreas.length===0||t&&e.printAreas.length===1&&e.printAreas[0]===t)&&(t||(e.orientation="landscape",e.fitToPage=!0,e.fitToWidth=1,e.fitToHeight=0,e.titleRows={r0:0,r1:0}),e.printAreas=[n],this._printArea=n,this.pageSetupChanged=!0)}fillChunk(s,e,n){if(s<this.timelineStart||!this.exporting){super.fillChunk(s,e,n);return}n.kinds.fill(0),n.store.fill(0),n.hasStyles=!1;const t=s-this.timelineStart,r=e<<10,a=this.scale.ticks[t],o=this.scale.ticks[t+1],l=this.schedule;if(l===null)return;const u=this._useShapes(),g=Math.min(1024,this.maxRow+1-r);for(let d=0;d<g;d++){const m=r+d;if(m===0){n.kinds[d]=ee,n.values[d]=this.book.strings.add(this.scale.label(t)),n.store[d]=this._headerStyle(),n.hasStyles=!0;continue}if(u)continue;const f=this.recordAtRow(m);if(f<0||f>=l.rows)continue;const T=l.momentStart[f],O=l.momentFinish[f];T===1/0||!(T<o&&O>a)||(n.store[d]=this._barStyle(f),n.hasStyles=!0)}}_barStyle(s){const e=this.schedule;return e.isSummary[s]===1?this._style("bar-s",{fill:this.colors.summary}):this.showCritical&&e.critical[s]===1?this._style("bar-c",{fill:"#d64545"}):this._style("bar",{fill:this.colors.bar})}reschedule({track:s=!0}={}){const{table:e,fields:n}=this;e.ensureAll();const t=Tt(e,n,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});this.schedule=t,this.lastCycle=t.inCycle;const r=e.column(n.start),a=e.column(n.finish),o=e.column(n.duration),l=e.column(n.progress),u=e.column(n.slack),g=e.column(n.critical),d=e.rowCount,m=s&&e.tracking,f=(y,k,S)=>{if(!y)return;const _=y.data[k];_===S||_!==_&&S!==S||(m&&e.state[k]!==fe.INSERTED&&e._track(k,y,_!==_?null:_,S!==S?null:S),y.data[k]=S,y.revision++)},{alive:T}=e,{durationUnit:O}=this;for(let y=0;y<d;y++){if(T[y]===0)continue;const k=t.calOf(y),S=k.unitsPer(O);if(f(r,y,t.start[y]),f(a,y,t.finish[y]),t.isSummary[y]===1){const _=t.momentStart[y],U=_!==1/0?k.unitsBetween(_,t.momentFinish[y])/S:NaN;f(o,y,U),l&&f(l,y,t.progress[y])}else f(o,y,Math.round(t.duration[y]/S*1e3)/1e3);u&&(u.data[y]=t.slack[y]),g&&(g.data[y]=t.critical[y])}return this._writeWbs(),this._writeSuccessors(),jt(this,t),this._layTimeline(),this.scheduleDirty=!1,t}_writeSuccessors(){const{table:s,fields:e,schedule:n}=this,t=s.column(e.successors);if(!t)return;const r=s.column(e.id).data,a=new Map,{from:o,to:l,type:u,lag:g}=n.links;for(let f=0;f<o.length;f++)a.has(o[f])||a.set(o[f],[]),a.get(o[f]).push({id:r[l[f]],type:Kt[u[f]],lag:g[f]});const{strings:d}=s.manager,{data:m}=t;for(let f=0;f<s.rowCount;f++){const T=a.get(f);m[f]=T?d.add(pt(T)):-1}t.revision++}_writeWbs(){const{table:s,fields:e,schedule:n}=this,t=s.column(e.wbs);if(!t)return;const r=s.column(e.order),a=s.rowCount,o=new Int32Array(s.liveCount);let l=0;for(let y=0;y<a;y++)s.alive[y]===1&&(o[l++]=y);r&&ie(o,l,r.data,!1);const u=new Int32Array(a+1),g=new Array(a);let d=0;const m=new Int32Array(a);for(let y=0;y<l;y++){const k=o[y],S=n.parentRow[k];m[k]=S>=0?++u[S]:++d}const{strings:f}=s.manager,T=[],O=t.data;for(let y=0;y<l;y++){let k=o[y];for(T.length=0;k>=0&&g[k]===void 0&&T.length<=a;)T.push(k),k=n.parentRow[k];let S=k>=0?g[k]??"":"";for(let _=T.length-1;_>=0;_--){const U=T[_];S=S===""?String(m[U]):`${S}.${m[U]}`,g[U]=S,O[U]=f.add(S)}}t.revision++}_layTimeline(){const s=this.schedule;if(!s)return;let e=s.projectStart,n=s.projectFinish;this.progressLine.visible&&this.statusDate!==null&&(e=Math.min(e,this.statusDate),n=Math.max(n,this.statusDate)),this.scale.build(e,n)}setScaleLevel(s){const e=typeof s=="string"?Ct(s):s,n=Math.max(0,Math.min(V.length-1,e));n===this.scale.level&&this.scale.factor===1&&this.scale.customTiers===null||(this.scale.level=n,this.scale.factor=1,this.scale.customTiers=null,this._relayTimeline())}setTiers(s){this.scale.customTiers=s,this._relayTimeline()}_relayTimeline(){this._layTimeline(),this.applyLayout(),this.onRefresh?.()}zoomIn(){this.setScaleLevel(this.scale.level-1)}zoomOut(){this.setScaleLevel(this.scale.level+1)}zoomTo(s){this.scale.factor=Math.max(.2,Math.min(8,s)),this._relayTimeline()}zoomToRange(s,e,n){for(let t=0;t<V.length;t++){const r=new Vt(t);if(r.padBefore=0,r.padAfter=0,r.build(s,e,2e3),r.level===t&&r.count*r.tickWidth<=n){this.scale.level=t,this.scale.factor=Math.min(3,n/Math.max(1,r.count*r.tickWidth)),this.scale.customTiers=null,this._relayTimeline();return}}this.setScaleLevel(V.length-1)}zoomToFit(s){const e=this.schedule;e&&this.zoomToRange(e.projectStart,e.projectFinish,s)}setRange({minDate:s=null,maxDate:e=null,autoFit:n="project",margin:t=null}={}){Object.assign(this.scale,{minDate:s,maxDate:e,autoFit:n,margin:t}),this._relayTimeline()}xOfDate(s){const e=this.scale.position(s);return this.cols.offsetOf(this.timelineStart)+e*this.scale.tickWidth}dateOfX(s){return this.scale.dateAt((s-this.cols.offsetOf(this.timelineStart))/this.scale.tickWidth)}newRecordValues(){const{table:s,fields:e}=this,n=s.column(e.id).data,t=s.column(e.order)?.data;let r=0,a=0;for(let l=0;l<s.rowCount;l++)n[l]>r&&(r=n[l]),t&&t[l]>a&&(a=t[l]);const o=this.schedule?.projectFinish??this.today;return{[e.id]:r+1,[e.order]:a+1,[e.duration]:1,[e.start]:o,[e.progress]:0}}_isBlankRecord(s){const{table:e,fields:n}=this;return e.column(n.name).kind(s)===te}_write(s,e,n,t){const r=this.recordAtRow(s),{fields:a,table:o}=this,l=this.schedule;if(r>=0&&r<l.rows&&l.isSummary[r]===1){const u=n.field;if(u===a.start||u===a.finish||u===a.duration||u===a.progress){this._reject(mt("Summary tasks take their dates and progress from their subtasks."));return}}if(n.field===a.predecessors&&t!==null&&rt(t)===null){this._reject(mt(`"{value}" isn't a list of predecessors. Use IDs with an optional type and lag, such as 3FS+2d, 5SS.`,{value:t}));return}if(n.field===a.progress&&typeof t=="number"&&t>1&&(t/=100),r>=0&&n.field===a.start&&t!==null){this._writing++;try{o.set(r,a.constraint,t)}finally{this._writing--}}else if(r>=0&&n.field===a.finish&&t!==null){const u=o.column(a.start).data[r];if(u===u){const g=l.calOf(r),d=g.fullDays?Math.floor(t)+1:t,m=Math.max(0,g.unitsBetween(u,d)/g.unitsPer(this.durationUnit));this._writing++;try{o.set(r,a.duration,m)}finally{this._writing--}}}if(r>=0&&n.field===a.resource&&this.assignmentTable){this._writing++;try{he(this,r,t)}finally{this._writing--}}super._write(s,e,n,t),n.field===a.predecessors&&this._checkCycle(r,t)}_checkCycle(s,e){const{table:n,fields:t}=this,r=Tt(n,t,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});r.inCycle.length>0&&s>=0&&(this.lastCycle=r.inCycle,this._reject(mt(`The predecessors "{value}" would make a task depend on itself. The tasks in that loop keep their dates until it's fixed.`,{value:e})))}afterRecordWrite(){this.scheduleDirty=!0}flush(){if(this.scheduleDirty){this._writing++;try{this.reschedule()}finally{this._writing--}}super.flush()}editTask(s,e,n){const{table:t}=this,r={};for(const a of Object.keys(n))r[a]=t.get(e,a);this.book.transact(s,()=>(this._writeTask(e,n),this._taskClosure(e,r,n))),this.onRefresh?.()}_writeTask(s,e){const{table:n}=this;this._writing++;try{n.batch(()=>{for(const[t,r]of Object.entries(e))n.set(s,t,r)}),this.reschedule()}finally{this._writing--}this.view.refresh(),this.applyLayout(),this.notifyEngine()}_taskClosure(s,e,n){return()=>(this._writeTask(s,e),this.onRefresh?.(),this._taskClosure(s,n,e))}moveTask(s,e){const{table:n,fields:t}=this,r=n.column(t.start).data[s],a=this.schedule.calOf(s).nextWork(r+e);this.editTask("move task",s,{[t.constraint]:a,[t.start]:a})}setTaskFinish(s,e){const{table:n,fields:t}=this,r=this.schedule.calOf(s),a=n.column(t.start).data[s],o=r.fullDays?Math.floor(Math.max(e,a))+1:Math.max(e,a),l=r.unitsPer(this.durationUnit),u=Math.max(r.unitsBetween(a,o),(r.fullDays,1));this.editTask("resize task",s,{[t.duration]:Math.round(u/l*1e3)/1e3})}setTaskProgress(s,e){this.editTask("progress",s,{[this.fields.progress]:Math.max(0,Math.min(1,e))})}completeThrough(s,e){const n=this.schedule,{table:t,fields:r}=this,a=s??[...Array(t.rowCount).keys()].filter(d=>t.alive[d]===1&&n.isSummary[d]===0),o=a.map(d=>t.get(d,r.progress)),l=d=>{this._writing++;try{t.batch(()=>{a.forEach((m,f)=>t.set(m,r.progress,d[f]))}),this.reschedule()}finally{this._writing--}this.view.refresh(),this.applyLayout()},u=a.map(d=>{const m=n.calOf(d),f=n.duration[d];return f<=0?e>=n.momentStart[d]?1:0:Math.max(0,Math.min(1,m.unitsBetween(n.momentStart[d],e)/f))}),g=(d,m)=>()=>(l(d),this.onRefresh?.(),g(m,d));this.book.transact("complete through",()=>(l(u),g(o,u))),this.onRefresh?.()}setTaskMode(s,e){const{fields:n,table:t}=this;t.column(n.manual)&&this.editTask("schedule mode",s,{[n.manual]:e==="manual"})}link(s,e,n="FS",t=0){const{table:r,fields:a}=this,o=r.column(a.id).data[s],l=r.column(a.predecessors),u=rt(l.get(e))??[];if(u.some(d=>d.id===o))return!0;const g=pt([...u,{id:o,type:n,lag:t}]);return this._wouldCycle(e,g)?!1:(this.editTask("link tasks",e,{[a.predecessors]:g}),!0)}unlink(s,e){const{table:n,fields:t}=this,r=n.column(t.id).data[s],a=n.column(t.predecessors),o=rt(a.get(e))??[];this.editTask("unlink tasks",e,{[t.predecessors]:pt(o.filter(l=>l.id!==r))})}_wouldCycle(s,e){const{table:n,fields:t}=this,r=n.column(t.predecessors),a=r.data[s];r.data[s]=n.manager.strings.add(e);const o=Tt(n,t,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});return r.data[s]=a,o.inCycle.length>0}addTask(s={},e=-1,n="task"){const{fields:t,table:r}=this,a=this.newRecordValues();if(n==="milestone"&&(a[t.duration]=0),e>=0){const l=r.column(t.order),u=r.column(t.parent).data[e];u===u&&(a[t.parent]=u);const g=l.data[e];let d=1/0;for(let m=0;m<r.rowCount;m++){const f=l.data[m];f>g&&f<d&&(d=f)}a[t.order]=d===1/0?g+1:(g+d)/2}let o=-1;return this.book.transact("add task",()=>{this._writing++;try{o=r.addRow({[t.name]:"New task",...a,...s}),this.view.invalidate(zt.FILTER),this.view.refresh(),this.reschedule()}finally{this._writing--}return this.view.refresh(),this._planRecordsClosure([o],!1)}),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),o}removeTasks(s){const e=this.schedule,{table:n}=this,t=new Set(s);for(let a=!0;a;){a=!1;for(let o=0;o<n.rowCount;o++)n.alive[o]===1&&!t.has(o)&&t.has(e.parentRow[o])&&(t.add(o),a=!0)}const r=[...t].filter(a=>n.alive[a]===1);return r.length===0?0:(this.book.transact("delete task",()=>(this._planApply(r,!0),this._planRecordsClosure(r,!0))),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),r.length)}_planApply(s,e){this._writing++;try{this.table.batch(()=>{for(const n of s)e?this.table.removeRow(n):this.table.restoreRow(n)}),this.view.invalidate(zt.FILTER),this.view.refresh(),this.reschedule()}finally{this._writing--}this.view.refresh()}_planRecordsClosure(s,e){return()=>(this._planApply(s,!e),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),this._planRecordsClosure(s,!e))}indent(s){const{fields:e,table:n}=this,t=this.view.rowOfRecord(s);if(t<=0)return!1;const r=this.view.treeLevel[s];for(let a=t-1;a>=0;a--){const o=this.view.recordAt(a);if(o<0)continue;const l=this.view.treeLevel[o];if(l===r)return this.editTask("indent",s,{[e.parent]:n.column(e.id).data[o]}),!0;if(l<r)return!1}return!1}outdent(s){const{fields:e,table:n}=this,t=this.schedule.parentRow[s];if(t<0)return!1;const r=n.column(e.parent).data[t],a=n.column(e.order),o=a.data[t];let l=1/0;for(let u=0;u<n.rowCount;u++){const g=a.data[u];g>o&&g<l&&(l=g)}return this.editTask("outdent",s,{[e.parent]:r===r?r:null,[e.order]:l===1/0?o+1:(o+l)/2}),!0}sortProject(s,e=!1,{keepOutline:n=!0,renumber:t=!1}={}){if(!t){this.viewOp("sort",f=>{f.setSort([{field:s,desc:e},{field:this.fields.order}]),n?f.spec.hierarchy||f.setHierarchy({key:this.fields.id,parent:this.fields.parent,column:this.fields.name}):f.setHierarchy(null)});return}const{table:r,fields:a}=this,o=new Int32Array(r.liveCount);let l=0;for(let f=0;f<r.rowCount;f++)r.alive[f]===1&&(o[l++]=f);const u=r.column(s);u&&re(r,o,l,u,e);const g=r.column(a.id),d=new Map;o.forEach((f,T)=>d.set(g.data[f],T+1));const m=f=>pt((rt(f)??[]).map(T=>({...T,id:d.get(T.id)??T.id})));this._writing++;try{r.batch(()=>{const f=r.column(a.predecessors),T=r.column(a.parent),O=this.assignmentTable;if(O){const y=O.column("taskId");for(let k=0;k<O.rowCount;k++){const S=y.data[k];d.has(S)&&(y.data[k]=d.get(S))}}for(let y=0;y<l;y++){const k=o[y],S=f.get(k);S&&r.set(k,a.predecessors,m(S));const _=T.data[k];_===_&&d.has(_)&&r.set(k,a.parent,d.get(_))}for(let y=0;y<l;y++){const k=o[y];r.set(k,a.id,y+1),r.set(k,a.order,y+1)}}),this.view.setSort([{field:a.order}]),this.reschedule()}finally{this._writing--}this._forgetSheetUndo(),this.view.refresh(),this.applyLayout(),this.onRefresh?.()}setBaseline(){const{table:s,fields:e}=this,n=[],t=s.rowCount,r=s.column(e.baselineStart),a=s.column(e.baselineFinish),o=s.column(e.start),l=s.column(e.finish);if(!r||!a)return;n.push(r.data.slice(0,t),a.data.slice(0,t));const u=(g,d)=>()=>{const m=r.data.slice(0,t),f=a.data.slice(0,t);return r.data.set(g),a.data.set(d),this.onRefresh?.(),u(m,f)};this.book.transact("baseline",()=>(r.data.set(o.data.subarray(0,t)),a.data.set(l.data.subarray(0,t)),u(n[0],n[1]))),this.onRefresh?.()}levelResources(){return this._leveling("level resources",()=>ce(this))}clearLeveling(){return this._leveling("clear leveling",()=>{const{table:s,fields:e}=this,n=s.column(e.levelStart).data,t=s.column(e.levelFrom).data,r=s.column(e.start).data;let a=0;for(let o=0;o<s.rowCount;o++)n[o]===n[o]&&(r[o]=t[o],n[o]=NaN,t[o]=NaN,a++);return a})}_leveling(s,e){const{table:n,fields:t}=this;for(const d of[t.levelStart,t.levelFrom])n.column(d)||n.addField({name:d,type:"date",hidden:!0});const r=[n.column(t.levelStart),n.column(t.levelFrom),n.column(t.start)],a=()=>{for(const d of r)d.revision++;this.reschedule(),this.view.refresh(),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()},o=()=>r.map(d=>d.data.slice()),l=d=>()=>{const m=o();return r.forEach((f,T)=>f.data.set(d[T])),a(),l(m)},u=o();let g=0;return this.book.transact(s,()=>(g=e(),a(),l(u))),g}linkIndex(){const s=this.schedule;if(this._linkIndex?.schedule===s)return this._linkIndex;const{from:e,to:n,type:t}=s.links,r=s.rows,a=new Int32Array(r+1),o=new Int32Array(r+1);for(let m=0;m<e.length;m++)a[e[m]+1]++,o[n[m]+1]++;for(let m=0;m<r;m++)a[m+1]+=a[m],o[m+1]+=o[m];const l=new Int32Array(e.length),u=new Int32Array(e.length),g=a.slice(),d=o.slice();for(let m=0;m<e.length;m++)l[g[e[m]]++]=m,u[d[n[m]]++]=m;return this._linkIndex={schedule:s,outStart:a,outList:l,inStart:o,inList:u,from:e,to:n,type:t},this._linkIndex}resourceNamesChanged(){const s=this.resourceTable;if(!s)return;const e=[];for(let t=0;t<s.rowCount;t++)s.alive[t]===1&&e.push(s.get(t,"name"));const{fields:n}=this;this.view.spec.columns=this.view.spec.columns.map(t=>t.field===n.resource?{...t,validator:{type:"list",items:e,errorStyle:"warning",allowBlank:!0}}:t),this.view._columns=null,this.schedule&&(jt(this,this.schedule),this.invalidateCells(),this.onRefresh?.())}toJSON(){const s=this.scale;return{fields:this.fields,calendar:this.calendar.toJSON(),calendars:Object.fromEntries([...this.calendars].map(([e,n])=>[e,n.toJSON()])),durationUnit:this.durationUnit,scaleLevel:s.level,scale:{factor:s.factor,customTiers:s.customTiers?.map(({label:e,...n})=>n)??null,minDate:s.minDate,maxDate:s.maxDate,autoFit:s.autoFit,margin:s.margin},showCritical:this.showCritical,showBaseline:this.showBaseline,showLinks:this.showLinks,showLabels:this.showLabels,showToday:this.showToday,statusDate:this.statusDate,taskbarRules:this.taskbarRules,taskbarStyles:this.taskbarStyles,layout:this.layoutOptions,gridlines:this.gridlines,nonWorking:this.nonWorking,progressLine:this.progressLine,frozenLimit:this.frozenLimit,resourceTable:this.resourceTable?.name??null,assignmentTable:this.assignmentTable?.name??null}}}export{ae as CALENDAR_PRESETS,Ne as GanttSheet,Kt as LINK_TYPES,V as SCALE_LEVELS,Vt as TimeScale,oe as WorkCalendar,Tt as computeSchedule,Ee as createPlanTable,pt as formatLinks,Ct as levelOf,ge as normalizePlanRows,rt as parseLinks,be as shownDateNames,Se as topLabel,Jt as unitLabel};
@@ -0,0 +1 @@
1
+ import"./query-function.js";import{Sheet as d}from"../core/sheet.js";import{DataManager as u}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as l}from"./table-sheet.js";import{createPlanTable as m,GanttSheet as c}from"./gantt.js";import{ReportTemplate as f}from"./report.js";import{TableBinding as g}from"./bind.js";import{CellPathBinding as p,RowsBinding as S}from"./path-binding.js";import{attachDataEntry as b}from"./report-entry.js";import{buildDataSheetPackage as _,dataSheetsFromJSON as w,dataSheetsToJSON as v,readDataSheetPackage as T}from"./persist.js";class E{constructor(e){this.book=e,this.manager=new u(e),e.dataSheets=this,this.sheets=[],this.bindings=[],this.reports=[],this.loaded=!1,this.onSheetAdded=null,this.savedSheets=null,this.loadNotes=[],this._hookInput(e)}_hookInput(e){if(e.setInputRouted)return;e.setInputRouted=!0;const t=e.setInput;e.setInput=function(i,r,n,h){const{sheet:a}=i;if(!(a.routeInput!==void 0&&a.routeInput(i,r,n,h)))return t.call(this,i,r,n,h)}}_uniqueName(e){const t=i=>this.book.sheets.some(r=>r.name.toLowerCase()===i.toLowerCase());let s=e;for(let i=2;t(s);i++)s=`${e}${i}`;return s}_insert(e,t=!0,s=null){const{book:i}=this;i.sheets.push(e),t&&(i.activeSheet=i.sheets.length-1),i.structureEdited=!0,i.engine?.sheetsChanged(),s?.(),i._emit("sheets")}_registerSheet(e){this.sheets.push(e),this.onSheetAdded?.(e)}_registerBinding(e){this.bindings.push(e),this.onSheetAdded?.(e.sheet)}isDataSheet(e){return e.isVirtual===!0}addTableFromSheetTable(e,t=null){const s=e,i=this.manager.addTable(t??`${s.name} Data`);return i.loadSheet(this.book,s.sheet,{r0:s.r0,c0:s.c0,r1:s.r1-s.totalsRows,c1:s.c1}),i}addTable(e,t){return this.manager.addTable(e,t)}addTableSheet(e,t,s={},i={}){const r=this.manager.table(t),n=s instanceof o?s:new o(r,s),h=new l(this.book,this._uniqueName(e),n,i);return this._insert(h,i.activate!==!1,()=>this._registerSheet(h)),h}addGanttSheet(e,t=null,s={}){const i=Array.isArray(t)?t:[],r=t&&!Array.isArray(t)?this.manager.table(t):m(this.manager,this._freeTable(`${e} Tasks`),i),n=new c(this.book,this._uniqueName(e),r,s);return this._insert(n,s.activate!==!1,()=>this._registerSheet(n)),n}_freeTable(e){let t=e;for(let s=2;this.manager.tables.has(t);s++)t=`${e} ${s}`;return t}addReportSheet(e,t={}){const s=new d(this._uniqueName(e));let i=null;return this._insert(s,t.activate!==!1,()=>{i=new f(this.manager,s,t),this.reports.push(i),this.onSheetAdded?.(s)}),i}bindPaths(e,t=null,s={}){const i=new p(this.book,e,t,s);return this._registerBinding(i),i}bindRows(e,t,s,i={}){const r=new S(this.book,e,t,s,i);return this._registerBinding(r),r}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return b(this.book,e,e.output)}toJSON(){return v(this)}fromJSON(e){return w(e,this),this}bindTable(e,t,s,i={}){const r=new g(this.book,e,t,s,i);return this._registerBinding(r),r}removeBinding(e){e.unbind(),this.bindings=this.bindings.filter(t=>t!==e)}_pruneDeleted(){const e=new Set(this.book.sheets);this.sheets=this.sheets.filter(t=>e.has(t)),this.bindings=this.bindings.filter(t=>e.has(t.sheet)),this.reports=this.reports.filter(t=>e.has(t.sheet))}prepareSave(){this._pruneDeleted();for(const e of this.sheets)e.prepareSave();this.savedSheets=this.sheets.slice()}async savePackage(){for(const t of this.sheets)t.savePlanned?.();const e=await _(this);return e.parts.length===0&&!this.loaded?null:e}finishSave(){for(const e of this.savedSheets??[])e.finishSave();this.savedSheets=null}async load(e){return T(e,this)}}export{E as DataSheets};
@@ -0,0 +1,2 @@
1
+ import{FORMULA as k,STR as q}from"../core/sheet.js";import{cellRef as B,colName as F,MAX_COLS as m}from"../core/address.js";import{translateFormula as T}from"../core/formula-refs.js";import{createTable as R,resizeTable as U}from"../core/tables.js";import{hookSheet as $,rawCells as p,TableBinding as v,unhookSheet as E,valueOfWrite as N,writeRaw as O}from"./bind.js";import{DataError as S}from"./data.js";import{getPath as y,setPath as w}from"./remote.js";const g=(i,t)=>i*m+t;function _(i){const t=i.book.dataSheets;t&&(t.bindings=t.bindings.filter(e=>e!==i)),i.unbind()}function C(i,t){const e=i.usedRange(),{captions:s,rows:r}=i.exportRows();switch(t){case"json":return JSON.stringify(r,null,2);case"csv":{const o=n=>{const h=n==null?"":String(n);return/[",\n]/.test(h)?`"${h.replace(/"/g,'""')}"`:h};return[s.map(o).join(","),...r.map(n=>s.map(h=>o(n[h])).join(","))].join(`\r
2
+ `)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class M{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},$(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,N(this.book.strings,s,r))}}class H extends M{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,A(n))}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const A=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class z extends M{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??I(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((a,l)=>{const u=s.col+l;a.width&&t.cols.setSize(u,a.width),this.headerRows&&p.setCell.call(t,s.row,u,q,e.strings.add(a.caption??A(a.path??`Column${l+1}`)));const b=this._styleOf(a.format);if(a.formula){const d=String(a.formula).replace(/^=/,"");for(let f=0;f<r.length;f++)p.setCell.call(t,n+f,u,k,0),p.setFormula.call(t,n+f,u,{f:T(d,f,0),typed:!0}),b&&p.setStyle.call(t,n+f,u,b);return}for(let d=0;d<r.length;d++){const f=y(r[d],a.path);O(t,e.strings,n+d,u,f===void 0?null:f),b&&t.cellStyle(n+d,u)===0&&p.setStyle.call(t,n+d,u,b)}});for(let a=r.length;a<this.lastRows;a++)for(let l=0;l<o.length;l++)p.setCell.call(t,n+a,s.col+l,0,0),p.setFormula.call(t,n+a,s.col+l,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((a,l)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+l,s.col+l)}),this._notify(c,x),this.table&&this.book.engine){const a=this.anchor,l={r0:a.row,c0:a.col,r1:a.row+Math.max(1,r.length),c1:a.col+o.length-1};this.table.r1!==l.r1&&U(this.book,this.table,l)}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function I(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}z.prototype.exportAs=function(t){return C(this,t)},v.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function J(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=J(e);return t}return null}export{H as CellPathBinding,z as RowsBinding,B as cellRef,F as colName,C as exportBinding,J as sampleOf,j as schemaOf};
@@ -0,0 +1,2 @@
1
+ const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>",`${e}</Types>`)}function L(a,o){let t=a.replace(new RegExp(`<Relationship\\b[^>]*Type="${h(w)}"[^>]*/>`,"g"),"").replace(/<Relationship\b[^>]*Target="\/?(?:\.\.\/)?customXml\/ds8c[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[]){const r=s.replace(/^customXml\//,"");t=t.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*customXml/${h(r)}"[^>]*/>`),"")}const e=(o?.parts??[]).map((s,r)=>`<Relationship Id="rId8cDs${r+1}" Type="${b}" Target="/${s.file}"/>`).join("");return t.replace("</Relationships>",`${e}</Relationships>`)}async function T(a,o){const t=new Uint8Array(262144);let e=0,s=0,r=0,i=0;const f=async()=>{e>0&&(await o(t.slice(0,e)),e=0)};for await(const p of a){let l=0;const d=p.length;if(i>0)if(i===1&&d>=2){const c=s<<16|p[0]<<8|p[1];l=2,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else if(i===2&&d>=1){const c=s<<16|r<<8|p[0];l=1,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else{i===1&&d===1&&(r=p[0],i=2);continue}for(;l+2<d;){e+4>t.length&&await f();const c=p[l]<<16|p[l+1]<<8|p[l+2];t[e]=n[c>>18],t[e+1]=n[c>>12&63],t[e+2]=n[c>>6&63],t[e+3]=n[c&63],e+=4,l+=3}l<d&&(s=p[l],i=1,l+1<d&&(r=p[l+1],i=2)),e+8>t.length&&await f()}i===1?(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4],t[e++]=61,t[e++]=61):i===2&&(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4|r>>4],t[e++]=n[(r&15)<<2],t[e++]=61),await f()}async function*E(a){const o=a.stream().getReader();for(;;){const{done:t,value:e}=await o.read();if(t)return;yield e}}async function N(a,o,t){for(const e of o?.parts??[]){t?.add(e.file);const s=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <d xmlns="${x}" n="${e.name}" b="${e.bytes}">`;await a.add(e.file,async r=>{await r(m.encode(s)),await T(E(e.blob),r),await r(m.encode("</d>"))},{large:e.blob.size>2952790016})}}export{y as CUSTOM_XML_TYPE,S as MANIFEST_NAME,x as NS,X as partFileName,D as patchDataSheetContentTypes,L as patchDataSheetWorkbookRels,C as skipOldDataSheetParts,N as writeDataSheetParts};
@@ -0,0 +1 @@
1
+ import{decodeBytes as Y}from"../core/strings.js";import{MANIFEST_NAME as L,NS as q,partFileName as K}from"./persist-writer.js";import{ROW as J}from"./data.js";import{TableView as Q}from"./view.js";import{TableSheet as Z}from"./table-sheet.js";import{GanttSheet as z,WorkCalendar as j}from"./gantt.js";import{ReportTemplate as ee}from"./report.js";import{TableBinding as te}from"./bind.js";import{CellPathBinding as ne,RowsBinding as oe}from"./path-binding.js";import{t as se}from"../i18n/index.js";const M=2,U=new TextEncoder,O=1<<18,A=()=>new Promise(e=>setTimeout(e,0)),$=e=>e!==null&&!e.lookup&&!e.rollup&&!e.window&&!e.name.startsWith("__formula:")&&!e.name.startsWith("__cross:");function F(e){const i={name:e.name,type:e.type};return e.caption!==e.name&&(i.caption=e.caption),e.format!=="General"&&!(e.type==="date"&&e.format==="yyyy-mm-dd")&&(i.format=e.format),e.readOnly&&(i.readOnly=!0),e.width!==null&&(i.width=e.width),e.hidden&&(i.hidden=!0),e.formula!==null&&(i.formula=e.formula),e.defaultValue!==null&&(i.defaultValue=e.defaultValue),e.required&&(i.required=!0),e.showNullAs!==null&&(i.showNullAs=e.showNullAs),e.validator!==null&&!e.validator.fn&&(i.validator=e.validator),e.trigger&&(i.trigger=e.trigger),i}function ie(e){const i=e.rowCount,{state:t,alive:r}=e;let o=!1;for(let l=0;l<i;l++)if(t[l]===J.PURGED&&r[l]===0){o=!0;break}if(!o)return null;const a=new Int32Array(i);let n=0;for(let l=0;l<i;l++)a[l]=t[l]===J.PURGED&&r[l]===0?-1:n++;return{map:a,count:n}}function C(e,i,t){if(t===null)return e.subarray(0,i);const r=new e.constructor(t.count);for(let o=0;o<i;o++)t.map[o]>=0&&(r[t.map[o]]=e[o]);return r}async function ae(e,i,t){const r=e.rowCount,o=ie(e),a=o?o.count:r,{strings:n}=e.manager,l=`t${i}/`,s=(d,h)=>(t.push({name:`${l}${d}`,blob:new Blob([h]),bytes:h.byteLength}),d),c=new Map,f=[],u=d=>{let h=c.get(d);return h===void 0&&(h=f.length,c.set(d,h),f.push(n.get(d))),h},m=[],g=[];let p=0;for(const d of e.columns){if(!$(d)||(m.push(F(d)),d.computed))continue;const h={field:d.name};if(d.isString){const b=C(d.data,r,o),y=new Int32Array(b.length);for(let w=0;w<b.length;w++){const D=b[w];y[w]=D<0?-1:u(D),++p%O===0&&await A()}h.encoding="i32",h.part=s(`c${d.index}.bin`,y)}else if(d.kinds!==null){const b=C(d.kinds,r,o),y=Float64Array.from(C(d.data,r,o));for(let w=0;w<y.length;w++)b[w]===2&&(y[w]=u(y[w])),++p%O===0&&await A();h.encoding="mixed",h.part=s(`c${d.index}.bin`,y),h.kinds=s(`c${d.index}.kinds`,b)}else h.encoding="f64",h.part=s(`c${d.index}.bin`,C(d.data,r,o));d.styles!==null&&(h.styles=s(`c${d.index}.styles`,C(d.styles,r,o))),g.push(h)}const S=[],k=new Float64Array(f.length+1);let x=0,v=[],N=0;const R=()=>{N!==0&&(S.push(U.encode(v.join(""))),v=[],N=0)};for(let d=0;d<f.length;d++){const h=re(f[d]);k[d]=x,x+=h,v.push(f[d]),N+=f[d].length,N>1<<20&&(R(),await A())}R(),k[f.length]=x,t.push({name:`${l}strings.bin`,blob:new Blob(S),bytes:x}),s("strings.idx",k);const G=C(e.alive,r,o),I=C(e.state,r,o);s("alive.bin",G),s("state.bin",I);const B=[];for(const[d,h]of e.originals){const b=o?o.map[d]:d;b<0||B.push([b,[...h].map(([y,w])=>[e.columns[y].name,_(w)])])}return{name:e.name,key:e.key,tracking:e.tracking,rowCount:a,dir:l,indexes:e.getIndexes(),windows:e.windowDefs,schema:e.schema,remote:E(e.remote),autoSync:e.autoSync,batch:e.batchSync,stringCount:f.length,fields:m,columns:g,originals:B,map:o}}function E(e){if(!e||typeof e!="object")return null;const i={};for(const[t,r]of Object.entries(e))typeof r!="function"&&(i[t]=r);return Object.keys(i).length>0?i:null}const _=e=>e!==null&&typeof e=="object"?{error:e.code}:e;function re(e){let i=e.length;for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=128)if(r<2048)i++;else if(r>=55296&&r<=56319){const o=e.charCodeAt(t+1);o>=56320&&o<=57343?(i+=2,t++):i+=2}else i+=2}return i}function T(e,i){const t=e.toJSON(),r=i.map;return r&&(t.pinnedRows=t.pinnedRows.map(o=>r.map[o]).filter(o=>o>=0),t.treeCollapsed=t.treeCollapsed.map(o=>r.map[o]).filter(o=>o>=0)),t}function le(e){return e.toJSON()}function W(e,i){let t=0;const r=new Map,{columns:o}=e;for(let a=0;a<o.length;a++){const n=o[a];if(n===void 0)continue;const l=n.length;for(let s=0;s<l;s++){const c=n[s];if(c===void 0)continue;const{kinds:f,values:u}=c;for(let m=0;m<f.length;m++){const g=f[m]&7;if(g===0)continue;let p;if(g===2){const k=u[m];if(p=r.get(k),p===void 0){p=7;const x=i.get(k);for(let v=0;v<x.length;v++)p=Math.imul(p,31)+x.charCodeAt(v)|0;r.set(k,p)}}else p=Math.round(u[m]*1e3)|0;const S=Math.imul((s<<10)+m+1,2654435761)^Math.imul(a+1,2246822507);t=t+Math.imul(p^S,625341585)|0}}}return t}function ce(e,i,t){return{sheet:e.name,kind:e.kindName,table:e.table.name,view:T(e.view,i(e.table)),options:e.options,gantt:e.kindName==="gantt"?e.toJSON():void 0,cells:W(e,t)}}function V(e,i){const{manager:t,sheets:r,bindings:o,reports:a,book:n}=e,l=s=>i.find(c=>c.name===s.name);return{format:"8sheets-datasheets",version:M,tables:i.map(({map:s,...c})=>c),relationships:t.relationships.map(s=>({from:s.from.name,fromField:s.fromField,to:s.to.name,toField:s.toField,name:s.name,inverse:s.inverse})),views:[...t.tables.values()].flatMap(s=>[...s.views.values()].map(c=>({table:s.name,name:c.name,view:T(c,l(s))}))),sheets:r.map(s=>ce(s,l,n.strings)),bindings:o.map(s=>s.toJSON?s.toJSON():{kind:"view",sheet:s.sheet.name,range:s.range,table:s.table.name,view:T(s.view,l(s.table)),options:{header:s.options.header,grow:s.options.grow,editable:s.options.editable,sticky:s.options.sticky}}),reports:a.map(le)}}async function Se(e){const{manager:i,sheets:t,bindings:r,reports:o}=e,a=e.sourceParts??[];if(!(i.tables.size>0||t.length>0||o.length>0||r.length>0))return{parts:[],replaced:a};const l=[],s=[];let c=0;for(const u of i.tables.values())s.push(await ae(u,c++,l));const f=U.encode(JSON.stringify(V(e,s)));return l.push({name:L,blob:new Blob([f]),bytes:f.length}),l.forEach((u,m)=>{u.file=K(m)}),{parts:l,replaced:a}}const fe=(()=>{const e=new Int8Array(256).fill(-1),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t<64;t++)e[i.charCodeAt(t)]=t;return e})();async function ue(e,i){const t=(await e.stream(i)).getReader(),{value:r}=await t.read();if(t.cancel().catch(()=>{}),!r)return null;const o=new TextDecoder().decode(r.subarray(0,400));if(!o.includes(q))return null;const a=/\bn="([^"]*)"/.exec(o)?.[1],n=Number(/\bb="(\d+)"/.exec(o)?.[1]??0);return a===void 0?null:{name:a,bytes:n,file:i}}async function H(e,i,t){const r=(await e.stream(i)).getReader(),o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let a=0,n=!1,l=0,s=0;for(;;){const{done:c,value:f}=await r.read();if(c)break;let u=0;if(!n){let m=0;for(;u<f.length;u++)if(f[u]===62&&(m++,m===2)){u++,n=!0;break}if(!n)continue}for(;u<f.length;u++){const m=fe[f[u]];m<0||(l=l<<6|m,s++,s===4&&(a+3<=o.length?(o[a]=l>>16,o[a+1]=l>>8&255,o[a+2]=l&255):(a<o.length&&(o[a]=l>>16),a+1<o.length&&(o[a+1]=l>>8&255)),a+=3,l=0,s=0))}}s===2&&a<o.length&&(o[a]=l>>4),s===3&&(a<o.length&&(o[a]=l>>10),a+1<o.length&&(o[a+1]=l>>2&255))}async function de(e,i,t){const r=i.addTable(t.name,{key:t.key,tracking:t.tracking,capacity:t.rowCount,fields:t.fields,windows:t.windows,schema:t.schema,remote:t.remote,autoSync:t.autoSync,batch:t.batch,indexes:t.indexes}),{dir:o}=t,a=new Float64Array(t.stringCount+1);await e(`${o}strings.idx`,a);const n=new Uint8Array(a[t.stringCount]);await e(`${o}strings.bin`,n);const l=new Int32Array(t.stringCount);for(let c=0;c<t.stringCount;c++)l[c]=i.strings.add(Y(n,a[c],a[c+1])),(c+1)%O===0&&await A();r.rowCount=t.rowCount;for(const c of t.columns){const f=r.byName.get(c.field);if(f){if(c.encoding==="i32"){const u=new Int32Array(t.rowCount);await e(`${o}${c.part}`,u);const{data:m}=f;for(let g=0;g<t.rowCount;g++){const p=u[g];m[g]=p<0?-1:l[p]}}else if(c.encoding==="mixed"){await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount)),f.kinds=new Uint8Array(r.capacity),await e(`${o}${c.kinds}`,new Uint8Array(f.kinds.buffer,0,t.rowCount));for(let u=0;u<t.rowCount;u++)f.kinds[u]===2&&(f.data[u]=l[f.data[u]])}else await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount));c.styles&&(f.styles=new Uint16Array(r.capacity),await e(`${o}${c.styles}`,new Uint16Array(f.styles.buffer,0,t.rowCount))),await A()}}await e(`${o}alive.bin`,new Uint8Array(r.alive.buffer,0,t.rowCount)),await e(`${o}state.bin`,new Uint8Array(r.state.buffer,0,t.rowCount));let s=0;for(let c=0;c<t.rowCount;c++)r.alive[c]===0&&s++;r.deletedCount=s;for(const[c,f]of t.originals)r.originals.set(c,new Map(f.map(([u,m])=>[r.byName.get(u)?.index,m]).filter(([u])=>u!==void 0)));return r.revision++,r.structureRevision++,r._markAllComputedStale(),r}function P(e,i){const t=new Q(e,i);return t.applySavedState(i),t}async function Ne(e,i){const t=new Map,r=[];for(const c of e.entries.keys()){if(!c.startsWith("customXml/")||c.includes("/_rels/")||!c.endsWith(".xml")||/itemProps/i.test(c))continue;const f=await ue(e,c);f&&(t.set(f.name,f),r.push(c))}const o=t.get(L);if(!o)return!1;const a=new Uint8Array(o.bytes);await H(e,o.file,a);const n=JSON.parse(new TextDecoder().decode(a));if(n.format!=="8sheets-datasheets"||n.version>M)return!1;i.sourceParts=me(e,r);const l=async(c,f)=>{const u=t.get(c);u&&await H(e,u.file,f)},{manager:s}=i;for(const c of n.tables)await de(l,s,c);return X(n,i),i.loaded=!0,!0}function me(e,i){const t=[];for(const r of i){t.push(r);const o=r.slice(10),a=`customXml/_rels/${o}.rels`;if(e.has(a)){t.push(a);const n=/(\d+)\.xml$/.exec(o)?.[1];n&&e.has(`customXml/itemProps${n}.xml`)&&t.push(`customXml/itemProps${n}.xml`)}}return t}function he(e,i,t){return{view:i,fields:e.fields,calendar:new j(e.calendar),calendars:e.calendars,durationUnit:e.durationUnit,scaleLevel:e.scaleLevel,scale:e.scale,showCritical:e.showCritical,showBaseline:e.showBaseline,showLinks:e.showLinks,showLabels:e.showLabels,showToday:e.showToday,statusDate:e.statusDate,taskbarRules:e.taskbarRules,taskbarStyles:e.taskbarStyles,layout:e.layout,gridlines:e.gridlines,nonWorking:e.nonWorking,progressLine:e.progressLine,frozenLimit:e.frozenLimit,sheet:t}}function X(e,i){const{book:t,manager:r}=i;for(const n of e.relationships)r.addRelationship(n);for(const n of e.views??[]){const l=r.table(n.table);l.views.set(n.name,P(l,n.view))}const o=n=>t.sheets.find(l=>l.name===n),a=[];for(const n of e.sheets){const l=o(n.sheet);if(!l)continue;if(n.cells!==void 0&&!l.isVirtual&&W(l,t.strings)!==n.cells){a.push(n.sheet);continue}const s=r.table(n.table),c=P(s,n.view);let f;n.kind==="gantt"?(f=new z(t,n.sheet,s,he(n.gantt,c,n.options)),n.gantt.resourceTable&&(f.resourceTable=r.tables.get(n.gantt.resourceTable)??null,f.assignmentTable=r.tables.get(n.gantt.assignmentTable)??null,f.resourceNamesChanged())):f=new Z(t,n.sheet,c,n.options),f.adoptFrom(l),t.sheets[t.sheets.indexOf(l)]=f,i._registerSheet(f)}a.length>0&&i.loadNotes.push(se("{sheets} changed outside this app, so they stay plain sheets. The data tables are still there.",{sheets:a.join(", "),count:a.length}));for(const n of e.bindings){const l=o(n.sheet);if(l)if(n.kind==="paths"){const s=new ne(t,l,n.source?.table?n.source:n.source?.data??null);s.paths=new Map(n.paths),s.fieldOptions=new Map(n.fieldOptions??[]),s.refresh(),i._registerBinding(s)}else if(n.kind==="rows")i._registerBinding(new oe(t,l,n.anchor,n.data,{columns:n.columns,...n.options,table:n.table?t.engine?.tables.get(n.table.toUpperCase())??null:null}));else{const s=P(r.table(n.table),n.view);i._registerBinding(new te(t,l,n.range,s,n.options))}}for(const n of e.reports){const l=o(n.sheet);if(!l)continue;const s=new ee(r,l,{table:n.table,name:n.name,titleRows:n.titleRows,pageSetup:n.pageSetup,mode:n.mode,pagination:n.pagination,layout:n.layout,dataEntry:n.dataEntry,charts:n.charts,pictures:n.pictures,states:n.states,showHiddenRows:n.showHiddenRows,showHiddenCols:n.showHiddenCols});for(const c of n.bindings)s.setBinding(c.row,c.col,c);for(const c of n.params)s.addParam(c.name,c);s.filters=n.filters,s.output=n.output?o(n.output)??null:null,i.reports.push(s)}t.engine?.sheetsChanged(),t.engine?.rebuild()}function Oe(e){const{manager:i,book:t}=e,r=[...i.tables.values()].map(a=>{const n=[],l=a.columns.filter(s=>$(s)&&!s.computed);for(let s=0;s<a.rowCount;s++){if(a.alive[s]===0)continue;const c={};for(const f of l){const u=f.get(s);u!==null&&(c[f.name]=_(u))}n.push(c)}return{name:a.name,key:a.key,tracking:a.tracking,windows:a.windowDefs,schema:a.schema,remote:E(a.remote),autoSync:a.autoSync,batch:a.batchSync,indexes:a.getIndexes(),fields:a.columns.filter($).map(F),rows:n}}),o=V(e,r.map(a=>({name:a.name,map:null})));o.tables=r;for(const a of o.sheets)delete a.cells;return o}function $e(e,i){const{book:t,manager:r}=i;for(const o of e.tables){const{rows:a,...n}=o;r.addTable(o.name,n).load(a)}for(const o of e.sheets)t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);for(const o of e.reports??[])t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);X(e,i)}export{Se as buildDataSheetPackage,$e as dataSheetsFromJSON,Oe as dataSheetsToJSON,he as ganttOptions,W as hashSheetCells,Ne as readDataSheetPackage};
@@ -0,0 +1 @@
1
+ import{raw as p}from"../calc/functions/registry.js";import{Arr as E,ERR as a,Ref as R,str as h}from"../calc/values.js";import{formulaHelper as g}from"./view.js";import{sortColumn as y}from"./sort.js";const A=l=>l??"";function C(l,n){const i=/^(.+?)(?:#(\d+)|\/(.+)|\?([^=]+)=(.*))?$/.exec(n),e=l?.tables.get(i?.[1]);if(!e)return null;if(i[2]!==void 0){const t=Number(i[2]);let d=-1;for(let u=0;u<e.rowCount;u++)if(e.alive[u]===1&&++d===t)return{table:e,rows:[u]};return{table:e,rows:[]}}const r=(t,d)=>{const u=[];e.ensure(t);for(let f=0;f<e.rowCount;f++)e.alive[f]===1&&String(t.get(f))===d&&u.push(f);return u};if(i[3]!==void 0){const t=e.column(e.key);return t?{table:e,rows:r(t,i[3])}:null}if(i[4]!==void 0){const t=e.column(i[4]);return t?{table:e,rows:r(t,i[5])}:null}const o=[];for(let t=0;t<e.rowCount;t++)e.alive[t]===1&&o.push(t);return{table:e,rows:o}}function S(l,n,i){if(n===void 0||n==="")return i.fields.map(r=>r.name);if(n instanceof R){const r=[];for(let o=n.r0;o<=n.r1;o++)for(let t=n.c0;t<=n.c1;t++)r.push(String(l.engine?.read?.(n.sheet,o,t)??""));return r.map(o=>o.trim()).filter(Boolean)}if(n instanceof E)return n.data.map(r=>String(r).trim()).filter(Boolean);const e=h(n).trim();return e===""?i.fields.map(r=>r.name):e.split(",").map(r=>r.trim())}p("QUERY",1,4,(l,n)=>{const i=C(l.book.dataSheets?.manager,h(n[0]));if(!i)return a.VALUE;const{table:e}=i,r=S(l,n[1],e).map(s=>e.column(s));if(r.some(s=>!s))return a.REF;for(const s of r)e.ensure(s);let o=Int32Array.from(i.rows);const t=n[2],d=t===!0;if(typeof t=="string"&&t!==""){const s=g(e,t);o=o.filter(c=>{const m=s.get(c);return m===!0||typeof m=="number"&&m!==0})}const u=n[3]===void 0?"":h(n[3]).trim();if(u!==""){const[s,c]=u.split(/\s+/),m=e.column(s);if(!m)return a.REF;e.ensure(m),y(e,o,o.length,m,/^desc/i.test(c??""))}const f=d?Math.min(1,o.length):o.length;if(f===0)return a.NA;const w=new Array(f*r.length);for(let s=0;s<f;s++)for(let c=0;c<r.length;c++)w[s*r.length+c]=A(r[c].get(o[s]));return new E(f,r.length,w)},{volatile:!0}),p("CALCULATE",1,2,(l,n)=>n[0]),p("REMOVEFILTERS",0,255,()=>0);
@@ -0,0 +1,3 @@
1
+ import{unescapeXml as T}from"../io/xml-scan.js";import{t as j}from"../i18n/index.js";import{mayReach as P,OFFLINE_MESSAGE as R,onlineAllowed as k}from"../core/online.js";function F(t,n){if(t===null||typeof t!="object")return;const r=t[n];if(r!==void 0)return r;if(n.includes("."))return A(t,n)}function A(t,n){let r=t;for(const e of String(n).split(".")){if(r==null)return;r=r[e]}return r}function J(t,n,r){const e=String(n).split(".");let o=t;for(let s=0;s<e.length-1;s++){const a=e[s];(o[a]===null||typeof o[a]!="object")&&(o[a]=/^\d+$/.test(e[s+1])?[]:{}),o=o[a]}o[e[e.length-1]]=r}function q(t,n="",r={}){for(const[e,o]of Object.entries(t)){const s=n?`${n}.${e}`:e;o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?q(o,s,r):r[s]=o}return r}function _(t,n=","){const r=[];let e=[],o="",s=!1;for(let u=0;u<t.length;u++){const c=t[u];s?c==='"'?t[u+1]==='"'?(o+='"',u++):s=!1:o+=c:c==='"'?s=!0:c===n?(e.push(o),o=""):c===`
2
+ `||c==="\r"?(c==="\r"&&t[u+1]===`
3
+ `&&u++,e.push(o),o="",r.push(e),e=[]):o+=c}if((o!==""||e.length>0)&&(e.push(o),r.push(e)),r.length===0)return[];const[a,...i]=r;return i.map(u=>{const c={};return a.forEach((d,g)=>{c[d]=E(u[g])}),c})}function E(t){if(t===void 0||t==="")return null;if(/^[+-]?(\d+([.]\d*)?|[.]\d+)([eE][+-]?\d+)?$/.test(t)&&!/^0\d/.test(t))return Number(t);const n=t.toUpperCase();return n==="TRUE"?!0:n==="FALSE"?!1:t}function C(t,n){const r=[],e=n??L(t);if(!e)return r;const o=new RegExp(`<${e}\\b([^>]*?)(?:/>|>([\\s\\S]*?)</${e}>)`,"g"),s=/<([A-Za-z_][\w.-]*)\b[^>]*?(?:\/>|>([\s\S]*?)<\/\1>)/g,a=/([A-Za-z_][\w.-]*)="([^"]*)"/g;for(const i of t.matchAll(o)){const u={};for(const c of(i[1]??"").matchAll(a))u[c[1]]=E(T(c[2]));for(const c of(i[2]??"").matchAll(s))u[c[1]]=E(T(c[2]??""));r.push(u)}return r}function L(t){const n=new Map;let r=0;for(const s of t.matchAll(/<(\/?)([A-Za-z_][\w.-]*)\b[^>]*?(\/?)>/g)){if(s[1]){r--;continue}r===1&&n.set(s[2],(n.get(s[2])??0)+1),s[3]||r++}let e=null,o=0;for(const[s,a]of n)a>o&&(e=s,o=a);return e}function z(t,n){const r=n.type??"json";let e=t;if(typeof e=="string"){if(r==="csv")return _(e,n.delimiter);if(r==="xml")return C(e,n.recordName);e=JSON.parse(e)}if(n.dataPath&&(e=A(e,n.dataPath)),r==="columnJson"&&e&&!Array.isArray(e)){const o=Object.keys(e),s=o.reduce((i,u)=>Math.max(i,e[u].length),0),a=new Array(s);for(let i=0;i<s;i++){const u={};for(const c of o)u[c]=e[c][i];a[i]=u}return a}return e??[]}function S(t,n){const r=n.min??n.value,e=n.max;switch(n.operator){case"between":return t>=r&&t<=e;case"notBetween":return t<r||t>e;case"equal":return t===r;case"notEqual":return t!==r;case"greaterThan":return t>r;case"lessThan":return t<r;case"greaterThanOrEqual":return t>=r;case"lessThanOrEqual":return t<=r;default:return!(n.min!==void 0&&t<n.min||n.max!==void 0&&t>n.max)}}function I(t,n,r=-1){const e=t.validator;if(n==null)return e.allowBlank===!1?j("The {field} field can't be blank.",{field:t.caption}):null;if(e.errorStyle==="warning"||e.errorStyle==="information")return null;const o=()=>e.message??j("That isn't a valid value for the {field} field.",{field:t.caption});switch(e.type){case"list":return(e.items??[]).some(s=>String(s).toLowerCase()===String(n).toLowerCase())?null:o();case"whole":return typeof n=="number"&&Number.isInteger(n)&&S(n,e)?null:o();case"number":case"decimal":case"date":return typeof n=="number"&&S(n,e)?null:o();case"time":return typeof n!="number"?o():S(n-Math.floor(n),e)?null:o();case"textLength":return S(String(n).length,e)?null:o();case"custom":{if(e.fn)return e.fn(n)?null:o();if(!e.formula||r<0)return null;const s=typeof n=="string"?`"${n.replace(/"/g,'""')}"`:String(n),a=String(e.formula).split(`[@${t.name}]`).join(s),i=t.table.manager.formulas.evaluateOnce(t.table,r,a);return i===!0||typeof i=="number"&&i!==0?null:o()}default:return null}}const h=t=>typeof t=="string"?{url:t}:t;async function m(t,{url:n,method:r,body:e,query:o}={}){const s=new URL(n??t.url,globalThis.location?.href??"http://localhost/");for(const[c,d]of Object.entries({...t.query??{},...o??{}}))s.searchParams.set(c,d);const a={method:r??t.method??"GET",headers:{Accept:"application/json",...t.headers??{}}};if(e!==void 0&&(a.headers["Content-Type"]=a.headers["Content-Type"]??"application/json",a.body=typeof e=="string"?e:JSON.stringify(e)),!P(s.href))throw new Error(j(R));k()||(a.redirect="error");const i=await fetch(s,a);if(!i.ok)throw new Error(`${i.status} ${i.statusText}`);if(i.status===204)return null;const u=i.headers.get("content-type")??"";return/json/.test(u)?i.json():i.text()}const $=(t,n)=>typeof t=="string"&&(n?.type??"json")==="json"?JSON.parse(t):t;async function Z(t,n){const r=t.read??t;if(typeof r=="function")return r();const e=h(r),o=e.protocol??t.protocol??"json";if(o==="graphql"){const a=$(await m(e,{method:"POST",body:{query:e.query_??e.graphql,variables:e.variables}}),n),i=a.data??a;return n?.dataPath?i:Object.values(i)[0]??[]}const s=$(await m(e,{body:e.body}),n);return o==="odata"&&!n?.dataPath?s?.d?.results??s?.d??s?.value??s:o==="odata4"&&!n?.dataPath?s?.value??s:s}const O=(t,n,r)=>r==="odata"||r==="odata4"?`${t.url}(${typeof n=="string"?`'${n}'`:n})`:`${String(t.url).replace(/\/$/,"")}/${encodeURIComponent(n)}`;async function B(t,n){const r=t.remote,{inserted:e,updated:o,deleted:s}=n,a=new Map,i={inserted:e.length,updated:o.length,deleted:s.length};if(typeof r=="object"&&r.create===void 0&&r.update===void 0&&r.delete===void 0&&r.remove===void 0&&r.batch===void 0)return{errors:a,counts:i};const{key:u}=t,c=r.protocol??h(r.read??{})?.protocol??"json";if(typeof r.batch=="function"||r.batch&&t.batchSync){const l=[...e.map(f=>({op:"insert",data:f})),...o.map(f=>({op:"update",data:f.record,original:f.original})),...s.map(f=>({op:"delete",data:f.record}))];if(l.length===0)return{errors:a,counts:i};try{typeof r.batch=="function"?await r.batch(l):await m(h(r.batch),{method:"POST",body:l})}catch(f){for(const p of e)a.set(p.__row,f.message);for(const p of o)a.set(p.row,f.message);for(const p of s)a.set(p.row,f.message)}return{errors:a,counts:i}}const d=async(l,f)=>{try{await f()}catch(p){a.set(l,p.message)}},g=(l,f)=>r[l]??(f?r[f]:void 0),y=g("create"),w=g("update"),b=g("delete","remove");if(typeof y=="function"){if(e.length>0)try{await y(e)}catch(l){for(const f of e)a.set(f.__row,l.message)}}else if(y)for(const l of e)await d(l.__row,()=>m(h(y),{method:"POST",body:l}));if(typeof w=="function"){if(o.length>0)try{await w(o)}catch(l){for(const f of o)a.set(f.row,l.message)}}else if(w){const l=h(w);for(const f of o)await d(f.row,()=>m(l,{url:O(l,u?f.record[u]:f.row,c),method:l.method??(c==="json"?"PUT":"PATCH"),body:c==="json"?f.record:f.changes}))}if(typeof b=="function"){if(s.length>0)try{await b(s)}catch(l){for(const f of s)a.set(f.row,l.message)}}else if(b){const l=h(b);for(const f of s)await d(f.row,()=>m(l,{url:O(l,u?f.record[u]:f.row,c),method:"DELETE"}))}return{errors:a,counts:i}}export{I as checkValidator,q as flattenRecord,A as getPath,z as parseSource,F as readField,Z as readRemote,B as sendChanges,J as setPath};
@@ -0,0 +1 @@
1
+ import{Sheet as p}from"../core/sheet.js";import{DataError as g,ROW as h}from"./data.js";import{valueOfWrite as m}from"./bind.js";import{t as b}from"../i18n/index.js";const d=p.prototype.setCell;class y{constructor(t,e,s){this.book=t,this.template=e,this.out=s,this.onRejected=null,this.onRefresh=null,this.writing=!1,this._hook()}get settings(){return this.template.dataEntry??{}}_hook(){const t=this,{out:e}=this;e.reportEntry||(e.reportEntry=this,e.setCell=function(r,n,l,i){if(this.reportWriting||t.writing){d.call(this,r,n,l,i);return}t._written(r,n,l,i)})}cellInfo(t,e){const s=this.out.reportMap;if(!s||t>=s.rowRec.length)return null;const r=s.colTpl[e],n=s.overlay?.get(t)??s.rowTpl[t],l=this.template.binding(n,r);if(!l||l.type!=="list"||l.editable===!1)return null;const i=this.template.manager.table(l.table),o=s.contexts[s.rowCtx[t]];let a=s.rowRec[t];if(a<0&&(a=o?.table===i&&o.rows.length>0?o.rows[0]:-1),a<0)return null;const c=i.column(l.field);return!c||c.computed||c.readOnly?null:{table:i,rec:a,field:l.field,column:c,binding:l}}_written(t,e,s,r){const n=this.cellInfo(t,e);if(n===null){this.onRejected?.(b("Only list cells of a report take entries."));return}this.updateCellValue(t,e,m(this.book.strings,s,r),n)}updateCellValue(t,e,s,r=null){const n=r??this.cellInfo(t,e);if(n===null)return!1;const{table:l,rec:i,field:o,column:a}=n;if(a.get(i)===s)return!0;if(!this.template.fire("dataChanging",{row:t,col:e,record:i,field:o,value:s,table:l}))return!1;try{l.set(i,o,s)}catch(u){if(!(u instanceof g))throw u;return this.onRejected?.(u.message),!1}this.writing=!0;const c=a.kind(i);return d.call(this.out,t,e,c,a.raw(i)),this.writing=!1,this.out.revision++,this.template.fire("dataChanged",{row:t,col:e,record:i,field:o,value:s,table:l}),!0}isDirty(t,e){const s=this.cellInfo(t,e);if(s===null)return!1;const{table:r,rec:n,column:l}=s;return r.state[n]===h.INSERTED||r.isCellEdited(n,l)}_regenerate(){const t=this.template.generate(this.book,{target:this.out});return this.onRefresh?.(),t}tables(){const t=new Set;for(const e of this.template.bindings.values())e.type==="list"&&e.editable!==!1&&t.add(this.template.manager.table(e.table));return[...t]}_bindingOfRow(t){const e=this.out.reportMap,s=e.overlay?.get(t)??e.rowTpl[t];for(const r of e.colTpl){const n=this.template.binding(s,r);if(n&&n.type==="list")return n}return null}addRecordAt(t){const e=this.out.reportMap,s=this._bindingOfRow(t)??[...this.template.bindings.values()].find(i=>i.type==="list");if(!s)return-1;const r=this.template.manager.table(s.table),n={};for(let i=e.contexts[e.rowCtx[t]];i;i=i.parent){const o=i.node?.binding;if(o&&o.type==="group"&&i.table===r&&!o.by&&!o.size&&!o.bins&&!o.formula&&i.rows.length>0){const a=r.column(o.field);a&&!a.computed&&(n[o.field]=a.get(i.rows[0]))}}for(const[i,o]of Object.entries(this.settings.defaults??{}))n[i]===void 0&&(n[i]=typeof o=="string"&&/^=\s*UUID\(\s*\)$/i.test(o)?w():o);const l=r.addRow(n);return this._regenerate(),l}deleteRecordAt(t){const e=this.out.reportMap,s=this._bindingOfRow(t);if(!s)return!1;let r=e.rowRec[t];const n=this.template.manager.table(s.table);if(r<0){const l=e.contexts[e.rowCtx[t]];r=l?.table===n&&l.rows.length===1?l.rows[0]:-1}return r<0?!1:(n.removeRow(r),this._regenerate(),!0)}getChanges(){const t={inserted:[],updated:[],deleted:[]};for(const e of this.tables()){const s=e.getChanges(),r=n=>n.map(l=>({table:e.name,...l}));t.inserted.push(...r(s.inserted)),t.updated.push(...r(s.updated)),t.deleted.push(...r(s.deleted))}return t}async submit(){const t=this.getChanges();if(!this.template.fire("submitting",{changes:t}))return null;const{skipEmpty:e}=this.settings,s=[];let r=0;for(const n of this.tables()){if(e)for(let o=0;o<n.rowCount;o++)n.state[o]===h.INSERTED&&n.alive[o]===1&&n.columns.every(a=>a===null||a.computed||a.hidden||a.kind(o)===0)&&n.removeRow(o);const l=n.getChanges(),i=l.inserted.length+l.updated.length+l.deleted.length;if(n.remote){await n.submitChanges();for(const[o,a]of n.rowErrors)s.push({table:n.name,row:o,message:a});r+=i-n.rowErrors.size}else n.acceptChanges(),r+=i}return this.template.fire("submitted",{succeeded:r,failed:s}),this._regenerate(),{succeeded:r,failed:s}}cancel(){for(const t of this.tables())t.rejectChanges();this._regenerate()}}function w(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function x(f,t,e=t.output){return e.reportEntry??new y(f,t,e)}export{y as ReportEntry,x as attachDataEntry};