@genesislcap/grid-pro 15.97.0 → 15.98.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 (33) hide show
  1. package/dist/custom-elements.json +4345 -2867
  2. package/dist/dts/datasource/cube.block-loads.d.ts +29 -0
  3. package/dist/dts/datasource/cube.block-loads.d.ts.map +1 -0
  4. package/dist/dts/datasource/cube.client.d.ts +50 -0
  5. package/dist/dts/datasource/cube.client.d.ts.map +1 -0
  6. package/dist/dts/datasource/cube.request.d.ts +99 -0
  7. package/dist/dts/datasource/cube.request.d.ts.map +1 -0
  8. package/dist/dts/datasource/cube.source.d.ts +43 -0
  9. package/dist/dts/datasource/cube.source.d.ts.map +1 -0
  10. package/dist/dts/datasource/infinite.datasource.d.ts +39 -3
  11. package/dist/dts/datasource/infinite.datasource.d.ts.map +1 -1
  12. package/dist/dts/datasource/infinite.resource-cube.d.ts +22 -0
  13. package/dist/dts/datasource/infinite.resource-cube.d.ts.map +1 -0
  14. package/dist/dts/datasource/server-side.datasource.d.ts +49 -1
  15. package/dist/dts/datasource/server-side.datasource.d.ts.map +1 -1
  16. package/dist/dts/datasource/server-side.resource-cube.d.ts +21 -0
  17. package/dist/dts/datasource/server-side.resource-cube.d.ts.map +1 -0
  18. package/dist/dts/grid-pro-genesis-datasource/datasource-events.types.d.ts +2 -1
  19. package/dist/dts/grid-pro-genesis-datasource/datasource-events.types.d.ts.map +1 -1
  20. package/dist/dts/react.d.ts +9 -9
  21. package/dist/esm/datasource/cube.block-loads.js +48 -0
  22. package/dist/esm/datasource/cube.client.js +144 -0
  23. package/dist/esm/datasource/cube.request.js +165 -0
  24. package/dist/esm/datasource/cube.source.js +73 -0
  25. package/dist/esm/datasource/infinite.datasource.js +157 -24
  26. package/dist/esm/datasource/infinite.resource-cube.js +56 -0
  27. package/dist/esm/datasource/server-side.datasource.js +197 -23
  28. package/dist/esm/datasource/server-side.resource-cube.js +58 -0
  29. package/dist/grid-pro.api.json +510 -3
  30. package/dist/grid-pro.d.ts +139 -3
  31. package/dist/react.cjs +6 -6
  32. package/dist/react.mjs +5 -5
  33. package/package.json +12 -12
@@ -0,0 +1,144 @@
1
+ import { __awaiter } from "tslib";
2
+ import { ConnectHttpError, FieldTypeEnum, } from '@genesislcap/foundation-comms';
3
+ import { CUBE_ALLOWED_AGG_FUNCS, CUBE_ROW_REF, isCubeGroupable, toCubeFlatQueryBody, toCubeQueryBody, toFieldMetadata, toOperationFieldMetadata, toOperationSearchParams, } from './cube.request';
4
+ import { getServerSideFilterParamsByFieldType } from './server-side.grid-definitions';
5
+ /** The grid's block size: `max-rows`, capped at the largest page the cube serves. */
6
+ export const cubePageSize = (maxRows, maxPageSize) => {
7
+ const pageSize = Math.max(Number(maxRows) || maxPageSize || 1, 1);
8
+ return maxPageSize ? Math.min(pageSize, maxPageSize) : pageSize;
9
+ };
10
+ // The cube's criteria parser has no Expr.containsWordsStartingWithIgnoreCase.
11
+ const UNSUPPORTED_FILTER_OPTIONS = new Set(['wordStartsWith']);
12
+ export const cubeFilterParams = (field) => {
13
+ const params = getServerSideFilterParamsByFieldType(field);
14
+ if (!Array.isArray(params === null || params === void 0 ? void 0 : params.filterOptions))
15
+ return params;
16
+ return Object.assign(Object.assign({}, params), { filterOptions: params.filterOptions.filter((option) => !UNSUPPORTED_FILTER_OPTIONS.has(typeof option === 'string' ? option : option.displayKey)) });
17
+ };
18
+ export const describeCubeError = (error) => {
19
+ var _a;
20
+ if (error instanceof ConnectHttpError) {
21
+ const detail = (_a = error.body) === null || _a === void 0 ? void 0 : _a.detail;
22
+ return typeof detail === 'string' ? `${error.status}: ${detail}` : error.message;
23
+ }
24
+ return error instanceof Error ? error.message : String(error);
25
+ };
26
+ /** A named operation's schema does not say which of its columns it lets callers filter, so none offer a filter. */
27
+ export const withoutColumnFilters = (colDefs) => colDefs.map((colDef) => (Object.assign(Object.assign({}, colDef), { filter: false })));
28
+ /** Cube columns other than dates become groupable, and number columns aggregatable, on the `query` endpoint. */
29
+ export const toCubeColumnDefs = (colDefs, fieldMetadata, operation) => {
30
+ if (operation) {
31
+ return withoutColumnFilters(colDefs);
32
+ }
33
+ const fieldTypes = new Map(fieldMetadata.map(({ name, type }) => [name, type]));
34
+ return colDefs.map((colDef) => {
35
+ const type = fieldTypes.get(colDef.field);
36
+ return type === FieldTypeEnum.NUMBER
37
+ ? Object.assign(Object.assign({}, colDef), { enableRowGroup: true, enableValue: true, allowedAggFuncs: CUBE_ALLOWED_AGG_FUNCS }) : Object.assign(Object.assign({}, colDef), { enableRowGroup: isCubeGroupable(type) });
38
+ });
39
+ };
40
+ export class CubeClient {
41
+ constructor(http, resource) {
42
+ this.http = http;
43
+ this.resource = resource;
44
+ }
45
+ get resourceUrl() {
46
+ const baseUrl = this.resource.baseUrl.replace(/\/+$/, '');
47
+ return `${baseUrl}/${encodeURIComponent(this.resource.resourceName)}`;
48
+ }
49
+ fetchCapabilities() {
50
+ var _a;
51
+ (_a = this.capabilities) !== null && _a !== void 0 ? _a : (this.capabilities = this.http.get(this.resourceUrl, {}));
52
+ return this.capabilities;
53
+ }
54
+ /**
55
+ * The capability document speaks for the resource's own rows. A named operation reshapes them,
56
+ * so its rows carry a `ROW_REF` only when its row schema lists one.
57
+ */
58
+ rowsCarryRowRef() {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ var _a, _b;
61
+ const { operation } = this.resource;
62
+ if (!operation) {
63
+ const { addressable } = yield this.fetchCapabilities();
64
+ return addressable !== false;
65
+ }
66
+ const { operations } = yield this.fetchSchemaDocument();
67
+ return CUBE_ROW_REF in ((_b = (_a = operations === null || operations === void 0 ? void 0 : operations[operation]) === null || _a === void 0 ? void 0 : _a.properties) !== null && _b !== void 0 ? _b : {});
68
+ });
69
+ }
70
+ /**
71
+ * A named operation's columns come from the resource's schema document. The `query` endpoint's
72
+ * schema does not list columns, so they come from a one-row page and enum values from a group-by.
73
+ */
74
+ fetchFieldMetadata(criteria) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ var _a;
77
+ const { operation } = this.resource;
78
+ if (operation)
79
+ return this.fetchOperationFieldMetadata(operation);
80
+ const probe = yield this.fetchEnvelope({ filter: criteria, page: 0, size: 1 });
81
+ return Promise.all(toFieldMetadata((_a = probe.columns) !== null && _a !== void 0 ? _a : []).map((field) => __awaiter(this, void 0, void 0, function* () {
82
+ return field.type === FieldTypeEnum.ENUM
83
+ ? Object.assign(Object.assign({}, field), { enumOptions: yield this.fetchDistinctValues(field.name) }) : field;
84
+ })));
85
+ });
86
+ }
87
+ fetchRows(request, options) {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ var _a, _b;
90
+ if (this.resource.operation && ((_a = request.rowGroupCols) === null || _a === void 0 ? void 0 : _a.length)) {
91
+ throw new Error(`Row grouping needs the cube's query endpoint; '${this.resource.operation}' is a named operation.`);
92
+ }
93
+ const dateGroup = (_b = request.rowGroupCols) === null || _b === void 0 ? void 0 : _b.find(({ field }) => !isCubeGroupable(options.fieldTypes.get(field)));
94
+ if (dateGroup) {
95
+ throw new Error(`Row grouping is not supported on the date column '${dateGroup.field}'.`);
96
+ }
97
+ // COUNT skips nulls, so counting the group column would give a null group no children.
98
+ const { identity } = yield this.fetchCapabilities();
99
+ return this.fetchEnvelope(toCubeQueryBody(request, Object.assign(Object.assign({}, options), { countField: identity[0] })));
100
+ });
101
+ }
102
+ fetchFlatRows(request, options) {
103
+ return this.fetchEnvelope(toCubeFlatQueryBody(request, options));
104
+ }
105
+ fetchSchemaDocument() {
106
+ var _a;
107
+ (_a = this.schema) !== null && _a !== void 0 ? _a : (this.schema = this.http.get(`${this.resourceUrl}/schema`, {}));
108
+ return this.schema;
109
+ }
110
+ fetchOperationFieldMetadata(operation) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const { operations } = yield this.fetchSchemaDocument();
113
+ const rowSchema = operations === null || operations === void 0 ? void 0 : operations[operation];
114
+ if (!rowSchema) {
115
+ throw new Error(`Cube resource '${this.resource.resourceName}' has no operation '${operation}'.`);
116
+ }
117
+ return toOperationFieldMetadata(rowSchema);
118
+ });
119
+ }
120
+ /** Read without the grid's criteria: that can widen later, and the values are read only once. */
121
+ fetchDistinctValues(fieldName_1) {
122
+ return __awaiter(this, arguments, void 0, function* (fieldName, page = 0) {
123
+ const { maxPageSize } = yield this.fetchCapabilities();
124
+ const { rows, hasMore } = yield this.fetchEnvelope({
125
+ page,
126
+ size: maxPageSize,
127
+ groupKeys: [{ expr: { type: 'field', attribute: fieldName }, alias: fieldName }],
128
+ });
129
+ const values = rows.map((row) => row[fieldName]).filter((value) => value != null);
130
+ const laterValues = hasMore ? yield this.fetchDistinctValues(fieldName, page + 1) : [];
131
+ return [...new Set([...values, ...laterValues])];
132
+ });
133
+ }
134
+ fetchEnvelope(body) {
135
+ const { operation } = this.resource;
136
+ if (operation) {
137
+ const url = `${this.resourceUrl}/${encodeURIComponent(operation)}`;
138
+ return this.http.get(`${url}?${toOperationSearchParams(body)}`, {});
139
+ }
140
+ return this.http.post(`${this.resourceUrl}/query`, {
141
+ body: JSON.stringify(body),
142
+ });
143
+ }
144
+ }
@@ -0,0 +1,165 @@
1
+ import { FieldTypeEnum } from '@genesislcap/foundation-comms';
2
+ import { escapeCriteriaString } from '@genesislcap/foundation-criteria';
3
+ import { convertFilterModelToCriteria } from './filter.utils';
4
+ export const CUBE_ROW_REF = 'ROW_REF';
5
+ export const CUBE_CHILD_COUNT = 'cubeChildCount';
6
+ const CUBE_AGG_FUNCTIONS = {
7
+ sum: 'SUM',
8
+ min: 'MIN',
9
+ max: 'MAX',
10
+ count: 'COUNT',
11
+ avg: 'AVG',
12
+ };
13
+ export const CUBE_ALLOWED_AGG_FUNCS = Object.keys(CUBE_AGG_FUNCTIONS);
14
+ const NUMBER_TYPES = new Set(['DOUBLE', 'FLOAT', 'LONG', 'INT', 'INTEGER', 'SHORT', 'BIGDECIMAL']);
15
+ const toFieldType = (cubeType) => {
16
+ if (NUMBER_TYPES.has(cubeType))
17
+ return FieldTypeEnum.NUMBER;
18
+ switch (cubeType) {
19
+ case 'BOOLEAN':
20
+ return FieldTypeEnum.BOOLEAN;
21
+ case 'ENUM':
22
+ return FieldTypeEnum.ENUM;
23
+ case 'DATE':
24
+ return FieldTypeEnum.DATE;
25
+ case 'DATETIME':
26
+ return FieldTypeEnum.DATETIME;
27
+ default:
28
+ return FieldTypeEnum.STRING;
29
+ }
30
+ };
31
+ export const toFieldMetadata = (columns) => columns
32
+ .filter((column) => column.role !== CUBE_ROW_REF)
33
+ .map((column) => ({ name: column.name, type: toFieldType(column.type) }));
34
+ export const toOperationFieldMetadata = ({ properties = {} }) => Object.entries(properties)
35
+ .filter(([name]) => name !== CUBE_ROW_REF)
36
+ .map(([name, column]) => {
37
+ var _a, _b, _c, _d;
38
+ const type = toFieldType((_a = column.genesisType) !== null && _a !== void 0 ? _a : '');
39
+ const enumOptions = (_b = column.enum) !== null && _b !== void 0 ? _b : (_d = (_c = column.oneOf) === null || _c === void 0 ? void 0 : _c.find((option) => option.enum)) === null || _d === void 0 ? void 0 : _d.enum;
40
+ return type === FieldTypeEnum.ENUM && enumOptions
41
+ ? { name, type, enumOptions }
42
+ : { name, type };
43
+ });
44
+ const field = (attribute) => ({ type: 'field', attribute });
45
+ /**
46
+ * A group's key becomes the equality criteria its children are read with. How the cube serialises
47
+ * dates, and which date literals its filter accepts, is not documented, so dates are not grouped.
48
+ */
49
+ export const isCubeGroupable = (type) => type !== FieldTypeEnum.DATE && type !== FieldTypeEnum.DATETIME;
50
+ const criteriaLiteral = (value, type) => {
51
+ if (value === null || value === undefined)
52
+ return 'null';
53
+ if (type === FieldTypeEnum.NUMBER || type === FieldTypeEnum.BOOLEAN)
54
+ return String(value);
55
+ return `'${escapeCriteriaString(String(value))}'`;
56
+ };
57
+ // The shared converter writes blanks as `== ''`, which the cube rejects on any non-string column.
58
+ const toNullOnlySetCriteria = (colId, model, type) => {
59
+ if (model.values == null)
60
+ return null;
61
+ if (!model.values.length)
62
+ return `(${colId} == null && ${colId} != null)`;
63
+ return `(${model.values.map((value) => `${colId} == ${criteriaLiteral(value, type)}`).join(' || ')})`;
64
+ };
65
+ const toColumnCriteria = (colId, model, type) => {
66
+ var _a, _b, _c;
67
+ if (type !== FieldTypeEnum.STRING && (model === null || model === void 0 ? void 0 : model.filterType) === 'set') {
68
+ return toNullOnlySetCriteria(colId, model, type);
69
+ }
70
+ if (type !== FieldTypeEnum.STRING && (model === null || model === void 0 ? void 0 : model.filterType) === 'multi') {
71
+ const joiner = String((_a = model.operator) !== null && _a !== void 0 ? _a : 'AND').toUpperCase() === 'OR' ? ' || ' : ' && ';
72
+ const fragments = ((_b = model.filterModels) !== null && _b !== void 0 ? _b : [])
73
+ .map((subModel) => toColumnCriteria(colId, subModel, type))
74
+ .filter(Boolean);
75
+ if (fragments.length <= 1)
76
+ return (_c = fragments[0]) !== null && _c !== void 0 ? _c : null;
77
+ return `(${fragments.join(joiner)})`;
78
+ }
79
+ return convertFilterModelToCriteria({ [colId]: model }) || null;
80
+ };
81
+ /** Joins criteria with `&&`, parenthesising each so an `||` inside one cannot leak. */
82
+ export const joinCriteria = (parts) => {
83
+ const present = parts.map((part) => part === null || part === void 0 ? void 0 : part.trim()).filter(Boolean);
84
+ if (present.length <= 1)
85
+ return present[0];
86
+ return present.map((part) => `(${part})`).join(' && ');
87
+ };
88
+ /** Sorts on columns outside `allowed` are dropped: the cube rejects sorting by a column it does not return. */
89
+ export const toCubeSort = (sortModel, allowed) => {
90
+ const orders = (sortModel !== null && sortModel !== void 0 ? sortModel : [])
91
+ .filter(({ colId }) => !allowed || allowed.has(colId))
92
+ .map(({ colId, sort }) => (sort === 'desc' ? `-${colId}` : colId));
93
+ return orders.length ? orders.join(',') : undefined;
94
+ };
95
+ const toAggregates = (valueCols) => valueCols.flatMap((column) => {
96
+ const cubeFunction = typeof column.aggFunc === 'string'
97
+ ? CUBE_AGG_FUNCTIONS[column.aggFunc]
98
+ : undefined;
99
+ return cubeFunction
100
+ ? [{ function: cubeFunction, input: field(column.field), alias: column.field }]
101
+ : [];
102
+ });
103
+ const toFilterCriteria = (filterModel, fieldTypes) => {
104
+ var _a;
105
+ return Object.entries((_a = filterModel) !== null && _a !== void 0 ? _a : {})
106
+ .filter(([colId]) => fieldTypes.has(colId))
107
+ .map(([colId, model]) => toColumnCriteria(colId, model, fieldTypes.get(colId)));
108
+ };
109
+ const toCubePage = ({ startRow, endRow }) => {
110
+ const size = endRow - startRow;
111
+ return { page: Math.floor(startRow / size), size };
112
+ };
113
+ export const toCubeFlatQueryBody = (request, { baseCriteria, fieldTypes, defaultSort }) => (Object.assign(Object.assign({ filter: joinCriteria([baseCriteria, ...toFilterCriteria(request.filterModel, fieldTypes)]) }, toCubePage(request)), { sort: toCubeSort(request.sortModel) || defaultSort || undefined }));
114
+ /**
115
+ * A level with a row-group column below it is read as a group-by of that column, aggregating the
116
+ * value columns; the keys of the expanded parent groups become equality criteria.
117
+ */
118
+ export const toCubeQueryBody = (request, { baseCriteria, fieldTypes, countField }) => {
119
+ var _a, _b, _c;
120
+ const rowGroupCols = (_a = request.rowGroupCols) !== null && _a !== void 0 ? _a : [];
121
+ const groupKeys = (_b = request.groupKeys) !== null && _b !== void 0 ? _b : [];
122
+ const filterCriteria = toFilterCriteria(request.filterModel, fieldTypes);
123
+ const parentCriteria = groupKeys.map((key, level) => {
124
+ const groupField = rowGroupCols[level].field;
125
+ return `${groupField} == ${criteriaLiteral(key, fieldTypes.get(groupField))}`;
126
+ });
127
+ const body = Object.assign({ filter: joinCriteria([baseCriteria, ...filterCriteria, ...parentCriteria]) }, toCubePage(request));
128
+ const groupColumn = rowGroupCols[groupKeys.length];
129
+ if (!groupColumn) {
130
+ // A sorted group column puts AG Grid's auto group column in the sort model beside its own.
131
+ body.sort = toCubeSort(request.sortModel, fieldTypes);
132
+ return body;
133
+ }
134
+ const aggregates = toAggregates((_c = request.valueCols) !== null && _c !== void 0 ? _c : []);
135
+ body.groupKeys = [{ expr: field(groupColumn.field), alias: groupColumn.field }];
136
+ body.aggregates = [
137
+ ...aggregates,
138
+ { function: 'COUNT', input: field(countField !== null && countField !== void 0 ? countField : groupColumn.field), alias: CUBE_CHILD_COUNT },
139
+ ];
140
+ body.sort = toCubeSort(request.sortModel, new Set([groupColumn.field, ...aggregates.map(({ alias }) => alias)]));
141
+ return body;
142
+ };
143
+ export const toOperationSearchParams = ({ filter, sort, page, size }) => {
144
+ const params = new URLSearchParams();
145
+ if (filter)
146
+ params.set('filter', filter);
147
+ if (sort)
148
+ params.set('sort', sort);
149
+ params.set('page', String(page));
150
+ params.set('size', String(size));
151
+ return params.toString();
152
+ };
153
+ /** The cube reports no total, so the row count stays open until the last page. */
154
+ export const cubeRowCount = (envelope, startRow) => { var _a; return envelope.hasMore ? undefined : startRow + ((_a = envelope.rows) !== null && _a !== void 0 ? _a : []).length; };
155
+ export const toLoadSuccess = (envelope, startRow) => {
156
+ var _a;
157
+ const rowData = (_a = envelope.rows) !== null && _a !== void 0 ? _a : [];
158
+ const rowCount = cubeRowCount(envelope, startRow);
159
+ return rowCount === undefined ? { rowData } : { rowData, rowCount };
160
+ };
161
+ /**
162
+ * Unique across group levels, which the Server-Side Row Model requires of row ids. `key` is a
163
+ * group row's group value, or a leaf's row id.
164
+ */
165
+ export const toCubeRowId = (parentKeys, key) => JSON.stringify([...(parentKeys !== null && parentKeys !== void 0 ? parentKeys : []), key !== null && key !== void 0 ? key : null]);
@@ -0,0 +1,73 @@
1
+ import { __awaiter } from "tslib";
2
+ import { CubeClient, cubePageSize } from './cube.client';
3
+ /**
4
+ * The cube state the infinite and server-side datasource elements share: the client for the
5
+ * element's current cube attributes, and whether a read still belongs to the grid it started for.
6
+ */
7
+ export class CubeSource {
8
+ constructor(host) {
9
+ this.host = host;
10
+ this.epoch = 0;
11
+ }
12
+ /** The element is tearing down or restarting: reads in flight are stale and the client is rebuilt. */
13
+ reset() {
14
+ this.epoch += 1;
15
+ this.cubeClient = undefined;
16
+ }
17
+ /** Resolves `undefined` when the element was reset while the cube was being read. */
18
+ readGridSettings() {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ const epoch = this.epoch;
21
+ const client = this.client;
22
+ // A failed read is reported by readSchema once the grid is ready.
23
+ const [capabilities, rowsCarryId] = yield Promise.all([
24
+ client.fetchCapabilities().catch(() => undefined),
25
+ this.rowsCarryId(client).catch(() => true),
26
+ ]);
27
+ if (epoch !== this.epoch)
28
+ return undefined;
29
+ return {
30
+ cacheBlockSize: cubePageSize(this.host.maxRows, capabilities === null || capabilities === void 0 ? void 0 : capabilities.maxPageSize),
31
+ rowsCarryId,
32
+ };
33
+ });
34
+ }
35
+ /**
36
+ * Resolves `undefined` when the element was reset while the cube was being read, and rejects
37
+ * when the cube cannot be read.
38
+ */
39
+ readSchema(criteria) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const epoch = this.epoch;
42
+ const client = this.client;
43
+ try {
44
+ yield client.fetchCapabilities();
45
+ const fieldMetadata = yield client.fetchFieldMetadata(criteria);
46
+ const rowsCarryId = yield this.rowsCarryId(client);
47
+ if (epoch !== this.epoch)
48
+ return undefined;
49
+ const fieldTypes = new Map(fieldMetadata.map(({ name, type }) => [name, type]));
50
+ return { client, fieldMetadata, fieldTypes, rowsCarryId };
51
+ }
52
+ catch (error) {
53
+ if (epoch !== this.epoch)
54
+ return undefined;
55
+ throw error;
56
+ }
57
+ });
58
+ }
59
+ rowsCarryId(client) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ return Boolean(this.host.rowIdAttr) || client.rowsCarryRowRef();
62
+ });
63
+ }
64
+ get client() {
65
+ var _a;
66
+ (_a = this.cubeClient) !== null && _a !== void 0 ? _a : (this.cubeClient = new CubeClient(this.host.http, {
67
+ baseUrl: this.host.cubeUrl,
68
+ resourceName: this.host.resourceName,
69
+ operation: this.host.cubeOperation,
70
+ }));
71
+ return this.cubeClient;
72
+ }
73
+ }
@@ -1,13 +1,17 @@
1
1
  import { __awaiter, __decorate } from "tslib";
2
- import { Connect, ConnectEvents, Datasource, normaliseCriteria, toFieldMetadata, } from '@genesislcap/foundation-comms';
2
+ import { Connect, ConnectEvents, Datasource, Http, normaliseCriteria, toFieldMetadata, } from '@genesislcap/foundation-comms';
3
3
  import { LifecycleMixin } from '@genesislcap/foundation-utils';
4
- import { customElement, DOM, observable } from '@microsoft/fast-element';
4
+ import { attr, customElement, DOM, observable } from '@microsoft/fast-element';
5
5
  import { debounceTime, skip } from 'rxjs/operators';
6
6
  import { gridProGenesisDatasourceEventNames } from '../grid-pro-genesis-datasource';
7
7
  import { datasourceEventNames, } from '../grid-pro-genesis-datasource/datasource-events.types';
8
8
  import { logger } from '../utils';
9
9
  import { GridProBaseDatasource } from './base.datasource';
10
+ import { cubeFilterParams, describeCubeError, withoutColumnFilters } from './cube.client';
11
+ import { CUBE_ROW_REF } from './cube.request';
12
+ import { CubeSource } from './cube.source';
10
13
  import { GenesisInfiniteDatasource } from './infinite.resource';
14
+ import { CubeInfiniteDatasource } from './infinite.resource-cube';
11
15
  import { getFilterByFieldType, getServerSideFilterParamsByFieldType, } from './server-side.grid-definitions';
12
16
  import { getIndexLeadingFields } from './sort-index.utils';
13
17
  const criteriaDelimiter = ';';
@@ -35,6 +39,16 @@ const FILTER_DEBOUNCE_MS = 600;
35
39
  * Use this instead of Server-Side Row Model when you don't need Enterprise features
36
40
  * like row grouping, aggregation, or pivoting.
37
41
  *
42
+ * **Genesis Spring data cubes**: with `cube-url` set, `resource-name` names a cube resource read
43
+ * over HTTP from that URL: its `query` endpoint as flat rows, or the named `cube-operation`.
44
+ * Filtering, sorting (on several columns) and paging run on the cube; `criteria` restricts every
45
+ * request and `order-by` takes a cube sort such as `-price,name` for a grid that is not sorted.
46
+ * Rows are read on demand, and re-read on a commit ACK for an event in `pollTriggerEvents`. The
47
+ * Genesis stream attributes (`is-snapshot`, `max-view`, `reverse`, `request`) do not apply.
48
+ * Rows that carry no id - a resource that is not `addressable`, or a named operation whose rows
49
+ * have no `ROW_REF`, with no `row-id` set - are identified by position and raise no
50
+ * `datasource-data-changed`.
51
+ *
38
52
  * @see https://www.ag-grid.com/javascript-data-grid/infinite-scrolling/
39
53
  * @beta
40
54
  *
@@ -59,8 +73,14 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
59
73
  constructor() {
60
74
  super(...arguments);
61
75
  this.request = {};
76
+ this.cube = new CubeSource(this);
77
+ this.initialised = false;
62
78
  /** @internal */
63
79
  this.onDatasourceReady = (_event) => __awaiter(this, void 0, void 0, function* () {
80
+ if (this.isCube) {
81
+ yield this.onCubeReady();
82
+ return;
83
+ }
64
84
  const initOK = yield this.initializeDatasource(this.datasourceOptions(), true, false);
65
85
  if (!initOK) {
66
86
  logger.debug(`Genesis Datasource init failed for ${this.resourceName}`);
@@ -113,24 +133,15 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
113
133
  defaultOrderBy: this.orderBy,
114
134
  defaultReverse: this.reverse,
115
135
  });
116
- // Emit event to set infinite datasource
117
- this.$emit(datasourceEventNames.setInfiniteDatasource, {
118
- datasource: this.infiniteDatasource,
119
- });
120
- // DATASERVER needs no live-update setup: it is live through the paging DATA_LOGON stream
121
- // itself (GenesisInfiniteDatasource reports pushes via onRowsInvalidated/onRowsUpdated).
122
- // REQUEST_SERVER is read on demand, but a write committed through this session should not
123
- // wait for the user to scroll or reload:
124
- this.setupCommitTriggeredRefresh();
125
- // Mark the grid host so its stylesheet can hover-gate the sort indicators for this row
126
- // model (the `.grid-pro-infinite` rules in the grid-pro styles).
127
- this.$emit(datasourceEventNames.addGridCssClass, {
128
- className: 'grid-pro-infinite',
129
- });
130
- // Emit event to restore cached filter config
131
- this.$emit(datasourceEventNames.filtersRestored);
136
+ this.attachInfiniteDatasource();
132
137
  });
133
138
  }
139
+ get rowId() {
140
+ return this.isCube ? this.rowIdAttr || CUBE_ROW_REF : super.rowId;
141
+ }
142
+ get isCube() {
143
+ return Boolean(this.cubeUrl);
144
+ }
134
145
  resourceNameChanged(oldValue, newValue) {
135
146
  if (!oldValue || oldValue === newValue)
136
147
  return;
@@ -138,6 +149,29 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
138
149
  yield this.restart();
139
150
  }));
140
151
  }
152
+ cubeUrlChanged(oldValue, newValue) {
153
+ this.restartOnCubeSourceChange(oldValue, newValue);
154
+ }
155
+ cubeOperationChanged(oldValue, newValue) {
156
+ this.restartOnCubeSourceChange(oldValue, newValue);
157
+ }
158
+ restartOnCubeSourceChange(oldValue, newValue) {
159
+ if (!this.initialised || oldValue === newValue)
160
+ return;
161
+ DOM.queueUpdate(() => {
162
+ this.syncConnectionSubscription();
163
+ return this.restart();
164
+ });
165
+ }
166
+ /** Cube reads go over HTTP, so a socket drop says nothing about them. */
167
+ syncConnectionSubscription() {
168
+ if (this.isCube) {
169
+ this.unsubscribeFromConnection();
170
+ }
171
+ else {
172
+ this.subscribeToConnection();
173
+ }
174
+ }
141
175
  criteriaChanged(oldCriteria, newCriteria) {
142
176
  const criteriaIsNotDuplicate = oldCriteria !== normaliseCriteria(newCriteria, criteriaDelimiter);
143
177
  if (this.infiniteDatasource && criteriaIsNotDuplicate) {
@@ -153,7 +187,7 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
153
187
  if (!shouldRunConnect)
154
188
  return;
155
189
  this.init();
156
- this.subscribeToConnection();
190
+ this.syncConnectionSubscription();
157
191
  this.subscribeToFilterChanges();
158
192
  });
159
193
  }
@@ -163,6 +197,7 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
163
197
  DOM.queueUpdate(() => __awaiter(this, void 0, void 0, function* () {
164
198
  if (!shouldRunDisconnect)
165
199
  return;
200
+ this.initialised = false;
166
201
  yield this.destroy();
167
202
  this.unsubscribeFromConnection();
168
203
  this.unsubscribeFromFilterChanges();
@@ -207,6 +242,10 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
207
242
  reloadResourceData() {
208
243
  return __awaiter(this, void 0, void 0, function* () {
209
244
  var _a, _b;
245
+ if (this.isCube) {
246
+ yield this.reloadCubeData();
247
+ return;
248
+ }
210
249
  // The paging DATA_LOGON is opened through connect.stream, not this.datasource, so destroying
211
250
  // the comms datasource below does not close it. Dispose the IDatasource explicitly or every
212
251
  // criteria change (e.g. a bound search box) leaks a live subscription and its block timers.
@@ -229,8 +268,12 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
229
268
  }
230
269
  init() {
231
270
  return __awaiter(this, void 0, void 0, function* () {
271
+ this.initialised = true;
272
+ const cubeOptions = this.isCube ? yield this.cubeGridOptions() : {};
273
+ if (!cubeOptions)
274
+ return;
232
275
  // Emit event to initialize grid with infinite row model options
233
- const gridOptions = Object.assign({ getRowId: (params) => {
276
+ const gridOptions = Object.assign(Object.assign({ getRowId: (params) => {
234
277
  if (!params.data) {
235
278
  return null;
236
279
  }
@@ -248,7 +291,7 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
248
291
  // would paint indicators whose direction is silently discarded.
249
292
  suppressMultiSort: true,
250
293
  // Infinite Row Model specific options
251
- cacheOverflowSize: 2, maxConcurrentDatasourceRequests: 1, infiniteInitialRowCount: 1, maxBlocksInCache: 10 }, this.deferredGridOptions);
294
+ cacheOverflowSize: 2, maxConcurrentDatasourceRequests: 1, infiniteInitialRowCount: 1, maxBlocksInCache: 10 }, cubeOptions), this.deferredGridOptions);
252
295
  this.$emit(datasourceEventNames.initialize, {
253
296
  options: gridOptions,
254
297
  keepColDefsOnClearRowData: this.keepColDefsOnClearRowData,
@@ -287,6 +330,85 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
287
330
  this.handleErrors(`Infinite row model is not supported for the REQUEST_SERVER resource '${this.resourceName}' because it does not support criteria-only requests. Set 'criteriaOnlyRequest = true' on the request reply definition, or use a client-side datasource for this resource.`, 'resource-type');
288
331
  return false;
289
332
  }
333
+ /** @internal */
334
+ attachInfiniteDatasource() {
335
+ // Emit event to set infinite datasource
336
+ this.$emit(datasourceEventNames.setInfiniteDatasource, {
337
+ datasource: this.infiniteDatasource,
338
+ });
339
+ // DATASERVER needs no live-update setup: it is live through the paging DATA_LOGON stream
340
+ // itself (GenesisInfiniteDatasource reports pushes via onRowsInvalidated/onRowsUpdated).
341
+ // REQUEST_SERVER and cube resources are read on demand, but a write committed through this
342
+ // session should not wait for the user to scroll or reload:
343
+ this.setupCommitTriggeredRefresh();
344
+ // Mark the grid host so its stylesheet can hover-gate the sort indicators for this row
345
+ // model (the `.grid-pro-infinite` rules in the grid-pro styles).
346
+ this.$emit(datasourceEventNames.addGridCssClass, {
347
+ className: 'grid-pro-infinite',
348
+ });
349
+ // Emit event to restore cached filter config
350
+ this.$emit(datasourceEventNames.filtersRestored);
351
+ }
352
+ cubeGridOptions() {
353
+ return __awaiter(this, void 0, void 0, function* () {
354
+ const settings = yield this.cube.readGridSettings();
355
+ if (!settings)
356
+ return undefined;
357
+ return Object.assign(Object.assign({}, (settings.rowsCarryId ? {} : { getRowId: undefined })), { cacheBlockSize: settings.cacheBlockSize, suppressMultiSort: false });
358
+ });
359
+ }
360
+ onCubeReady() {
361
+ return __awaiter(this, void 0, void 0, function* () {
362
+ let schema;
363
+ try {
364
+ schema = yield this.cube.readSchema(this.buildCriteria());
365
+ }
366
+ catch (error) {
367
+ this.handleErrors(describeCubeError(error), 'resource-validation');
368
+ this.clearRowData();
369
+ return;
370
+ }
371
+ if (!schema)
372
+ return;
373
+ const { client, fieldMetadata, fieldTypes, rowsCarryId } = schema;
374
+ this.$emit(gridProGenesisDatasourceEventNames.dataInit);
375
+ this.clearErrors();
376
+ const colDefs = this.generateColumnDefsFromMetadata(fieldMetadata, cubeFilterParams, getFilterByFieldType).map((colDef) => (Object.assign(Object.assign({}, colDef), { sortable: true })));
377
+ this.$emit(datasourceEventNames.schemaUpdated, {
378
+ schema: this.cubeOperation ? withoutColumnFilters(colDefs) : colDefs,
379
+ metadata: fieldMetadata,
380
+ });
381
+ this.infiniteDatasource = new CubeInfiniteDatasource({
382
+ rowId: rowsCarryId ? this.rowId : undefined,
383
+ fetchRows: (request) => client.fetchFlatRows(request, {
384
+ baseCriteria: this.buildCriteria(),
385
+ fieldTypes,
386
+ defaultSort: this.orderBy,
387
+ }),
388
+ onRowsDelivered: (rows) => this.reportDeliveredRows(rows),
389
+ onRowsWithdrawn: (rowIds) => this.reportWithdrawnRows(rowIds),
390
+ onRowCacheReset: () => this.clearRowData(false),
391
+ onNoDataAvailable: () => this.$emit(datasourceEventNames.noDataAvailable),
392
+ onDataAvailable: () => this.$emit(datasourceEventNames.loadingFinished),
393
+ onError: (error) => this.handleErrors(describeCubeError(error), 'stream'),
394
+ });
395
+ this.attachInfiniteDatasource();
396
+ });
397
+ }
398
+ reloadCubeData() {
399
+ return __awaiter(this, void 0, void 0, function* () {
400
+ if (!(this.infiniteDatasource instanceof CubeInfiniteDatasource)) {
401
+ yield this.restart();
402
+ return;
403
+ }
404
+ this.infiniteDatasource.invalidatePendingLoads();
405
+ this.clearRowData(false);
406
+ this.clearErrors();
407
+ this.$emit(datasourceEventNames.refreshInfiniteCache, {
408
+ purge: true,
409
+ });
410
+ });
411
+ }
290
412
  /**
291
413
  * A pushed INSERT/DELETE changes which rows exist or their order, so the change is reported
292
414
  * and then the rows are re-read (purge).
@@ -335,6 +457,7 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
335
457
  destroy() {
336
458
  return __awaiter(this, void 0, void 0, function* () {
337
459
  var _a, _b;
460
+ this.cube.reset();
338
461
  // A ready event arriving after teardown must not re-run the initialization.
339
462
  this.clearReadyListener();
340
463
  this.teardownCommitTriggeredRefresh();
@@ -378,14 +501,15 @@ let GridProInfiniteDatasource = class GridProInfiniteDatasource extends Lifecycl
378
501
  * Honours `pollTriggerEvents` without polling: a commit ACK for one of the listed events
379
502
  * means a write went through this session, so the loaded blocks are re-read in place - the
380
503
  * same action as `applyTransaction`, which keeps the grid's row count and scroll position.
381
- * @remarks REQUEST_SERVER only. DATASERVER already receives every change on the paging
382
- * subscription, so a commit-triggered re-read there would just duplicate the live push.
504
+ * @remarks REQUEST_SERVER and cube resources only. DATASERVER already receives every change on
505
+ * the paging subscription, so a commit-triggered re-read there would just duplicate the live push.
383
506
  * @internal
384
507
  */
385
508
  setupCommitTriggeredRefresh() {
386
509
  var _a;
387
510
  this.teardownCommitTriggeredRefresh();
388
- if (this.isSnapshot || !this.isRequestServer || !((_a = this.pollTriggerEvents) === null || _a === void 0 ? void 0 : _a.length)) {
511
+ const readsOnDemand = this.isCube || this.isRequestServer;
512
+ if (this.isSnapshot || !readsOnDemand || !((_a = this.pollTriggerEvents) === null || _a === void 0 ? void 0 : _a.length)) {
389
513
  return;
390
514
  }
391
515
  this.commitResponseUnsubscribe = this.connectEvents.addCommitResponseListener((event) => {
@@ -469,6 +593,15 @@ __decorate([
469
593
  __decorate([
470
594
  Datasource
471
595
  ], GridProInfiniteDatasource.prototype, "datasource", void 0);
596
+ __decorate([
597
+ Http
598
+ ], GridProInfiniteDatasource.prototype, "http", void 0);
599
+ __decorate([
600
+ attr({ attribute: 'cube-url' })
601
+ ], GridProInfiniteDatasource.prototype, "cubeUrl", void 0);
602
+ __decorate([
603
+ attr({ attribute: 'cube-operation' })
604
+ ], GridProInfiniteDatasource.prototype, "cubeOperation", void 0);
472
605
  __decorate([
473
606
  observable
474
607
  ], GridProInfiniteDatasource.prototype, "request", void 0);