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