@8sheets/data-grid 1.0.2 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/api/theme-core.js +2 -0
  4. package/calc/adjust.js +1 -1
  5. package/calc/compile.js +1 -1
  6. package/calc/engine.js +1 -1
  7. package/calc/functions/array.js +1 -1
  8. package/calc/functions/database.js +1 -1
  9. package/calc/functions/date.js +1 -1
  10. package/calc/functions/financial.js +1 -1
  11. package/calc/functions/helpers.js +1 -1
  12. package/calc/functions/info.js +1 -1
  13. package/calc/functions/logical.js +1 -1
  14. package/calc/functions/lookup.js +1 -1
  15. package/calc/functions/math.js +1 -1
  16. package/calc/functions/stat.js +1 -1
  17. package/calc/functions/text.js +1 -1
  18. package/calc/parser.js +3 -3
  19. package/calc/values.js +1 -1
  20. package/calcx/async.js +1 -1
  21. package/calcx/culture/custom.js +1 -0
  22. package/calcx/culture/format-locale.js +1 -1
  23. package/calcx/culture/separators.js +1 -0
  24. package/calcx/functions/dynamic.js +1 -1
  25. package/calcx/functions/ets.js +1 -1
  26. package/calcx/functions/misc.js +1 -1
  27. package/calcx/lang/convert.js +1 -0
  28. package/cells/axis-ops.js +1 -1
  29. package/cells/block.js +1 -0
  30. package/cells/book-css.js +2 -2
  31. package/cells/cell-defaults.js +1 -1
  32. package/cells/cf-engine.js +1 -1
  33. package/cells/consolidate-links.js +1 -1
  34. package/cells/find-engine.js +2 -2
  35. package/cells/format-panes.js +3 -3
  36. package/cells/format-tabs.js +2 -2
  37. package/cells/outline-column.js +1 -1
  38. package/cells/panes.js +1 -1
  39. package/cells/rich-runs.js +2 -2
  40. package/cells/rich-values.js +1 -1
  41. package/cells/selection-modes.js +1 -1
  42. package/cells/shift-check.js +1 -0
  43. package/cells/table-rows.js +1 -0
  44. package/cells/text-layout.js +9 -8
  45. package/cells/ui-kit.js +15 -0
  46. package/cells/view-options.js +1 -1
  47. package/celltypes/cell-types.js +2 -2
  48. package/celltypes/diagonal.js +1 -1
  49. package/celltypes/dropdowns.js +3 -2
  50. package/celltypes/file-cell.js +2 -2
  51. package/celltypes/range-template.js +2 -2
  52. package/core/autofill.js +1 -1
  53. package/core/axis-styles.js +1 -0
  54. package/core/axis.js +1 -1
  55. package/core/cell-type-rules.js +1 -0
  56. package/core/changes.js +1 -1
  57. package/core/cond-format.js +1 -1
  58. package/core/culture.js +1 -0
  59. package/core/formula-refs.js +1 -1
  60. package/core/input.js +1 -1
  61. package/core/merge.js +1 -0
  62. package/core/numfmt.js +1 -1
  63. package/core/region-input.js +1 -0
  64. package/core/row-fit.js +1 -0
  65. package/core/sheet.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/structure.js +1 -0
  68. package/core/styles.js +1 -1
  69. package/core/tables.js +2 -2
  70. package/core/validation-ranges.js +1 -0
  71. package/core/whatif.js +1 -1
  72. package/core/workbook.js +1 -1
  73. package/datasheets/data-core.js +1 -1
  74. package/datasheets/gantt-paint.js +1 -1
  75. package/datasheets/manager.js +1 -1
  76. package/datasheets/path-binding.js +2 -2
  77. package/datasheets/rules.js +1 -1
  78. package/datasheets/view.js +2 -2
  79. package/i18n/dom.js +1 -1
  80. package/i18n/en/cells.js +1 -1
  81. package/i18n/en/format.js +1 -1
  82. package/i18n/en/misc.js +1 -1
  83. package/i18n/en/shell.js +2 -2
  84. package/i18n/pl/cells.js +1 -1
  85. package/i18n/pl/format.js +1 -1
  86. package/i18n/pl/misc.js +1 -1
  87. package/i18n/pl/shell.js +2 -2
  88. package/io/client.js +1 -1
  89. package/io/csv.js +8 -8
  90. package/io/plan.js +1 -1
  91. package/io/text-split.js +3 -3
  92. package/io/xlsx-read.js +1 -1
  93. package/io/xlsx-write.js +1 -1
  94. package/io/xml-scan.js +2 -1
  95. package/io/zip-reader.js +1 -1
  96. package/objects/chart-model.js +1 -1
  97. package/package.json +1 -1
  98. package/pivot/engine.js +1 -1
  99. package/pivot/xml.js +2 -2
  100. package/print/paginate.js +1 -1
  101. package/print/render-page.js +3 -3
  102. package/slicers/format.js +2 -2
  103. package/slicers/structured.js +1 -1
  104. package/table-view/api.js +1 -1
  105. package/table-view/cell-editor.js +2 -1
  106. package/table-view/chart.js +1 -0
  107. package/table-view/column-drag.js +1 -1
  108. package/table-view/context-menu.js +1 -0
  109. package/table-view/editors.js +1 -0
  110. package/table-view/events.js +1 -1
  111. package/table-view/files.js +1 -1
  112. package/table-view/fill-handle.js +1 -0
  113. package/table-view/filter-builder.js +1 -0
  114. package/table-view/find.js +1 -0
  115. package/table-view/grid-keys.js +2 -2
  116. package/table-view/labels-de.js +1 -0
  117. package/table-view/labels-es.js +1 -0
  118. package/table-view/labels-fr.js +1 -0
  119. package/table-view/labels-ja.js +1 -0
  120. package/table-view/labels.js +1 -1
  121. package/table-view/model.js +1 -1
  122. package/table-view/mount.js +1 -1
  123. package/table-view/panel.js +1 -1
  124. package/table-view/pivot-spec.js +1 -0
  125. package/table-view/pivot.js +1 -1
  126. package/table-view/public.d.ts +277 -28
  127. package/table-view/reader.worker.js +1 -1
  128. package/table-view/remote.js +1 -1
  129. package/table-view/row-drag.js +1 -0
  130. package/table-view/sparkline.js +1 -0
  131. package/table-view/state-check.js +1 -0
  132. package/table-view/table-css.js +380 -0
  133. package/table-view/version.js +1 -1
  134. package/ui/dialogs.js +3 -3
  135. package/ui/menu-base.js +1 -1
  136. package/ui/protection-ui.js +1 -1
@@ -1 +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};
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,{host:n=!1}={}){const s=typeof e=="string"?this.column(e):e;if(!s)throw new m(`No field ${e} in ${this.name}`);if(s.computed)throw new m(_("The {field} field is calculated, so it can't be edited.",{field:s.caption}));if(s.readOnly&&!n)throw new m(_("The {field} field is read-only.",{field:s.caption}));const r=s.coerce(i),o=s.get(t);if(G(o,r))return!1;if(s.validator!==null){const h=Y(s,r,t);if(h)throw new m(h)}if(s.required&&(r===null||r===""))throw new m(_("The {field} field can't be blank.",{field:s.caption}));return this.tracking&&this.state[t]!==u.INSERTED&&this._track(t,s,o,r),s.put(t,r),s.revision++,this._dropIndexOf(s),this.triggers.length>0&&this._runTriggers(t,!1),this._afterEdit(t,s),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};
@@ -1 +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};
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,o,l,a){const s=Math.min(a,o/2,l/2);n.beginPath(),n.moveTo(i+s,e),n.lineTo(i+o-s,e),n.quadraticCurveTo(i+o,e,i+o,e+s),n.lineTo(i+o,e+l-s),n.quadraticCurveTo(i+o,e+l,i+o-s,e+l),n.lineTo(i+s,e+l),n.quadraticCurveTo(i,e+l,i,e+l-s),n.lineTo(i,e+s),n.quadraticCurveTo(i,e,i+s,e),n.closePath()}function an(n,i,e,o,l,a,s,u){if(!a||a==="solid")return;n.save(),n.beginPath(),n.rect(i,e,o,l),n.clip(),n.strokeStyle=s,n.fillStyle=s,n.lineWidth=Math.max(1,u*.75);const t=5*u;if(a==="dots")for(let r=i;r<i+o;r+=t)for(let f=e;f<e+l;f+=t)n.fillRect(r,f,Math.max(1,u),Math.max(1,u));else{n.beginPath();for(let r=-l;r<o;r+=t)n.moveTo(i+r,e+l),n.lineTo(i+r+l,e);n.stroke()}n.restore()}function dn(n,i,e,o){let a=n.taskbarStyles[e]??null;const s=n.taskbarRules;for(let u=0;u<s.length;u++){const t=s[u];if(t.type&&t.type!==e)continue;let r=!0;if(t.formula){let f=o[u];f===void 0&&(f=mn(n.table,t.formula),o[u]=f);const S=f.get(i);r=S===!0||typeof S=="number"&&S!==0}r&&(a=a===null?t.style:{...a,...t.style})}return a}function rn(n,i,e,o,l,a,s,u){if(!i)return;const t=o+l/2,r=l*.75,f=u?1:-1;n.fillStyle=a,n.beginPath(),i==="diamond"?(n.moveTo(e,t-r),n.lineTo(e+r,t),n.lineTo(e,t+r),n.lineTo(e-r,t)):i==="triangle"?(n.moveTo(e,t-r),n.lineTo(e+f*r,t),n.lineTo(e,t+r)):i==="circle"?n.arc(e,t,r*.8,0,Math.PI*2):n.rect(e-s*1.5,o-s,3*s,l+2*s),n.closePath(),n.fill()}function Mn(n,i,e,o=null){const l=e.schedule;if(!l)return;const{dpr:a}=i,{zoom:s}=i,u=o?.displayCols.scale??1;for(const t of cn(i,o)){n.save(),n.beginPath(),n.rect(t.x*a,t.y*a,t.w*a,t.h*a),n.clip();const r=m=>(t.x+(m*u-t.originX)*s)*a,f=m=>(t.y+(m-t.originY)*s)*a,S=s*a,{rows:h,cols:C}=e,d=t.originX/u,T=(t.originX+t.w/s)/u,w=t.originY,y=t.originY+t.h/s,g=C.offsetOf(e.timelineStart);if(T>g){const m=t.frozenR?0:Math.max(h.indexAt(w),e.frozenRows),b=t.frozenR?e.frozenRows-1:h.indexAt(y),M=Math.max(w,h.offsetOf(e.frozenRows));(!t.frozenR||t.print)&&fn(n,e,r,f,S,d,T,M,y,t),(!t.frozenR||t.print)&&un(n,e,l,r,f,S,d,T,M,y,m,b),m===0&&!t.print&&(t.frozenR||e.frozenRows===0)&&sn(n,e,r,f,S,d,T),t.print&&w<h.sizeOf(0)&&sn(n,e,r,f,S,d,T),(b>=e.bodyStart||t.frozenR)&&yn(n,e,l,r,f,S,Math.max(m,1),Math.min(b,e.bodyStart+e.view.count-1),d,T),e.nonWorking.mode==="front"&&!t.frozenR&&fn(n,e,r,f,S,d,T,M,y,t,!0),t.frozenR||bn(n,e,l,r,f,S,w,y),e.progressLine.visible&&!t.frozenR&&pn(n,e,l,r,f,S,Math.max(m,1),Math.min(b,e.bodyStart+e.view.count-1))}n.restore()}}function sn(n,i,e,o,l,a,s){const{scale:u,cols:t,colors:r}=i,f=t.offsetOf(i.timelineStart),S=u.tickWidth,h=i.rows.sizeOf(0),C=o(0),d=Math.max(f,a),T=r?.tier??B.tier,w=r?.tierInk??B.tierInk,y=r?.tierLine??B.tierLine;n.fillStyle=T,n.fillRect(e(d),C,e(s)-e(d),h*l),n.textBaseline="middle";const g=Math.round(10.5*l);n.font=`${g}px -apple-system, "Helvetica Neue", Arial, sans-serif`;const m=Math.max(0,Math.floor((a-f)/S)),b=Math.min(u.count-1,Math.floor((s-f)/S)),M=u.tiers,R=h/Math.max(1,M.length),k=Math.max(1,Math.round(l*.75));M.forEach((v,W)=>{const P=W*R,{marks:F}=v;let I=0,c=F.length-1;for(;I<c;){const z=I+c+1>>>1;F[z].tick<=m?I=z:c=z-1}n.textAlign=v.bottom?"center":"left";for(let z=I;z<F.length;z++){const L=F[z];if(L.tick>b)break;const Z=z+1<F.length?F[z+1].tick:u.count,q=f+L.tick*S,D=f+Z*S;n.fillStyle=y,n.fillRect(Math.round(e(q)),o(P),k,R*l),n.fillStyle=w,v.bottom?n.fillText(L.label,e((q+D)/2),o(P+R/2)):(n.save(),n.beginPath(),n.rect(e(q),o(P),e(D)-e(q),R*l),n.clip(),n.fillText(L.label,e(Math.max(q,a)+4),o(P+R/2)),n.restore())}n.fillStyle=y,n.fillRect(e(d),o(P+R)-k,e(s)-e(d),k)})}function fn(n,i,e,o,l,a,s,u,t,r,f=!1){const{scale:S,cols:h,calendar:C,nonWorking:d}=i;if(r.frozenR||d.mode==="none"||d.mode==="front"!==f)return;const{unit:T}=S.bottomTier;if(T!=="day"&&T!=="hour"&&T!=="minute")return;const w=h.offsetOf(i.timelineStart),y=S.tickWidth,g=Math.max(0,Math.floor((a-w)/y)),m=Math.min(S.count-1,Math.floor((s-w)/y));n.fillStyle=d.color;const b=n.globalCompositeOperation;!f&&n.fillRect&&!r.print&&(n.globalCompositeOperation="multiply");for(let M=g;M<=m;M++){const R=S.ticks[M];(T==="day"?C.isWorkDay(R):C.isWorkTime(R+1e-6))||(n.fillRect(e(w+M*y),o(u),e(w+(M+1)*y)-e(w+M*y),(t-u)*l),d.pattern&&d.pattern!=="solid"&&(n.globalCompositeOperation=b,an(n,e(w+M*y),o(u),e(w+(M+1)*y)-e(w+M*y),(t-u)*l,d.pattern,"#b8b8b8",l),!f&&!r.print&&(n.globalCompositeOperation="multiply"),n.fillStyle=d.color))}n.globalCompositeOperation=b}function un(n,i,e,o,l,a,s,u,t,r,f,S){const{scale:h,cols:C,gridlines:d,rows:T}=i,w=Math.max(1,Math.round(a*.75));if(d.interval>0){const y=C.offsetOf(i.timelineStart),g=h.tickWidth,m=Math.max(0,Math.floor((s-y)/g)),b=Math.min(h.count-1,Math.floor((u-y)/g));n.fillStyle=d.intervalColor;for(let M=m-m%d.interval;M<=b;M+=d.interval)n.fillRect(o(y+M*g),l(t),w,(r-t)*a)}if(d.rowInterval>0){n.fillStyle=d.rowColor;const y=Math.max(i.bodyStart,f);for(let g=y-(y-i.bodyStart)%d.rowInterval;g<=S;g+=d.rowInterval)n.fillRect(o(s),l(T.offsetOf(g)),o(u)-o(s),w)}}function Y(n,i,e,o,l,a,s){n.strokeStyle=l,n.lineWidth=Math.max(1,a),n.setLineDash(s.map(u=>u*a)),n.beginPath(),n.moveTo(i,e),n.lineTo(i,o),n.stroke(),n.setLineDash([])}function bn(n,i,e,o,l,a,s,u){const{gridlines:t}=i,r=l(s),f=l(u);i.showToday&&t.current!==!1&&Y(n,o(i.xOfDate(i.today)),r,f,B.today,a,[4,3]),t.status&&i.statusDate!==null&&Y(n,o(i.xOfDate(i.statusDate)),r,f,"#7a4fb5",a,[2,2]),t.projectStart&&Y(n,o(i.xOfDate(e.projectStart)),r,f,"#2f6fb3",a,[6,3]),t.projectFinish&&Y(n,o(i.xOfDate(e.projectFinish)),r,f,"#2f6fb3",a,[6,3])}function pn(n,i,e,o,l,a,s,u){const{progressLine:t,rows:r,table:f,fields:S}=i,h=t.reference==="current"?i.today:i.statusDate??i.today,C=i.xOfDate(h),d=f.column(S.progress)?.data,T=[];for(let m=s;m<=u;m++){const b=i.recordAtRow(m);if(b<0||b>=e.rows||e.isSummary[b]===1||e.momentStart[b]===1/0)continue;const M=i.xOfDate(e.momentStart[b]),R=i.xOfDate(e.momentFinish[b]),k=d?d[b]:0,v=k===k?k:0,W=v>=1&&e.momentFinish[b]<=h||v<=0&&e.momentStart[b]>=h;T.push({x:W?C:M+(R-M)*v,y:r.offsetOf(m)+r.sizeOf(m)/2,row:m})}n.strokeStyle=t.color,n.fillStyle=t.color,n.lineWidth=Math.max(1,a*(t.width??1)),n.beginPath();let w=!1,y=null;const g=(m,b)=>{w?n.lineTo(o(m),l(b)):(n.moveTo(o(m),l(b)),w=!0)};for(const m of T){if(t.returnToAnchor){const b=m.y-r.sizeOf(m.row)/2;g(C,b),t.path==="square"&&g(m.x,b),g(m.x,m.y),t.path==="square"&&g(m.x,b+r.sizeOf(m.row)),g(C,b+r.sizeOf(m.row))}else y&&t.path==="square"&&g(y.x,m.y),g(m.x,m.y);y=m}n.stroke();for(const m of T)n.beginPath(),n.arc(o(m.x),l(m.y),2.2*a,0,Math.PI*2),n.fill();T.length>0&&t.showDate!==!1&&(n.font=`${Math.round(10*a)}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textAlign="center",n.textBaseline="bottom",n.fillText(ln("d-mmm").number(Math.floor(h)),o(C),l(T[0].y-r.sizeOf(T[0].row)/2)))}const V=(n,i,e,o)=>{if(!e)return"";const l=n.table.column(e);if(!l)return String(e);const a=l.get(i);if(a==null)return"";if(typeof a=="number"){const s=o??l.format;return s&&s!=="General"?ln(s).number(a):String(a)}return typeof a=="object"?a.code:String(a)};function yn(n,i,e,o,l,a,s,u,t,r){const{table:f,view:S,fields:h,rows:C,layoutOptions:d,colors:T}=i,w=f.column(h.progress)?.data,y=f.column(h.name),g=f.column(h.resource),m=i.showBaseline?f.column(h.deadline)?.data:null,b=i.showBaseline?f.column(h.baselineStart)?.data:null,M=i.showBaseline?f.column(h.baselineFinish)?.data:null,R=Math.round(11*a);n.font=`${R}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textBaseline="middle",n.textAlign="left";const k=i.bodyStart+S.count-1;i.showLinks&&d.linkMode!=="noLinks"&&Sn(n,i,e,o,l,a,s,Math.min(u,k));const v=[],W=d.roundToDays,P=T?.bar??B.bar,F=T?.barDone??B.barDone;for(let I=s;I<=u&&I<=k;I++){const c=i.recordAtRow(I);if(c<0||c>=e.rows||e.momentStart[c]===1/0)continue;const z=C.offsetOf(I),L=C.sizeOf(I),Z=W?Math.floor(e.momentStart[c]):e.momentStart[c],q=W?Math.ceil(e.momentFinish[c]):e.momentFinish[c],D=i.xOfDate(Z),H=i.xOfDate(q);if(H<t-300||D>r+40)continue;const E=e.isSummary[c]===1,j=!E&&e.duration[c]===0,$=i.showCritical&&e.critical[c]===1,K=f.column(h.manual)?.data[c]===1,p=dn(i,c,E?"summary":j?"milestone":K?"manual":$?"critical":"task",v),_=d.barHeight??L-8-(b?2:0),U=z+(L-_)/2-(b?1:0);if(b&&b[c]===b[c]&&!E){const A=i.xOfDate(b[c]),O=i.xOfDate(M[c]+(f.column(h.baselineFinish)&&e.calOf(c).fullDays?1:0));n.fillStyle=i.taskbarStyles.baseline?.fill??B.baseline,n.fillRect(o(A),l(z+L-4),Math.max(2,o(O)-o(A)),Math.max(2,2*a))}if(E){const A=p?.fill??($?B.criticalDone:T?.summary??B.summary);n.fillStyle=A;const O=U+1,N=Math.max(3,_*.45);n.fillRect(o(D),l(O),Math.max(2,o(H)-o(D)),N*a);const J=Math.min(5,Math.max(2,(H-D)/2)),G=N+3;n.beginPath(),n.moveTo(o(D),l(O)),n.lineTo(o(D+J),l(O)),n.lineTo(o(D),l(O+G)),n.closePath(),n.moveTo(o(H),l(O)),n.lineTo(o(H-J),l(O)),n.lineTo(o(H),l(O+G)),n.closePath(),n.fill()}else if(j){const A=z+L/2,O=Math.min(L/2-2,6);n.fillStyle=p?.fill??($?B.critical:B.milestone),n.beginPath(),n.moveTo(o(D),l(A-O)),n.lineTo(o(D+O),l(A)),n.lineTo(o(D),l(A+O)),n.lineTo(o(D-O),l(A)),n.closePath(),n.fill()}else{const A=Math.max(3/a,H-D),O=o(D),N=l(U),J=o(D+A)-O,G=_*a,x=p?.fill??($?B.critical:K?"#7fa8d1":P);n.fillStyle=x,tn(n,O,N,J,G,2*a),n.fill(),p?.pattern&&an(n,O,N,J,G,p.pattern,p.patternColor??"#ffffff",a),K&&!p&&(n.strokeStyle=F,n.lineWidth=Math.max(1,a*.75),n.strokeRect(O,N,J,G));const en=w?w[c]:0;en>0&&(n.fillStyle=p?.progressFill??($?B.criticalDone:F),tn(n,O,N,J*Math.min(1,en),G,2*a),n.fill()),p?.startShape&&rn(n,p.startShape,O,N,G,p.shapeColor??x,a,!1),p?.endShape&&rn(n,p.endShape,O+J,N,G,p.shapeColor??x,a,!0)}if(m&&m[c]===m[c]){const A=i.xOfDate(m[c]+1),O=e.momentFinish[c]>m[c]+1;n.strokeStyle=B.deadline,n.lineWidth=Math.max(1,(O?2:1)*a),n.beginPath(),n.moveTo(o(A),l(z+2)),n.lineTo(o(A),l(z+L-2)),n.stroke(),n.fillStyle=B.deadline,n.beginPath(),n.moveTo(o(A-3),l(z+2)),n.lineTo(o(A+3),l(z+2)),n.lineTo(o(A),l(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,c,p.textRight,d.barDateFormat),o(H+X),l(z+L/2)),p.textInside&&(n.save(),n.beginPath(),n.rect(o(D),l(U),o(H)-o(D),_*a),n.clip(),n.fillStyle=p.insideColor??"#ffffff",n.fillText(V(i,c,p.textInside,d.barDateFormat),o(D+3),l(z+L/2)),n.restore()),n.textAlign="right",p.textLeft&&n.fillText(V(i,c,p.textLeft,d.barDateFormat),o(D-X),l(z+L/2)),n.textAlign="center",p.textTop&&(n.textBaseline="bottom",n.fillText(V(i,c,p.textTop,d.barDateFormat),o((D+H)/2),l(U))),p.textBottom&&(n.textBaseline="top",n.fillText(V(i,c,p.textBottom,d.barDateFormat),o((D+H)/2),l(U+_))),n.textAlign="left",n.textBaseline="middle";else if(i.showLabels){const O=(g&&g.kind(c)===on?g.get(c):null)??((E||j)&&y.kind(c)===on?y.get(c):"");O&&(n.fillStyle=nn,n.fillText(O,o(H+X),l(z+L/2)))}}}function Sn(n,i,e,o,l,a,s,u){const{rows:t,layoutOptions:r}=i,f=i.linkIndex(),{outStart:S,outList:h,inStart:C,inList:d,from:T,to:w,type:y}=f,g=new Set;n.lineWidth=Math.max(1,a);const m=r.linkMode==="toEnd",b=R=>{const k=i.rowOfRecord(R);return k<0?null:t.offsetOf(k)+t.sizeOf(k)/2},M=R=>{if(g.has(R))return;g.add(R);const k=T[R],v=w[R],W=b(k),P=b(v);if(W===null||P===null)return;const F=y[R],I=i.xOfDate(F===0||F===2?e.momentFinish[k]:e.momentStart[k]),c=i.xOfDate(F===0||F===1?e.momentStart[v]:e.momentFinish[v]),L=i.showCritical&&e.critical[k]===1&&e.critical[v]===1&&e.isSummary[k]===0&&e.isSummary[v]===0?B.linkCritical:B.link;n.strokeStyle=L,n.fillStyle=L;const q=F===0||F===1?1:-1,D=F===0||F===2?1:-1,H=7;n.beginPath(),n.moveTo(o(I),l(W));const E=I+D*H,j=c-q*H,$=W+(P>W?1:-1)*(t.defaultSize/2);if(!m&&F===0&&c>=I+2){const K=(P>W?-1:1)*Math.min(4,t.defaultSize/2-2),Q=c+3;n.lineTo(o(Q),l(W)),n.lineTo(o(Q),l(P+K-(P>W?3:-3))),n.stroke();const p=P+K,_=P>W?1:-1;n.beginPath(),n.moveTo(o(Q),l(p)),n.lineTo(o(Q-3),l(p-_*4)),n.lineTo(o(Q+3),l(p-_*4)),n.closePath(),n.fill();return}q===1&&j>=E||q===-1&&j<=E?(n.lineTo(o(j),l(W)),n.lineTo(o(j),l(P))):(n.lineTo(o(E),l(W)),n.lineTo(o(E),l($)),n.lineTo(o(j),l($)),n.lineTo(o(j),l(P))),n.lineTo(o(c-q*3),l(P)),n.stroke(),n.beginPath(),n.moveTo(o(c),l(P)),n.lineTo(o(c-q*4),l(P-3)),n.lineTo(o(c-q*4),l(P+3)),n.closePath(),n.fill()};for(let R=s;R<=u;R++){const k=i.recordAtRow(R);if(!(k<0||k>=e.rows)){for(let v=C[k];v<C[k+1];v++)M(d[v]);for(let v=S[k];v<S[k+1];v++)M(h[v])}}}export{B as BAR_COLORS,dn as barStyleOf,Mn as paintGantt,cn as viewAreas};
@@ -1 +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};
1
+ import"./query-function.js";import{Sheet as u}from"../core/sheet.js";import{DataManager as l}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as m}from"./table-sheet.js";import{createPlanTable as c,GanttSheet as f}from"./gantt.js";import{ReportTemplate as g}from"./report.js";import{TableBinding as p}from"./bind.js";import{CellPathBinding as S,RowsBinding as b}from"./path-binding.js";import{attachDataEntry as _}from"./report-entry.js";import{buildDataSheetPackage as w,dataSheetsFromJSON as v,dataSheetsToJSON as T,readDataSheetPackage as k}from"./persist.js";class J{constructor(e){this.book=e,this.manager=new l(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,d){const{sheet:a}=i;if(!(a.routeInput!==void 0&&a.routeInput(i,r,n,h)))return t.call(this,i,r,n,h,d)}}_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 m(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):c(this.manager,this._freeTable(`${e} Tasks`),i),n=new f(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 u(this._uniqueName(e));let i=null;return this._insert(s,t.activate!==!1,()=>{i=new g(this.manager,s,t),this.reports.push(i),this.onSheetAdded?.(s)}),i}bindPaths(e,t=null,s={}){const i=new S(this.book,e,t,s);return this._registerBinding(i),i}bindRows(e,t,s,i={}){const r=new b(this.book,e,t,s,i);return this._registerBinding(r),r}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return _(this.book,e,e.output)}toJSON(){return T(this)}fromJSON(e){return v(e,this),this}bindTable(e,t,s,i={}){const r=new p(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 w(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 k(e,this)}}export{J as DataSheets};
@@ -1,2 +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};
1
+ import{FORMULA as k,STR as q}from"../core/sheet.js";import{cellRef as B,colName as F,MAX_COLS as m}from"../core/address.js";import{translateFormula as T}from"../core/formula-refs.js";import{createTable as R,resizeTable as v}from"../core/tables.js";import{hookSheet as U,rawCells as p,TableBinding as $,unhookSheet as E,valueOfWrite as L,writeRaw as O}from"./bind.js";import{DataError as S}from"./data.js";import{getPath as y,setPath as w}from"./remote.js";const g=(i,t)=>i*m+t;function _(i){const t=i.book.dataSheets;t&&(t.bindings=t.bindings.filter(e=>e!==i)),i.unbind()}function C(i,t){const e=i.usedRange(),{captions:s,rows:r}=i.exportRows();switch(t){case"json":return JSON.stringify(r,null,2);case"csv":{const o=n=>{const h=n==null?"":String(n);return/[",\n]/.test(h)?`"${h.replace(/"/g,'""')}"`:h};return[s.map(o).join(","),...r.map(n=>s.map(h=>o(n[h])).join(","))].join(`\r
2
+ `)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class A{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},U(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,L(this.book.strings,s,r))}}class H extends A{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,M(n),{overLimitAsText:!0})}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const M=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class N extends A{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??z(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((a,l)=>{const f=s.col+l;a.width&&t.cols.setSize(f,a.width),this.headerRows&&p.setCell.call(t,s.row,f,q,e.strings.add(a.caption??M(a.path??`Column${l+1}`)));const b=this._styleOf(a.format);if(a.formula){const d=String(a.formula).replace(/^=/,"");for(let u=0;u<r.length;u++)p.setCell.call(t,n+u,f,k,0),p.setFormula.call(t,n+u,f,{f:T(d,u,0),typed:!0}),b&&p.setStyle.call(t,n+u,f,b);return}for(let d=0;d<r.length;d++){const u=y(r[d],a.path);O(t,e.strings,n+d,f,u===void 0?null:u),b&&t.cellStyle(n+d,f)===0&&p.setStyle.call(t,n+d,f,b)}});for(let a=r.length;a<this.lastRows;a++)for(let l=0;l<o.length;l++)p.setCell.call(t,n+a,s.col+l,0,0),p.setFormula.call(t,n+a,s.col+l,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((a,l)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+l,s.col+l)}),this._notify(c,x),this.table&&this.book.engine){const a=this.anchor,l={r0:a.row,c0:a.col,r1:a.row+Math.max(1,r.length),c1:a.col+o.length-1};this.table.r1!==l.r1&&v(this.book,this.table,l)}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function z(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}N.prototype.exportAs=function(t){return C(this,t)},$.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function I(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=I(e);return t}return null}export{H as CellPathBinding,N as RowsBinding,B as cellRef,F as colName,C as exportBinding,I as sampleOf,j as schemaOf};
@@ -1 +1 @@
1
- import{formulaHelper as w}from"./view.js";import{colName as k}from"../core/address.js";import{tableColors as $}from"../core/tables.js";import{ROW as S}from"./data.js";import{tint as s}from"../core/color.js";const m={headerFill:"#107c41",headerInk:"#ffffff",band:"#f1f8f4",group:["#d9ead3","#e8f3e4","#f1f8ee","#f7fbf5"],footer:"#f2f2f2",total:"#e4e4e4",pinned:"#fff7dc",rule:"#8fbfa3",tier:"#f3f3f3",tierInk:"#3b3b3b",tierLine:"#d0d0d0",bar:"#4a90d9",barDone:"#22598f",summary:"#404040"};function c(e){return{...m,headerFill:e,band:s(e,.93),group:[s(e,.75),s(e,.85),s(e,.9),s(e,.95)],rule:s(e,.45),bar:s(e,.15),barDone:s(e,-.35)}}const E={green:m,blue:c("#2f6fb3"),orange:c("#c56a00"),red:c("#b23a3a"),purple:c("#7a4fb5"),teal:c("#1f8a8a"),gray:{...c("#5f6368"),bar:"#7c7f85",barDone:"#3c4043"},plain:{...m,headerFill:"#f3f3f3",headerInk:"#242424",band:"#fafafa",group:["#ececec","#f2f2f2","#f6f6f6","#fafafa"],rule:"#c8c8c8"}};function V(e,t){if(!e)return m;if(E[e])return E[e];const r=$(e,t);if(!r)return m;const a=r.headerFill??r.rule??"#404040";return{...c(a),headerFill:r.headerFill??"#ffffff",headerInk:r.headerFill?r.headerInk??"#ffffff":"#000000",band:r.band??m.band}}const y=e=>{const t={};for(const r of["fill","color","bold","italic","underline","strike","numFmt","hAlign","vAlign","indent","wrap","fontSize","fontName","borders"])e[r]!==void 0&&(t[r]=e[r]);return t};class D{constructor(t){this.sheet=t,this.table=t.table,this.list=[],this.overlays={};for(const r of t.view.spec.rules){const a=y(r.style??{});if(r.state==="hover"||r.state==="selected"){this.overlays[r.state]=a.fill??"#107c41";continue}const u={rule:r,patch:a,key:JSON.stringify(a),fields:r.fields?new Set(r.fields):null,helper:null};r.formula&&(u.helper=w(this.table,r.formula)),this.list.push(u)}}get active(){return this.list.length>0}apply(t,r,a,u){let o=t;const{table:n}=this,{styles:i}=this.sheet.book;for(const l of this.list){if(l.fields!==null&&!l.fields.has(a.field))continue;let f;if(l.helper!==null){const d=l.helper.get(r);f=d===!0||typeof d=="number"&&d!==0}else switch(l.rule.state){case"dirty":f=n.state[r]===S.UPDATED&&(n.isCellEdited(r,a.col)||l.fields===null);break;case"inserted":f=n.state[r]===S.INSERTED;break;case"pinned":f=u;break;case"readOnly":f=a.readOnly;break;case"required":f=a.col.required===!0&&a.col.kind(r)===0;break;default:f=!1}f&&(o=i.derive(o,l.patch,l.key))}return o}}const q={greaterThan:"greaterThan",lessThan:"lessThan",greaterThanOrEqual:"greaterThanOrEqual",lessThanOrEqual:"lessThanOrEqual",equal:"equal",notEqual:"notEqual",between:"between",notBetween:"notBetween"},v=e=>typeof e=="number"?String(e):`"${String(e).replace(/"/g,'""')}"`;function R(e,t,r,a){let u=null;t.style&&(e.dxfs||(e.dxfs=[]),e.dxfs.push(y(t.style)),u=e.dxfs.length-1);const o={priority:r,dxfId:u,stopIfTrue:t.stopIfTrue===!0};switch(t.type){case"cellValue":return{...o,type:"cellIs",operator:q[t.operator]??"equal",formulas:[t.value,t.value2].filter(n=>n!==void 0).map(v)};case"text":{const n=t.operator??"contains",i=String(t.value??""),l=v(i);return n==="beginsWith"?{...o,type:"beginsWith",operator:"beginsWith",text:i,formulas:[`LEFT(${a},${i.length})=${l}`]}:n==="endsWith"?{...o,type:"endsWith",operator:"endsWith",text:i,formulas:[`RIGHT(${a},${i.length})=${l}`]}:n==="notContains"?{...o,type:"notContainsText",operator:"notContains",text:i,formulas:[`ISERROR(SEARCH(${l},${a}))`]}:{...o,type:"containsText",operator:"containsText",text:i,formulas:[`NOT(ISERROR(SEARCH(${l},${a})))`]}}case"date":return{...o,type:"timePeriod",timePeriod:t.period??"today",formulas:[]};case"top":case"bottom":return{...o,type:"top10",rank:t.rank??10,percent:t.percent===!0,bottom:t.type==="bottom"};case"average":return{...o,type:"aboveAverage",aboveAverage:t.above!==!1,equalAverage:t.equal===!0};case"duplicate":return{...o,type:"duplicateValues"};case"unique":return{...o,type:"uniqueValues"};case"blank":return{...o,type:"containsBlanks",formulas:[`LEN(TRIM(${a}))=0`]};case"notBlank":return{...o,type:"notContainsBlanks",formulas:[`LEN(TRIM(${a}))>0`]};case"errors":return{...o,type:"containsErrors",formulas:[`ISERROR(${a})`]};case"formula":return{...o,type:"expression",formulas:[String(t.formula).replace(/^=/,"")]};case"dataBar":return{...o,type:"dataBar",dataBar:{cfvo:[{type:"min"},{type:"max"}],color:T(t.color??"#638EC6"),showValue:t.showValue!==!1}};case"colorScale":{const n=t.colors??["#F8696B","#FFEB84","#63BE7B"],i=n.length===2?[{type:"min"},{type:"max"}]:[{type:"min"},{type:"percentile",val:"50"},{type:"max"}];return{...o,type:"colorScale",colorScale:{cfvo:i,colors:n.map(T)}}}case"iconSet":{const n=t.name??"3TrafficLights1",i=Number(n[0])||3,l=[];for(let f=0;f<i;f++)l.push({type:"percent",val:String(Math.round(f*100/i))});return{...o,type:"iconSet",iconSet:{name:n,cfvo:l,reverse:t.reverse===!0,showValue:t.showValue!==!1}}}default:return null}}const T=e=>({rgb:`FF${e.slice(1).toUpperCase()}`});function B(e,t){const r={sqref:t,allowBlank:e.allowBlank!==!1,showErrorMessage:!0,showInputMessage:!!e.prompt,promptTitle:e.promptTitle,prompt:e.prompt,errorStyle:e.errorStyle??"stop",errorTitle:e.errorTitle,error:e.message};switch(e.type){case"list":return{...r,type:"list",formula1:e.formula??`"${(e.items??[]).join(",")}"`,showDropDown:!0};case"number":case"decimal":case"whole":case"date":case"time":case"textLength":{const a=e.type==="number"?e.whole?"whole":"decimal":e.type;if(e.operator){const u=e.operator==="between"||e.operator==="notBetween";return{...r,type:a,operator:e.operator,formula1:String(e.min??e.value??0),...u?{formula2:String(e.max??0)}:{}}}return e.min!==void 0&&e.max!==void 0?{...r,type:a,operator:"between",formula1:String(e.min),formula2:String(e.max)}:e.min!==void 0?{...r,type:a,operator:"greaterThanOrEqual",formula1:String(e.min)}:e.max!==void 0?{...r,type:a,operator:"lessThanOrEqual",formula1:String(e.max)}:null}case"custom":return e.formula?{...r,type:"custom",formula1:String(e.formula).replace(/^=/,"")}:null;default:return null}}function M(e){const{view:t,book:r}=e,a=e.bodyStart+1,u=Math.max(a,e.bodyStart+t.count),o=[],n=[];let i=1;t.columns.forEach((d,x)=>{const p=k(x),b=`${p}${a}:${p}${u}`;for(const h of d.conditionalFormats??[]){const g=R(r,h,i++,`${p}${a}`);g&&o.push({sqref:b,rules:[g]})}if(d.validator){const h=B(d.validator,b);h&&n.push(h)}});const l=e.cf&&e.cf.length>0;(o.length>0||l)&&(e.cf=o,e.cfChanged=!0,e.cfEval=void 0);const f=e.validations&&e.validations.length>0;(n.length>0||f)&&(e.validations=n,e.validationsChanged=!0)}export{D as StyleRules,E as THEMES,M as applyColumnRules,y as stylePatch,V as themeColors};
1
+ import{formulaHelper as w}from"./view.js";import{colName as k}from"../core/address.js";import{tableColors as $}from"../core/tables.js";import{ROW as S}from"./data.js";import{tint as s}from"../core/color.js";const c={headerFill:"#107c41",headerInk:"#ffffff",band:"#f1f8f4",group:["#d9ead3","#e8f3e4","#f1f8ee","#f7fbf5"],footer:"#f2f2f2",total:"#e4e4e4",pinned:"#fff7dc",rule:"#8fbfa3",tier:"#f3f3f3",tierInk:"#3b3b3b",tierLine:"#d0d0d0",bar:"#4a90d9",barDone:"#22598f",summary:"#404040"};function m(e){return{...c,headerFill:e,band:s(e,.93),group:[s(e,.75),s(e,.85),s(e,.9),s(e,.95)],rule:s(e,.45),bar:s(e,.15),barDone:s(e,-.35)}}const E={green:c,blue:m("#2f6fb3"),orange:m("#c56a00"),red:m("#b23a3a"),purple:m("#7a4fb5"),teal:m("#1f8a8a"),gray:{...m("#5f6368"),bar:"#7c7f85",barDone:"#3c4043"},plain:{...c,headerFill:"#f3f3f3",headerInk:"#242424",band:"#fafafa",group:["#ececec","#f2f2f2","#f6f6f6","#fafafa"],rule:"#c8c8c8"}};function V(e,t){if(!e)return c;if(E[e])return E[e];const r=$(e,t);if(!r)return c;const a=r.headerFill??r.rule??"#404040";return{...m(a),headerFill:r.headerFill??"#ffffff",headerInk:r.headerFill?r.headerInk??"#ffffff":"#000000",band:r.band??c.band}}const y=e=>{const t={};for(const r of["fill","color","bold","italic","underline","strike","numFmt","hAlign","vAlign","indent","wrap","fontSize","fontName","borders"])e[r]!==void 0&&(t[r]=e[r]);return t};class D{constructor(t){this.sheet=t,this.table=t.table,this.list=[],this.overlays={};for(const r of t.view.spec.rules){const a=y(r.style??{});if(r.state==="hover"||r.state==="selected"){this.overlays[r.state]=a.fill??"#107c41";continue}const u={rule:r,patch:a,key:JSON.stringify(a),fields:r.fields?new Set(r.fields):null,helper:null};r.formula&&(u.helper=w(this.table,r.formula)),this.list.push(u)}}get active(){return this.list.length>0}apply(t,r,a,u){let o=t;const{table:n}=this,{styles:i}=this.sheet.book;for(const l of this.list){if(l.fields!==null&&!l.fields.has(a.field))continue;let f;if(l.helper!==null){const d=l.helper.get(r);f=d===!0||typeof d=="number"&&d!==0}else switch(l.rule.state){case"dirty":f=n.state[r]===S.UPDATED&&(n.isCellEdited(r,a.col)||l.fields===null);break;case"inserted":f=n.state[r]===S.INSERTED;break;case"pinned":f=u;break;case"readOnly":f=a.readOnly;break;case"required":f=a.col.required===!0&&a.col.kind(r)===0;break;default:f=!1}f&&(o=i.derive(o,l.patch,l.key))}return o}}const q={greaterThan:"greaterThan",lessThan:"lessThan",greaterThanOrEqual:"greaterThanOrEqual",lessThanOrEqual:"lessThanOrEqual",equal:"equal",notEqual:"notEqual",between:"between",notBetween:"notBetween"},v=e=>typeof e=="number"?String(e):`"${String(e).replace(/"/g,'""')}"`;function R(e,t,r,a){let u=null;t.style&&(e.dxfs||(e.dxfs=[]),e.dxfs.push(y(t.style)),u=e.dxfs.length-1);const o={priority:r,dxfId:u,stopIfTrue:t.stopIfTrue===!0};switch(t.type){case"cellValue":return{...o,type:"cellIs",operator:q[t.operator]??"equal",formulas:[t.value,t.value2].filter(n=>n!==void 0).map(v)};case"text":{const n=t.operator??"contains",i=String(t.value??""),l=v(i);return n==="beginsWith"?{...o,type:"beginsWith",operator:"beginsWith",text:i,formulas:[`LEFT(${a},${i.length})=${l}`]}:n==="endsWith"?{...o,type:"endsWith",operator:"endsWith",text:i,formulas:[`RIGHT(${a},${i.length})=${l}`]}:n==="notContains"?{...o,type:"notContainsText",operator:"notContains",text:i,formulas:[`ISERROR(SEARCH(${l},${a}))`]}:{...o,type:"containsText",operator:"containsText",text:i,formulas:[`NOT(ISERROR(SEARCH(${l},${a})))`]}}case"date":return{...o,type:"timePeriod",timePeriod:t.period??"today",formulas:[]};case"top":case"bottom":return{...o,type:"top10",rank:t.rank??10,percent:t.percent===!0,bottom:t.type==="bottom"};case"average":return{...o,type:"aboveAverage",aboveAverage:t.above!==!1,equalAverage:t.equal===!0};case"duplicate":return{...o,type:"duplicateValues"};case"unique":return{...o,type:"uniqueValues"};case"blank":return{...o,type:"containsBlanks",formulas:[`LEN(TRIM(${a}))=0`]};case"notBlank":return{...o,type:"notContainsBlanks",formulas:[`LEN(TRIM(${a}))>0`]};case"errors":return{...o,type:"containsErrors",formulas:[`ISERROR(${a})`]};case"formula":return{...o,type:"expression",formulas:[String(t.formula).replace(/^=/,"")]};case"dataBar":return{...o,type:"dataBar",dataBar:{cfvo:[{type:"min"},{type:"max"}],color:T(t.color??"#638EC6"),showValue:t.showValue!==!1}};case"colorScale":{const n=t.colors??["#F8696B","#FFEB84","#63BE7B"],i=n.length===2?[{type:"min"},{type:"max"}]:[{type:"min"},{type:"percentile",val:"50"},{type:"max"}];return{...o,type:"colorScale",colorScale:{cfvo:i,colors:n.map(T)}}}case"iconSet":{const n=t.name??"3TrafficLights1",i=Number(n[0])||3,l=[];for(let f=0;f<i;f++)l.push({type:"percent",val:String(Math.round(f*100/i))});return{...o,type:"iconSet",iconSet:{name:n,cfvo:l,reverse:t.reverse===!0,showValue:t.showValue!==!1}}}default:return null}}const T=e=>({rgb:`FF${e.slice(1).toUpperCase()}`});function B(e,t){const r={sqref:t,allowBlank:e.allowBlank!==!1,showErrorMessage:!0,showPrompt:!!(e.prompt||e.promptTitle),promptTitle:e.promptTitle,prompt:e.prompt,errorStyle:e.errorStyle??"stop",errorTitle:e.errorTitle,error:e.message};switch(e.type){case"list":return{...r,type:"list",formula1:e.formula??`"${(e.items??[]).join(",")}"`,showDropDown:!0};case"number":case"decimal":case"whole":case"date":case"time":case"textLength":{const a=e.type==="number"?e.whole?"whole":"decimal":e.type;if(e.operator){const u=e.operator==="between"||e.operator==="notBetween";return{...r,type:a,operator:e.operator,formula1:String(e.min??e.value??0),...u?{formula2:String(e.max??0)}:{}}}return e.min!==void 0&&e.max!==void 0?{...r,type:a,operator:"between",formula1:String(e.min),formula2:String(e.max)}:e.min!==void 0?{...r,type:a,operator:"greaterThanOrEqual",formula1:String(e.min)}:e.max!==void 0?{...r,type:a,operator:"lessThanOrEqual",formula1:String(e.max)}:null}case"custom":return e.formula?{...r,type:"custom",formula1:String(e.formula).replace(/^=/,"")}:null;default:return null}}function N(e){const{view:t,book:r}=e,a=e.bodyStart+1,u=Math.max(a,e.bodyStart+t.count),o=[],n=[];let i=1;t.columns.forEach((d,x)=>{const p=k(x),b=`${p}${a}:${p}${u}`;for(const h of d.conditionalFormats??[]){const g=R(r,h,i++,`${p}${a}`);g&&o.push({sqref:b,rules:[g]})}if(d.validator){const h=B(d.validator,b);h&&n.push(h)}});const l=e.cf&&e.cf.length>0;(o.length>0||l)&&(e.cf=o,e.cfChanged=!0,e.cfEval=void 0);const f=e.validations&&e.validations.length>0;(n.length>0||f)&&(e.validations=n,e.validationsChanged=!0)}export{D as StyleRules,E as THEMES,N as applyColumnRules,y as stylePatch,V as themeColors};
@@ -1,3 +1,3 @@
1
- import{crossColumnsOf as B,fillGenerated as K,sliceColumnsOf as W}from"./cross.js";import{BOOL as H,EMPTY as k,ERR as Y,NUM as F,STR as R}from"../core/sheet.js";import{formatGeneral as X,getFormatter as V,partsToSerial as E,serialToParts as x}from"../core/numfmt.js";import{colName as J,MAX_ROWS as U}from"../core/address.js";import{sortByF64 as G,sortByU32 as j,sortColumn as Q}from"./sort.js";import{DataTable as O,keyIndex as Z}from"./data-core.js";import{XlError as tt}from"../calc/values.js";const C={NONE:0,FLATTEN:1,GROUP:2,SORT:3,FILTER:4},et=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wt=["sum","count","countAll","average","min","max","product","stdev","stdevp","var","varp","median","distinct"],vt={sum:"Sum",count:"Count",countAll:"Rows",average:"Average",min:"Min",max:"Max",product:"Product",stdev:"StdDev",stdevp:"StdDevP",var:"Var",varp:"VarP",median:"Median",distinct:"Distinct"},bt={equal:"filter|Equals",notEqual:"Does not equal",gt:"Greater than",gte:"Greater than or equal to",lt:"Less than",lte:"Less than or equal to",between:"Between",notBetween:"Not between",contains:"Contains",notContains:"Does not contain",beginsWith:"Begins with",endsWith:"Ends with",blank:"Is blank",notBlank:"Is not blank",top:"Top N",bottom:"Bottom N",aboveAverage:"Above average",belowAverage:"Below average",today:"Today",yesterday:"Yesterday",tomorrow:"Tomorrow",thisWeek:"This week",thisMonth:"This month",lastMonth:"Last month",thisYear:"This year",lastYear:"Last year"};function P(b,t,e,s,n){if(t==="countAll")return n-s;if(b.stale&&b.table.ensure(b),t==="count"||t==="distinct"){if(t==="count"){let y=0;if(b.isString){const{data:d}=b;for(let g=s;g<n;g++)d[e[g]]>=0&&y++}else if(b.kinds!==null){const{kinds:d}=b;for(let g=s;g<n;g++)d[e[g]]!==k&&y++}else{const{data:d}=b;for(let g=s;g<n;g++){const w=d[e[g]];w===w&&y++}}return y}const p=new Set;for(let y=s;y<n;y++){const d=e[y];b.kind(d)!==k&&p.add(b.raw(d))}return p.size}if(b.isString)return NaN;const{data:r,kinds:l}=b;let a=0,o=0,h=1/0,i=-1/0,u=1,c=0,f=0;const m=t==="stdev"||t==="stdevp"||t==="var"||t==="varp";if(t==="median"){const p=new Float64Array(n-s);let y=0;for(let g=s;g<n;g++){const w=e[g];if(l!==null&&l[w]!==F)continue;const _=r[w];_===_&&(p[y++]=_)}if(y===0)return NaN;const d=p.subarray(0,y).sort();return y%2===1?d[y>>1]:(d[(y>>1)-1]+d[y>>1])/2}for(let p=s;p<n;p++){const y=e[p];if(l!==null&&l[y]!==F)continue;const d=r[y];if(d===d&&(o++,a+=d,d<h&&(h=d),d>i&&(i=d),t==="product"&&(u*=d),m)){const g=d-f;f+=g/o,c+=g*(d-f)}}if(o===0)return NaN;switch(t){case"sum":return a;case"average":return a/o;case"min":return h;case"max":return i;case"product":return u;case"var":return o>1?c/(o-1):NaN;case"varp":return c/o;case"stdev":return o>1?Math.sqrt(c/(o-1)):NaN;case"stdevp":return Math.sqrt(c/o);default:return NaN}}const st=/\bCALCULATE\s*\(\s*(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)\s*(?:,\s*REMOVEFILTERS\s*\(\s*(?:"([^"]*)"|\[@?([^\]]*)\])?\s*\))?\s*\)/gi,nt=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,rt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max",PRODUCT:"product",STDEV:"stdev",STDEVP:"stdevp",VAR:"var",VARP:"varp",MEDIAN:"median"};function it(b,t){const e=Math.floor(t),s=x(e);switch(b){case"today":return[e,e+1];case"yesterday":return[e-1,e];case"tomorrow":return[e+1,e+2];case"thisWeek":return[e-s.weekday,e-s.weekday+7];case"thisMonth":return[E(s.year,s.month,1),s.month===12?E(s.year+1,1,1):E(s.year,s.month+1,1)];case"lastMonth":return[s.month===1?E(s.year-1,12,1):E(s.year,s.month-1,1),E(s.year,s.month,1)];case"thisYear":return[E(s.year,1,1),E(s.year+1,1,1)];case"lastYear":return[E(s.year-1,1,1),E(s.year,1,1)];default:return null}}const ot=()=>{const b=new Date;return E(b.getFullYear(),b.getMonth()+1,b.getDate())};function lt(b,t){const e=t.formula?M(b,t.formula):b.column(t.field);if(!e)return null;b.ensure(e);const s=b.rowCount,n=new Float64Array(s),{data:r,kinds:l}=e;if(e.isString){const{rank:a}=e.ranks();for(let o=0;o<s;o++){const h=r[o];n[o]=h<0?NaN:a[h]}return n}if(l!==null){const{rank:a}=e.ranks();for(let o=0;o<s;o++)switch(l[o]){case F:n[o]=r[o];break;case R:n[o]=1e300+a[r[o]]*1e290;break;case H:n[o]=15e307+r[o]*1e300;break;case Y:n[o]=17e307;break;default:n[o]=NaN}return n}if(t.by&&t.by!=="value"){const a=new Map;for(let o=0;o<s;o++){const h=r[o];if(h!==h){n[o]=NaN;continue}const i=Math.floor(h);let u=a.get(i);if(u===void 0){const c=x(i);switch(t.by){case"year":u=c.year;break;case"quarter":u=c.year*4+Math.floor((c.month-1)/3);break;case"month":u=c.year*12+c.month-1;break;case"week":u=Math.floor((i-1)/7);break;default:u=i}a.set(i,u)}n[o]=u}return n}if(t.size>0){for(let a=0;a<s;a++){const o=r[a];n[a]=o!==o?NaN:Math.floor(o/t.size)}return n}if(t.bins){const{bins:a}=t;for(let o=0;o<s;o++){const h=r[o];let i=NaN;if(h===h)for(let u=0;u<a.length;u++){const c=a[u];if((c.min===void 0||h>=c.min)&&(c.max===void 0||h<c.max)){i=u;break}}n[o]=i}return n}return n.set(r.subarray(0,s)),n}function M(b,t){const e=`__formula:${t}`;let s=b.byName.get(e);return s||(s=b.addHelper({name:e,formula:t,type:"any",hidden:!0,readOnly:!0}),b.manager.formulas.bind(s)),b.ensure(s),s}const D={type:"number",caption:"",computed:!0,stale:!1,isString:!1,kinds:null,data:new Float64Array(0),styles:null,table:null,validator:null,required:!1,kind:()=>k,raw:()=>0,get:()=>null},$=b=>typeof b=="string"?{field:b}:{...b};class at{constructor(t,e={}){this.table=t,this.spec={columns:(e.columns??t.fields.map(s=>s.name)).map($),sort:e.sort??[],filters:e.filters??[],groups:e.groups??[],hierarchy:e.hierarchy??null,pinnedRows:e.pinnedRows??[],totals:e.totals??[],search:e.search??"",rules:e.rules??[],groupLayout:e.groupLayout??"outline",options:e.options??{}},this.name=e.name??null,this.listeners=new Set,this.hooks=null,this.dirty=C.FILTER,this.needsFilter=!1,this.revision=0,this.count=0,this.map=new Int32Array(0),this.filtered=new Int32Array(0),this.filteredCount=0,this.perm=new Int32Array(0),this.inverse=null,this.truncated=!1,this.nodeCount=0,this.nodeStart=new Int32Array(0),this.nodeEnd=new Int32Array(0),this.nodeLevel=new Int8Array(0),this.nodeChild=new Int32Array(0),this.nodeChildEnd=new Int32Array(0),this.nodeParent=new Int32Array(0),this.nodeCollapsed=new Uint8Array(0),this.levelStart=[],this.summaryValues=new Map,this.summariesStale=!1,this.collapsedPaths=new Set,this.collapseFromLevel=1/0,this.treeLevel=null,this.treeHasKids=null,this.treeCollapsed=new Set,this.treeParent=null,this.rollups=new Map,this.pinned=new Int32Array(0),this._columns=null,this._unsubscribe=t.onChange(s=>this._tableChanged(s)),this.refresh()}dispose(){if(this._unsubscribe(),this._crossSources)for(const t of this._crossSources.values())t()}fetch(t=!1){return this.table.fetch(t).then(()=>this)}length(){return this.spec.columns.length}visibleLength(){return this.columns.length}on(t,e){return this.hooks===null&&(this.hooks=new Map),this.hooks.has(t)||this.hooks.set(t,new Set),this.hooks.get(t).add(e),()=>this.hooks.get(t).delete(e)}_fire(t,e){const s=this.hooks?.get(t);if(!s)return!0;let n=!0;for(const r of s)r(e)===!1&&(n=!1);return n}addStyleRule(t,e){this.spec.rules=[...this.spec.rules.filter(s=>s.name!==t),{name:t,...e}],this._rulesChanged()}removeStyleRule(t){this.spec.rules=this.spec.rules.filter(e=>e.name!==t),this._rulesChanged()}clearStyleRules(){this.spec.rules=[],this._rulesChanged()}getStyleRule(t){return t===void 0?this.spec.rules:this.spec.rules.find(e=>e.name===t)}_rulesChanged(){this.revision++,this._emit({type:"columns"})}moveRecords(t,e=-1){const s=this.table.ensureOrderColumn().data,n=new Set(t),r=this.spec.hierarchy?this.perm.subarray(0,this.filteredCount):this.map.subarray(0,this.count).filter(h=>h>=0);let l=1/0,a=-1/0;if(e>=0){l=s[e];for(const h of r)if(!n.has(h)){if(h===e)break;a=s[h]}}else for(const h of r)!n.has(h)&&s[h]>a&&(a=s[h]);a===-1/0&&(a=l===1/0?0:l-t.length-1),l===1/0&&(l=a+t.length+1);const o=(l-a)/(t.length+1);t.forEach((h,i)=>{s[h]=a+o*(i+1)}),this.invalidate(C.FILTER),this.refresh()}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){for(const e of this.listeners)e(t)}get columns(){if(this._columns!==null)return this._columns;const t=[];for(const r of this.spec.columns){if(r.hidden)continue;if(r.special){t.push({def:r,col:D,field:r.field??r.special,special:r.special,caption:r.caption??(r.special==="rowNumber"?"#":""),format:"General",width:r.width??(r.special==="rowNumber"?44:72),pinned:r.pinned===!0,readOnly:!0,align:r.align??null,allowSort:!1,allowFilter:!1});continue}if(r.cross){t.push(...B(this,r,M));continue}const l=this.table.column(r.field);l&&t.push({def:r,col:l,field:r.field,caption:r.caption??l.caption,format:r.format??l.format,width:r.width??l.width??null,pinned:r.pinned===!0,readOnly:r.readOnly===!0||l.readOnly||l.computed,align:r.align??null,allowSort:r.allowSort!==!1,allowFilter:r.allowFilter!==!1,showNullAs:r.showNullAs??l.showNullAs,showEmptyAs:r.showEmptyAs??null,display:r.display??null,style:r.style??null,headerStyle:r.headerStyle??null,headerFit:r.headerFit??"normal",captionPath:r.captionPath??null,cellType:r.cellType??null,validator:r.validator??l.validator,conditionalFormats:r.conditionalFormats??null,sparkline:r.sparkline??null})}this.spec.groups.some(r=>r.summaries?.some(l=>l.slice||l.own))&&t.push(...W(this,M));const e=t.filter(r=>r.pinned),s=e.length>0?[...e,...t.filter(r=>!r.pinned)]:t,n=s.findIndex(r=>r.special==="actions");if(n>0&&s.unshift(...s.splice(n,1)),this._columns=s,this._generated=s.filter(r=>r.fill),this._generated.length>0){const r=this._sourceStamp();(r!==this._crossStamp||this._generated.some(l=>!this._filled?.has(l.col)))&&(K(this,this._generated),this._crossStamp=r,this._filled=new Set(this._generated.map(l=>l.col)))}return this._columns}_useCrossSource(t){t!==this.table&&(this._crossSources||(this._crossSources=new Map),this._crossSources.has(t)||this._crossSources.set(t,t.onChange(()=>this._sourceChanged())))}_sourceStamp(){let t=`${this.table.revision}`;if(this._crossSources)for(const e of this._crossSources.keys())t+=`|${e.revision}`;return t}_syncGenerated(){if(!this._generated||this._generated.length===0||this._sourceStamp()===this._crossStamp)return!1;const e=this._generated.map(n=>n.field).join(`
1
+ import{crossColumnsOf as B,fillGenerated as K,sliceColumnsOf as W}from"./cross.js";import{BOOL as H,EMPTY as T,ERR as Y,NUM as F,STR as R}from"../core/sheet.js";import{formatGeneral as X,getFormatter as V,partsToSerial as E,serialToParts as x}from"../core/numfmt.js";import{colName as J,MAX_ROWS as U}from"../core/address.js";import{sortByF64 as G,sortByU32 as j,sortColumn as Q}from"./sort.js";import{DataTable as O,keyIndex as Z}from"./data-core.js";import{XlError as tt}from"../calc/values.js";const S={NONE:0,FLATTEN:1,GROUP:2,SORT:3,FILTER:4},et=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wt=["sum","count","countAll","average","min","max","product","stdev","stdevp","var","varp","median","distinct"],vt={sum:"Sum",count:"Count",countAll:"Rows",average:"Average",min:"Min",max:"Max",product:"Product",stdev:"StdDev",stdevp:"StdDevP",var:"Var",varp:"VarP",median:"Median",distinct:"Distinct"},_t={equal:"filter|Equals",notEqual:"Does not equal",gt:"Greater than",gte:"Greater than or equal to",lt:"Less than",lte:"Less than or equal to",between:"Between",notBetween:"Not between",contains:"Contains",notContains:"Does not contain",beginsWith:"Begins with",endsWith:"Ends with",blank:"Is blank",notBlank:"Is not blank",top:"Top N",bottom:"Bottom N",aboveAverage:"Above average",belowAverage:"Below average",today:"Today",yesterday:"Yesterday",tomorrow:"Tomorrow",thisWeek:"This week",thisMonth:"This month",lastMonth:"Last month",thisYear:"This year",lastYear:"Last year"};function P(_,t,e,s,n){if(t==="countAll")return n-s;if(_.stale&&_.table.ensure(_),t==="count"||t==="distinct"){if(t==="count"){let y=0;if(_.isString){const{data:d}=_;for(let g=s;g<n;g++)d[e[g]]>=0&&y++}else if(_.kinds!==null){const{kinds:d}=_;for(let g=s;g<n;g++)d[e[g]]!==T&&y++}else{const{data:d}=_;for(let g=s;g<n;g++){const w=d[e[g]];w===w&&y++}}return y}const p=new Set;for(let y=s;y<n;y++){const d=e[y];_.kind(d)!==T&&p.add(_.raw(d))}return p.size}if(_.isString)return NaN;const{data:r,kinds:l}=_;let a=0,o=0,h=1/0,i=-1/0,u=1,c=0,f=0;const m=t==="stdev"||t==="stdevp"||t==="var"||t==="varp";if(t==="median"){const p=new Float64Array(n-s);let y=0;for(let g=s;g<n;g++){const w=e[g];if(l!==null&&l[w]!==F)continue;const b=r[w];b===b&&(p[y++]=b)}if(y===0)return NaN;const d=p.subarray(0,y).sort();return y%2===1?d[y>>1]:(d[(y>>1)-1]+d[y>>1])/2}for(let p=s;p<n;p++){const y=e[p];if(l!==null&&l[y]!==F)continue;const d=r[y];if(d===d&&(o++,a+=d,d<h&&(h=d),d>i&&(i=d),t==="product"&&(u*=d),m)){const g=d-f;f+=g/o,c+=g*(d-f)}}if(o===0)return NaN;switch(t){case"sum":return a;case"average":return a/o;case"min":return h;case"max":return i;case"product":return u;case"var":return o>1?c/(o-1):NaN;case"varp":return c/o;case"stdev":return o>1?Math.sqrt(c/(o-1)):NaN;case"stdevp":return Math.sqrt(c/o);default:return NaN}}const st=/\bCALCULATE\s*\(\s*(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)\s*(?:,\s*REMOVEFILTERS\s*\(\s*(?:"([^"]*)"|\[@?([^\]]*)\])?\s*\))?\s*\)/gi,nt=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,rt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max",PRODUCT:"product",STDEV:"stdev",STDEVP:"stdevp",VAR:"var",VARP:"varp",MEDIAN:"median"};function it(_,t){const e=Math.floor(t),s=x(e);switch(_){case"today":return[e,e+1];case"yesterday":return[e-1,e];case"tomorrow":return[e+1,e+2];case"thisWeek":return[e-s.weekday,e-s.weekday+7];case"thisMonth":return[E(s.year,s.month,1),s.month===12?E(s.year+1,1,1):E(s.year,s.month+1,1)];case"lastMonth":return[s.month===1?E(s.year-1,12,1):E(s.year,s.month-1,1),E(s.year,s.month,1)];case"thisYear":return[E(s.year,1,1),E(s.year+1,1,1)];case"lastYear":return[E(s.year-1,1,1),E(s.year,1,1)];default:return null}}const ot=()=>{const _=new Date;return E(_.getFullYear(),_.getMonth()+1,_.getDate())};function lt(_,t){const e=t.formula?M(_,t.formula):_.column(t.field);if(!e)return null;_.ensure(e);const s=_.rowCount,n=new Float64Array(s),{data:r,kinds:l}=e;if(e.isString){const{rank:a}=e.ranks();for(let o=0;o<s;o++){const h=r[o];n[o]=h<0?NaN:a[h]}return n}if(l!==null){const{rank:a}=e.ranks();for(let o=0;o<s;o++)switch(l[o]){case F:n[o]=r[o];break;case R:n[o]=1e300+a[r[o]]*1e290;break;case H:n[o]=15e307+r[o]*1e300;break;case Y:n[o]=17e307;break;default:n[o]=NaN}return n}if(t.by&&t.by!=="value"){const a=new Map;for(let o=0;o<s;o++){const h=r[o];if(h!==h){n[o]=NaN;continue}const i=Math.floor(h);let u=a.get(i);if(u===void 0){const c=x(i);switch(t.by){case"year":u=c.year;break;case"quarter":u=c.year*4+Math.floor((c.month-1)/3);break;case"month":u=c.year*12+c.month-1;break;case"week":u=Math.floor((i-1)/7);break;default:u=i}a.set(i,u)}n[o]=u}return n}if(t.size>0){for(let a=0;a<s;a++){const o=r[a];n[a]=o!==o?NaN:Math.floor(o/t.size)}return n}if(t.bins){const{bins:a}=t;for(let o=0;o<s;o++){const h=r[o];let i=NaN;if(h===h)for(let u=0;u<a.length;u++){const c=a[u];if((c.min===void 0||h>=c.min)&&(c.max===void 0||h<c.max)){i=u;break}}n[o]=i}return n}return n.set(r.subarray(0,s)),n}function M(_,t){const e=`__formula:${t}`;let s=_.byName.get(e);return s||(s=_.addHelper({name:e,formula:t,type:"any",hidden:!0,readOnly:!0}),_.manager.formulas.bind(s)),_.ensure(s),s}const D={type:"number",caption:"",computed:!0,stale:!1,isString:!1,kinds:null,data:new Float64Array(0),styles:null,table:null,validator:null,required:!1,kind:()=>T,raw:()=>0,get:()=>null},$=_=>typeof _=="string"?{field:_}:{..._};class at{constructor(t,e={}){this.table=t,this.spec={columns:(e.columns??t.fields.map(s=>s.name)).map($),sort:e.sort??[],filters:e.filters??[],groups:e.groups??[],hierarchy:e.hierarchy??null,pinnedRows:e.pinnedRows??[],totals:e.totals??[],search:e.search??"",rules:e.rules??[],groupLayout:e.groupLayout??"outline",options:e.options??{}},this.name=e.name??null,this.listeners=new Set,this.hooks=null,this.dirty=S.FILTER,this.needsFilter=!1,this.revision=0,this.count=0,this.map=new Int32Array(0),this.filtered=new Int32Array(0),this.filteredCount=0,this.perm=new Int32Array(0),this.inverse=null,this.truncated=!1,this.nodeCount=0,this.nodeStart=new Int32Array(0),this.nodeEnd=new Int32Array(0),this.nodeLevel=new Int8Array(0),this.nodeChild=new Int32Array(0),this.nodeChildEnd=new Int32Array(0),this.nodeParent=new Int32Array(0),this.nodeCollapsed=new Uint8Array(0),this.levelStart=[],this.summaryValues=new Map,this.summariesStale=!1,this.collapsedPaths=new Set,this.collapseFromLevel=1/0,this.treeLevel=null,this.treeHasKids=null,this.treeCollapsed=new Set,this.treeParent=null,this.rollups=new Map,this.pinned=new Int32Array(0),this._columns=null,this._unsubscribe=t.onChange(s=>this._tableChanged(s)),this.refresh()}dispose(){if(this._unsubscribe(),this._crossSources)for(const t of this._crossSources.values())t()}fetch(t=!1){return this.table.fetch(t).then(()=>this)}length(){return this.spec.columns.length}visibleLength(){return this.columns.length}on(t,e){return this.hooks===null&&(this.hooks=new Map),this.hooks.has(t)||this.hooks.set(t,new Set),this.hooks.get(t).add(e),()=>this.hooks.get(t).delete(e)}_fire(t,e){const s=this.hooks?.get(t);if(!s)return!0;let n=!0;for(const r of s)r(e)===!1&&(n=!1);return n}addStyleRule(t,e){this.spec.rules=[...this.spec.rules.filter(s=>s.name!==t),{name:t,...e}],this._rulesChanged()}removeStyleRule(t){this.spec.rules=this.spec.rules.filter(e=>e.name!==t),this._rulesChanged()}clearStyleRules(){this.spec.rules=[],this._rulesChanged()}getStyleRule(t){return t===void 0?this.spec.rules:this.spec.rules.find(e=>e.name===t)}_rulesChanged(){this.revision++,this._emit({type:"columns"})}moveRecords(t,e=-1){const s=this.table.ensureOrderColumn().data,n=new Set(t),r=this.spec.hierarchy?this.perm.subarray(0,this.filteredCount):this.map.subarray(0,this.count).filter(h=>h>=0);let l=1/0,a=-1/0;if(e>=0){l=s[e];for(const h of r)if(!n.has(h)){if(h===e)break;a=s[h]}}else for(const h of r)!n.has(h)&&s[h]>a&&(a=s[h]);a===-1/0&&(a=l===1/0?0:l-t.length-1),l===1/0&&(l=a+t.length+1);const o=(l-a)/(t.length+1);t.forEach((h,i)=>{s[h]=a+o*(i+1)}),this.invalidate(S.FILTER),this.refresh()}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){for(const e of this.listeners)e(t)}get columns(){if(this._columns!==null)return this._columns;const t=[];for(const r of this.spec.columns){if(r.hidden)continue;if(r.special){t.push({def:r,col:D,field:r.field??r.special,special:r.special,caption:r.caption??(r.special==="rowNumber"?"#":""),format:"General",width:r.width??(r.special==="rowNumber"?44:72),pinned:r.pinned===!0,readOnly:!0,align:r.align??null,allowSort:!1,allowFilter:!1});continue}if(r.cross){t.push(...B(this,r,M));continue}const l=this.table.column(r.field);l&&t.push({def:r,col:l,field:r.field,caption:r.caption??l.caption,format:r.format??l.format,width:r.width??l.width??null,pinned:r.pinned===!0,readOnly:r.readOnly===!0||l.readOnly||l.computed,align:r.align??null,allowSort:r.allowSort!==!1,allowFilter:r.allowFilter!==!1,showNullAs:r.showNullAs??l.showNullAs,showEmptyAs:r.showEmptyAs??null,display:r.display??null,style:r.style??null,headerStyle:r.headerStyle??null,headerFit:r.headerFit??"normal",captionPath:r.captionPath??null,cellType:r.cellType??null,validator:r.validator??l.validator,conditionalFormats:r.conditionalFormats??null,sparkline:r.sparkline??null})}this.spec.groups.some(r=>r.summaries?.some(l=>l.slice||l.own))&&t.push(...W(this,M));const e=t.filter(r=>r.pinned),s=e.length>0?[...e,...t.filter(r=>!r.pinned)]:t,n=s.findIndex(r=>r.special==="actions");if(n>0&&s.unshift(...s.splice(n,1)),this._columns=s,this._generated=s.filter(r=>r.fill),this._generated.length>0){const r=this._sourceStamp();(r!==this._crossStamp||this._generated.some(l=>!this._filled?.has(l.col)))&&(K(this,this._generated),this._crossStamp=r,this._filled=new Set(this._generated.map(l=>l.col)))}return this._columns}_useCrossSource(t){t!==this.table&&(this._crossSources||(this._crossSources=new Map),this._crossSources.has(t)||this._crossSources.set(t,t.onChange(()=>this._sourceChanged())))}_sourceStamp(){let t=`${this.table.revision}`;if(this._crossSources)for(const e of this._crossSources.keys())t+=`|${e.revision}`;return t}_syncGenerated(){if(!this._generated||this._generated.length===0||this._sourceStamp()===this._crossStamp)return!1;const e=this._generated.map(n=>n.field).join(`
2
2
  `);this._columns=null;const s=this.columns;return this.summariesStale=!0,e!==s.filter(n=>n.fill).map(n=>n.field).join(`
3
- `)}_sourceChanged(){this._syncGenerated()?this._columnsChanged():this._emit({type:"cells"})}get pinnedColumnCount(){return this.columns.reduce((t,e)=>t+(e.pinned?1:0),0)}columnIndex(t){return this.columns.findIndex(e=>e.field===t)}addColumn(t){const e=$(t);e.formula&&(this.table.byName.has(e.field)||this.table.addField({name:e.field,caption:e.caption,formula:e.formula,type:e.type??"any",format:e.format,readOnly:!0}),delete e.formula,delete e.type),this.spec.columns=[...this.spec.columns,e],this._columnsChanged()}removeColumn(t){this.spec.columns=this.spec.columns.filter(e=>e.field!==t),this._columnsChanged()}setColumn(t,e){this.spec.columns=this.spec.columns.map(s=>s.field===t?{...s,...e}:s),this._columnsChanged()}moveColumn(t,e){const s=[...this.spec.columns],n=s.findIndex(l=>l.field===t);if(n<0)return;const[r]=s.splice(n,1);s.splice(Math.max(0,Math.min(s.length,e)),0,r),this.spec.columns=s,this._columnsChanged()}_columnsChanged(){this._columns=null,this.revision++,this._emit({type:"columns"})}setSort(t){this._fire("beforeSort",{sort:t})&&(this.spec.sort=t??[],this.invalidate(C.SORT),this.refresh(),this._fire("afterSort",{sort:this.spec.sort}))}setFilter(t,e){if(!this._fire("beforeFilter",{field:t,condition:e}))return;const s=this.spec.filters.filter(n=>n.field!==t);this.spec.filters=e?[...s,{...e,field:t}]:s,this.invalidate(C.FILTER),this.refresh(),this._fire("afterFilter",{field:t,condition:e})}setFilters(t){this.spec.filters=t??[],this.invalidate(C.FILTER),this.refresh()}setSearch(t){this.spec.search=t??"",this.invalidate(C.FILTER),this.refresh()}setGroups(t){this.spec.groups=t??[],this._columns=null,this.invalidate(C.SORT),this.refresh()}setTotals(t){this.spec.totals=t??[],this.invalidate(C.GROUP),this.refresh()}setHierarchy(t){this.spec.hierarchy=t??null,this.invalidate(C.FILTER),this.refresh()}pinRecord(t){this.spec.pinnedRows.includes(t)||(this.spec.pinnedRows=[...this.spec.pinnedRows,t]),this.invalidate(C.FLATTEN),this.refresh()}unpinRecord(t){this.spec.pinnedRows=this.spec.pinnedRows.filter(e=>e!==t),this.invalidate(C.FLATTEN),this.refresh()}isPinned(t){return this.spec.pinnedRows.includes(t)}invalidate(t){t>this.dirty&&(this.dirty=t)}snapshot(){return{spec:{...this.spec},collapsedPaths:new Set(this.collapsedPaths),collapseFromLevel:this.collapseFromLevel,treeCollapsed:new Set(this.treeCollapsed)}}restore(t){this.spec={...t.spec},this.collapsedPaths=new Set(t.collapsedPaths),this.collapseFromLevel=t.collapseFromLevel,this.treeCollapsed=new Set(t.treeCollapsed),this._columns=null,this.invalidate(C.FILTER),this.refresh()}toJSON(){const{spec:t}=this;return{name:this.name,columns:t.columns,sort:t.sort,filters:t.filters.filter(e=>!e.fn),groups:t.groups.map(e=>({...e,summaries:e.summaries?.filter(s=>!s.fn)})),hierarchy:t.hierarchy,pinnedRows:t.pinnedRows,totals:t.totals,search:t.search,rules:t.rules,groupLayout:t.groupLayout,options:t.options,collapsedPaths:[...this.collapsedPaths],collapseFromLevel:this.collapseFromLevel===1/0?null:this.collapseFromLevel,treeCollapsed:[...this.treeCollapsed]}}applySavedState(t){this.collapsedPaths=new Set(t.collapsedPaths??[]),this.collapseFromLevel=t.collapseFromLevel??1/0,this.treeCollapsed=new Set(t.treeCollapsed??[]),this.invalidate(C.FILTER),this.refresh()}_tableChanged(t){if(this._generated?.length>0&&t.type!=="schema"&&this._syncGenerated()){this._columnsChanged();return}switch(t.type){case"cell":this.summariesStale=!0,this.revision++,this._emit({type:"cell",row:t.row,col:t.col});return;case"cells":this.revision++,this._emit({type:"cells"});return;case"rows":{if(this.spec.groups.length===0&&!this.spec.hierarchy&&this.spec.totals.length===0&&this.dirty===C.NONE){this.needsFilter=!0,t.added?this._appendToMap(t.row):this._removeFromMap(t.row),this.revision++,this._emit({type:"layout"});return}this.invalidate(C.FILTER),this.refresh();return}case"schema":this._columns=null,this.invalidate(C.FILTER),this.refresh();return;default:this.invalidate(C.FILTER),this.refresh()}}_appendToMap(t){if(!(this.count>=U-2)){if(this.count===this.map.length){const e=new Int32Array(Math.max(1024,this.map.length*2));e.set(this.map),this.map=e}this.map[this.count++]=t,this.inverse!==null&&(this.inverse=null)}}_removeFromMap(t){const e=this.map.subarray(0,this.count).indexOf(t);e>=0&&(this.map.copyWithin(e,e+1,this.count),this.count--),this.inverse=null,this.spec.pinnedRows.includes(t)&&(this.spec.pinnedRows=this.spec.pinnedRows.filter(s=>s!==t),this.pinned=Int32Array.from(this.spec.pinnedRows))}refresh(){this._columns===null&&this.columns;const t=this.needsFilter&&this.dirty>C.NONE?C.FILTER:this.dirty;if(t===C.NONE){this.summariesStale&&this._computeSummaries();return}t>=C.FILTER&&this._filter(),t>=C.SORT&&this._sort(),t>=C.GROUP&&this._group(),this._flatten(),this.dirty=C.NONE,this.needsFilter=!1,this.revision++,this._emit({type:"layout"})}_filter(){const t=this.table;t.ensureAll();const e=t.rowCount,s=new Uint8Array(e),{alive:n}=t;s.set(n.subarray(0,e));for(const o of this.spec.filters)this._applyCondition(o,s,e);this.spec.search&&this._applySearch(this.spec.search,s,e),this.spec.hierarchy&&this._buildTreeLinks(s,e);let r=0;for(let o=0;o<e;o++)r+=s[o];const l=new Int32Array(r);let a=0;for(let o=0;o<e;o++)s[o]!==0&&(l[a++]=o);this.filtered=l,this.filteredCount=r}_applyCondition(t,e,s){if(t.fn){for(let l=0;l<s;l++)e[l]!==0&&!t.fn(l,this.table)&&(e[l]=0);return}if(t.formula){const l=M(this.table,t.formula);for(let a=0;a<s;a++){if(e[a]===0)continue;const o=l.get(a);o===!0||typeof o=="number"&&o!==0||(e[a]=0)}return}const n=this.table.column(t.field);if(!n)return;this.table.ensure(n);const{op:r}=t;if(r==="in"||r==="notIn"){this._applyIn(n,t,e,s);return}if(r==="blank"||r==="notBlank"){const l=r==="blank";for(let a=0;a<s;a++)e[a]!==0&&(n.kind(a)===k||n.isString&&n.get(a)==="")!==l&&(e[a]=0);return}if(r==="contains"||r==="notContains"||r==="beginsWith"||r==="endsWith"){this._applyText(n,r,String(t.value??"").toLowerCase(),e,s);return}if(n.isString){this._applyStringCompare(n,t,e,s);return}if(n.kinds!==null){this._applyMixedCompare(n,t,e,s);return}this._applyNumeric(n,t,e,s)}_applyIn(t,e,s,n){const r=e.op==="in",l=new Set,a=new Set;let o=!1;for(const u of e.values??[])u===null||u===""?o=!0:typeof u=="number"?l.add(u):typeof u=="boolean"?l.add(u?1:0):a.add(String(u).toLowerCase());const{strings:h}=this.table.manager,{data:i}=t;if(t.isString||t.kinds!==null){const u=new Int8Array(h.size),c=f=>{let m=u[f];return m===0&&(m=a.has(h.get(f).toLowerCase())?1:-1,u[f]=m),m>0};for(let f=0;f<n;f++){if(s[f]===0)continue;const m=t.kind(f);let p;m===k?p=o:m===R?p=c(i[f]):p=l.has(i[f]),p!==r&&(s[f]=0)}return}for(let u=0;u<n;u++){if(s[u]===0)continue;const c=i[u];(c!==c?o:l.has(c))!==r&&(s[u]=0)}}_applyText(t,e,s,n,r){const{strings:l}=this.table.manager,a=e==="beginsWith"?h=>h.startsWith(s):e==="endsWith"?h=>h.endsWith(s):h=>h.includes(s),o=e==="notContains";if(t.isString){const h=new Int8Array(l.size),{data:i}=t;for(let u=0;u<r;u++){if(n[u]===0)continue;const c=i[u];if(c<0){o||(n[u]=0);continue}let f=h[c];f===0&&(f=a(l.get(c).toLowerCase())?1:-1,h[c]=f),f>0===o&&(n[u]=0)}return}for(let h=0;h<r;h++){if(n[h]===0)continue;const i=t.get(h);(i!==null&&a((typeof i=="number"?T(i):String(i)).toLowerCase()))===o&&(n[h]=0)}}_applyStringCompare(t,e,s,n){const{rank:r}=t.ranks(),{strings:l}=this.table.manager,{data:a}=t,o=String(e.value??"").toLowerCase();if(e.op==="equal"||e.op==="notEqual"){const c=e.op==="equal",f=new Int8Array(l.size);for(let m=0;m<n;m++){if(s[m]===0)continue;const p=a[m];let y=!1;if(p>=0){let d=f[p];d===0&&(d=l.get(p).toLowerCase()===o?1:-1,f[p]=d),y=d>0}else y=o==="";y!==c&&(s[m]=0)}return}const h=c=>{const f=String(c??"").toLowerCase();let m=-1;const p=new Int8Array(l.size);for(let y=0;y<n;y++){const d=a[y];d<0||p[d]||(p[d]=1,l.get(d).toLowerCase()<=f&&r[d]>m&&(m=r[d]))}return m+.5},i=h(e.value),u=e.value2!==void 0?h(e.value2):i;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=a[c];if(f<0){s[c]=0;continue}const m=r[f];let p;switch(e.op){case"gt":p=m>i;break;case"gte":p=m>i-1;break;case"lt":p=m<i-1;break;case"lte":p=m<i;break;case"between":p=m>i-1&&m<u;break;case"notBetween":p=!(m>i-1&&m<u);break;default:p=!0}p||(s[c]=0)}}_applyMixedCompare(t,e,s,n){const r=e.value;for(let l=0;l<n;l++){if(s[l]===0)continue;const a=t.get(l);let o;if(e.op==="equal"||e.op==="notEqual"){const h=a===r||typeof a=="string"&&typeof r=="string"&&a.toLowerCase()===r.toLowerCase();o=e.op==="equal"?h:!h}else typeof a!="number"?o=!1:o=ut(e.op,a,Number(r),Number(e.value2));o||(s[l]=0)}}_applyNumeric(t,e,s,n){const{data:r}=t,{op:l}=e,a=it(l,e.now??ot());if(a!==null){const[i,u]=a;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=r[c];f>=i&&f<u||(s[c]=0)}return}if(l==="top"||l==="bottom"){const i=new Float64Array(n);let u=0;for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];y===y&&(i[u++]=y)}const c=i.subarray(0,u).sort(),f=Math.max(0,Math.min(u,e.percent?Math.floor(u*Number(e.value)/100):Number(e.value)));if(f===0){s.fill(0);return}const m=l==="top"?c[u-f]:c[f-1];for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];(l==="top"?y>=m:y<=m)||(s[p]=0)}return}if(l==="aboveAverage"||l==="belowAverage"){let i=0,u=0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];m===m&&(i+=m,u++)}const c=u>0?i/u:0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];(l==="aboveAverage"?m>c:m<c)||(s[f]=0)}return}const o=q(e.value),h=q(e.value2);switch(l){case"gt":for(let i=0;i<n;i++)r[i]>o||(s[i]=0);return;case"gte":for(let i=0;i<n;i++)r[i]>=o||(s[i]=0);return;case"lt":for(let i=0;i<n;i++)r[i]<o||(s[i]=0);return;case"lte":for(let i=0;i<n;i++)r[i]<=o||(s[i]=0);return;case"equal":for(let i=0;i<n;i++)r[i]!==o&&(s[i]=0);return;case"notEqual":for(let i=0;i<n;i++)r[i]===o&&(s[i]=0);return;case"between":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h||(s[i]=0);return;case"notBetween":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h&&(s[i]=0);return;default:}}_applySearch(t,e,s){const n=t.toLowerCase(),{strings:r}=this.table.manager,l=ht(n),a=this.columns.map(i=>i.col).filter(i=>l||i.isString||i.kinds!==null),o=new Int8Array(r.size),h=i=>{let u=o[i];return u===0&&(u=r.get(i).toLowerCase().includes(n)?1:-1,o[i]=u),u>0};for(let i=0;i<s;i++){if(e[i]===0)continue;let u=!1;for(let c=0;c<a.length&&!u;c++){const f=a[c],m=f.kind(i);if(f!==D){if(m===R)u=h(f.data[i]);else if(m===F){const p=T(f.data[i]);u=(p.includes("E")?p.toLowerCase():p).includes(n)}}}u||(e[i]=0)}}_sortColumn(t,e,s,n){Q(this.table,t,e,s,n)}_groupKeys(t){return lt(this.table,this.spec.groups[t])}_sort(){const t=this.filteredCount,e=this.perm.length===t?this.perm:new Int32Array(t);e.set(this.filtered.subarray(0,t)),this.perm=e;const{sort:s,groups:n,hierarchy:r}=this.spec,l=this.table.byName.get("__order");l&&G(e,t,l.data,!1);for(let a=s.length-1;a>=0;a--){const o=this.table.column(s[a].field);o&&this._sortColumn(e,t,o,s[a].desc===!0)}if(this._keys=[],!r)for(let a=n.length-1;a>=0;a--){const o=this._groupKeys(a);o!==null&&(this._keys[a]=o,G(e,t,o,n[a].desc===!0))}}_group(){const{groups:t,hierarchy:e}=this.spec,s=this.filteredCount;if(e||t.length===0&&this.spec.totals.length===0){this.nodeCount=0,this.summaryValues.clear(),e&&this._computeRollups();return}(this._keys===void 0||this._keys.length===0&&t.length>0)&&this._sort();const n=t.length;let r=16,l=new Int32Array(r),a=new Int32Array(r),o=new Int32Array(r),h=new Int8Array(r),i=new Int32Array(r),u=new Int32Array(r);const c=()=>{const d=(g,w)=>{const _=new g(r*2);return _.set(w),_};l=d(Int32Array,l),a=d(Int32Array,a),o=d(Int32Array,o),h=d(Int8Array,h),i=d(Int32Array,i),u=d(Int32Array,u),r*=2};l[0]=0,a[0]=s,h[0]=-1,o[0]=-1;let f=1,m=0,p=1;this.levelStart=[];const{perm:y}=this;for(let d=0;d<n;d++){const g=this._keys[d];this.levelStart[d]=f;for(let w=m;w<p;w++){if(i[w]=f,g){let _=l[w];const A=a[w];for(;_<A;){const v=g[y[_]];let S=_+1;if(v===v)for(;S<A&&g[y[S]]===v;)S++;else for(;S<A&&g[y[S]]!==g[y[S]];)S++;f===r&&c(),l[f]=_,a[f]=S,o[f]=w,h[f]=d,f++,_=S}}u[w]=f}m=p,p=f}for(let d=m;d<p;d++)i[d]=0,u[d]=0;this.nodeCount=f,this.nodeStart=l,this.nodeEnd=a,this.nodeParent=o,this.nodeLevel=h,this.nodeChild=i,this.nodeChildEnd=u,this._applyCollapse(),this._computeSummaries()}_nodePath(t){const e=[];for(let s=t;s>0;s=this.nodeParent[s]){const n=this.spec.groups[this.nodeLevel[s]],r=this.groupKeyValue(s,n);e.push(r===null?"":String(r).toLowerCase())}return e.reverse().join("")}groupKeyValue(t,e=this.spec.groups[this.nodeLevel[t]]){const s=e.formula?M(this.table,e.formula):this.table.column(e.field),n=this.perm[this.nodeStart[t]],r=s.get(n);if(typeof r=="number"){if(e.by&&e.by!=="value")return this._keys[this.nodeLevel[t]][n];if(e.size>0)return Math.floor(r/e.size)*e.size;if(e.bins)return e.bins[this._keys[this.nodeLevel[t]][n]]?.name??"(other)"}return r instanceof tt?r.code:r}_applyCollapse(){const t=new Uint8Array(this.nodeCount),e=this.collapsedPaths.size>0,s=this.collapseFromLevel;if(e||s!==1/0)for(let n=1;n<this.nodeCount;n++){let r=this.nodeLevel[n]>=s;e&&this.collapsedPaths.has(this._nodePath(n))&&(r=!r),t[n]=r?1:0}this.nodeCollapsed=t}_computeSummaries(){if(this.summariesStale=!1,this.summaryValues.clear(),this.spec.hierarchy){this._computeRollups();return}if(this.nodeCount===0)return;const{groups:t,totals:e}=this.spec,s=this._generated??[],n=(l,a)=>{const o=s.filter(i=>i.sliceLevel===void 0?!0:i.sliceLevel===l).map(i=>({field:i.field,agg:i.summaryAgg??"sum"})),h=(a??[]).filter(i=>!i.slice&&!i.own);return o.length>0?[...h,...o]:h},r=(l,a,o,h)=>{if(!a||a.length===0)return;const i=a.length,u=new Float64Array((h-o)*i),{perm:c,nodeStart:f,nodeEnd:m}=this;a.forEach((p,y)=>{const d=p.field?this.table.column(p.field):null;if(p.where&&d){const g=M(this.table,p.where),w=new Int32Array(c.length);for(let _=o;_<h;_++){let A=0;for(let v=f[_];v<m[_];v++){const S=g.get(c[v]);(S===!0||typeof S=="number"&&S!==0)&&(w[A++]=c[v])}u[(_-o)*i+y]=P(d,p.agg??"sum",w,0,A)}}else if(p.formula){const g=this._summaryFormula(p.formula);for(let w=o;w<h;w++)u[(w-o)*i+y]=g(c,f[w],m[w],w)}else if(p.fn)for(let g=o;g<h;g++)u[(g-o)*i+y]=p.fn(c.subarray(f[g],m[g]),this.table);else if(d)for(let g=o;g<h;g++)u[(g-o)*i+y]=P(d,p.agg??"sum",c,f[g],m[g]);else u.fill(NaN)}),this.summaryValues.set(l,{values:u,per:i,list:a,first:o})};r(-1,e?.length>0?n(-1,e):e,0,1);for(let l=0;l<t.length;l++){const a=this.levelStart[l],o=l+1<t.length?this.levelStart[l+1]:this.nodeCount;r(l,n(l,t[l].summaries),a,o)}}_summaryFormula(t){const e=[],s=(i,u,c)=>(e.push({agg:rt[i.toUpperCase()],col:this.table.column(u.trim()),scope:c}),`$${J(e.length-1)}$1`),n=String(t).replace(/^=/,"").replace(st,(i,u,c,f,m)=>{if(!/REMOVEFILTERS/i.test(i))return s(u,c,null);const p=f??m,y=p?this.spec.groups.findIndex(d=>d.field===p.trim()):0;return s(u,c,{up:Math.max(0,y)})}).replace(nt,(i,u,c)=>s(u,c,null)),r=this.table.manager.formulas._engineFor(),l=r.template(n,0,0),a=e.map(()=>({kinds:new Uint8Array(1024),values:new Float64Array(1024),styles:null})),o=this.table.manager.formulas._sheet(this.table),h=(i,u)=>{let c=i;for(;c>0&&this.nodeLevel[c]>=u;)c=this.nodeParent[c];return c};return(i,u,c,f=0)=>{o.columns.length=0,e.forEach((p,y)=>{let d=u,g=c;if(p.scope){const _=h(f,p.scope.up);d=this.nodeStart[_],g=this.nodeEnd[_]}const w=p.col?P(p.col,p.agg,i,d,g):NaN;a[y].kinds[0]=w===w?F:k,a[y].values[0]=w,o.columns[y]=[a[y]]});let m;try{m=l.fn(0,0,o),m&&m.isCell&&(m=r.read(m.sheet,m.r0,m.c0))}catch{m=NaN}return o.columns.length=0,typeof m=="number"?m:NaN}}summaryFor(t,e){const s=this.nodeLevel[t],n=this.summaryValues.get(s);if(!n)return;const r=n.list.findIndex(l=>l.field===e||l.column===e);if(!(r<0))return n.values[(t-n.first)*n.per+r]}_buildTreeLinks(t,e){const s=this.spec.hierarchy,n=this.table,r=new Int32Array(e).fill(-1);if(s.level){const l=n.column(s.level);n.ensure(l);const{data:a}=l,o=[];for(let h=0;h<e;h++){if(!n.alive[h])continue;const i=a[h]===a[h]?a[h]:0;o.length=Math.min(o.length,i),r[h]=o.length>0?o[o.length-1]:-1,o[i]=h}}else{const l=n.column(s.key??n.key),a=n.column(s.parent);if(n.ensure(l),n.ensure(a),l.isString===a.isString&&l.kinds===null&&a.kinds===null){const o=Z(l,n),{data:h}=a;for(let i=0;i<e;i++){const u=h[i];u===u&&u!==-1&&(r[i]=o(u))}}else{const o=new Map;for(let h=e-1;h>=0;h--)n.alive[h]&&o.set(String(l.get(h)),h);for(let h=0;h<e;h++){const i=a.get(h);i!==null&&(r[h]=o.get(String(i))??-1)}}}if(this.treeParent=r,this.spec.filters.length>0||this.spec.search){for(let l=0;l<e;l++)if(t[l]!==0)for(let a=r[l];a>=0&&t[a]===0;a=r[a])t[a]=1}}_flattenTree(t,e){const s=this.filteredCount,n=this.table.rowCount,r=this.treeParent,{perm:l}=this,a=new Int32Array(n).fill(-1),o=new Int32Array(n).fill(-1),h=new Uint16Array(n),i=new Uint8Array(n),u=new Uint8Array(n);for(let w=0;w<s;w++)u[l[w]]=1;const c=[];for(let w=s-1;w>=0;w--){const _=l[w],A=r[_];A>=0&&u[A]===1&&A!==_?(o[_]=a[A],a[A]=_,i[A]=1):c.push(_)}const f=new Uint8Array(n),m=this.treeCollapsed;let p=0;const y=new Int32Array(Math.max(16,s+1));let d=0;const g=w=>{for(y[d++]=w;d>0;){const _=y[--d];if(f[_]===1)continue;f[_]=1,(!e||e[_]===0)&&(p<t.length&&(t[p]=_),p++);const A=h[_];if(a[_]>=0&&!m.has(_)){let v=a[_];const S=d;let L=0;for(;v>=0;)h[v]=A+1,y[d++]=v,L++,v=o[v];for(let I=S,N=S+L-1;I<N;I++,N--){const z=y[I];y[I]=y[N],y[N]=z}}}};for(let w=c.length-1;w>=0;w--)g(c[w]);if(!m.size)for(let w=0;w<s;w++)f[l[w]]===0&&g(l[w]);return this.treeLevel=h,this.treeHasKids=i,p}_computeRollups(){this.rollups.clear();const t=this.spec.hierarchy?.rollups;if(!t||t.length===0||!this.treeParent)return;const e=this.filteredCount,{perm:s,treeParent:n}=this,r=this.table.rowCount,l=new Int32Array(r).fill(-1),a=i=>{const u=[];let c=i;for(;c>=0&&l[c]<0&&u.length<r;)u.push(c),l[c]=0,c=n[c];let f=c>=0?l[c]+1:0;for(let m=u.length-1;m>=0;m--)l[u[m]]=f++};for(let i=0;i<e;i++)a(s[i]);const o=s.slice(0,e),h=new Uint32Array(e);for(let i=0;i<e;i++)h[i]=l[o[i]];j(o,e,h);for(const i of t){const u=this.table.column(i.field);if(!u)continue;this.table.ensure(u);const c=i.agg??"sum",f=new Float64Array(r).fill(NaN),m=new Float64Array(r),p=new Uint8Array(r);for(let y=0;y<e;y++){const d=o[y],g=u.isString?u.data[d]>=0?1:NaN:u.kinds!==null&&u.kinds[d]!==F?NaN:u.data[d];g===g&&(f[d]=c==="count"?1:g,m[d]=1)}for(let y=e-1;y>=0;y--){const d=o[y],g=n[d];if(g<0||l[g]<0||m[d]===0)continue;p[g]===0&&(p[g]=1,f[g]=NaN,m[g]=0);const w=f[d],_=f[g];c==="min"?f[g]=_!==_||w<_?w:_:c==="max"?f[g]=_!==_||w>_?w:_:f[g]=(_!==_?0:_)+w,m[g]+=m[d]}if(c==="average")for(let y=0;y<e;y++){const d=o[y];p[d]===1&&m[d]>0&&(f[d]/=m[d])}this.rollups.set(i.field,{values:f,touched:p})}}_flatten(){const t=this.spec.pinnedRows.filter(v=>v<this.table.rowCount&&this.table.alive[v]===1);this.pinned=Int32Array.from(t);let e=null;if(t.length>0){e=new Uint8Array(this.table.rowCount);for(const v of t)e[v]=1}const s=U-2-t.length;if(this.spec.hierarchy){const v=this.map.length>=this.filteredCount?this.map:new Int32Array(this.filteredCount);this.count=this._flattenTree(v,e),this.map=v,this.truncated=this.count>s,this.truncated&&(this.count=s),this.inverse=null;return}const n=this.spec.groups,r=this.filteredCount,{perm:l}=this;if(n.length===0&&this.spec.totals.length===0){const v=Math.min(r,s),S=this.map.length>=v?this.map:new Int32Array(v);if(e===null)S.set(l.subarray(0,v)),this.count=v;else{let L=0;for(let I=0;I<r&&L<v;I++){const N=l[I];e[N]===0&&(S[L++]=N)}this.count=L}this.map=S,this.truncated=r>s,this.inverse=null;return}this.groupStartOf=null,this.groupStartNode=null;const a=n.map(v=>v.footer===!0),o=this.spec.totals.length>0;let h=r+(o?1:0);for(let v=1;v<this.nodeCount;v++)h+=a[this.nodeLevel[v]]?2:1;const i=Math.min(h,s),u=this.map.length>=i?this.map:new Int32Array(i);let c=0;const f=n.length-1,{nodeChild:m,nodeChildEnd:p,nodeLevel:y,nodeCollapsed:d,nodeStart:g,nodeEnd:w}=this,_=this.spec.groupLayout==="tabular",A=v=>{if(c>=i)return;const S=y[v];if((!_||d[v]===1)&&(u[c++]=-(1+v*2)),d[v]!==1){if(S===f){const L=g[v],I=w[v];if(_&&this._markGroupStart(L,S,v),e===null){const N=Math.min(I-L,i-c);u.set(l.subarray(L,L+N),c),c+=N}else for(let N=L;N<I&&c<i;N++)e[l[N]]===0&&(u[c++]=l[N])}else for(let L=m[v];L<p[v];L++)A(L);a[S]&&c<i&&(u[c++]=-(2+v*2))}};if(n.length===0){const v=Math.min(r,i-1);if(e===null)u.set(l.subarray(0,v),0),c=v;else for(let S=0;S<r&&c<i-1;S++)e[l[S]]===0&&(u[c++]=l[S])}else for(let v=m[0];v<p[0];v++)A(v);o&&c<i&&(u[c++]=-2),this.count=c,this.map=u,this.truncated=h>s,this.inverse=null}_markGroupStart(t,e,s){const n=this.perm[t];this.groupStartOf||(this.groupStartOf=new Map),this.groupStartNode||(this.groupStartNode=new Map),this.groupStartNode.set(n,s);let r=e;for(let l=e-1;l>=0;l--){const a=this._keys[l],o=t>0?this.perm[t-1]:-1;if(o>=0&&(a[o]===a[n]||a[o]!==a[o]&&a[n]!==a[n]))break;r=l}this.groupStartOf.set(n,r)}showsGroupValue(t,e){const s=this.groupStartOf?.get(t);return s!==void 0&&s<=e}summaryOfRecord(t,e){let s=this.groupStartNode?.get(t);if(s!==void 0){for(;s>0&&this.nodeLevel[s]>e.sliceLevel;)s=this.nodeParent[s];return this.summariesStale&&this._computeSummaries(),this.summaryFor(s,e.field)}}recordNumberAt(t){if(this.spec.groups.length===0)return t+1;if(this._numbersOf!==this.map){const e=new Int32Array(this.count);let s=0;for(let n=0;n<this.count;n++)this.map[n]>=0&&(e[n]=++s);this._numbers=e,this._numbersOf=this.map}return this._numbers[t]}rowInfo(t){if(t<0||t>=this.count)return null;const e=this.map[t];if(e>=0){const r=this.treeLevel?this.treeLevel[e]:0;return{kind:"record",record:e,level:r,hasChildren:this.treeHasKids?this.treeHasKids[e]===1:!1,collapsed:this.treeCollapsed.has(e)}}const s=-e-1,n=s>>>1;return{kind:s&1?"footer":"group",node:n,level:this.nodeLevel[n],collapsed:this.nodeCollapsed[n]===1}}recordAt(t){const e=this.map[t];return t>=0&&t<this.count&&e>=0?e:-1}rowOfRecord(t){if(this.inverse===null){const e=new Int32Array(this.table.rowCount).fill(-1);for(let s=0;s<this.count;s++){const n=this.map[s];n>=0&&(e[n]=s)}this.inverse=e}return t<this.inverse.length?this.inverse[t]:-1}groupCaption(t){const e=this.nodeLevel[t],s=this.spec.groups[e],n=this.table.column(s.field),r=this.nodeEnd[t]-this.nodeStart[t],l=s.caption??n?.caption??s.field,a=this.groupKeyValue(t,s);return this.spec.groupLayout==="condensed"?`${this._groupValueText(a,s,n)} (${r})`:`${l}: ${this._groupValueText(a,s,n)} (${r})`}_groupValueText(t,e,s){if(t==null)return"(blank)";if(typeof t=="number"){switch(e.by){case"year":return String(t);case"quarter":return`Q${t%4+1} ${Math.floor(t/4)}`;case"month":return`${et[t%12]} ${Math.floor(t/12)}`;case"week":{const n=x(t*7+1);return`Week of ${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}default:}return e.size>0?`${T(t)} to ${T(t+e.size)}`:s&&s.format!=="General"?V(s.format).number(t):T(t)}return typeof t=="boolean"?t?"TRUE":"FALSE":String(t)}toggleRow(t){const e=this.rowInfo(t);return e?e.kind==="group"?(this._setNode(e.node,!e.collapsed),this._relayout(),!0):e.kind==="record"&&e.hasChildren?(e.collapsed?this.treeCollapsed.delete(e.record):this.treeCollapsed.add(e.record),this._relayout(),!0):!1:!1}_setNode(t,e){this.nodeCollapsed[t]=e?1:0;const s=this._nodePath(t),n=this.nodeLevel[t]>=this.collapseFromLevel;e===n?this.collapsedPaths.delete(s):this.collapsedPaths.add(s)}showLevel(t){if(this.collapsedPaths.clear(),this.collapseFromLevel=t,this.treeCollapsed.clear(),this.spec.hierarchy&&t!==1/0){const e=this.treeLevelsAll(),s=this.table.rowCount;for(let n=0;n<s;n++)e[n]>=t&&this.treeHasKids[n]===1&&this.treeCollapsed.add(n)}this.nodeCount>0&&this._applyCollapse(),this._relayout()}treeLevelsAll(){const t=this.table.rowCount,e=new Uint16Array(t),s=this.treeParent,n=new Uint8Array(t),r=[];for(let l=0;l<t;l++){let a=l;for(r.length=0;a>=0&&n[a]===0&&r.length<=t;)r.push(a),n[a]=1,a=s[a];let o=a>=0?e[a]+1:0;for(let h=r.length-1;h>=0;h--)e[r[h]]=o++}return e}expandAll(){this.showLevel(1/0)}collapseAll(){this.showLevel(0)}_relayout(){this.invalidate(C.FLATTEN),this.refresh()}distinctValues(t,{limit:e=5e3}={}){const s=this.table.column(t);if(!s)return{values:[],total:0};this.table.ensure(s);const n=this.table.rowCount,r=new Uint8Array(n);r.set(this.table.alive.subarray(0,n));for(const h of this.spec.filters)h.field!==t&&this._applyCondition(h,r,n);const l=new Map;for(let h=0;h<n;h++){if(r[h]===0)continue;const i=s.kind(h),u=i===k?null:i===R||s.isString?`s${s.data[h]}`:s.data[h];l.set(u,(l.get(u)??0)+1)}const{strings:a}=this.table.manager,o=[];for(const[h,i]of l)if(h===null)o.push({value:null,text:"(Blanks)",count:i});else if(typeof h=="string"){const u=a.get(Number(h.slice(1)));o.push({value:u,text:u,count:i})}else{const u=s.format!=="General"?V(s.format).number(h):T(h);o.push({value:s.type==="boolean"?h!==0:h,text:s.type==="boolean"?h?"TRUE":"FALSE":u,count:i})}return o.sort((h,i)=>h.value===null?1:i.value===null?-1:typeof h.value=="number"&&typeof i.value=="number"?h.value-i.value:String(h.text).localeCompare(String(i.text))),{values:o.slice(0,e),total:o.length}}}function T(b){return X(b)}function ht(b){const t=new Set("0123456789eE");for(const e of[-1.5,1e20,1e-20,1/0,-1/0,NaN])for(const s of T(e))t.add(s);for(const e of b)if(!t.has(e))return!1;return!0}function q(b){return typeof b=="number"?b:typeof b=="boolean"?b?1:0:b==null||b===""?NaN:Number(b)}function ut(b,t,e,s){switch(b){case"gt":return t>e;case"gte":return t>=e;case"lt":return t<e;case"lte":return t<=e;case"between":return t>=e&&t<=s;case"notBetween":return!(t>=e&&t<=s);default:return!0}}O.prototype.addView=function(t,e,s={}){const n=new at(this,{name:t,columns:e,...s});return this.views.set(t,n),n},O.prototype.getView=function(t){return this.views.get(t)??null},O.prototype.removeView=function(t){this.views.get(t)?.dispose(),this.views.delete(t)};export{vt as AGG_LABEL,bt as FILTER_OPS,C as STAGE,wt as SUMMARY_AGGS,at as TableView,P as aggregate,M as formulaHelper,lt as groupKeys,ot as todaySerial};
3
+ `)}_sourceChanged(){this._syncGenerated()?this._columnsChanged():this._emit({type:"cells"})}get pinnedColumnCount(){return this.columns.reduce((t,e)=>t+(e.pinned?1:0),0)}columnIndex(t){return this.columns.findIndex(e=>e.field===t)}addColumn(t){const e=$(t);e.formula&&(this.table.byName.has(e.field)||this.table.addField({name:e.field,caption:e.caption,formula:e.formula,type:e.type??"any",format:e.format,readOnly:!0}),delete e.formula,delete e.type),this.spec.columns=[...this.spec.columns,e],this._columnsChanged()}removeColumn(t){this.spec.columns=this.spec.columns.filter(e=>e.field!==t),this._columnsChanged()}setColumn(t,e){this.spec.columns=this.spec.columns.map(s=>s.field===t?{...s,...e}:s),this._columnsChanged()}moveColumn(t,e){const s=[...this.spec.columns],n=s.findIndex(l=>l.field===t);if(n<0)return;const[r]=s.splice(n,1);s.splice(Math.max(0,Math.min(s.length,e)),0,r),this.spec.columns=s,this._columnsChanged()}_columnsChanged(){this._columns=null,this.revision++,this._emit({type:"columns"})}setSort(t){this._fire("beforeSort",{sort:t})&&(this.spec.sort=t??[],this.invalidate(S.SORT),this.refresh(),this._fire("afterSort",{sort:this.spec.sort}))}setFilter(t,e){if(!this._fire("beforeFilter",{field:t,condition:e}))return;const s=this.spec.filters.filter(n=>n.field!==t);this.spec.filters=e?[...s,{...e,field:t}]:s,this.invalidate(S.FILTER),this.refresh(),this._fire("afterFilter",{field:t,condition:e})}setFilters(t){this.spec.filters=t??[],this.invalidate(S.FILTER),this.refresh()}setSearch(t){this.spec.search=t??"",this.invalidate(S.FILTER),this.refresh()}setGroups(t){this.spec.groups=t??[],this._columns=null,this.invalidate(S.SORT),this.refresh()}setTotals(t){this.spec.totals=t??[],this.invalidate(S.GROUP),this.refresh()}setHierarchy(t){this.spec.hierarchy=t??null,this.invalidate(S.FILTER),this.refresh()}pinRecord(t){this.spec.pinnedRows.includes(t)||(this.spec.pinnedRows=[...this.spec.pinnedRows,t]),this.invalidate(S.FLATTEN),this.refresh()}unpinRecord(t){this.spec.pinnedRows=this.spec.pinnedRows.filter(e=>e!==t),this.invalidate(S.FLATTEN),this.refresh()}isPinned(t){return this.spec.pinnedRows.includes(t)}invalidate(t){t>this.dirty&&(this.dirty=t)}snapshot(){return{spec:{...this.spec},collapsedPaths:new Set(this.collapsedPaths),collapseFromLevel:this.collapseFromLevel,treeCollapsed:new Set(this.treeCollapsed)}}restore(t){this.spec={...t.spec},this.collapsedPaths=new Set(t.collapsedPaths),this.collapseFromLevel=t.collapseFromLevel,this.treeCollapsed=new Set(t.treeCollapsed),this._columns=null,this.invalidate(S.FILTER),this.refresh()}toJSON(){const{spec:t}=this;return{name:this.name,columns:t.columns,sort:t.sort,filters:t.filters.filter(e=>!e.fn),groups:t.groups.map(e=>({...e,summaries:e.summaries?.filter(s=>!s.fn)})),hierarchy:t.hierarchy,pinnedRows:t.pinnedRows,totals:t.totals,search:t.search,rules:t.rules,groupLayout:t.groupLayout,options:t.options,collapsedPaths:[...this.collapsedPaths],collapseFromLevel:this.collapseFromLevel===1/0?null:this.collapseFromLevel,treeCollapsed:[...this.treeCollapsed]}}applySavedState(t){this.collapsedPaths=new Set(t.collapsedPaths??[]),this.collapseFromLevel=t.collapseFromLevel??1/0,this.treeCollapsed=new Set(t.treeCollapsed??[]),this.invalidate(S.FILTER),this.refresh()}_tableChanged(t){if(this._generated?.length>0&&t.type!=="schema"&&this._syncGenerated()){this._columnsChanged();return}switch(t.type){case"cell":this.summariesStale=!0,this.revision++,this._emit({type:"cell",row:t.row,col:t.col});return;case"cells":this.revision++,this._emit({type:"cells"});return;case"rows":{if(this.spec.groups.length===0&&!this.spec.hierarchy&&this.spec.totals.length===0&&this.dirty===S.NONE){this.needsFilter=!0,t.added?this._appendToMap(t.row):this._removeFromMap(t.row),this.revision++,this._emit({type:"layout"});return}this.invalidate(S.FILTER),this.refresh();return}case"schema":this._columns=null,this.invalidate(S.FILTER),this.refresh();return;default:this.invalidate(S.FILTER),this.refresh()}}_appendToMap(t){if(!(this.count>=U-2)){if(this.count===this.map.length){const e=new Int32Array(Math.max(1024,this.map.length*2));e.set(this.map),this.map=e}this.map[this.count++]=t,this.inverse!==null&&(this.inverse=null)}}_removeFromMap(t){const e=this.map.subarray(0,this.count).indexOf(t);e>=0&&(this.map.copyWithin(e,e+1,this.count),this.count--),this.inverse=null,this.spec.pinnedRows.includes(t)&&(this.spec.pinnedRows=this.spec.pinnedRows.filter(s=>s!==t),this.pinned=Int32Array.from(this.spec.pinnedRows))}refresh(){this._columns===null&&this.columns;const t=this.needsFilter&&this.dirty>S.NONE?S.FILTER:this.dirty;if(t===S.NONE){this.summariesStale&&this._computeSummaries();return}t>=S.FILTER&&this._filter(),t>=S.SORT&&this._sort(),t>=S.GROUP&&this._group(),this._flatten(),this.dirty=S.NONE,this.needsFilter=!1,this.revision++,this._emit({type:"layout"})}_filter(){const t=this.table;t.ensureAll();const e=t.rowCount,s=new Uint8Array(e),{alive:n}=t;s.set(n.subarray(0,e));for(const o of this.spec.filters)this._applyCondition(o,s,e);this.spec.search&&this._applySearch(this.spec.search,s,e),this.spec.hierarchy&&this._buildTreeLinks(s,e);let r=0;for(let o=0;o<e;o++)r+=s[o];const l=new Int32Array(r);let a=0;for(let o=0;o<e;o++)s[o]!==0&&(l[a++]=o);this.filtered=l,this.filteredCount=r}_applyCondition(t,e,s){if(Array.isArray(t.all)){for(const l of t.all)this._applyCondition(l,e,s);return}if(Array.isArray(t.any)){if(!t.any.length)return;const l=new Uint8Array(s);for(const a of t.any){const o=e.slice();this._applyCondition(a,o,s);for(let h=0;h<s;h++)o[h]!==0&&(l[h]=1)}for(let a=0;a<s;a++)l[a]===0&&(e[a]=0);return}if(t.fn){for(let l=0;l<s;l++)e[l]!==0&&!t.fn(l,this.table)&&(e[l]=0);return}if(t.formula){const l=M(this.table,t.formula);for(let a=0;a<s;a++){if(e[a]===0)continue;const o=l.get(a);o===!0||typeof o=="number"&&o!==0||(e[a]=0)}return}const n=this.table.column(t.field);if(!n)return;this.table.ensure(n);const{op:r}=t;if(r==="in"||r==="notIn"){this._applyIn(n,t,e,s);return}if(r==="blank"||r==="notBlank"){const l=r==="blank";for(let a=0;a<s;a++)e[a]!==0&&(n.kind(a)===T||n.isString&&n.get(a)==="")!==l&&(e[a]=0);return}if(r==="contains"||r==="notContains"||r==="beginsWith"||r==="endsWith"){this._applyText(n,r,String(t.value??"").toLowerCase(),e,s);return}if(n.isString){this._applyStringCompare(n,t,e,s);return}if(n.kinds!==null){this._applyMixedCompare(n,t,e,s);return}this._applyNumeric(n,t,e,s)}_applyIn(t,e,s,n){const r=e.op==="in",l=new Set,a=new Set;let o=!1;for(const u of e.values??[])u===null||u===""?o=!0:typeof u=="number"?l.add(u):typeof u=="boolean"?l.add(u?1:0):a.add(String(u).toLowerCase());const{strings:h}=this.table.manager,{data:i}=t;if(t.isString||t.kinds!==null){const u=new Int8Array(h.size),c=f=>{let m=u[f];return m===0&&(m=a.has(h.get(f).toLowerCase())?1:-1,u[f]=m),m>0};for(let f=0;f<n;f++){if(s[f]===0)continue;const m=t.kind(f);let p;m===T?p=o:m===R?p=c(i[f]):p=l.has(i[f]),p!==r&&(s[f]=0)}return}for(let u=0;u<n;u++){if(s[u]===0)continue;const c=i[u];(c!==c?o:l.has(c))!==r&&(s[u]=0)}}_applyText(t,e,s,n,r){const{strings:l}=this.table.manager,a=e==="beginsWith"?h=>h.startsWith(s):e==="endsWith"?h=>h.endsWith(s):h=>h.includes(s),o=e==="notContains";if(t.isString){const h=new Int8Array(l.size),{data:i}=t;for(let u=0;u<r;u++){if(n[u]===0)continue;const c=i[u];if(c<0){o||(n[u]=0);continue}let f=h[c];f===0&&(f=a(l.get(c).toLowerCase())?1:-1,h[c]=f),f>0===o&&(n[u]=0)}return}for(let h=0;h<r;h++){if(n[h]===0)continue;const i=t.get(h);(i!==null&&a((typeof i=="number"?k(i):String(i)).toLowerCase()))===o&&(n[h]=0)}}_applyStringCompare(t,e,s,n){const{rank:r}=t.ranks(),{strings:l}=this.table.manager,{data:a}=t,o=String(e.value??"").toLowerCase();if(e.op==="equal"||e.op==="notEqual"){const c=e.op==="equal",f=new Int8Array(l.size);for(let m=0;m<n;m++){if(s[m]===0)continue;const p=a[m];let y=!1;if(p>=0){let d=f[p];d===0&&(d=l.get(p).toLowerCase()===o?1:-1,f[p]=d),y=d>0}else y=o==="";y!==c&&(s[m]=0)}return}const h=c=>{const f=String(c??"").toLowerCase();let m=-1;const p=new Int8Array(l.size);for(let y=0;y<n;y++){const d=a[y];d<0||p[d]||(p[d]=1,l.get(d).toLowerCase()<=f&&r[d]>m&&(m=r[d]))}return m+.5},i=h(e.value),u=e.value2!==void 0?h(e.value2):i;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=a[c];if(f<0){s[c]=0;continue}const m=r[f];let p;switch(e.op){case"gt":p=m>i;break;case"gte":p=m>i-1;break;case"lt":p=m<i-1;break;case"lte":p=m<i;break;case"between":p=m>i-1&&m<u;break;case"notBetween":p=!(m>i-1&&m<u);break;default:p=!0}p||(s[c]=0)}}_applyMixedCompare(t,e,s,n){const r=e.value;for(let l=0;l<n;l++){if(s[l]===0)continue;const a=t.get(l);let o;if(e.op==="equal"||e.op==="notEqual"){const h=a===r||typeof a=="string"&&typeof r=="string"&&a.toLowerCase()===r.toLowerCase();o=e.op==="equal"?h:!h}else typeof a!="number"?o=!1:o=ut(e.op,a,Number(r),Number(e.value2));o||(s[l]=0)}}_applyNumeric(t,e,s,n){const{data:r}=t,{op:l}=e,a=it(l,e.now??ot());if(a!==null){const[i,u]=a;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=r[c];f>=i&&f<u||(s[c]=0)}return}if(l==="top"||l==="bottom"){const i=new Float64Array(n);let u=0;for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];y===y&&(i[u++]=y)}const c=i.subarray(0,u).sort(),f=Math.max(0,Math.min(u,e.percent?Math.floor(u*Number(e.value)/100):Number(e.value)));if(f===0){s.fill(0);return}const m=l==="top"?c[u-f]:c[f-1];for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];(l==="top"?y>=m:y<=m)||(s[p]=0)}return}if(l==="aboveAverage"||l==="belowAverage"){let i=0,u=0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];m===m&&(i+=m,u++)}const c=u>0?i/u:0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];(l==="aboveAverage"?m>c:m<c)||(s[f]=0)}return}const o=q(e.value),h=q(e.value2);switch(l){case"gt":for(let i=0;i<n;i++)r[i]>o||(s[i]=0);return;case"gte":for(let i=0;i<n;i++)r[i]>=o||(s[i]=0);return;case"lt":for(let i=0;i<n;i++)r[i]<o||(s[i]=0);return;case"lte":for(let i=0;i<n;i++)r[i]<=o||(s[i]=0);return;case"equal":for(let i=0;i<n;i++)r[i]!==o&&(s[i]=0);return;case"notEqual":for(let i=0;i<n;i++)r[i]===o&&(s[i]=0);return;case"between":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h||(s[i]=0);return;case"notBetween":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h&&(s[i]=0);return;default:}}_applySearch(t,e,s){const n=t.toLowerCase(),{strings:r}=this.table.manager,l=ht(n),a=this.columns.map(i=>i.col).filter(i=>l||i.isString||i.kinds!==null),o=new Int8Array(r.size),h=i=>{let u=o[i];return u===0&&(u=r.get(i).toLowerCase().includes(n)?1:-1,o[i]=u),u>0};for(let i=0;i<s;i++){if(e[i]===0)continue;let u=!1;for(let c=0;c<a.length&&!u;c++){const f=a[c],m=f.kind(i);if(f!==D){if(m===R)u=h(f.data[i]);else if(m===F){const p=k(f.data[i]);u=(p.includes("E")?p.toLowerCase():p).includes(n)}}}u||(e[i]=0)}}_sortColumn(t,e,s,n){Q(this.table,t,e,s,n)}_groupKeys(t){return lt(this.table,this.spec.groups[t])}_sort(){const t=this.filteredCount,e=this.perm.length===t?this.perm:new Int32Array(t);e.set(this.filtered.subarray(0,t)),this.perm=e;const{sort:s,groups:n,hierarchy:r}=this.spec,l=this.table.byName.get("__order");l&&G(e,t,l.data,!1);for(let a=s.length-1;a>=0;a--){const o=this.table.column(s[a].field);o&&this._sortColumn(e,t,o,s[a].desc===!0)}if(this._keys=[],!r)for(let a=n.length-1;a>=0;a--){const o=this._groupKeys(a);o!==null&&(this._keys[a]=o,G(e,t,o,n[a].desc===!0))}}_group(){const{groups:t,hierarchy:e}=this.spec,s=this.filteredCount;if(e||t.length===0&&this.spec.totals.length===0){this.nodeCount=0,this.summaryValues.clear(),e&&this._computeRollups();return}(this._keys===void 0||this._keys.length===0&&t.length>0)&&this._sort();const n=t.length;let r=16,l=new Int32Array(r),a=new Int32Array(r),o=new Int32Array(r),h=new Int8Array(r),i=new Int32Array(r),u=new Int32Array(r);const c=()=>{const d=(g,w)=>{const b=new g(r*2);return b.set(w),b};l=d(Int32Array,l),a=d(Int32Array,a),o=d(Int32Array,o),h=d(Int8Array,h),i=d(Int32Array,i),u=d(Int32Array,u),r*=2};l[0]=0,a[0]=s,h[0]=-1,o[0]=-1;let f=1,m=0,p=1;this.levelStart=[];const{perm:y}=this;for(let d=0;d<n;d++){const g=this._keys[d];this.levelStart[d]=f;for(let w=m;w<p;w++){if(i[w]=f,g){let b=l[w];const A=a[w];for(;b<A;){const v=g[y[b]];let C=b+1;if(v===v)for(;C<A&&g[y[C]]===v;)C++;else for(;C<A&&g[y[C]]!==g[y[C]];)C++;f===r&&c(),l[f]=b,a[f]=C,o[f]=w,h[f]=d,f++,b=C}}u[w]=f}m=p,p=f}for(let d=m;d<p;d++)i[d]=0,u[d]=0;this.nodeCount=f,this.nodeStart=l,this.nodeEnd=a,this.nodeParent=o,this.nodeLevel=h,this.nodeChild=i,this.nodeChildEnd=u,this._applyCollapse(),this._computeSummaries()}_nodePath(t){const e=[];for(let s=t;s>0;s=this.nodeParent[s]){const n=this.spec.groups[this.nodeLevel[s]],r=this.groupKeyValue(s,n);e.push(r===null?"":String(r).toLowerCase())}return e.reverse().join("")}groupKeyValue(t,e=this.spec.groups[this.nodeLevel[t]]){const s=e.formula?M(this.table,e.formula):this.table.column(e.field),n=this.perm[this.nodeStart[t]],r=s.get(n);if(typeof r=="number"){if(e.by&&e.by!=="value")return this._keys[this.nodeLevel[t]][n];if(e.size>0)return Math.floor(r/e.size)*e.size;if(e.bins)return e.bins[this._keys[this.nodeLevel[t]][n]]?.name??"(other)"}return r instanceof tt?r.code:r}_applyCollapse(){const t=new Uint8Array(this.nodeCount),e=this.collapsedPaths.size>0,s=this.collapseFromLevel;if(e||s!==1/0)for(let n=1;n<this.nodeCount;n++){let r=this.nodeLevel[n]>=s;e&&this.collapsedPaths.has(this._nodePath(n))&&(r=!r),t[n]=r?1:0}this.nodeCollapsed=t}_computeSummaries(){if(this.summariesStale=!1,this.summaryValues.clear(),this.spec.hierarchy){this._computeRollups();return}if(this.nodeCount===0)return;const{groups:t,totals:e}=this.spec,s=this._generated??[],n=(l,a)=>{const o=s.filter(i=>i.sliceLevel===void 0?!0:i.sliceLevel===l).map(i=>({field:i.field,agg:i.summaryAgg??"sum"})),h=(a??[]).filter(i=>!i.slice&&!i.own);return o.length>0?[...h,...o]:h},r=(l,a,o,h)=>{if(!a||a.length===0)return;const i=a.length,u=new Float64Array((h-o)*i),{perm:c,nodeStart:f,nodeEnd:m}=this;a.forEach((p,y)=>{const d=p.field?this.table.column(p.field):null;if(p.where&&d){const g=M(this.table,p.where),w=new Int32Array(c.length);for(let b=o;b<h;b++){let A=0;for(let v=f[b];v<m[b];v++){const C=g.get(c[v]);(C===!0||typeof C=="number"&&C!==0)&&(w[A++]=c[v])}u[(b-o)*i+y]=P(d,p.agg??"sum",w,0,A)}}else if(p.formula){const g=this._summaryFormula(p.formula);for(let w=o;w<h;w++)u[(w-o)*i+y]=g(c,f[w],m[w],w)}else if(p.fn)for(let g=o;g<h;g++)u[(g-o)*i+y]=p.fn(c.subarray(f[g],m[g]),this.table);else if(d)for(let g=o;g<h;g++)u[(g-o)*i+y]=P(d,p.agg??"sum",c,f[g],m[g]);else u.fill(NaN)}),this.summaryValues.set(l,{values:u,per:i,list:a,first:o})};r(-1,e?.length>0?n(-1,e):e,0,1);for(let l=0;l<t.length;l++){const a=this.levelStart[l],o=l+1<t.length?this.levelStart[l+1]:this.nodeCount;r(l,n(l,t[l].summaries),a,o)}}_summaryFormula(t){const e=[],s=(i,u,c)=>(e.push({agg:rt[i.toUpperCase()],col:this.table.column(u.trim()),scope:c}),`$${J(e.length-1)}$1`),n=String(t).replace(/^=/,"").replace(st,(i,u,c,f,m)=>{if(!/REMOVEFILTERS/i.test(i))return s(u,c,null);const p=f??m,y=p?this.spec.groups.findIndex(d=>d.field===p.trim()):0;return s(u,c,{up:Math.max(0,y)})}).replace(nt,(i,u,c)=>s(u,c,null)),r=this.table.manager.formulas._engineFor(),l=r.template(n,0,0),a=e.map(()=>({kinds:new Uint8Array(1024),values:new Float64Array(1024),styles:null})),o=this.table.manager.formulas._sheet(this.table),h=(i,u)=>{let c=i;for(;c>0&&this.nodeLevel[c]>=u;)c=this.nodeParent[c];return c};return(i,u,c,f=0)=>{o.columns.length=0,e.forEach((p,y)=>{let d=u,g=c;if(p.scope){const b=h(f,p.scope.up);d=this.nodeStart[b],g=this.nodeEnd[b]}const w=p.col?P(p.col,p.agg,i,d,g):NaN;a[y].kinds[0]=w===w?F:T,a[y].values[0]=w,o.columns[y]=[a[y]]});let m;try{m=l.fn(0,0,o),m&&m.isCell&&(m=r.read(m.sheet,m.r0,m.c0))}catch{m=NaN}return o.columns.length=0,typeof m=="number"?m:NaN}}summaryFor(t,e){const s=this.nodeLevel[t],n=this.summaryValues.get(s);if(!n)return;const r=n.list.findIndex(l=>l.field===e||l.column===e);if(!(r<0))return n.values[(t-n.first)*n.per+r]}_buildTreeLinks(t,e){const s=this.spec.hierarchy,n=this.table,r=new Int32Array(e).fill(-1);if(s.level){const l=n.column(s.level);n.ensure(l);const{data:a}=l,o=[];for(let h=0;h<e;h++){if(!n.alive[h])continue;const i=a[h]===a[h]?a[h]:0;o.length=Math.min(o.length,i),r[h]=o.length>0?o[o.length-1]:-1,o[i]=h}}else{const l=n.column(s.key??n.key),a=n.column(s.parent);if(n.ensure(l),n.ensure(a),l.isString===a.isString&&l.kinds===null&&a.kinds===null){const o=Z(l,n),{data:h}=a;for(let i=0;i<e;i++){const u=h[i];u===u&&u!==-1&&(r[i]=o(u))}}else{const o=new Map;for(let h=e-1;h>=0;h--)n.alive[h]&&o.set(String(l.get(h)),h);for(let h=0;h<e;h++){const i=a.get(h);i!==null&&(r[h]=o.get(String(i))??-1)}}}if(this.treeParent=r,this.spec.filters.length>0||this.spec.search){for(let l=0;l<e;l++)if(t[l]!==0)for(let a=r[l];a>=0&&t[a]===0;a=r[a])t[a]=1}}_flattenTree(t,e){const s=this.filteredCount,n=this.table.rowCount,r=this.treeParent,{perm:l}=this,a=new Int32Array(n).fill(-1),o=new Int32Array(n).fill(-1),h=new Uint16Array(n),i=new Uint8Array(n),u=new Uint8Array(n);for(let w=0;w<s;w++)u[l[w]]=1;const c=[];for(let w=s-1;w>=0;w--){const b=l[w],A=r[b];A>=0&&u[A]===1&&A!==b?(o[b]=a[A],a[A]=b,i[A]=1):c.push(b)}const f=new Uint8Array(n),m=this.treeCollapsed;let p=0;const y=new Int32Array(Math.max(16,s+1));let d=0;const g=w=>{for(y[d++]=w;d>0;){const b=y[--d];if(f[b]===1)continue;f[b]=1,(!e||e[b]===0)&&(p<t.length&&(t[p]=b),p++);const A=h[b];if(a[b]>=0&&!m.has(b)){let v=a[b];const C=d;let L=0;for(;v>=0;)h[v]=A+1,y[d++]=v,L++,v=o[v];for(let I=C,N=C+L-1;I<N;I++,N--){const z=y[I];y[I]=y[N],y[N]=z}}}};for(let w=c.length-1;w>=0;w--)g(c[w]);if(!m.size)for(let w=0;w<s;w++)f[l[w]]===0&&g(l[w]);return this.treeLevel=h,this.treeHasKids=i,p}_computeRollups(){this.rollups.clear();const t=this.spec.hierarchy?.rollups;if(!t||t.length===0||!this.treeParent)return;const e=this.filteredCount,{perm:s,treeParent:n}=this,r=this.table.rowCount,l=new Int32Array(r).fill(-1),a=i=>{const u=[];let c=i;for(;c>=0&&l[c]<0&&u.length<r;)u.push(c),l[c]=0,c=n[c];let f=c>=0?l[c]+1:0;for(let m=u.length-1;m>=0;m--)l[u[m]]=f++};for(let i=0;i<e;i++)a(s[i]);const o=s.slice(0,e),h=new Uint32Array(e);for(let i=0;i<e;i++)h[i]=l[o[i]];j(o,e,h);for(const i of t){const u=this.table.column(i.field);if(!u)continue;this.table.ensure(u);const c=i.agg??"sum",f=new Float64Array(r).fill(NaN),m=new Float64Array(r),p=new Uint8Array(r);for(let y=0;y<e;y++){const d=o[y],g=u.isString?u.data[d]>=0?1:NaN:u.kinds!==null&&u.kinds[d]!==F?NaN:u.data[d];g===g&&(f[d]=c==="count"?1:g,m[d]=1)}for(let y=e-1;y>=0;y--){const d=o[y],g=n[d];if(g<0||l[g]<0||m[d]===0)continue;p[g]===0&&(p[g]=1,f[g]=NaN,m[g]=0);const w=f[d],b=f[g];c==="min"?f[g]=b!==b||w<b?w:b:c==="max"?f[g]=b!==b||w>b?w:b:f[g]=(b!==b?0:b)+w,m[g]+=m[d]}if(c==="average")for(let y=0;y<e;y++){const d=o[y];p[d]===1&&m[d]>0&&(f[d]/=m[d])}this.rollups.set(i.field,{values:f,touched:p})}}_flatten(){const t=this.spec.pinnedRows.filter(v=>v<this.table.rowCount&&this.table.alive[v]===1);this.pinned=Int32Array.from(t);let e=null;if(t.length>0){e=new Uint8Array(this.table.rowCount);for(const v of t)e[v]=1}const s=U-2-t.length;if(this.spec.hierarchy){const v=this.map.length>=this.filteredCount?this.map:new Int32Array(this.filteredCount);this.count=this._flattenTree(v,e),this.map=v,this.truncated=this.count>s,this.truncated&&(this.count=s),this.inverse=null;return}const n=this.spec.groups,r=this.filteredCount,{perm:l}=this;if(n.length===0&&this.spec.totals.length===0){const v=Math.min(r,s),C=this.map.length>=v?this.map:new Int32Array(v);if(e===null)C.set(l.subarray(0,v)),this.count=v;else{let L=0;for(let I=0;I<r&&L<v;I++){const N=l[I];e[N]===0&&(C[L++]=N)}this.count=L}this.map=C,this.truncated=r>s,this.inverse=null;return}this.groupStartOf=null,this.groupStartNode=null;const a=n.map(v=>v.footer===!0),o=this.spec.totals.length>0;let h=r+(o?1:0);for(let v=1;v<this.nodeCount;v++)h+=a[this.nodeLevel[v]]?2:1;const i=Math.min(h,s),u=this.map.length>=i?this.map:new Int32Array(i);let c=0;const f=n.length-1,{nodeChild:m,nodeChildEnd:p,nodeLevel:y,nodeCollapsed:d,nodeStart:g,nodeEnd:w}=this,b=this.spec.groupLayout==="tabular",A=v=>{if(c>=i)return;const C=y[v];if((!b||d[v]===1)&&(u[c++]=-(1+v*2)),d[v]!==1){if(C===f){const L=g[v],I=w[v];if(b&&this._markGroupStart(L,C,v),e===null){const N=Math.min(I-L,i-c);u.set(l.subarray(L,L+N),c),c+=N}else for(let N=L;N<I&&c<i;N++)e[l[N]]===0&&(u[c++]=l[N])}else for(let L=m[v];L<p[v];L++)A(L);a[C]&&c<i&&(u[c++]=-(2+v*2))}};if(n.length===0){const v=Math.min(r,i-1);if(e===null)u.set(l.subarray(0,v),0),c=v;else for(let C=0;C<r&&c<i-1;C++)e[l[C]]===0&&(u[c++]=l[C])}else for(let v=m[0];v<p[0];v++)A(v);o&&c<i&&(u[c++]=-2),this.count=c,this.map=u,this.truncated=h>s,this.inverse=null}_markGroupStart(t,e,s){const n=this.perm[t];this.groupStartOf||(this.groupStartOf=new Map),this.groupStartNode||(this.groupStartNode=new Map),this.groupStartNode.set(n,s);let r=e;for(let l=e-1;l>=0;l--){const a=this._keys[l],o=t>0?this.perm[t-1]:-1;if(o>=0&&(a[o]===a[n]||a[o]!==a[o]&&a[n]!==a[n]))break;r=l}this.groupStartOf.set(n,r)}showsGroupValue(t,e){const s=this.groupStartOf?.get(t);return s!==void 0&&s<=e}summaryOfRecord(t,e){let s=this.groupStartNode?.get(t);if(s!==void 0){for(;s>0&&this.nodeLevel[s]>e.sliceLevel;)s=this.nodeParent[s];return this.summariesStale&&this._computeSummaries(),this.summaryFor(s,e.field)}}recordNumberAt(t){if(this.spec.groups.length===0)return t+1;if(this._numbersOf!==this.map){const e=new Int32Array(this.count);let s=0;for(let n=0;n<this.count;n++)this.map[n]>=0&&(e[n]=++s);this._numbers=e,this._numbersOf=this.map}return this._numbers[t]}rowInfo(t){if(t<0||t>=this.count)return null;const e=this.map[t];if(e>=0){const r=this.treeLevel?this.treeLevel[e]:0;return{kind:"record",record:e,level:r,hasChildren:this.treeHasKids?this.treeHasKids[e]===1:!1,collapsed:this.treeCollapsed.has(e)}}const s=-e-1,n=s>>>1;return{kind:s&1?"footer":"group",node:n,level:this.nodeLevel[n],collapsed:this.nodeCollapsed[n]===1}}recordAt(t){const e=this.map[t];return t>=0&&t<this.count&&e>=0?e:-1}rowOfRecord(t){if(this.inverse===null){const e=new Int32Array(this.table.rowCount).fill(-1);for(let s=0;s<this.count;s++){const n=this.map[s];n>=0&&(e[n]=s)}this.inverse=e}return t<this.inverse.length?this.inverse[t]:-1}groupCaption(t){const e=this.nodeLevel[t],s=this.spec.groups[e],n=this.table.column(s.field),r=this.nodeEnd[t]-this.nodeStart[t],l=s.caption??n?.caption??s.field,a=this.groupKeyValue(t,s);return this.spec.groupLayout==="condensed"?`${this._groupValueText(a,s,n)} (${r})`:`${l}: ${this._groupValueText(a,s,n)} (${r})`}_groupValueText(t,e,s){if(t==null)return"(blank)";if(typeof t=="number"){switch(e.by){case"year":return String(t);case"quarter":return`Q${t%4+1} ${Math.floor(t/4)}`;case"month":return`${et[t%12]} ${Math.floor(t/12)}`;case"week":{const n=x(t*7+1);return`Week of ${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}default:}return e.size>0?`${k(t)} to ${k(t+e.size)}`:s&&s.format!=="General"?V(s.format).number(t):k(t)}return typeof t=="boolean"?t?"TRUE":"FALSE":String(t)}toggleRow(t){const e=this.rowInfo(t);return e?e.kind==="group"?(this._setNode(e.node,!e.collapsed),this._relayout(),!0):e.kind==="record"&&e.hasChildren?(e.collapsed?this.treeCollapsed.delete(e.record):this.treeCollapsed.add(e.record),this._relayout(),!0):!1:!1}_setNode(t,e){this.nodeCollapsed[t]=e?1:0;const s=this._nodePath(t),n=this.nodeLevel[t]>=this.collapseFromLevel;e===n?this.collapsedPaths.delete(s):this.collapsedPaths.add(s)}showLevel(t){if(this.collapsedPaths.clear(),this.collapseFromLevel=t,this.treeCollapsed.clear(),this.spec.hierarchy&&t!==1/0){const e=this.treeLevelsAll(),s=this.table.rowCount;for(let n=0;n<s;n++)e[n]>=t&&this.treeHasKids[n]===1&&this.treeCollapsed.add(n)}this.nodeCount>0&&this._applyCollapse(),this._relayout()}treeLevelsAll(){const t=this.table.rowCount,e=new Uint16Array(t),s=this.treeParent,n=new Uint8Array(t),r=[];for(let l=0;l<t;l++){let a=l;for(r.length=0;a>=0&&n[a]===0&&r.length<=t;)r.push(a),n[a]=1,a=s[a];let o=a>=0?e[a]+1:0;for(let h=r.length-1;h>=0;h--)e[r[h]]=o++}return e}expandAll(){this.showLevel(1/0)}collapseAll(){this.showLevel(0)}_relayout(){this.invalidate(S.FLATTEN),this.refresh()}distinctValues(t,{limit:e=5e3}={}){const s=this.table.column(t);if(!s)return{values:[],total:0};this.table.ensure(s);const n=this.table.rowCount,r=new Uint8Array(n);r.set(this.table.alive.subarray(0,n));for(const h of this.spec.filters)h.field!==t&&this._applyCondition(h,r,n);const l=new Map;for(let h=0;h<n;h++){if(r[h]===0)continue;const i=s.kind(h),u=i===T?null:i===R||s.isString?`s${s.data[h]}`:s.data[h];l.set(u,(l.get(u)??0)+1)}const{strings:a}=this.table.manager,o=[];for(const[h,i]of l)if(h===null)o.push({value:null,text:"(Blanks)",count:i});else if(typeof h=="string"){const u=a.get(Number(h.slice(1)));o.push({value:u,text:u,count:i})}else{const u=s.format!=="General"?V(s.format).number(h):k(h);o.push({value:s.type==="boolean"?h!==0:h,text:s.type==="boolean"?h?"TRUE":"FALSE":u,count:i})}return o.sort((h,i)=>h.value===null?1:i.value===null?-1:typeof h.value=="number"&&typeof i.value=="number"?h.value-i.value:String(h.text).localeCompare(String(i.text))),{values:o.slice(0,e),total:o.length}}}function k(_){return X(_)}function ht(_){const t=new Set("0123456789eE");for(const e of[-1.5,1e20,1e-20,1/0,-1/0,NaN])for(const s of k(e))t.add(s);for(const e of _)if(!t.has(e))return!1;return!0}function q(_){return typeof _=="number"?_:typeof _=="boolean"?_?1:0:_==null||_===""?NaN:Number(_)}function ut(_,t,e,s){switch(_){case"gt":return t>e;case"gte":return t>=e;case"lt":return t<e;case"lte":return t<=e;case"between":return t>=e&&t<=s;case"notBetween":return!(t>=e&&t<=s);default:return!0}}O.prototype.addView=function(t,e,s={}){const n=new at(this,{name:t,columns:e,...s});return this.views.set(t,n),n},O.prototype.getView=function(t){return this.views.get(t)??null},O.prototype.removeView=function(t){this.views.get(t)?.dispose(),this.views.delete(t)};export{vt as AGG_LABEL,_t as FILTER_OPS,S as STAGE,wt as SUMMARY_AGGS,at as TableView,P as aggregate,M as formulaHelper,lt as groupKeys,ot as todaySerial};
package/i18n/dom.js CHANGED
@@ -1 +1 @@
1
- import{t as n}from"./index.js";import{keyText as c}from"./key-text.js";const o=new WeakMap;function x(t,r){const e={...o.get(t),...r};o.set(t,e),t.dataset.i18n=Object.keys(e).join(" ");for(const[s,i]of Object.entries(r))s==="text"?t.textContent=n(i):t.setAttribute(s,n(i));return t}function u(t){if(!t?.querySelectorAll)return;const r=t.matches?.("[data-i18n]")?[t,...t.querySelectorAll("[data-i18n]")]:t.querySelectorAll("[data-i18n]");for(const e of r){let s=o.get(e);if(!s){s={};for(const i of e.dataset.i18n.split(/\s+/))i==="text"?s.text=e.textContent:e.hasAttribute(i)&&(s[i]=e.getAttribute(i));o.set(e,s)}for(const[i,a]of Object.entries(s))i==="text"?e.textContent=n(a):e.setAttribute(i,i==="title"?c(n(a)):n(a))}}export{x as bindText,u as localizeTree};
1
+ import{t as n}from"./index.js";import{keyText as a}from"./key-text.js";const l=(t,s)=>t==="title"||t==="placeholder"?a(n(s)):n(s),o=new WeakMap;function x(t,s){const e={...o.get(t),...s};o.set(t,e),t.dataset.i18n=Object.keys(e).join(" ");for(const[r,i]of Object.entries(s))r==="text"?t.textContent=n(i):t.setAttribute(r,l(r,i));return t}function b(t){if(!t?.querySelectorAll)return;const s=t.matches?.("[data-i18n]")?[t,...t.querySelectorAll("[data-i18n]")]:t.querySelectorAll("[data-i18n]");for(const e of s){let r=o.get(e);if(!r){r={};for(const i of e.dataset.i18n.split(/\s+/))i==="text"?r.text=e.textContent:e.hasAttribute(i)&&(r[i]=e.getAttribute(i));o.set(e,r)}for(const[i,c]of Object.entries(r))i==="text"?e.textContent=n(c):e.setAttribute(i,l(i,c))}}export{x as bindText,b as localizeTree};