markdown-up 1.7.4 → 1.8.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.
package/lib/data.js CHANGED
@@ -3,219 +3,70 @@
3
3
 
4
4
  /** @module lib/data */
5
5
 
6
- import {parseCSV, parseCSVDatetime, parseCSVNumber} from './csv.js';
7
- import {compareValues} from './util.js';
8
- import {encodeMarkdownText} from 'markdown-model/lib/parser.js';
9
6
  import {evaluateExpression} from 'calc-script/lib/runtime.js';
10
7
  import {parseExpression} from 'calc-script/lib/parser.js';
11
-
12
-
13
- // Data expression functions
14
- const dataExprFunctions = {
15
- 'markdownEncode': ([text]) => encodeMarkdownText(text)
16
- };
17
-
18
-
19
- // Helper function to create the data expression's variables argument
20
- function createDataVariables(chart, variables = null) {
21
- const dataVariables = {...dataExprFunctions};
22
-
23
- // Add the chart model variable expressions
24
- if (chart !== null && 'var' in chart) {
25
- for (const varName of Object.keys(chart.var)) {
26
- const varExpr = parseExpression(chart.var[varName]);
27
- dataVariables[varName] = evaluateExpression(varExpr, dataVariables);
28
- }
29
- }
30
-
31
- // Add the options variables
32
- if (variables !== null) {
33
- Object.assign(dataVariables, variables);
34
- }
35
-
36
- return dataVariables;
37
- }
38
-
39
-
40
- /**
41
- * The loadChartData result object
42
- *
43
- * @typedef {Object} LoadChartDataResult
44
- * @property {Object[]} data - The data row object array
45
- * @property {Object} types - The map of field name to field type ("datetime", "number", "string")
46
- * @property {Object} variables - The map of computed variable expression values
47
- */
8
+ import {parseSchemaMarkdown} from 'schema-markdown/lib/parser.js';
9
+ import {validateType} from 'schema-markdown/lib/schema.js';
48
10
 
49
11
 
50
12
  /**
51
- * Load the chart's data
13
+ * Parse and validate CSV text to a data array
52
14
  *
53
- * @async
54
- * @param {Object} chart - The chart model
55
- * @param {Object} [options=null] - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
56
- * @returns {module:lib/data~LoadChartDataResult}
15
+ * @param {string} text - The CSV text
16
+ * @returns {Object[]} The data array
57
17
  */
58
- export async function loadChartData(chart, options = null) {
59
- // Load the data resources
60
- let {data, types} = await loadData(chart.data, options);
61
-
62
- // Compute the data variable values
63
- const variables = createDataVariables(chart, options !== null ? options.variables : null);
64
-
65
- // Add calculated fields
66
- if ('calc' in chart) {
67
- for (const calculatedField of chart.calc) {
68
- types[calculatedField.name] = addCalculatedField(data, calculatedField.name, calculatedField.expr, variables);
69
- }
70
- }
71
-
72
- // Filter the data
73
- if ('filter' in chart) {
74
- data = filterData(data, chart.filter, variables);
75
- }
76
-
77
- // Aggregate the data
78
- if ('agg' in chart) {
79
- ({data, types} = aggregateData(chart.agg, data, types));
80
- }
81
-
82
- // Add the post-aggregation calculated fields
83
- if ('aggcalc' in chart) {
84
- for (const calculatedField of chart.aggcalc) {
85
- types[calculatedField.name] = addCalculatedField(data, calculatedField.name, calculatedField.expr, variables);
18
+ export function parseCSV(text) {
19
+ // Line-split the text
20
+ const lines = [];
21
+ if (typeof text === 'string') {
22
+ lines.push(...text.split(rCSVLineSplit));
23
+ } else {
24
+ for (const textPart of text) {
25
+ lines.push(...textPart.split(rCSVLineSplit));
86
26
  }
87
27
  }
88
28
 
89
- // Sort the data
90
- if ('sort' in chart) {
91
- sortData(chart.sort, data);
92
- }
93
-
94
- // Top the data
95
- if ('top' in chart) {
96
- data = topData(chart.top, data);
97
- }
98
-
99
- return {data, types, variables};
100
- }
101
-
102
-
103
- /**
104
- * The loadData result object
105
- *
106
- * @typedef {Object} LoadDataResult
107
- * @property {Object[]} data - The data row object array
108
- * @property {Object} types - The map of field name to field type ("datetime", "number", "string")
109
- */
110
-
111
-
112
- /**
113
- * Load a data model
114
- *
115
- * @async
116
- * @param {Object} dataModel - The data model
117
- * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
118
- * @returns {module:lib/data~LoadDataResult}
119
- */
120
- export async function loadData(dataModel, options) {
121
- const dataBases = [dataModel, ...('join' in dataModel ? dataModel.join : [])];
122
- const dataURLs = dataBases.map((base) => base.url);
123
- const dataResponses = await Promise.all(dataURLs.map((joinURL) => options.fetchFn(options.urlFn(joinURL))));
124
- const dataTypes = await Promise.all(dataResponses.map((response, ixResponse) => dataResponseHandler(dataURLs[ixResponse], response)));
125
-
126
- // Compute the data variable values
127
- const dataVariables = options.variables ?? createDataVariables(null);
128
-
129
- // Join the data
130
- let [{data}] = dataTypes;
131
- const [{types}] = dataTypes;
132
- if ('join' in dataModel) {
133
- // Helper function to compute a unique field name
134
- const mapFieldName = (field) => {
135
- let unique = field;
136
- let ixUnique = 2;
137
- while (unique in types) {
138
- unique = `${field}${ixUnique}`;
139
- ixUnique += 1;
140
- }
141
- return [field, unique];
142
- };
143
-
144
- // Perform each join in sequence
145
- let leftData;
146
- for (let ixJoin = 0; ixJoin < dataModel.join.length; ixJoin++) {
147
- const join = dataModel.join[ixJoin];
148
- const {'leftJoin': isLeftJoin = false} = join;
149
- const leftExpression = parseExpression(join.left);
150
- const rightExpression = parseExpression('right' in join ? join.right : join.left);
151
- const rightData = dataTypes[ixJoin + 1].data;
152
- const rightTypes = dataTypes[ixJoin + 1].types;
153
-
154
- // Bucket the right rows by the right expression value
155
- const rightCategoryRows = {};
156
- for (const row of rightData) {
157
- const categoryKey = JSON.stringify(evaluateExpression(rightExpression, dataVariables, row));
158
- if (!(categoryKey in rightCategoryRows)) {
159
- rightCategoryRows[categoryKey] = [];
160
- }
161
- rightCategoryRows[categoryKey].push(row);
29
+ // Split lines into rows
30
+ const rows = lines.filter((line) => !line.match(rCSVBlankLine)).map((line) => {
31
+ const row = [];
32
+ let linePart = line;
33
+ while (linePart !== '') {
34
+ // Quoted field?
35
+ const mQuoted = linePart.match(rCSVQuotedField) ?? linePart.match(rCSVQuotedFieldEnd);
36
+ if (mQuoted !== null) {
37
+ row.push(mQuoted[1].replaceAll(rCSVQuoteEscape, '"'));
38
+ linePart = linePart.slice(mQuoted[0].length);
39
+ continue;
162
40
  }
163
41
 
164
- // Compute the right column names
165
- const rightFieldMap = Object.fromEntries(Object.keys(rightTypes).map(mapFieldName));
166
- for (const rightField of Object.keys(rightTypes)) {
167
- types[rightFieldMap[rightField]] = rightTypes[rightField];
168
- }
169
-
170
- // Join the left with the right
171
- leftData = data;
172
-
173
- data = [];
174
- for (const row of leftData) {
175
- const categoryKey = JSON.stringify(evaluateExpression(leftExpression, dataVariables, row));
176
- if (categoryKey in rightCategoryRows) {
177
- for (const rightRow of rightCategoryRows[categoryKey]) {
178
- const joinRow = {...row};
179
- for (const rightField of Object.keys(rightTypes)) {
180
- if (rightField in rightRow) {
181
- joinRow[rightFieldMap[rightField]] = rightRow[rightField];
182
- }
183
- }
184
- data.push(joinRow);
185
- }
186
- } else if (!isLeftJoin) {
187
- data.push(row);
188
- }
189
- }
42
+ // Non-quoted field
43
+ const ixComma = linePart.indexOf(',');
44
+ row.push(ixComma !== -1 ? linePart.slice(0, ixComma) : linePart);
45
+ linePart = (ixComma !== -1 ? linePart.slice(ixComma + 1) : '');
46
+ }
47
+ return row;
48
+ });
49
+
50
+ // Assemble the data rows
51
+ const result = [];
52
+ if (rows.length >= 2) {
53
+ const [fields] = rows;
54
+ for (let ixLine = 1; ixLine < rows.length; ixLine += 1) {
55
+ const row = rows[ixLine];
56
+ result.push(Object.fromEntries(fields.map(
57
+ (field, ixField) => [field, ixField < row.length ? row[ixField] : 'null']
58
+ )));
190
59
  }
191
60
  }
192
61
 
193
- return {data, types};
62
+ return result;
194
63
  }
195
64
 
196
-
197
- // Helper function to handle data fetch responses
198
- async function dataResponseHandler(url, response) {
199
- // Fetch error?
200
- if (!response.ok) {
201
- const status = response.statusText;
202
- throw new Error(`Could not fetch "${url}"${status === '' ? '' : `, ${JSON.stringify(status)}`}`);
203
- }
204
-
205
- // CSV?
206
- let data;
207
- const csv = url.endsWith('.csv');
208
- if (csv) {
209
- data = parseCSV(await response.text());
210
- } else {
211
- data = await response.json();
212
- }
213
-
214
- // Validate the data
215
- const types = validateData(data, csv);
216
-
217
- return {data, types};
218
- }
65
+ const rCSVLineSplit = /\r?\n/;
66
+ const rCSVBlankLine = /^\s*$/;
67
+ const rCSVQuotedField = /^"((?:""|[^"])*)",/;
68
+ const rCSVQuotedFieldEnd = /^"((?:""|[^"])*)"\s*$/;
69
+ const rCSVQuoteEscape = /""/g;
219
70
 
220
71
 
221
72
  /**
@@ -224,6 +75,7 @@ async function dataResponseHandler(url, response) {
224
75
  * @param {Object[]} data - The data array. Row objects are updated with parsed/validated values.
225
76
  * @param {boolean} [csv=false] - If true, parse number and null strings
226
77
  * @returns {Object} The map of field name to field type ("datetime", "number", "string")
78
+ * @throws Throws an error if data is invalid
227
79
  */
228
80
  export function validateData(data, csv = false) {
229
81
  // Determine field types
@@ -236,9 +88,9 @@ export function validateData(data, csv = false) {
236
88
  } else if (value instanceof Date) {
237
89
  types[field] = 'datetime';
238
90
  } else if (typeof value === 'string' && (!csv || value !== 'null')) {
239
- if (parseCSVDatetime(value) !== null) {
91
+ if (parseDatetime(value) !== null) {
240
92
  types[field] = 'datetime';
241
- } else if (csv && parseCSVNumber(value) !== null) {
93
+ } else if (csv && parseNumber(value) !== null) {
242
94
  types[field] = 'number';
243
95
  } else {
244
96
  types[field] = 'string';
@@ -254,7 +106,7 @@ export function validateData(data, csv = false) {
254
106
  };
255
107
  for (const row of data) {
256
108
  for (const [field, value] of Object.entries(row)) {
257
- const fieldType = field in types ? types[field] : 'string';
109
+ const fieldType = types[field];
258
110
 
259
111
  // Null string?
260
112
  if (csv && value === 'null') {
@@ -263,7 +115,7 @@ export function validateData(data, csv = false) {
263
115
  // Number field
264
116
  } else if (fieldType === 'number') {
265
117
  if (csv && typeof value === 'string') {
266
- const numberValue = parseCSVNumber(value);
118
+ const numberValue = parseNumber(value);
267
119
  if (numberValue === null) {
268
120
  throwFieldError(field, fieldType, value);
269
121
  }
@@ -275,12 +127,12 @@ export function validateData(data, csv = false) {
275
127
  // Datetime field
276
128
  } else if (fieldType === 'datetime') {
277
129
  if (typeof value === 'string') {
278
- const datetimeValue = parseCSVDatetime(value);
130
+ const datetimeValue = parseDatetime(value);
279
131
  if (datetimeValue === null) {
280
132
  throwFieldError(field, fieldType, value);
281
133
  }
282
134
  row[field] = datetimeValue;
283
- } else if (value !== null && !(value instanceof 'Date')) {
135
+ } else if (value !== null && !(value instanceof Date)) {
284
136
  throwFieldError(field, fieldType, value);
285
137
  }
286
138
 
@@ -297,218 +149,380 @@ export function validateData(data, csv = false) {
297
149
  }
298
150
 
299
151
 
152
+ function parseNumber(text) {
153
+ const value = Number.parseFloat(text);
154
+ if (Number.isNaN(value) || !Number.isFinite(value)) {
155
+ return null;
156
+ }
157
+ return value;
158
+ }
159
+
160
+
161
+ function parseDatetime(text) {
162
+ if (rDate.test(text)) {
163
+ const localDate = new Date(text);
164
+ return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate());
165
+ } else if (rDatetime.test(text)) {
166
+ return new Date(text);
167
+ }
168
+ return null;
169
+ }
170
+
171
+ const rDate = /^\d{4}-\d{2}-\d{2}$/;
172
+ const rDatetime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;
173
+
174
+
300
175
  /**
301
- * Add a calculated field to each row of a data array
176
+ * Join two data arrays
302
177
  *
303
- * @param {Object[]} data - The data array. Row objects are updated with the calculated field values.
304
- * @param {string} name - The calculated field name
305
- * @param {string} expr - The calculated field expression
306
- * @param {Object} [variables = null] - Map of variables to variable value
307
- * @returns {string} The field type ("datetime", "number", "string")
178
+ * @param {Object} leftData - The left data array
179
+ * @param {Object} rightData - The left data array
180
+ * @param {string} joinExpr - The join [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
181
+ * @param {?string} [rightExpr = null] - The right join [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
182
+ * @param {boolean} [isLeftJoin = false] - If true, perform a left join (always include left row)
183
+ * @param {?Object} [variables = null] - Additional variables for expression evaluation
184
+ * @returns {Object[]} The joined data array
308
185
  */
309
- export function addCalculatedField(data, name, expr, variables = null) {
310
- // Parse the calculation expression
311
- const calcExpr = parseExpression(expr);
312
-
313
- // Compute the data variable values
314
- const dataVariables = variables ?? createDataVariables(null);
186
+ export function joinData(leftData, rightData, joinExpr, rightExpr = null, isLeftJoin = false, variables = null) {
187
+ // Compute the map of row field name to joined row field name
188
+ const leftNames = {};
189
+ for (const row of leftData) {
190
+ for (const fieldName of Object.keys(row)) {
191
+ if (!(fieldName in leftNames)) {
192
+ leftNames[fieldName] = fieldName;
193
+ }
194
+ }
195
+ }
196
+ const rightNames = {};
197
+ for (const row of rightData) {
198
+ for (const fieldName of Object.keys(row)) {
199
+ if (!(fieldName in rightNames)) {
200
+ if (!(fieldName in leftNames)) {
201
+ rightNames[fieldName] = fieldName;
202
+ } else {
203
+ let uniqueName = fieldName;
204
+ let ixUnique = 2;
205
+ do {
206
+ uniqueName = `${fieldName}${ixUnique}`;
207
+ ixUnique += 1;
208
+ } while (uniqueName in leftNames || uniqueName in rightNames);
209
+ rightNames[fieldName] = uniqueName;
210
+ }
211
+ }
212
+ }
213
+ }
315
214
 
316
- // Compute the calculated fields for each row
317
- let calcType = null;
318
- for (const row of data) {
319
- const calcValue = evaluateExpression(calcExpr, dataVariables, row);
320
- row[name] = calcValue;
215
+ // Parse the left and right expressions
216
+ const evalOptions = (variables !== null ? {'globals': variables} : null);
217
+ const leftExpression = parseExpression(joinExpr);
218
+ const rightExpression = (rightExpr !== null ? parseExpression(rightExpr) : leftExpression);
219
+
220
+ // Bucket the right rows by the right expression value
221
+ const rightCategoryRows = {};
222
+ for (const rightRow of rightData) {
223
+ const categoryKey = JSON.stringify(evaluateExpression(rightExpression, evalOptions, rightRow));
224
+ if (!(categoryKey in rightCategoryRows)) {
225
+ rightCategoryRows[categoryKey] = [];
226
+ }
227
+ rightCategoryRows[categoryKey].push(rightRow);
228
+ }
321
229
 
322
- // Determine the calculated field type
323
- if (calcValue !== null && calcType === null) {
324
- calcType = getCalculatedValueType(calcValue);
230
+ // Join the left with the right
231
+ const data = [];
232
+ for (const leftRow of leftData) {
233
+ const categoryKey = JSON.stringify(evaluateExpression(leftExpression, evalOptions, leftRow));
234
+ if (categoryKey in rightCategoryRows) {
235
+ for (const rightRow of rightCategoryRows[categoryKey]) {
236
+ const joinRow = {...leftRow};
237
+ for (const [rightName, rightValue] of Object.entries(rightRow)) {
238
+ joinRow[rightNames[rightName]] = rightValue;
239
+ }
240
+ data.push(joinRow);
241
+ }
242
+ } else if (!isLeftJoin) {
243
+ data.push({...leftRow});
325
244
  }
326
245
  }
327
246
 
328
- return calcType !== null ? calcType : 'string';
247
+ return data;
329
248
  }
330
249
 
331
250
 
332
251
  /**
333
- * Get an computed expression value's type
252
+ * Add a calculated field to each row of a data array
334
253
  *
335
- * @param {*} value - The computed expression value
336
- * @returns {string} The field type ("datetime", "number", "string")
254
+ * @param {Object[]} data - The data array. Row objects are updated with the calculated field values.
255
+ * @param {string} fieldName - The calculated field name
256
+ * @param {string} expr - The calculated field expression
257
+ * @param {?Object} [variables = null] - Additional variables for expression evaluation
258
+ * @returns {Object[]} The updated data array
337
259
  */
338
- export function getCalculatedValueType(value) {
339
- if (typeof value === 'number' || typeof value === 'boolean') {
340
- return 'number';
341
- } else if (value instanceof Date) {
342
- return 'datetime';
260
+ export function addCalculatedField(data, fieldName, expr, variables = null) {
261
+ // Parse the calculation expression
262
+ const calcExpr = parseExpression(expr);
263
+
264
+ // Compute the calculated field for each row
265
+ const evalOptions = (variables !== null ? {'globals': variables} : null);
266
+ for (const row of data) {
267
+ row[fieldName] = evaluateExpression(calcExpr, evalOptions, row);
343
268
  }
344
- return 'string';
269
+ return data;
345
270
  }
346
271
 
347
272
 
348
273
  /**
349
274
  * Filter data rows
350
275
  *
351
- * @param {Object[]} data - The data array. Row objects are updated with parsed/validated values.
352
- * @param {string} expr - The boolean filter expression
353
- * @param {Object} [variables = null] - Map of variables to variable value
276
+ * @param {Object[]} data - The data array
277
+ * @param {string} expr - The boolean filter [expression]{@link https://craigahobbs.github.io/calc-script/language/#expressions}
278
+ * @param {?Object} [variables = null] - Additional variables for expression evaluation
354
279
  * @returns {Object[]} The filtered data array
355
280
  */
356
281
  export function filterData(data, expr, variables = null) {
282
+ const result = [];
283
+
357
284
  // Parse the filter expression
358
285
  const filterExpr = parseExpression(expr);
359
286
 
360
- // Compute the data variable values
361
- const dataVariables = variables ?? createDataVariables(null);
362
-
363
287
  // Filter the data
364
- const filteredData = [];
288
+ const evalOptions = (variables !== null ? {'globals': variables} : null);
365
289
  for (const row of data) {
366
- if (evaluateExpression(filterExpr, dataVariables, row)) {
367
- filteredData.push(row);
290
+ if (evaluateExpression(filterExpr, evalOptions, row)) {
291
+ result.push(row);
368
292
  }
369
293
  }
370
- return filteredData;
294
+
295
+ return result;
296
+ }
297
+
298
+
299
+ // The aggregation model
300
+ export const aggregationTypes = parseSchemaMarkdown(`\
301
+ group "Aggregation"
302
+
303
+
304
+ # A data aggregation specification
305
+ struct Aggregation
306
+
307
+ # The aggregation category fields
308
+ optional string[len > 0] categories
309
+
310
+ # The aggregation measures
311
+ AggregationMeasure[len > 0] measures
312
+
313
+
314
+ # An aggregation measure specification
315
+ struct AggregationMeasure
316
+
317
+ # The aggregation measure field
318
+ string field
319
+
320
+ # The aggregation function
321
+ AggregationFunction function
322
+
323
+ # The aggregated-measure field name
324
+ optional string name
325
+
326
+
327
+ # An aggregation function
328
+ enum AggregationFunction
329
+
330
+ # The average of the measure's values
331
+ average
332
+
333
+ # The count of the measure's values
334
+ count
335
+
336
+ # The greatest of the measure's values
337
+ max
338
+
339
+ # The least of the measure's values
340
+ min
341
+
342
+ # The sum of the measure's values
343
+ sum
344
+ `);
345
+
346
+
347
+ /**
348
+ * Validate an aggregation model
349
+ *
350
+ * @param {Object} aggregation - The
351
+ * [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
352
+ * @returns {Object} The validated
353
+ * [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
354
+ * @throws [ValidationError]{@link https://craigahobbs.github.io/schema-markdown-js/module-lib_schema.ValidationError.html}
355
+ */
356
+ export function validateAggregation(aggregation) {
357
+ return validateType(aggregationTypes, 'Aggregation', aggregation);
371
358
  }
372
359
 
373
360
 
374
361
  /**
375
362
  * Aggregate data rows
376
363
  *
377
- * @param {Object} aggregationModel - The aggregation model
378
364
  * @param {Object[]} data - The data array
379
- * @param {Object} types - The map of field name to field type ("datetime", "number", "string")
380
- * @returns {module:lib/data~LoadDataResult}
365
+ * @param {Object} aggregation - The
366
+ * [aggregation model]{@link https://craigahobbs.github.io/markdown-up/library/model.html#var.vName='Aggregation'}
367
+ * @returns {Object[]} The aggregated data array
381
368
  */
382
- export function aggregateData(aggregationModel, data, types) {
383
- // Compute the aggregate field types
384
- const aggregateTypes = {};
385
- for (const categoryField of aggregationModel.category) {
386
- if (!(categoryField in types)) {
387
- throw new Error(`Unknown aggregation category field "${categoryField}"`);
388
- }
389
- aggregateTypes[categoryField] = types[categoryField];
390
- }
391
- for (const measure of aggregationModel.measure) {
392
- if (!(measure.field in types)) {
393
- throw new Error(`Unknown aggregation category field "${measure.field}"`);
394
- }
395
- if ((measure.func === 'Average' || measure.func === 'Sum') && types[measure.field] !== 'number') {
396
- throw new Error(`Invalid aggregation measure function "${measure.func}" ` +
397
- `for field "${measure.field}" (type "${types[measure.field]}")`);
398
- }
399
- const measureName = ('name' in measure ? measure.name : measure.field);
400
- aggregateTypes[measureName] = types[measure.field];
401
- }
369
+ export function aggregateData(data, aggregation) {
370
+ const categories = aggregation.categories ?? null;
402
371
 
403
372
  // Create the aggregate rows
404
- const measureRows = {};
373
+ const categoryRows = {};
405
374
  for (const row of data) {
406
375
  // Compute the category values
407
- const categoryValues = aggregationModel.category.map((categoryField) => row[categoryField]);
376
+ const categoryValues = (categories !== null ? categories.map((categoryField) => row[categoryField]) : null);
408
377
 
409
378
  // Get or create the aggregate row
410
379
  let aggregateRow;
411
- const rowKey = JSON.stringify(categoryValues);
412
- if (rowKey in measureRows) {
413
- aggregateRow = measureRows[rowKey];
380
+ const rowKey = (categoryValues !== null ? JSON.stringify(categoryValues) : '');
381
+ if (rowKey in categoryRows) {
382
+ aggregateRow = categoryRows[rowKey];
414
383
  } else {
415
384
  aggregateRow = {};
416
- measureRows[rowKey] = aggregateRow;
417
- for (let ixCategoryField = 0; ixCategoryField < aggregationModel.category.length; ixCategoryField++) {
418
- aggregateRow[aggregationModel.category[ixCategoryField]] = categoryValues[ixCategoryField];
385
+ categoryRows[rowKey] = aggregateRow;
386
+ if (categories !== null) {
387
+ for (let ixCategoryField = 0; ixCategoryField < categories.length; ixCategoryField++) {
388
+ aggregateRow[categories[ixCategoryField]] = categoryValues[ixCategoryField];
389
+ }
419
390
  }
420
391
  }
421
392
 
422
393
  // Add to the aggregate measure values
423
- for (const measure of aggregationModel.measure) {
424
- const measureName = ('name' in measure ? measure.name : measure.field);
425
- const value = (measure.field in row ? row[measure.field] : null);
426
- if (value !== null) {
427
- if (!(measureName in aggregateRow)) {
428
- aggregateRow[measureName] = [];
429
- }
430
- aggregateRow[measureName].push(value);
394
+ for (const measure of aggregation.measures) {
395
+ const field = measure.name ?? measure.field;
396
+ const value = row[measure.field] ?? null;
397
+ if (!(field in aggregateRow)) {
398
+ aggregateRow[field] = [];
431
399
  }
400
+ aggregateRow[field].push(value);
432
401
  }
433
402
  }
434
403
 
435
404
  // Compute the measure values aggregate function value
436
- const aggregateRows = Object.values(measureRows);
405
+ const aggregateRows = Object.values(categoryRows);
437
406
  for (const aggregateRow of aggregateRows) {
438
- for (const measure of aggregationModel.measure) {
439
- const measureName = ('name' in measure ? measure.name : measure.field);
440
- const measureValues = measureName in aggregateRow ? aggregateRow[measureName] : null;
441
- const measureFunction = measure.func;
442
- if (measureValues === null) {
443
- aggregateRow[measureName] = null;
444
- } else if (measureFunction === 'Average') {
445
- aggregateRow[measureName] = measureValues.reduce((sum, val) => sum + val) / measureValues.length;
446
- } else if (measureFunction === 'Count') {
447
- aggregateRow[measureName] = measureValues.length;
448
- } else if (measureFunction === 'Max') {
449
- aggregateRow[measureName] = measureValues.reduce((max, val) => (val > max ? val : max));
450
- } else if (measureFunction === 'Min') {
451
- aggregateRow[measureName] = measureValues.reduce((min, val) => (val < min ? val : min));
452
- } else if (measureFunction === 'Sum') {
453
- aggregateRow[measureName] = measureValues.reduce((sum, val) => sum + val);
407
+ for (const measure of aggregation.measures) {
408
+ const field = measure.name ?? measure.field;
409
+ const func = measure.function;
410
+ const measureValues = aggregateRow[field];
411
+ if (func === 'count') {
412
+ aggregateRow[field] = measureValues.length;
413
+ } else if (func === 'max') {
414
+ aggregateRow[field] = measureValues.reduce((max, val) => (val > max ? val : max));
415
+ } else if (func === 'min') {
416
+ aggregateRow[field] = measureValues.reduce((min, val) => (val < min ? val : min));
417
+ } else if (func === 'sum') {
418
+ aggregateRow[field] = measureValues.reduce((sum, val) => sum + val, 0);
419
+ } else {
420
+ aggregateRow[field] = measureValues.reduce((sum, val) => sum + val, 0) / measureValues.length;
454
421
  }
455
422
  }
456
423
  }
457
424
 
458
- return {'data': aggregateRows, 'types': aggregateTypes};
425
+ return aggregateRows;
459
426
  }
460
427
 
461
428
 
462
429
  /**
463
430
  * Sort data rows
464
431
  *
465
- * @param {Object} sortModels - The sort model array
466
- * @param {Object[]} data - The sorted data array
432
+ * @param {Object[]} data - The data array
433
+ * @param {Object[]} sorts - The sort field-name/descending-sort tuples
434
+ * @returns {Object[]} The sorted data array
467
435
  */
468
- export function sortData(sortModels, data) {
469
- data.sort((row1, row2) => sortModels.reduce((result, sort) => {
436
+ export function sortData(data, sorts) {
437
+ return data.sort((row1, row2) => sorts.reduce((result, sort) => {
470
438
  if (result !== 0) {
471
439
  return result;
472
440
  }
473
- const value1 = sort.field in row1 ? row1[sort.field] : null;
474
- const value2 = sort.field in row2 ? row2[sort.field] : null;
441
+ const [field, desc = false] = sort;
442
+ const value1 = row1[field] ?? null;
443
+ const value2 = row2[field] ?? null;
475
444
  const compare = compareValues(value1, value2);
476
- return 'desc' in sort && sort.desc ? -compare : compare;
445
+ return desc ? -compare : compare;
477
446
  }, 0));
478
447
  }
479
448
 
480
449
 
481
- /**
482
- * Top data rows
483
- *
484
- * @param {Object} topModel - The top model
485
- * @param {Object[]} data - The data array
486
- * @returns {Object[]} The top data array
487
- */
488
- export function topData(topModel, data) {
489
- // Bucket rows by category
490
- const categoryRows = {};
491
- const categoryOrder = [];
492
- const categoryFields = 'category' in topModel ? topModel.category : [];
493
- for (const row of data) {
494
- const categoryKey = JSON.stringify(categoryFields.map((field) => (field in row ? row[field] : null)));
495
- if (!(categoryKey in categoryRows)) {
496
- categoryRows[categoryKey] = [];
497
- categoryOrder.push(categoryKey);
450
+ // Helper function to format labels
451
+ export function formatValue(value, precision = null, datetime = null) {
452
+ if (value instanceof Date) {
453
+ if (datetime === 'year') {
454
+ // Round to nearest year
455
+ let valueRounded = value;
456
+ if (value.getUTCMonth() > 5) {
457
+ valueRounded = new Date(value);
458
+ valueRounded.setUTCFullYear(value.getUTCFullYear() + 1);
459
+ }
460
+
461
+ const isoFormat = valueRounded.toISOString();
462
+ return isoFormat.slice(0, isoFormat.indexOf('T') - 6);
463
+ } else if (datetime === 'month') {
464
+ // Round to the nearest month
465
+ let valueRounded = value;
466
+ if (value.getUTCDate() > 15) {
467
+ valueRounded = new Date(value);
468
+ valueRounded.setMonth(value.getUTCMonth() + 1);
469
+ }
470
+
471
+ const isoFormat = valueRounded.toISOString();
472
+ return isoFormat.slice(0, isoFormat.indexOf('T') - 3);
473
+ } else if (datetime === 'day') {
474
+ const isoFormat = value.toISOString();
475
+ return isoFormat.slice(0, isoFormat.indexOf('T'));
498
476
  }
499
- categoryRows[categoryKey].push(row);
477
+ return value.toISOString().replace(rDateCleanup, '');
478
+ } else if (typeof value === 'number') {
479
+ const numberFormat = value.toFixed(precision ?? defaultPrecision);
480
+ return numberFormat.replace(rNumberCleanup, '');
500
481
  }
482
+ return `${value}`;
483
+ }
501
484
 
502
- // Take only the top rows
503
- const dataTop = [];
504
- const topCount = topModel.count;
505
- for (const categoryKey of categoryOrder) {
506
- const categoryKeyRows = categoryRows[categoryKey];
507
- const categoryKeyLength = categoryKeyRows.length;
508
- for (let ixRow = 0; ixRow < topCount && ixRow < categoryKeyLength; ixRow++) {
509
- dataTop.push(categoryKeyRows[ixRow]);
510
- }
485
+ const defaultPrecision = 2;
486
+ const rNumberCleanup = /\.0*$/;
487
+ const rDateCleanup = /(?:(?:(?:-01)?T00:00)?:00)?\.\d\d\dZ$/;
488
+
489
+
490
+ // Helper function to compare values
491
+ export function compareValues(value1, value2) {
492
+ if (value1 === null) {
493
+ return value2 === null ? 0 : -1;
494
+ } else if (value2 === null) {
495
+ return 1;
496
+ } else if (value1 instanceof Date) {
497
+ const time1 = value1.getTime();
498
+ const time2 = value2.getTime();
499
+ return time1 < time2 ? -1 : (time1 === time2 ? 0 : 1);
500
+ }
501
+ return value1 < value2 ? -1 : (value1 === value2 ? 0 : 1);
502
+ }
503
+
504
+
505
+ // Helper function to compute a value's parameter
506
+ export function valueParameter(value, minValue, maxValue) {
507
+ if (minValue === maxValue) {
508
+ return 0;
509
+ }
510
+
511
+ if (minValue instanceof Date) {
512
+ const minDateValue = minValue.valueOf();
513
+ return (value.valueOf() - minDateValue) / (maxValue.valueOf() - minDateValue);
514
+ }
515
+
516
+ return (value - minValue) / (maxValue - minValue);
517
+ }
518
+
519
+
520
+ // Helper function to compute a value from a parameter
521
+ export function parameterValue(param, minValue, maxValue) {
522
+ if (minValue instanceof Date) {
523
+ const minDateValue = minValue.valueOf();
524
+ return new Date(minDateValue + param * (maxValue.valueOf() - minDateValue));
511
525
  }
512
526
 
513
- return dataTop;
527
+ return minValue + param * (maxValue - minValue);
514
528
  }