@omnigrid/core 0.1.24 → 0.1.25

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.
@@ -0,0 +1,211 @@
1
+ function isBuildGroupNode(node) {
2
+ return node.type === 'group';
3
+ }
4
+ /**
5
+ * Builds a group tree from flat data.
6
+ *
7
+ * Rows are inserted level by level according to `groupBy`. The result is a
8
+ * rooted tree whose root is a synthetic group (level -1). Use
9
+ * `flattenTree` to obtain the linear `TreeRowNode[]` consumed by the
10
+ * virtualizer.
11
+ *
12
+ * @param data - Filtered/sorted flat row data.
13
+ * @param groupBy - Grouping fields in nesting order.
14
+ * @param expandedGroups - Initial expanded state keyed by group id.
15
+ * @param getRowId - Stable row id resolver.
16
+ * @returns The root group node, or `null` when `groupBy` is empty.
17
+ * @api
18
+ */
19
+ export function buildGroupTree(data, groupBy, expandedGroups, getRowId) {
20
+ if (!groupBy || groupBy.length === 0)
21
+ return null;
22
+ const root = {
23
+ type: 'group',
24
+ id: '__root__',
25
+ field: '',
26
+ key: '',
27
+ level: -1,
28
+ expanded: true,
29
+ childrenCount: 0,
30
+ aggregations: {},
31
+ children: [],
32
+ leaves: [],
33
+ };
34
+ for (let index = 0; index < data.length; index += 1) {
35
+ const row = data[index];
36
+ insertRow(root, row, groupBy, 0, index, getRowId, expandedGroups);
37
+ }
38
+ return root;
39
+ }
40
+ function insertRow(node, row, groupBy, level, rowIndex, getRowId, expandedGroups) {
41
+ if (level === groupBy.length) {
42
+ node.leaves.push({
43
+ type: 'leaf',
44
+ id: getRowId(row, rowIndex),
45
+ data: row,
46
+ level,
47
+ parent: node,
48
+ });
49
+ return;
50
+ }
51
+ const field = groupBy[level];
52
+ const key = String(row[field] ?? '');
53
+ const groupId = `${node.id}/${field}:${key}`;
54
+ let child = node.children.find((c) => c.type === 'group' && c.field === field && c.key === key);
55
+ if (!child) {
56
+ child = {
57
+ type: 'group',
58
+ id: groupId,
59
+ field,
60
+ key,
61
+ level,
62
+ expanded: expandedGroups[groupId] !== false,
63
+ childrenCount: 0,
64
+ aggregations: {},
65
+ children: [],
66
+ leaves: [],
67
+ parent: node,
68
+ };
69
+ node.children.push(child);
70
+ }
71
+ insertRow(child, row, groupBy, level + 1, rowIndex, getRowId, expandedGroups);
72
+ }
73
+ /**
74
+ * Flattens a group tree into the linear array consumed by the virtualizer.
75
+ *
76
+ * Only expanded groups contribute their descendants to the output; a collapsed
77
+ * group appears as a single row. Group `expanded` is re-derived from
78
+ * `expandedGroups` on every call, so toggling a group only requires re-flatten
79
+ * (no tree rebuild).
80
+ *
81
+ * @param root - Root group node from `buildGroupTree`.
82
+ * @param expandedGroups - Current expanded state keyed by group id.
83
+ * @returns The flattened `TreeRowNode[]` in pre-order.
84
+ * @api
85
+ */
86
+ export function flattenTree(root, expandedGroups) {
87
+ const result = [];
88
+ if (!root)
89
+ return result;
90
+ for (const child of root.children) {
91
+ if (child.type === 'group') {
92
+ flattenGroup(child, result, expandedGroups);
93
+ }
94
+ else {
95
+ result.push(child);
96
+ }
97
+ }
98
+ return result;
99
+ }
100
+ function flattenGroup(node, result, expandedGroups) {
101
+ const expanded = expandedGroups[node.id] !== false;
102
+ const flat = {
103
+ type: 'group',
104
+ id: node.id,
105
+ field: node.field,
106
+ key: node.key,
107
+ level: node.level,
108
+ expanded,
109
+ childrenCount: node.childrenCount,
110
+ aggregations: node.aggregations,
111
+ children: [],
112
+ };
113
+ result.push(flat);
114
+ if (!expanded)
115
+ return;
116
+ for (const child of node.children) {
117
+ if (child.type === 'group') {
118
+ flattenGroup(child, result, expandedGroups);
119
+ }
120
+ else {
121
+ result.push(child);
122
+ }
123
+ }
124
+ // Leaf rows live in `leaves` (kept separate from sub-groups so
125
+ // computeAggregations does not double-count them).
126
+ for (const leaf of node.leaves)
127
+ result.push(leaf);
128
+ }
129
+ /**
130
+ * Computes per-column aggregates for every group in the tree (bottom-up).
131
+ *
132
+ * Aggregates cover all descendant leaf rows. Results are written into each
133
+ * group node's `aggregations` map and `childrenCount`.
134
+ *
135
+ * @param root - Root group node.
136
+ * @param aggregations - Column id -> aggregation function map, provided by an
137
+ * aggregation plugin (e.g. `@omnigrid/aggregation-plugin`).
138
+ * @api
139
+ */
140
+ export function computeAggregations(root, aggregations) {
141
+ if (!root)
142
+ return;
143
+ const aggFuncs = new Map(Object.entries(aggregations));
144
+ visit(root);
145
+ function visit(node) {
146
+ const leafValues = {};
147
+ // Direct leaf values.
148
+ for (const leaf of node.leaves) {
149
+ for (const [columnId, func] of aggFuncs) {
150
+ let values = leafValues[columnId];
151
+ if (!values) {
152
+ values = [];
153
+ leafValues[columnId] = values;
154
+ }
155
+ values.push(leaf.data[columnId]);
156
+ }
157
+ }
158
+ // Descendant group values.
159
+ for (const child of node.children) {
160
+ if (!isBuildGroupNode(child))
161
+ continue;
162
+ const childValues = visit(child);
163
+ for (const [columnId, values] of Object.entries(childValues)) {
164
+ let target = leafValues[columnId];
165
+ if (!target) {
166
+ target = [];
167
+ leafValues[columnId] = target;
168
+ }
169
+ target.push(...values);
170
+ }
171
+ }
172
+ // Resolve aggregates for this group.
173
+ node.childrenCount = descendantLeafCount(node);
174
+ const aggregations = {};
175
+ for (const [columnId, func] of aggFuncs) {
176
+ const values = leafValues[columnId] ?? [];
177
+ aggregations[columnId] = resolveAggregation(func, values);
178
+ }
179
+ node.aggregations = aggregations;
180
+ return leafValues;
181
+ }
182
+ }
183
+ function descendantLeafCount(node) {
184
+ let count = node.leaves.length;
185
+ for (const child of node.children) {
186
+ if (child.type === 'leaf')
187
+ count += 1;
188
+ else
189
+ count += descendantLeafCount(child);
190
+ }
191
+ return count;
192
+ }
193
+ function resolveAggregation(func, values) {
194
+ if (typeof func === 'function')
195
+ return func(values);
196
+ const nums = values.filter((v) => typeof v === 'number' && Number.isFinite(v));
197
+ switch (func) {
198
+ case 'count':
199
+ return values.length;
200
+ case 'sum':
201
+ return nums.reduce((total, v) => total + v, 0);
202
+ case 'avg':
203
+ return nums.length > 0 ? nums.reduce((total, v) => total + v, 0) / nums.length : undefined;
204
+ case 'min':
205
+ return nums.length > 0 ? Math.min(...nums) : undefined;
206
+ case 'max':
207
+ return nums.length > 0 ? Math.max(...nums) : undefined;
208
+ default:
209
+ return undefined;
210
+ }
211
+ }
package/dist/index.d.ts CHANGED
@@ -7,10 +7,13 @@ export { Grid } from "./grid";
7
7
  export { Grid as GridCore } from "./grid";
8
8
  export { SlotManager } from "./slots";
9
9
  export { Store } from "./store";
10
+ export type { StateUpdater } from "./store";
11
+ export { DataPipeline, PIPELINE_STAGE_ORDER } from "./pipeline";
12
+ export type { PipelineProcessor, PipelineStage } from "./pipeline";
10
13
  export { applyFilterModel, applyQuickFilter, isActiveCondition, isFilterModelActive, matchesColumnFilter } from "./filtering";
11
14
  export type { ColumnFilterModel, FilterCondition, FilterModel, FilterOperator } from "./filtering";
12
15
  export type { UIButtonControl, UICheckboxDescriptor, UIControlBase, UIControlDescriptor, UIGroupControl, UIInputControl, UIPopupAnchor, UIPopupDescriptor, UISelectControl, UISelectOption, UITextBlockControl, UIMultiSelectControl, UIMultiSelectOption, } from "./ui";
13
16
  export type { OverlayOptions, OverlayScope, OverlayState, OverlayType } from "./overlays";
14
- export type { BlockConfig, CellAlign, CellRenderParams, CellClassRules, CellSpan, CellSpanningParams, CheckboxControl, CheckboxRenderParams, ColSpanDef, ColumnClassRules, ColumnDataType, ColumnFilterType, ColumnDef, ColumnGroupDef, ColumnGroupViewport, ColumnLeafDef, ColumnStyle, ColumnStyleParams, DataProcessor, DomPoolBindings, DomPoolUpdate, DomPoolUpdateOptions, GridApi, GridEvents, GridOptions, GridPlugin, GridState, HeaderClassRules, HeaderGroupClassRules, HeaderGroupRenderParams, HeaderRenderParams, HeaderStyle, OverlayComponent, OverlayComponentProps, PooledRow, Range, RowClassRules, RowClickEvent, RowHeightUpdateOptions, RowHost, RowHoverEvent, RowId, RowNode, RowRenderParams, RowSpanLayout, RowStyle, RowTransaction, ScrollPosition, SlotComponentContent, SlotContent, SlotHtmlContent, SlotMount, SlotMountOptions, SlotName, SlotNodeContent, SlotNodeEvent, SlotNodeEventName, SlotPosition, SlotProvider, SlotRenderContext, SortDirection, TransactionResult, ViewportData, ViewportState, VirtualItem, } from "./types";
17
+ export type { BlockConfig, CellAlign, AggregationFunc, CellRenderParams, CellClassRules, CellSpan, CellSpanningParams, CheckboxControl, CheckboxRenderParams, ColSpanDef, ColumnClassRules, ColumnDataType, ColumnFilterType, ColumnDef, ColumnGroupDef, ColumnGroupViewport, ColumnLeafDef, ColumnStyle, ColumnStyleParams, DataProcessor, DataRowNode, DomPoolBindings, DomPoolUpdate, DomPoolUpdateOptions, GroupRowNode, GroupRowRenderParams, GroupRowRenderer, CoreGridApi, CoreGridState, GridApi, GridEvents, GridOptions, GridPlugin, GridState, PluginApiExtensions, PluginStateExtensions, HeaderClassRules, HeaderGroupClassRules, HeaderGroupRenderParams, HeaderRenderParams, HeaderStyle, OverlayComponent, OverlayComponentProps, PooledRow, Range, RowClassRules, RowClickEvent, RowHeightUpdateOptions, RowHost, RowHoverEvent, RowId, RowHierarchy, RowHierarchyScope, RowNode, RowRenderParams, RowSpanLayout, RowStyle, RowTransaction, ScrollPosition, SlotComponentContent, SlotContent, SlotHtmlContent, SlotMount, SlotMountOptions, SlotName, SlotNodeContent, SlotNodeEvent, SlotNodeEventName, SlotPosition, SlotProvider, SlotRenderContext, SortDirection, TransactionResult, TreeRowNode, ViewportData, ViewportState, VirtualItem, } from "./types";
15
18
  export { getColumnGroups, flattenColumns, isColumnGroup, isColumnLeaf, getCellValue, getCellSpanningParams, resolveColSpan, getRowSpans } from "./columns";
16
19
  export { Virtualizer, RowHeightRegistry } from "./virtualizer";
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { Grid } from "./grid";
6
6
  export { Grid as GridCore } from "./grid";
7
7
  export { SlotManager } from "./slots";
8
8
  export { Store } from "./store";
9
+ export { DataPipeline, PIPELINE_STAGE_ORDER } from "./pipeline";
9
10
  export { applyFilterModel, applyQuickFilter, isActiveCondition, isFilterModelActive, matchesColumnFilter } from "./filtering";
10
11
  export { getColumnGroups, flattenColumns, isColumnGroup, isColumnLeaf, getCellValue, getCellSpanningParams, resolveColSpan, getRowSpans } from "./columns";
11
12
  export { Virtualizer, RowHeightRegistry } from "./virtualizer";
@@ -0,0 +1,68 @@
1
+ import type { GridState } from "./types";
2
+ /**
3
+ * Stages of the data pipeline executed in ascending order.
4
+ * - `filter`: eliminates rows that do not match active predicates
5
+ * - `sort`: orders rows by one or more comparator keys
6
+ * - `group`: builds hierarchy or inserts group headers
7
+ * - `aggregate`: computes summary values across groups or totals
8
+ * - `paginate`: slices rows to the active page
9
+ *
10
+ * @api
11
+ */
12
+ export type PipelineStage = "filter" | "sort" | "group" | "aggregate" | "paginate";
13
+ export declare const PIPELINE_STAGE_ORDER: Record<PipelineStage, number>;
14
+ /**
15
+ * A discrete data transformation processor registered in the grid pipeline.
16
+ *
17
+ * @api
18
+ */
19
+ export interface PipelineProcessor<T> {
20
+ /** Optional identifier for debugging and inspection. */
21
+ id?: string;
22
+ /** Pipeline stage where this processor runs. */
23
+ stage: PipelineStage;
24
+ /**
25
+ * Priority within the same stage. Higher numbers run earlier.
26
+ *
27
+ * @default 0
28
+ */
29
+ priority?: number;
30
+ /**
31
+ * Pure function transforming rows.
32
+ * @param data - Rows output by the previous processor.
33
+ * @param state - Current snapshot of the grid state.
34
+ * @returns Transformed rows.
35
+ */
36
+ process: (data: T[], state: GridState<T>) => T[];
37
+ }
38
+ /**
39
+ * Coordinates extensible data transformation stages.
40
+ *
41
+ * Plugins register processors targeting specific stages (`filter`, `sort`, etc.),
42
+ * ensuring that data transformations always execute in the correct order
43
+ * regardless of when plugins are initialized.
44
+ *
45
+ * @api
46
+ */
47
+ export declare class DataPipeline<T> {
48
+ private readonly processors;
49
+ private readonly onInvalidate?;
50
+ constructor(onInvalidate?: () => void);
51
+ /**
52
+ * Registers a new data processor into the pipeline.
53
+ * @param processor - The pipeline processor definition.
54
+ * @returns Cleanup callback to unregister the processor.
55
+ * @api
56
+ */
57
+ registerProcessor(processor: PipelineProcessor<T>): () => void;
58
+ /**
59
+ * Runs all registered processors against the input dataset in stage order.
60
+ * @param data - Input rows.
61
+ * @param state - Current grid state snapshot.
62
+ * @returns Transformed rows.
63
+ * @api
64
+ */
65
+ process(data: T[], state: GridState<T>): T[];
66
+ /** Clears all registered processors. @api */
67
+ clear(): void;
68
+ }
@@ -0,0 +1,62 @@
1
+ export const PIPELINE_STAGE_ORDER = {
2
+ filter: 10,
3
+ sort: 20,
4
+ group: 30,
5
+ aggregate: 40,
6
+ paginate: 50,
7
+ };
8
+ /**
9
+ * Coordinates extensible data transformation stages.
10
+ *
11
+ * Plugins register processors targeting specific stages (`filter`, `sort`, etc.),
12
+ * ensuring that data transformations always execute in the correct order
13
+ * regardless of when plugins are initialized.
14
+ *
15
+ * @api
16
+ */
17
+ export class DataPipeline {
18
+ constructor(onInvalidate) {
19
+ this.processors = new Set();
20
+ this.onInvalidate = onInvalidate;
21
+ }
22
+ /**
23
+ * Registers a new data processor into the pipeline.
24
+ * @param processor - The pipeline processor definition.
25
+ * @returns Cleanup callback to unregister the processor.
26
+ * @api
27
+ */
28
+ registerProcessor(processor) {
29
+ this.processors.add(processor);
30
+ this.onInvalidate?.();
31
+ return () => {
32
+ this.processors.delete(processor);
33
+ this.onInvalidate?.();
34
+ };
35
+ }
36
+ /**
37
+ * Runs all registered processors against the input dataset in stage order.
38
+ * @param data - Input rows.
39
+ * @param state - Current grid state snapshot.
40
+ * @returns Transformed rows.
41
+ * @api
42
+ */
43
+ process(data, state) {
44
+ if (this.processors.size === 0)
45
+ return data;
46
+ const sorted = Array.from(this.processors).sort((a, b) => {
47
+ const stageDiff = (PIPELINE_STAGE_ORDER[a.stage] ?? 0) - (PIPELINE_STAGE_ORDER[b.stage] ?? 0);
48
+ if (stageDiff !== 0)
49
+ return stageDiff;
50
+ return (b.priority ?? 0) - (a.priority ?? 0);
51
+ });
52
+ let current = data;
53
+ for (let i = 0; i < sorted.length; i += 1) {
54
+ current = sorted[i].process(current, state);
55
+ }
56
+ return current;
57
+ }
58
+ /** Clears all registered processors. @api */
59
+ clear() {
60
+ this.processors.clear();
61
+ }
62
+ }