markdown-up 1.7.5 → 1.8.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.
package/lib/barChart.js DELETED
@@ -1,36 +0,0 @@
1
- // Licensed under the MIT License
2
- // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
-
4
- /** @module lib/barChart */
5
-
6
- import {chartCodeBlock} from './util.js';
7
- import {loadChartData} from './data.js';
8
- import {validateBarChart} from './model.js';
9
-
10
-
11
- /* c8 ignore start */
12
-
13
-
14
- /**
15
- * Bar chart code block function
16
- *
17
- * @param {object} codeBlock - The code block model
18
- * @param {Object} [options=null] - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
19
- * @returns {Object} The bar chart element model
20
- */
21
- export function barChartCodeBlock(codeBlock, options = null) {
22
- return chartCodeBlock(codeBlock, options, validateBarChart, barChartElements);
23
- }
24
-
25
-
26
- /**
27
- * Render a bar chart
28
- *
29
- * @param {Object} barChart - The bar chart model
30
- * @param {Object} [options=null] - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
31
- * @returns {Object} The bar chart element model
32
- */
33
- export async function barChartElements(barChart, options = null) {
34
- const {data} = await loadChartData(barChart, options);
35
- return {'html': 'pre', 'elem': {'text': JSON.stringify(data, null, 4)}};
36
- }
package/lib/csv.js DELETED
@@ -1,68 +0,0 @@
1
- // Licensed under the MIT License
2
- // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
-
4
- /** @module lib/csv */
5
-
6
-
7
- /* c8 ignore start */
8
-
9
-
10
- /**
11
- * Parse CSV text to a JSON data array
12
- *
13
- * @param {string} text - The CSV text
14
- * @returns {Object[]}
15
- */
16
- export function parseCSV(text) {
17
- const data = [];
18
- const splitLines = text.split(rCSVLineSplit).map((line) => line.replace(rCSVLineScrub, '$1').split(rCSVFieldSplit));
19
- const [fields] = splitLines;
20
- for (let ixLine = 1; ixLine < splitLines.length; ixLine += 1) {
21
- const splitLine = splitLines[ixLine];
22
- if (splitLine.length > 1 || splitLine[0] !== '') {
23
- data.push(Object.fromEntries(fields.map(
24
- (field, ixField) => [field, ixField < splitLine.length ? splitLine[ixField] : 'null']
25
- )));
26
- }
27
- }
28
- return data;
29
- }
30
-
31
- const rCSVLineSplit = /\r?\n/;
32
- const rCSVLineScrub = /^"?(.*?)"?$/;
33
- const rCSVFieldSplit = /"?,"?/;
34
-
35
-
36
- /**
37
- * Parse a CSV number
38
- *
39
- * @param {string} text - The text to parse
40
- * @returns {number} The parsed number
41
- */
42
- export function parseCSVNumber(text) {
43
- const value = Number.parseFloat(text);
44
- if (Number.isNaN(value) || !Number.isFinite(value)) {
45
- return null;
46
- }
47
- return value;
48
- }
49
-
50
-
51
- /**
52
- * Parse a CSV datetime
53
- *
54
- * @param {string} text - The text to parse
55
- * @returns {Date} The parsed Date
56
- */
57
- export function parseCSVDatetime(text) {
58
- if (rCSVDate.test(text)) {
59
- const localDate = new Date(text);
60
- return new Date(localDate.getUTCFullYear(), localDate.getUTCMonth(), localDate.getUTCDate());
61
- } else if (rCSVDatetime.test(text)) {
62
- return new Date(text);
63
- }
64
- return null;
65
- }
66
-
67
- const rCSVDate = /^\d{4}-\d{2}-\d{2}$/;
68
- const rCSVDatetime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})$/;
package/lib/model.js DELETED
@@ -1,292 +0,0 @@
1
- // Licensed under the MIT License
2
- // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
-
4
- /** @module lib/model */
5
-
6
- import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
7
- import {validateType} from 'schema-markdown/lib/schema.js';
8
-
9
-
10
- /**
11
- * Validate a bar chart model
12
- *
13
- * @param {Object} barChart - The bar chart model
14
- * @returns {Object}
15
- */
16
- export function validateBarChart(barChart) {
17
- return validateType(chartTypes, 'BarChart', barChart);
18
- }
19
-
20
-
21
- /**
22
- * Validate a data table model
23
- *
24
- * @param {Object} dataTable - The data table model
25
- * @returns {Object}
26
- */
27
- export function validateDataTable(dataTable) {
28
- return validateType(chartTypes, 'DataTable', dataTable);
29
- }
30
-
31
-
32
- /**
33
- * Validate a line chart model
34
- *
35
- * @param {Object} lineChart - The line chart model
36
- * @returns {Object}
37
- */
38
- export function validateLineChart(lineChart) {
39
- return validateType(chartTypes, 'LineChart', lineChart);
40
- }
41
-
42
-
43
- /**
44
- * The chart model defined using Schema Markdown
45
- */
46
- const chartSmd = `\
47
- # Base struct for all chart types
48
- struct ChartBase
49
-
50
- # The data specification
51
- Data data
52
-
53
- # The map of variable name to variable expression
54
- optional string{len > 0} var
55
-
56
- # The calculated fields
57
- optional CalculatedField[len > 0] calc
58
-
59
- # The data row boolean filter expression. Omit any row that does not match.
60
- optional string filter
61
-
62
- # The data aggregation specification
63
- optional Aggregation agg
64
-
65
- # The post-aggregation calculated fields
66
- optional CalculatedField[len > 0] aggcalc
67
-
68
- # The data's sort specification
69
- optional SortField[len > 0] sort
70
-
71
- # The data's top specification
72
- optional Top top
73
-
74
- # The numeric formatting precision (default is 2)
75
- optional int(>= 0) precision
76
-
77
- # The datetime format
78
- optional DatetimeFormat datetime
79
-
80
-
81
- # A chart data specification
82
- struct Data
83
-
84
- # The data resource URL. The data resource is formatted either as a CSV or as a JSON array of row objects.
85
- string url
86
-
87
- # Data joins
88
- optional DataJoin[len > 0] join
89
-
90
-
91
- # A data join specification
92
- struct DataJoin
93
-
94
- # The data resource URL. The data resource is formatted either as a CSV or as a JSON array of row objects.
95
- string url
96
-
97
- # If true, the join is a left join (default is right join)
98
- optional bool leftJoin
99
-
100
- # The join expression for the left row
101
- string left
102
-
103
- # The join expression for the right row
104
- optional string right
105
-
106
-
107
- # A datetime format
108
- enum DatetimeFormat
109
-
110
- # ISO datetime year format
111
- Year
112
-
113
- # ISO datetime month format
114
- Month
115
-
116
- # ISO datetime day format
117
- Day
118
-
119
-
120
- # A calculated field specification
121
- struct CalculatedField
122
-
123
- # The calculated field name
124
- string name
125
-
126
- # The calculation expression
127
- string expr
128
-
129
-
130
- # A data aggregation specification
131
- struct Aggregation
132
-
133
- # The aggregation category fields
134
- string[len > 0] category
135
-
136
- # The aggregation measures
137
- AggregationMeasure[len > 0] measure
138
-
139
-
140
- # An aggregation measure specification
141
- struct AggregationMeasure
142
-
143
- # The aggregated-measure field name
144
- optional string name
145
-
146
- # The aggregation measure field
147
- string field
148
-
149
- # The aggregation function
150
- AggregationFunction func
151
-
152
-
153
- # An aggregation function
154
- enum AggregationFunction
155
-
156
- # The average of the measure's values
157
- Average
158
-
159
- # The count of the measure's values
160
- Count
161
-
162
- # The greatest of the measure's values
163
- Max
164
-
165
- # The least of the measure's values
166
- Min
167
-
168
- # The sum of the measure's values
169
- Sum
170
-
171
-
172
- # A sort field specification
173
- struct SortField
174
-
175
- # The field to sort by
176
- string field
177
-
178
- # If true, sort this field in descending order
179
- optional bool desc
180
-
181
-
182
- # A data top specification
183
- struct Top
184
-
185
- # The maximum number of rows to keep per category
186
- optional int(> 0) count
187
-
188
- # The category fields
189
- optional string[len > 0] category
190
-
191
-
192
- # Base struct for line and bar charts
193
- struct ChartCommon
194
-
195
- # The chart title expression
196
- optional string title
197
-
198
- # The chart width expression
199
- optional string width
200
-
201
- # The chart height expression
202
- optional string height
203
-
204
-
205
- # A bar chart specification
206
- struct BarChart (ChartCommon, ChartBase)
207
-
208
- # The bar measure fields
209
- string[len > 0] measure
210
-
211
- # The bar category fields
212
- optional string[len > 0] bar
213
-
214
- # The category fields
215
- optional string[len > 0] category
216
-
217
- # The color encoding field
218
- optional string[len > 0] color
219
-
220
- # If true, the bar chart is rendered "reversed". The default is false.
221
- optional bool reverse
222
-
223
-
224
- # A data table specification
225
- struct DataTable (ChartBase)
226
-
227
- # The table's category fields
228
- optional string[len > 0] category
229
-
230
- # The table's fields
231
- optional string[len > 0] field
232
-
233
- # The "categoryFields" and "fields" to be rendered as Markdown text
234
- optional string[len > 0] markdown
235
-
236
-
237
- # A line chart specification
238
- struct LineChart (ChartCommon, ChartBase)
239
-
240
- # The line chart's X-axis field
241
- string x
242
-
243
- # The line chart's Y-axis fields
244
- string[len > 0] y
245
-
246
- # The color encoding field
247
- optional string color
248
-
249
- # The X-axis tick mark specification
250
- optional AxisTicks xtick
251
-
252
- # The Y-axis tick mark specification
253
- optional AxisTicks ytick
254
-
255
- # The X-axis annotations
256
- optional AxisAnnotation[len > 0] xline
257
-
258
- # The Y-axis annotations
259
- optional AxisAnnotation[len > 0] yline
260
-
261
-
262
- # An axis annotation
263
- struct AxisAnnotation
264
-
265
- # The axis field value expression
266
- string value
267
-
268
- # The annotation label expression
269
- optional string label
270
-
271
-
272
- # Automatically-generated, evenly-spaced tick marks specification
273
- struct AxisTicks
274
-
275
- # The tick mark count expression. Default is 3.
276
- optional string count
277
-
278
- # The field value expression of the first tick mark. Default is the minimum field value.
279
- optional string start
280
-
281
- # The field value expression of the last tick mark. Default is the maximum field value.
282
- optional string end
283
-
284
- # The number of tick mark labels to skip after a rendered label
285
- optional int(> 0) skip
286
- `;
287
-
288
-
289
- /**
290
- * The chart model
291
- */
292
- export const chartTypes = (new SchemaMarkdownParser(chartSmd)).types;
package/lib/util.js DELETED
@@ -1,176 +0,0 @@
1
- // Licensed under the MIT License
2
- // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
-
4
- /** @module lib/util */
5
-
6
- import {decodeQueryString} from 'schema-markdown/lib/encode.js';
7
- import {renderElements} from 'element-model/lib/elementModel.js';
8
-
9
-
10
- /* c8 ignore start */
11
-
12
-
13
- // The categorical color palette
14
- export const categoricalColors = [
15
- '#1f77b4',
16
- '#ff7f0e',
17
- '#2ca02c',
18
- '#d62728',
19
- '#9467bd',
20
- '#8c564b',
21
- '#e377c2',
22
- '#7f7f7f',
23
- '#bcbd22',
24
- '#17becf',
25
- '#aec7e8',
26
- '#ffbb78',
27
- '#98df8a',
28
- '#ff9896',
29
- '#c5b0d5',
30
- '#c49c94',
31
- '#f7b6d2',
32
- '#c7c7c7',
33
- '#dbdb8d',
34
- '#9edae5'
35
- ];
36
-
37
-
38
- // Helper function to format labels
39
- export function formatValue(value, chart) {
40
- if (value instanceof Date) {
41
- const isoFormat = value.toISOString();
42
- if ('datetime' in chart && chart.datetime === 'Year') {
43
- return isoFormat.slice(0, isoFormat.indexOf('T') - 6);
44
- } else if ('datetime' in chart && chart.datetime === 'Month') {
45
- return isoFormat.slice(0, isoFormat.indexOf('T') - 3);
46
- } else if ('datetime' in chart && chart.datetime === 'Day') {
47
- return isoFormat.slice(0, isoFormat.indexOf('T'));
48
- }
49
- return isoFormat.replace(rDateCleanup, '');
50
- } else if (typeof value === 'number') {
51
- const numberFormat = value.toFixed('precision' in chart ? chart.precision : defaultPrecision);
52
- return numberFormat.replace(rNumberCleanup, '');
53
- }
54
- return `${value}`;
55
- }
56
-
57
- const defaultPrecision = 2;
58
- const rNumberCleanup = /\.0*$/;
59
- const rDateCleanup = /(?:(?:(?:-01)?T00:00)?:00)?\.\d\d\dZ$/;
60
-
61
-
62
- // Helper function to compare values
63
- export function compareValues(value1, value2) {
64
- if (value1 === null) {
65
- return value2 === null ? 0 : 1;
66
- } else if (value2 === null) {
67
- return value1 === null ? 0 : -1;
68
- } else if (value1 instanceof Date) {
69
- const time1 = value1.getTime();
70
- const time2 = value2.getTime();
71
- return time1 < time2 ? -1 : (time1 === time2 ? 0 : 1);
72
- }
73
- return value1 < value2 ? -1 : (value1 === value2 ? 0 : 1);
74
- }
75
-
76
-
77
- // Helper function to compute a value's parameter
78
- export function valueParameter(value, minValue, maxValue) {
79
- if (minValue === maxValue) {
80
- return 0;
81
- }
82
-
83
- if (minValue instanceof Date) {
84
- const minDateValue = minValue.valueOf();
85
- return (value.valueOf() - minDateValue) / (maxValue.valueOf() - minDateValue);
86
- }
87
-
88
- return (value - minValue) / (maxValue - minValue);
89
- }
90
-
91
-
92
- // Helper function to compute a value from a parameter
93
- export function parameterValue(param, minValue, maxValue) {
94
- if (minValue instanceof Date) {
95
- const minDateValue = minValue.valueOf();
96
- return new Date(minDateValue + param * (maxValue.valueOf() - minDateValue));
97
- }
98
-
99
- return minValue + param * (maxValue - minValue);
100
- }
101
-
102
-
103
- // Generic code block helper function
104
- export function chartCodeBlock(codeBlock, options, validationFn, renderFn) {
105
- // Decode and validate the chart model
106
- let chart;
107
- try {
108
- chart = validationFn(decodeChartLines(codeBlock.lines));
109
- } catch ({message}) {
110
- return {'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': `Error: ${message}`}}};
111
- }
112
-
113
- // Render the chart asynchronously
114
- return {
115
- 'html': 'p',
116
- 'elem': !('width' in chart) ? null : {
117
- 'svg': 'svg',
118
- 'attr': {
119
- 'width': chart.width,
120
- 'height': chart.height
121
- }
122
- },
123
- 'callback': (parent) => {
124
- renderFn(chart, options).
125
- then((elements) => {
126
- renderElements(parent, elements);
127
- }).
128
- catch(({message}) => {
129
- renderElements(parent, {'html': 'pre', 'elem': {'text': `Error: ${message}`}});
130
- });
131
- }
132
- };
133
- }
134
-
135
-
136
- // Chart code block regular expressions
137
- const rComment = /^\s*(?:(?:#|\/\/).*)?$/;
138
- const rKeyValue = /^\s*(?<key>.+?)\s*(:\s*(?<value>.*?)\s*)?$/;
139
- const rContinuation = /\\\s*$/;
140
-
141
-
142
- // Helper function to decode chart lines
143
- function decodeChartLines(lines) {
144
- // Parse and URI-encode the chart model key/value pairs
145
- const keyValues = [];
146
- const lineContinuation = [];
147
- for (const linePart of lines) {
148
- // Line continuation?
149
- const linePartNoContinuation = linePart.replace(rContinuation, '');
150
- if (lineContinuation.length || linePartNoContinuation !== linePart) {
151
- lineContinuation.push(linePartNoContinuation);
152
- }
153
- if (linePartNoContinuation !== linePart) {
154
- continue;
155
- }
156
- let line;
157
- if (lineContinuation.length) {
158
- line = lineContinuation.join('');
159
- lineContinuation.length = 0;
160
- } else {
161
- line = linePart;
162
- }
163
-
164
- // Skip comment lines
165
- if (line.match(rComment) !== null) {
166
- continue;
167
- }
168
-
169
- // Split the key/value
170
- const {key, value = ''} = line.match(rKeyValue).groups;
171
- keyValues.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
172
- }
173
-
174
- // Decode the chart model
175
- return decodeQueryString(keyValues.join('&'));
176
- }