@xh/hoist 90.0.0 → 90.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +136 -54
  2. package/admin/columns/Tracking.ts +9 -3
  3. package/admin/tabs/activity/tracking/ActivityTrackingModel.ts +155 -47
  4. package/admin/tabs/activity/tracking/ActivityTrackingPanel.ts +25 -4
  5. package/admin/tabs/activity/tracking/chart/AggChartModel.ts +2 -3
  6. package/appcontainer/ImpersonationBarModel.ts +8 -5
  7. package/build/types/admin/tabs/activity/tracking/ActivityTrackingModel.d.ts +25 -5
  8. package/build/types/cmp/cubegrid/CubeGrid.d.ts +26 -0
  9. package/build/types/cmp/cubegrid/CubeGridModel.d.ts +103 -0
  10. package/build/types/cmp/cubegrid/CubeGridPivotModel.d.ts +181 -0
  11. package/build/types/cmp/cubegrid/Types.d.ts +85 -0
  12. package/build/types/cmp/cubegrid/index.d.ts +4 -0
  13. package/build/types/cmp/dataview/DataViewModel.d.ts +6 -10
  14. package/build/types/cmp/grid/GridModel.d.ts +8 -33
  15. package/build/types/cmp/grid/Types.d.ts +51 -1
  16. package/build/types/cmp/grid/columns/Column.d.ts +2 -1
  17. package/build/types/cmp/grid/columns/ColumnGroup.d.ts +6 -0
  18. package/build/types/cmp/grid/helpers/GridCountLabel.d.ts +6 -3
  19. package/build/types/cmp/grid/impl/ColumnWidthCalculator.d.ts +6 -0
  20. package/build/types/cmp/grid/impl/GridLikeModel.d.ts +3 -0
  21. package/build/types/cmp/grid/impl/MenuSupport.d.ts +13 -0
  22. package/build/types/cmp/pdfviewer/PdfViewer.d.ts +14 -0
  23. package/build/types/cmp/pdfviewer/PdfViewerModel.d.ts +150 -0
  24. package/build/types/cmp/pdfviewer/Types.d.ts +55 -0
  25. package/build/types/cmp/pdfviewer/impl/PdfFindInputModel.d.ts +14 -0
  26. package/build/types/cmp/pdfviewer/impl/PdfViewerToolbarModel.d.ts +34 -0
  27. package/build/types/cmp/pdfviewer/impl/ZoomOptions.d.ts +10 -0
  28. package/build/types/cmp/pdfviewer/index.d.ts +3 -0
  29. package/build/types/cmp/statcard/StatCard.d.ts +90 -0
  30. package/build/types/cmp/statcard/index.d.ts +1 -0
  31. package/build/types/cmp/store/StoreFilterField.d.ts +8 -9
  32. package/build/types/cmp/store/impl/StoreFilterFieldImplModel.d.ts +4 -4
  33. package/build/types/cmp/zoneGrid/ZoneGridModel.d.ts +6 -10
  34. package/build/types/core/types/Types.d.ts +6 -0
  35. package/build/types/data/Field.d.ts +8 -1
  36. package/build/types/data/Store.d.ts +12 -0
  37. package/build/types/data/cube/Cube.d.ts +2 -0
  38. package/build/types/data/cube/CubeField.d.ts +3 -2
  39. package/build/types/data/cube/Query.d.ts +66 -4
  40. package/build/types/data/cube/View.d.ts +82 -4
  41. package/build/types/data/cube/ViewRowData.d.ts +13 -0
  42. package/build/types/data/cube/aggregate/MedianAggregator.d.ts +19 -0
  43. package/build/types/data/cube/aggregate/SumIfSameAggregator.d.ts +30 -0
  44. package/build/types/data/cube/impl/RowCache.d.ts +5 -0
  45. package/build/types/data/cube/impl/RowDataGenerator.d.ts +26 -0
  46. package/build/types/data/cube/impl/ViewDiagnostics.d.ts +27 -0
  47. package/build/types/data/cube/pivot/PivotCellRow.d.ts +27 -0
  48. package/build/types/data/cube/pivot/PivotPath.d.ts +45 -0
  49. package/build/types/data/cube/pivot/impl/PivotCells.d.ts +111 -0
  50. package/build/types/data/cube/pivot/impl/PivotReference.d.ts +39 -0
  51. package/build/types/data/cube/pivot/impl/PivotStructure.d.ts +105 -0
  52. package/build/types/data/cube/row/BaseRow.d.ts +12 -0
  53. package/build/types/data/cube/row/LeafRow.d.ts +4 -4
  54. package/build/types/data/cube/row/ParentRow.d.ts +20 -4
  55. package/build/types/data/cube/row/RowUpdate.d.ts +2 -0
  56. package/build/types/data/index.d.ts +3 -0
  57. package/build/types/desktop/cmp/button/grid/ColAutosizeButton.d.ts +6 -3
  58. package/build/types/desktop/cmp/button/grid/ColChooserButton.d.ts +7 -3
  59. package/build/types/desktop/cmp/button/grid/ExpandToLevelButton.d.ts +6 -3
  60. package/build/types/desktop/cmp/button/grid/ExportButton.d.ts +6 -3
  61. package/build/types/desktop/cmp/grid/find/GridFindField.d.ts +8 -9
  62. package/build/types/desktop/cmp/grid/find/impl/GridFindFieldImplModel.d.ts +3 -4
  63. package/build/types/desktop/cmp/pdfviewer/impl/PdfViewerToolbar.d.ts +12 -0
  64. package/build/types/desktop/cmp/statcard/impl/StatCardInfoImpl.d.ts +12 -0
  65. package/build/types/dynamics/desktop.d.ts +2 -0
  66. package/build/types/dynamics/mobile.d.ts +1 -0
  67. package/build/types/icon/Icon.d.ts +12 -0
  68. package/build/types/kit/pdfjs/index.d.ts +23 -0
  69. package/build/types/kit/pdfjs/styles.d.ts +2 -0
  70. package/build/types/kit/swiper/index.d.ts +7 -7
  71. package/build/types/mobile/cmp/button/grid/ColAutosizeButton.d.ts +6 -3
  72. package/build/types/mobile/cmp/button/grid/ColChooserButton.d.ts +6 -3
  73. package/build/types/mobile/cmp/button/grid/ExpandCollapseButton.d.ts +4 -4
  74. package/build/types/mobile/cmp/button/grid/ExpandToLevelButton.d.ts +4 -4
  75. package/build/types/mobile/cmp/pdfviewer/impl/PdfViewerToolbar.d.ts +12 -0
  76. package/cmp/README.md +3 -0
  77. package/cmp/ag-grid/AgGrid.ts +25 -3
  78. package/cmp/cubegrid/CubeGrid.ts +60 -0
  79. package/cmp/cubegrid/CubeGridModel.ts +365 -0
  80. package/cmp/cubegrid/CubeGridPivotModel.ts +943 -0
  81. package/cmp/cubegrid/README.md +343 -0
  82. package/cmp/cubegrid/Types.ts +105 -0
  83. package/cmp/cubegrid/index.ts +10 -0
  84. package/cmp/dataview/DataViewModel.ts +13 -8
  85. package/cmp/grid/Grid.scss +21 -5
  86. package/cmp/grid/GridModel.ts +41 -47
  87. package/cmp/grid/Types.ts +58 -1
  88. package/cmp/grid/columns/Column.ts +3 -1
  89. package/cmp/grid/columns/ColumnGroup.ts +10 -0
  90. package/cmp/grid/helpers/GridCountLabel.ts +12 -5
  91. package/cmp/grid/impl/ColumnGroupHeader.ts +18 -4
  92. package/cmp/grid/impl/ColumnWidthCalculator.ts +24 -0
  93. package/cmp/grid/impl/GridLikeModel.ts +17 -0
  94. package/cmp/grid/impl/MenuSupport.ts +36 -20
  95. package/cmp/pdfviewer/PdfViewer.scss +48 -0
  96. package/cmp/pdfviewer/PdfViewer.ts +102 -0
  97. package/cmp/pdfviewer/PdfViewerModel.ts +641 -0
  98. package/cmp/pdfviewer/README.md +224 -0
  99. package/cmp/pdfviewer/Types.ts +72 -0
  100. package/cmp/pdfviewer/impl/PdfFindInputModel.ts +44 -0
  101. package/cmp/pdfviewer/impl/PdfViewerToolbarModel.ts +45 -0
  102. package/cmp/pdfviewer/impl/ZoomOptions.ts +36 -0
  103. package/cmp/pdfviewer/index.ts +9 -0
  104. package/cmp/statcard/StatCard.scss +181 -0
  105. package/cmp/statcard/StatCard.ts +320 -0
  106. package/cmp/statcard/index.ts +1 -0
  107. package/cmp/store/StoreFilterField.ts +8 -9
  108. package/cmp/store/impl/StoreFilterFieldImplModel.ts +14 -14
  109. package/cmp/zoneGrid/ZoneGridModel.ts +13 -8
  110. package/core/types/Types.ts +7 -0
  111. package/data/Field.ts +10 -0
  112. package/data/Store.ts +25 -2
  113. package/data/cube/Cube.ts +5 -0
  114. package/data/cube/CubeField.ts +5 -0
  115. package/data/cube/Query.ts +170 -17
  116. package/data/cube/README.md +77 -2
  117. package/data/cube/View.ts +211 -32
  118. package/data/cube/ViewRowData.ts +22 -0
  119. package/data/cube/aggregate/MedianAggregator.ts +88 -0
  120. package/data/cube/aggregate/SumIfSameAggregator.ts +128 -0
  121. package/data/cube/impl/RowCache.ts +32 -11
  122. package/data/cube/impl/RowDataGenerator.ts +96 -4
  123. package/data/cube/impl/ViewDiagnostics.ts +47 -0
  124. package/data/cube/pivot/PivotCellRow.ts +73 -0
  125. package/data/cube/pivot/PivotPath.ts +67 -0
  126. package/data/cube/pivot/impl/PivotCells.ts +538 -0
  127. package/data/cube/pivot/impl/PivotReference.ts +125 -0
  128. package/data/cube/pivot/impl/PivotStructure.ts +500 -0
  129. package/data/cube/row/BaseRow.ts +26 -0
  130. package/data/cube/row/LeafRow.ts +9 -8
  131. package/data/cube/row/ParentRow.ts +58 -25
  132. package/data/cube/row/RowUpdate.ts +8 -0
  133. package/data/index.ts +3 -0
  134. package/desktop/appcontainer/AppContainer.ts +5 -1
  135. package/desktop/cmp/button/grid/ColAutosizeButton.ts +21 -5
  136. package/desktop/cmp/button/grid/ColChooserButton.ts +11 -5
  137. package/desktop/cmp/button/grid/ExpandToLevelButton.ts +20 -5
  138. package/desktop/cmp/button/grid/ExportButton.ts +19 -7
  139. package/desktop/cmp/dash/canvas/DashCanvas.ts +26 -2
  140. package/desktop/cmp/grid/find/GridFindField.ts +8 -9
  141. package/desktop/cmp/grid/find/impl/GridFindFieldImplModel.ts +15 -16
  142. package/desktop/cmp/grid/impl/colchooser/ColChooserBucketModel.ts +1 -1
  143. package/desktop/cmp/pdfviewer/impl/PdfViewerToolbar.ts +190 -0
  144. package/desktop/cmp/statcard/impl/StatCardInfoImpl.ts +27 -0
  145. package/docs/README.md +6 -2
  146. package/docs/doc-registry.json +21 -5
  147. package/docs/upgrade-notes/v90-upgrade-notes.md +130 -0
  148. package/docs/version-compatibility.md +2 -1
  149. package/dynamics/desktop.ts +4 -0
  150. package/dynamics/mobile.ts +2 -0
  151. package/format/FormatNumber.ts +6 -2
  152. package/icon/Icon.ts +18 -0
  153. package/icon/index.ts +32 -0
  154. package/kit/README.md +2 -0
  155. package/kit/pdfjs/PdfJs.scss +25 -0
  156. package/kit/pdfjs/index.ts +103 -0
  157. package/kit/pdfjs/pdf_viewer.css +6481 -0
  158. package/kit/pdfjs/styles.ts +12 -0
  159. package/mcp/README.md +13 -0
  160. package/mcp/data/import-paths.ts +4 -8
  161. package/mcp/data/index-cache.ts +2 -1
  162. package/mcp/data/ts-registry.ts +8 -29
  163. package/mcp/util/paths.ts +26 -0
  164. package/mobile/appcontainer/AppContainer.ts +3 -1
  165. package/mobile/cmp/button/grid/ColAutosizeButton.ts +20 -5
  166. package/mobile/cmp/button/grid/ColChooserButton.ts +12 -5
  167. package/mobile/cmp/button/grid/ExpandCollapseButton.ts +10 -6
  168. package/mobile/cmp/button/grid/ExpandToLevelButton.ts +10 -6
  169. package/mobile/cmp/pdfviewer/impl/PdfViewerToolbar.ts +137 -0
  170. package/package.json +14 -8
  171. package/public/msal-redirect-bridge.min.js +1 -1
  172. package/styles/vars.scss +59 -0
package/data/cube/View.ts CHANGED
@@ -8,6 +8,8 @@
8
8
  import type {GridFilterBindTarget} from '@xh/hoist/cmp/grid';
9
9
  import type {PlainObject, Some} from '@xh/hoist/core';
10
10
  import {HoistBase} from '@xh/hoist/core';
11
+ import type {HoistException} from '@xh/hoist/exception';
12
+ import {isHoistException} from '@xh/hoist/exception';
11
13
  import {instanceManager} from '@xh/hoist/core/impl/InstanceManager';
12
14
  import type {
13
15
  CubeField,
@@ -17,19 +19,22 @@ import type {
17
19
  FilterValueSource,
18
20
  Query,
19
21
  QueryConfig,
20
- Store,
22
+ StoreConfig,
21
23
  StoreRecord,
22
24
  StoreRecordId
23
25
  } from '@xh/hoist/data';
24
- import {Cube} from '@xh/hoist/data';
26
+ import {Cube, Store} from '@xh/hoist/data';
25
27
  import type {ViewRowData} from '@xh/hoist/data/cube/ViewRowData';
28
+ import {VIEW_ROW_DATA_FIELDS} from '@xh/hoist/data/cube/ViewRowData';
26
29
  import {ViewDiagnostics} from './impl/ViewDiagnostics';
27
30
  import {action, observable, observableRef} from '@xh/hoist/mobx';
28
31
  import {throwIf} from '@xh/hoist/utils/js';
29
32
  import {castArray, forEach, groupBy, isEmpty, isNil, map} from 'lodash';
30
33
  import {AggregationContext} from './aggregate/AggregationContext';
34
+ import {PivotCells} from './pivot/impl/PivotCells';
31
35
  import {RowCache} from './impl/RowCache';
32
36
  import {RowDataGenerator} from './impl/RowDataGenerator';
37
+ import type {PivotCellField, PivotPath} from './pivot/PivotPath';
33
38
  import {BaseRow} from './row/BaseRow';
34
39
  import type {LeafRow, LeafUpdateChanges} from './row/LeafRow';
35
40
  import {ExposedLeafRow, HiddenLeafRow} from './row/LeafRow';
@@ -81,6 +86,47 @@ export interface ViewResult {
81
86
  * safe to publish. Use {@link Cube.store} to read source records directly in that case.
82
87
  */
83
88
  leafMap: Map<StoreRecordId, ExposedLeafRow>;
89
+
90
+ /**
91
+ * Pivot path tree, top-level paths first with nested `children`. Empty unless the query sets
92
+ * {@link QueryConfig.pivot}. Identity-stable while the pivot structure is unchanged - track it
93
+ * to decide whether to rebuild columns.
94
+ */
95
+ paths: PivotPath[];
96
+
97
+ /**
98
+ * One entry per (pivot path, measure), including the root-path row summaries. Identity-stable
99
+ * with `paths` - track it to decide whether to re-declare Store fields. Note both move on a
100
+ * `measures`-only change, even though the path tree itself is structurally unchanged.
101
+ */
102
+ cellFields: PivotCellField[];
103
+
104
+ /**
105
+ * Set when the View declined to produce a result from this data: a step in its pipeline threw
106
+ * a routine `HoistException`, such as the pivot cap in {@link PivotSpec.maxPivotPaths} or an
107
+ * app aggregator rejecting the values it was given. The query is valid and the code is
108
+ * correct, but this data does not fit it, so the message is addressed to the user. `rows`,
109
+ * `paths` and `cellFields` are empty and connected stores are cleared while set. Null
110
+ * otherwise.
111
+ *
112
+ * Any other exception is a bug and propagates from the update that hit it. Mark an exception
113
+ * routine only when the user, not the developer, can clear it.
114
+ */
115
+ exception: HoistException;
116
+ }
117
+
118
+ /**
119
+ * Configuration for {@link View.createStore}. Accepts the full {@link StoreConfig} surface,
120
+ * defaulting `loadTreeData` and `projectionOnly` to true.
121
+ * @internal
122
+ */
123
+ export interface ViewStoreConfig extends StoreConfig {
124
+ /**
125
+ * True to register the new Store for live updates from this view. The *caller* owns the store
126
+ * and must call {@link View.disconnectStore} when done with it. False (default) to declare
127
+ * fields and load once from the current result, then never again.
128
+ */
129
+ connect?: boolean;
84
130
  }
85
131
 
86
132
  export interface DimensionValue {
@@ -98,6 +144,10 @@ export interface DimensionValue {
98
144
  *
99
145
  * Use `updateQuery()` to change dimensions, filters, or options dynamically.
100
146
  *
147
+ * A query with {@link QueryConfig.pivot} additionally slices its aggregates across a pivot axis,
148
+ * publishing each cell as a synthetic field on its group row - see {@link ViewResult.cellFields}
149
+ * and `PivotCells`.
150
+ *
101
151
  * See the Cube package README (`data/cube/README.md`) for query patterns and examples
102
152
  * of grand totals, leaf drill-down, and store integration.
103
153
  *
@@ -139,18 +189,26 @@ export class View
139
189
  @observable accessor lastUpdated: number;
140
190
 
141
191
  /** @internal */
142
- readonly diagnostics = new ViewDiagnostics(this);
192
+ readonly diagnostics: ViewDiagnostics;
143
193
 
144
194
  _created = Date.now();
145
195
 
146
196
  // Implementation
147
197
  private _rowDatas: ViewRowData[] = null;
148
- private _leafMap: Map<StoreRecordId, LeafRow> = null;
198
+ _rootRows: BaseRow[] = null; // generated root rows, the top of the aggregation network
199
+ _leafMap: Map<StoreRecordId, LeafRow> = null;
149
200
  _records: RecordSet = null; // cube records passing this view's filter
150
201
  private _bucketDependentFields = new Set<string>();
151
202
 
152
203
  private _fieldsByName: Map<string, CubeField> = null;
153
- private _rowDataGenerator: RowDataGenerator = null;
204
+ // Fields whose values place a record in the row hierarchy - query and pivot dimensions. Bucket
205
+ // dependencies are tracked separately, as they are known only once rows generate.
206
+ private _structuralDimNames: string[] = null;
207
+ _rowDataGenerator: RowDataGenerator = null;
208
+ // Pivot cells - null until the query first pivots, retained thereafter. See PivotCells.
209
+ _pivot: PivotCells = null;
210
+ // Stores minted by `createStore`, whose summary-row flag follows the query's `includeRoot`.
211
+ private _ownStores = new WeakSet<Store>();
154
212
  // Fields eligible for aggregation at each level of the query - i.e. those with an aggregator
155
213
  // that are not themselves an applied dimension there - and useful subsets of same. Indexed by
156
214
  // row depth, with entry 0 (no dimensions applied) holding the superset for the whole query.
@@ -169,6 +227,7 @@ export class View
169
227
  {query, stores = [], connect = false, xhName = null} = config;
170
228
 
171
229
  this.xhName = xhName;
230
+ this.diagnostics = new ViewDiagnostics(this);
172
231
  this.query = query;
173
232
  this.stores = this.parseStores(stores);
174
233
  this._rowCache = new RowCache(this);
@@ -288,6 +347,46 @@ export class View
288
347
  this.updateQuery({filter});
289
348
  }
290
349
 
350
+ /**
351
+ * Create a Store shaped for this view's results - a Field per {@link ViewRowData} member, per
352
+ * query field and, for a pivoted query, per {@link ViewResult.cellFields} entry, kept in sync
353
+ * as the pivot structure changes. `loadRootAsSummary` follows the query's `includeRoot`.
354
+ *
355
+ * The caller owns the returned Store, and with `connect: true` must call
356
+ * {@link disconnectStore} from its own `destroy()`.
357
+ * @internal - used by `CubeGridModel`
358
+ */
359
+ createStore(config?: ViewStoreConfig): Store {
360
+ const {connect = false, fields = [], ...rest} = config ?? {};
361
+
362
+ const store = new Store({
363
+ loadTreeData: true,
364
+ projectionOnly: true,
365
+ loadRootAsSummary: this.query.includeRoot,
366
+ xhName: this.childXhName('store'),
367
+ ...rest,
368
+ fields: [...VIEW_ROW_DATA_FIELDS, ...this.fields, ...fields]
369
+ });
370
+ this._ownStores.add(store);
371
+
372
+ // `parseStores` installs the row digest and rejects a conflicting one, connected or not.
373
+ const [parsed] = this.parseStores(store);
374
+ if (connect) this.stores = [...this.stores, parsed];
375
+
376
+ this._pivot?.syncStore(store);
377
+ this.loadStore(store);
378
+
379
+ return store;
380
+ }
381
+
382
+ /**
383
+ * Stop loading the given Store from this view. Callers of {@link createStore} own this call.
384
+ * @internal
385
+ */
386
+ disconnectStore(store: Store) {
387
+ this.stores = this.stores.filter(it => it !== store);
388
+ }
389
+
291
390
  //-----------------------
292
391
  // Entry point for cube
293
392
  //-----------------------
@@ -349,8 +448,14 @@ export class View
349
448
  return ret;
350
449
  }
351
450
 
451
+ /** Derive the per-query lookup tables. Runs at construction and on every `updateQuery`. */
352
452
  private buildIndices() {
453
+ const {query} = this;
353
454
  this._fieldsByName = new Map(this.fields.map(it => [it.name, it]));
455
+ this._structuralDimNames = [
456
+ ...(query.dimensions ?? []),
457
+ ...(query.isPivoted ? query.pivot.dimensions : [])
458
+ ].map(it => it.name);
354
459
 
355
460
  // Aggregation eligibility is a function of level alone - dimensions apply in order, and
356
461
  // bucket rows share the level of the aggregate row above them. Note depth 0 has no applied
@@ -376,14 +481,31 @@ export class View
376
481
  this._complexAggFieldsByDepth = this._aggFieldsByDepth.map(fields =>
377
482
  fields.filter(it => !it.aggregator.dependsOnChildrenOnly)
378
483
  );
484
+
485
+ if (query.pivot) this._pivot ??= new PivotCells(this);
486
+ this._pivot?.buildIndices();
379
487
  }
380
488
 
381
489
  private fullUpdate(trigger: 'load' | 'update' | 'query', start: number) {
382
490
  this.filterRecords();
383
491
  this.createAggregationContext();
384
- this.generateRows();
492
+
493
+ let exception: HoistException = null;
494
+ try {
495
+ this._pivot?.discoverPaths();
496
+ this.generateRows();
497
+ this._pivot?.generateCells();
498
+ // Closed after cell generation, so cell rows count toward the generation.
499
+ this._rowCache.endGeneration();
500
+ } catch (e) {
501
+ // Routine means the data is at fault - publish and empty. See `ViewResult.exception`.
502
+ if (!isHoistException(e) || !e.isRoutine) throw e;
503
+ exception = e;
504
+ this.clearGeneratedRows();
505
+ }
506
+
385
507
  this.loadStores();
386
- this.updateResults();
508
+ this.updateResults(exception);
387
509
 
388
510
  const {diagnostics} = this;
389
511
  switch (trigger) {
@@ -401,7 +523,7 @@ export class View
401
523
 
402
524
  // Apply value changes to leaves already in the view, adjusting ancestor aggregates in place.
403
525
  private dataOnlyUpdate(updates: StoreRecord[], changedFields: Set<string>, start: number) {
404
- const {_leafMap, stores, fields} = this,
526
+ const {_leafMap, fields} = this,
405
527
  changed: LeafUpdateChanges = {rows: new Set(), fields: new Set()};
406
528
 
407
529
  // Fields to diff at each leaf - those that changed, plus any aggregated from them.
@@ -415,17 +537,15 @@ export class View
415
537
  _leafMap.get(rec.id)?.applyLeafDataUpdate(rec, checkFields, changed);
416
538
  });
417
539
 
418
- changed.rows.forEach(rowData => BaseRow.assignDigest(rowData));
540
+ changed.rows.forEach(row => BaseRow.assignDigest(row.data as ViewRowData));
419
541
 
420
542
  this.createAggregationContext();
421
543
 
422
- stores.forEach(store => {
423
- const recordUpdates = [];
424
- changed.rows.forEach(rowData => {
425
- if (store.getById(rowData.id)) recordUpdates.push(rowData);
426
- });
427
- store.updateData({update: recordUpdates, changedFields: changed.fields});
428
- });
544
+ // Cells publish onto their group rows, so a pivot rewrites and reports those instead.
545
+ const rows = this._pivot
546
+ ? this._pivot.projectUpdatedRows(changed.rows, changed.fields)
547
+ : changed.rows;
548
+ this.loadUpdatedRows(rows, changed.fields);
429
549
  this.updateResults();
430
550
  this.diagnostics.noteUpdate('dataOnly', start);
431
551
  }
@@ -437,27 +557,63 @@ export class View
437
557
  this.diagnostics.noteUpdate('unchanged', start);
438
558
  }
439
559
 
560
+ /** Push the rows touched by an incremental update into any connected stores. */
561
+ private loadUpdatedRows(updatedRows: Set<BaseRow>, changedFields: Set<string>) {
562
+ this.stores.forEach(store => {
563
+ const recordUpdates = [];
564
+ updatedRows.forEach(row => {
565
+ const {data} = row;
566
+ if (store.getById(data.id)) recordUpdates.push(data);
567
+ });
568
+ // Parents only rewrite fields leaves reported changed, so the leaf-level union is complete.
569
+ store.updateData({update: recordUpdates, changedFields});
570
+ });
571
+ }
572
+
440
573
  private loadStores() {
574
+ this.stores.forEach(s => {
575
+ this._pivot?.syncStore(s);
576
+ this.loadStore(s);
577
+ });
578
+ }
579
+
580
+ /** Load a single store from the current row data, if any has been generated. */
581
+ private loadStore(store: Store) {
441
582
  const {_leafMap, _rowDatas} = this;
442
583
  if (!_leafMap || !_rowDatas) return;
443
584
 
585
+ // Keep a minted store's summary flag in step with `includeRoot`; app stores are their own.
586
+ if (this._ownStores.has(store)) store.setLoadRootAsSummary(this.query.includeRoot);
587
+
444
588
  // Skip degenerate root in stores/grids, but preserve in object api.
445
- const storeRows = _leafMap.size !== 0 ? _rowDatas : [];
446
- this.stores.forEach(s => s.loadData(storeRows));
589
+ store.loadData(_leafMap.size !== 0 ? _rowDatas : []);
447
590
  }
448
591
 
449
- private updateResults() {
450
- const {_leafMap, _rowDatas} = this;
592
+ private updateResults(exception: HoistException = null) {
593
+ const {_leafMap, _rowDatas, _pivot} = this;
451
594
  this.result = {
452
595
  rows: _rowDatas,
453
596
  // Hidden leaves adopt Cube record data outright - never publish them.
454
- leafMap: this.exposesLeaves ? (_leafMap as Map<StoreRecordId, ExposedLeafRow>) : null
597
+ leafMap: this.exposesLeaves ? (_leafMap as Map<StoreRecordId, ExposedLeafRow>) : null,
598
+ paths: _pivot?.paths ?? EMPTY_PATHS,
599
+ cellFields: _pivot?.cellFields ?? EMPTY_CELL_FIELDS,
600
+ exception
455
601
  };
456
602
  this.info = this.cube.info;
457
603
  this.cubeUpdated = this.cube.lastUpdated;
458
604
  this.lastUpdated = Date.now();
459
605
  }
460
606
 
607
+ // Rows and cells of a declined update are discarded whole, so stores load empty rather than
608
+ // stale. The next successful update rebuilds from scratch.
609
+ private clearGeneratedRows() {
610
+ this._rowCache.clear();
611
+ this._pivot?.reset();
612
+ this._leafMap = new Map();
613
+ this._rootRows = [];
614
+ this._rowDatas = [];
615
+ }
616
+
461
617
  // Generate a new full data representation from the filtered records
462
618
  private generateRows() {
463
619
  const {query} = this,
@@ -493,6 +649,7 @@ export class View
493
649
  }
494
650
 
495
651
  this._leafMap = leafMap;
652
+ this._rootRows = newRows;
496
653
 
497
654
  if (query.bucketSpecFn) newRows.forEach(row => row.syncBuckets(null));
498
655
 
@@ -500,8 +657,6 @@ export class View
500
657
  // This hides all the meta information, as well as unwanted leaves and skipped rows.
501
658
  // Underlying network still there and updates will flow up through it via the leaves.
502
659
  this._rowDatas = newRows.flatMap(it => it.getVisibleDatas());
503
-
504
- rowCache.endGeneration();
505
660
  }
506
661
 
507
662
  private groupAndInsertRecords(
@@ -614,12 +769,16 @@ export class View
614
769
  // false if leaf population changing, or aggregations are complex
615
770
  private getSimpleUpdates(t: RecordSetDelta): StoreRecord[] | false {
616
771
  if (!t) return [];
772
+ // A declined result has no leaves to patch - rerun in full.
773
+ if (this.result?.exception) return false;
617
774
  if (!this.aggregatorsAreSimple) return false;
618
775
  const {_leafMap, query} = this;
619
776
 
620
777
  // 1) Simple case: no filter
621
778
  if (!query.filter) {
622
- return isEmpty(t.add) && isEmpty(t.remove) && !this.hasDimOrBucketUpdates(t.update)
779
+ return isEmpty(t.add) &&
780
+ isEmpty(t.remove) &&
781
+ !this.hasDimOrBucketUpdates(t.update, t.changedFields)
623
782
  ? t.update
624
783
  : false;
625
784
  }
@@ -642,23 +801,30 @@ export class View
642
801
  }
643
802
 
644
803
  // 2c) Examine the final set of updates for any changes to dimension field values which would
645
- // require rebuilding the row hierarchy
646
- if (this.hasDimOrBucketUpdates(ret)) return false;
804
+ // require rebuilding the row hierarchy. `changedFields` covers all of `t.update`, a
805
+ // superset of `ret`.
806
+ if (this.hasDimOrBucketUpdates(ret, t.changedFields)) return false;
647
807
 
648
808
  return ret;
649
809
  }
650
810
 
651
- private hasDimOrBucketUpdates(update: StoreRecord[]): boolean {
652
- const {dimensions} = this.query,
811
+ /**
812
+ * True if any update moves a field that restructures the row hierarchy. `changedFields`, when
813
+ * given, is the producer's assertion of every field touched - if it names nothing structural,
814
+ * no record is examined.
815
+ */
816
+ private hasDimOrBucketUpdates(update: StoreRecord[], changedFields?: Set<string>): boolean {
817
+ const dimNames = this._structuralDimNames,
653
818
  bucketFields = this._bucketDependentFields;
654
819
 
655
- if (isEmpty(dimensions) && !bucketFields.size) return false;
820
+ if (!dimNames.length && !bucketFields.size) return false;
821
+ if (changedFields && !this.hasStructuralChange(changedFields)) return false;
656
822
 
657
823
  for (const rec of update) {
658
824
  const curData = this._records.getById(rec.id).data,
659
825
  {data} = rec;
660
- for (const dim of dimensions) {
661
- if (data[dim.name] !== curData[dim.name]) return true;
826
+ for (const name of dimNames) {
827
+ if (data[name] !== curData[name]) return true;
662
828
  }
663
829
  for (const name of bucketFields) {
664
830
  if (data[name] !== curData[name]) return true;
@@ -668,6 +834,15 @@ export class View
668
834
  return false;
669
835
  }
670
836
 
837
+ // True if any named field could restructure the row hierarchy.
838
+ private hasStructuralChange(changedFields: Set<string>): boolean {
839
+ if (this._structuralDimNames.some(name => changedFields.has(name))) return true;
840
+ for (const name of this._bucketDependentFields) {
841
+ if (changedFields.has(name)) return true;
842
+ }
843
+ return false;
844
+ }
845
+
671
846
  private filterRecords() {
672
847
  const {query, cube} = this;
673
848
  this._records = cube.store._filtered.withFilter(query.filter, this._records);
@@ -697,7 +872,8 @@ export class View
697
872
  }
698
873
 
699
874
  private parseStores(stores: Some<Store>): Store[] {
700
- const ret = castArray(stores);
875
+ // `castArray(null)` yields `[null]` - null is a legitimate "no stores" here.
876
+ const ret = isNil(stores) ? [] : castArray(stores);
701
877
 
702
878
  throwIf(
703
879
  ret.some(s => s.digestSpec != null && s.digestSpec !== 'cubeRowDigest'),
@@ -725,3 +901,6 @@ export class View
725
901
  super.destroy();
726
902
  }
727
903
  }
904
+
905
+ const EMPTY_PATHS: PivotPath[] = [],
906
+ EMPTY_CELL_FIELDS: PivotCellField[] = [];
@@ -5,6 +5,7 @@
5
5
  * Copyright © 2026 Extremely Heavy Industries Inc.
6
6
  */
7
7
  import type {Some} from '@xh/hoist/core';
8
+ import type {FieldSpec} from '@xh/hoist/data';
8
9
  import {flatMap} from 'lodash';
9
10
 
10
11
  /**
@@ -29,6 +30,13 @@ export interface ViewRowData {
29
30
  /** Dimension on which this row was computed, or null for leaf rows. */
30
31
  cubeDimension: string;
31
32
 
33
+ /**
34
+ * Raw, typed value behind {@link cubeLabel} - the dimension or bucket value, or a leaf's record
35
+ * id; null on the root. Bind a tree column's `sortValue` to it so numbers and dates sort by
36
+ * value rather than as text.
37
+ */
38
+ cubeLabelValue: any;
39
+
32
40
  /**
33
41
  * Buckets this row appears in
34
42
  */
@@ -58,6 +66,20 @@ export interface ViewRowData {
58
66
  [key: string]: any;
59
67
  }
60
68
 
69
+ /**
70
+ * Store Field specs for the published members of {@link ViewRowData}. Excludes `id` and
71
+ * `children`, which Store consumes structurally, and `cubeRowDigest`, read as a digest.
72
+ * @internal
73
+ */
74
+ export const VIEW_ROW_DATA_FIELDS: FieldSpec[] = [
75
+ {name: 'cubeRowType', type: 'string'},
76
+ {name: 'cubeLabel', type: 'string'},
77
+ {name: 'cubeDimension', type: 'string'},
78
+ {name: 'cubeLabelValue', type: 'auto'},
79
+ {name: 'cubeBuckets', type: 'auto'},
80
+ {name: 'isCubeLeaf', type: 'bool'}
81
+ ];
82
+
61
83
  /**
62
84
  * All visible (i.e. non-locked) cube leaves associated with a row.
63
85
  *
@@ -0,0 +1,88 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2026 Extremely Heavy Industries Inc.
6
+ */
7
+
8
+ import {shallowEqualArrays} from '@xh/hoist/utils/impl';
9
+ import {sortedIndex, sortedIndexOf} from 'lodash';
10
+ import type {AggregationContext} from './AggregationContext';
11
+ import {Aggregator} from './Aggregator';
12
+ import type {ViewRow} from '../ViewRow';
13
+
14
+ /**
15
+ * Takes the median of numeric values across all leaf rows, skipping nulls. Returns null if no leaf
16
+ * has a value.
17
+ *
18
+ * A median cannot be composed from child medians, so each row holds the sorted values beneath it
19
+ * as aggregator state. A full aggregation walks and sorts those values. An update to a leaf moves
20
+ * its value within the sorted values of each ancestor - a binary search, then an array shift
21
+ * linear in the number of values.
22
+ *
23
+ * A row whose `canAggregateFn` returned false contributes its published null, not the leaves
24
+ * beneath it.
25
+ */
26
+ export class MedianAggregator extends Aggregator {
27
+ override aggregate(rows, fieldName, context) {
28
+ const vals: number[] = [];
29
+ this.collectValues(rows, fieldName, context, vals);
30
+
31
+ // Sorts in place, where lodash `sortBy` would copy.
32
+ vals.sort((a, b) => a - b);
33
+
34
+ // Holds the sorted values as state, which marks this row as aggregated for the walk. New
35
+ // state when the values change makes the View re-aggregate the parent, whose median can
36
+ // change while this row's median holds. Unchanged values keep the prior state, so the
37
+ // row is not marked as changed.
38
+ const prev: MedianState = context.getAggState();
39
+ context.setAggState(prev && shallowEqualArrays(prev.vals, vals) ? prev : {vals});
40
+ return this.median(vals);
41
+ }
42
+
43
+ override replace(rows, currVal, update, context) {
44
+ const state: MedianState = context.getAggState();
45
+ if (!state) return super.replace(rows, currVal, update, context);
46
+
47
+ const {vals} = state,
48
+ {leafOldValue, leafNewValue} = update;
49
+ if (leafOldValue != null) {
50
+ const idx = sortedIndexOf(vals, leafOldValue);
51
+ // Not expected - state out of step with the leaves, so rebuild it.
52
+ if (idx < 0) return super.replace(rows, currVal, update, context);
53
+ vals.splice(idx, 1);
54
+ }
55
+ if (leafNewValue != null) {
56
+ vals.splice(sortedIndex(vals, leafNewValue), 0, leafNewValue);
57
+ }
58
+ return this.median(vals);
59
+ }
60
+
61
+ private median(vals: number[]): number {
62
+ if (!vals.length) return null;
63
+ const mid = Math.floor(vals.length / 2);
64
+ return vals.length % 2 ? vals[mid] : (vals[mid - 1] + vals[mid]) / 2;
65
+ }
66
+
67
+ private collectValues(
68
+ rows: ViewRow[],
69
+ fieldName: string,
70
+ context: AggregationContext,
71
+ vals: number[]
72
+ ) {
73
+ for (const row of rows) {
74
+ // Descend only into rows that aggregated the field - see `getAggState()`.
75
+ if (!row.isLeaf && context.getAggState(row)) {
76
+ this.collectValues(row.children, fieldName, context, vals);
77
+ } else {
78
+ const val = row.data[fieldName];
79
+ if (val != null) vals.push(val);
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ interface MedianState {
86
+ /** Sorted non-null values beneath the row. */
87
+ vals: number[];
88
+ }
@@ -0,0 +1,128 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2026 Extremely Heavy Industries Inc.
6
+ */
7
+
8
+ import type {PlainObject} from '@xh/hoist/core';
9
+ import type {AggregationContext} from './AggregationContext';
10
+ import {Aggregator} from './Aggregator';
11
+ import type {ViewLeafRow, ViewRow} from '../ViewRow';
12
+
13
+ /**
14
+ * Sums numeric values across all leaf rows, but only if every leaf with a value shares the same
15
+ * value for a second field - for example, amounts that share a currency. Returns null if those
16
+ * leaves disagree, or if no leaf has a value. Values of the second field are compared by identity,
17
+ * so should be strings, numbers or null - a null counts as a value of its own.
18
+ *
19
+ * Reads the second field from each leaf's source record, so the query need not include it. Not
20
+ * supported where the query groups by the summed field itself - the second field is not checked
21
+ * across those groups.
22
+ *
23
+ * Each row tracks one value of the second field - the most common among its leaves - with a count
24
+ * of the leaves holding it, a count of all leaves with a value, and their total. The row has a
25
+ * single shared value when the two counts are equal. An update to a leaf adjusts these in constant
26
+ * time, except when the last leaf holding the tracked value changes and others remain - the row
27
+ * then walks its leaves to choose a new value to track. A full aggregation also walks the leaves.
28
+ *
29
+ * Create one per field: `{name: 'amount', aggregator: new SumIfSameAggregator('currency')}`.
30
+ */
31
+ export class SumIfSameAggregator extends Aggregator {
32
+ readonly matchField: string;
33
+ private readonly _dependsOn: string[];
34
+
35
+ constructor(matchField: string) {
36
+ super();
37
+ this.matchField = matchField;
38
+ this._dependsOn = [matchField];
39
+ }
40
+
41
+ override get dependsOn() {
42
+ return this._dependsOn;
43
+ }
44
+
45
+ override aggregate(rows, fieldName, context) {
46
+ const counts = new Map<any, number>(),
47
+ state: SumIfSameState = {match: null, matchCount: 0, count: 0, total: 0};
48
+ this.collect(rows, fieldName, context, counts, state);
49
+
50
+ counts.forEach((matchCount, match) => {
51
+ if (matchCount > state.matchCount) Object.assign(state, {match, matchCount});
52
+ });
53
+
54
+ context.setAggState(state);
55
+ return this.result(state);
56
+ }
57
+
58
+ override replace(rows, currVal, update, context) {
59
+ const state: SumIfSameState = context.getAggState();
60
+ if (!state) return super.replace(rows, currVal, update, context);
61
+
62
+ const {leafOldData, leafNewData, field} = update;
63
+ this.adjust(state, leafOldData, field.name, -1);
64
+ this.adjust(state, leafNewData, field.name, 1);
65
+
66
+ // Reset once no leaf contributes, so fractional amounts net to exactly zero.
67
+ if (!state.count) state.total = 0;
68
+
69
+ // The tracked value is gone, but other leaves remain - choose a new one.
70
+ if (!state.matchCount && state.count) return this.aggregate(rows, field.name, context);
71
+
72
+ return this.result(state);
73
+ }
74
+
75
+ //------------------
76
+ // Implementation
77
+ //------------------
78
+ private result(state: SumIfSameState): number {
79
+ const {count, matchCount, total} = state;
80
+ return count && matchCount === count ? total : null;
81
+ }
82
+
83
+ // Add (sign 1) or remove (sign -1) a leaf's contribution.
84
+ private adjust(state: SumIfSameState, data: PlainObject, fieldName: string, sign: number) {
85
+ const val = data[fieldName];
86
+ if (val == null) return;
87
+ state.count += sign;
88
+ state.total += sign * val;
89
+ if (data[this.matchField] === state.match) state.matchCount += sign;
90
+ }
91
+
92
+ private collect(
93
+ rows: ViewRow[],
94
+ fieldName: string,
95
+ context: AggregationContext,
96
+ counts: Map<any, number>,
97
+ state: SumIfSameState
98
+ ) {
99
+ for (const row of rows) {
100
+ // Descend only into rows that aggregated the field - see `getAggState()`.
101
+ if (!row.isLeaf && context.getAggState(row)) {
102
+ this.collect(row.children, fieldName, context, counts, state);
103
+ continue;
104
+ }
105
+
106
+ // A leaf, or a row that did not aggregate the field - read its values directly.
107
+ const data = row.isLeaf ? (row as ViewLeafRow).cubeRecord.data : row.data,
108
+ val = data[fieldName];
109
+ if (val == null) continue;
110
+
111
+ const match = data[this.matchField];
112
+ counts.set(match, (counts.get(match) ?? 0) + 1);
113
+ state.count++;
114
+ state.total += val;
115
+ }
116
+ }
117
+ }
118
+
119
+ interface SumIfSameState {
120
+ /** Value of the match field tracked by this row - the most common when last chosen. */
121
+ match: any;
122
+ /** Number of contributing leaves whose match field holds `match`. */
123
+ matchCount: number;
124
+ /** Number of contributing leaves - those with a non-null value. */
125
+ count: number;
126
+ /** Sum of contributing values. */
127
+ total: number;
128
+ }