markdown-up 1.6.0 → 1.7.2

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/script.js ADDED
@@ -0,0 +1,462 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ /** @module lib/script */
5
+
6
+ import {encodeMarkdownText, getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
7
+ import {validateType, validateTypeModel} from 'schema-markdown/lib/schema.js';
8
+ import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
9
+ import {encodeQueryString} from 'schema-markdown/lib/encode.js';
10
+ import {executeScriptAsync} from 'calc-script/lib/runtimeAsync.js';
11
+ import {markdownElementsAsync} from 'markdown-model/lib/elements.js';
12
+ import {parseScript} from 'calc-script/lib/parser.js';
13
+ import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
14
+ import {typeModel} from 'schema-markdown/lib/typeModel.js';
15
+
16
+
17
+ /**
18
+ * markdown-script code block function
19
+ *
20
+ * @async
21
+ * @param {string} language - The code block language
22
+ * @param {string[]} lines - The code block's text lines
23
+ * @param {module:lib/util~MarkdownScriptOptions} [options=null] - Markdown script options
24
+ * @returns {Object} The generated element model
25
+ */
26
+ export async function markdownScriptCodeBlock(language, lines, options = null) {
27
+ // Get/create the script's runtime
28
+ const runtime = (
29
+ options !== null && 'runtime' in options && options.runtime !== null
30
+ ? options.runtime
31
+ : new MarkdownScriptRuntime(options)
32
+ );
33
+
34
+ // Add the options variables to the runtime's globals
35
+ if (options !== null && 'variables' in options) {
36
+ Object.assign(runtime.globals, options.variables);
37
+ }
38
+
39
+ // Execute the calculation script
40
+ let errorMessage = null;
41
+ try {
42
+ await executeScriptAsync(parseScript(lines), runtime.globals, options);
43
+ } catch ({message}) {
44
+ errorMessage = message;
45
+ } finally {
46
+ runtime.finishDrawingPath();
47
+ }
48
+
49
+ // Create the markdownElements options
50
+ const markdownElementsOptions = {'headerIds': true};
51
+ if (options !== null && 'urlFn' in options) {
52
+ markdownElementsOptions.urlFn = options.urlFn;
53
+ }
54
+
55
+ // Render the element model parts
56
+ const elements = [];
57
+ for (const part of runtime.elementParts) {
58
+ if ('drawing' in part) {
59
+ elements.push({'html': 'p', 'elem': part.drawing});
60
+ } else if ('markdown' in part) {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ elements.push(await markdownElementsAsync(parseMarkdown(part.markdown), markdownElementsOptions));
63
+ } else {
64
+ elements.push(part.elements);
65
+ }
66
+ }
67
+ runtime.elementParts.length = 0;
68
+
69
+ // If an error occurred, render the error message
70
+ if (errorMessage !== null) {
71
+ elements.push({'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': errorMessage}}});
72
+ }
73
+
74
+ return elements;
75
+ }
76
+
77
+
78
+ // markdown-script runtime constants
79
+ const defaultDrawingWidth = 300;
80
+ const defaultDrawingHeight = 200;
81
+ const svgPrecision = 8;
82
+ const fontWidthRatio = 0.6;
83
+ const pixelsPerPoint = 4 / 3;
84
+ const defaultFontFamily = 'Arial, Helvetica, sans-serif';
85
+ const defaultFontSizePx = 12 * pixelsPerPoint;
86
+
87
+
88
+ /**
89
+ * @typedef {Object} ElementPart
90
+ * @property {Object} drawing - SVG element model
91
+ * @property {string[]} markdown - Markdown text lines
92
+ */
93
+
94
+
95
+ /**
96
+ * markdown-script runtime state
97
+ *
98
+ * @property {Object} globals - The global variables
99
+ * @property {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
100
+ * @property {module:lib/script~ElementPart[]} elementParts - The element model parts to render
101
+ * @property {?string} documentTitle - The document title
102
+ */
103
+ export class MarkdownScriptRuntime {
104
+ /**
105
+ * @param {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
106
+ */
107
+ constructor(options = null) {
108
+ this.options = options;
109
+
110
+ // The runtime's global variables
111
+ this.globals = {
112
+ // Drawing functions
113
+ 'drawArc': (args) => this.drawArc(...args),
114
+ 'drawCircle': (args) => this.drawCircle(...args),
115
+ 'drawClose': () => this.drawClose(),
116
+ 'drawEllipse': (args) => this.drawEllipse(...args),
117
+ 'drawHLine': (args) => this.drawHLine(...args),
118
+ 'drawLine': (args) => this.drawLine(...args),
119
+ 'drawMove': (args) => this.drawMove(...args),
120
+ 'drawOnClick': (args) => this.drawOnClick(...args),
121
+ 'drawRect': (args) => this.drawRect(...args),
122
+ 'drawStyle': (args) => this.drawStyle(...args),
123
+ 'drawText': (args) => this.drawText(...args),
124
+ 'drawTextStyle': (args) => this.drawTextStyle(...args),
125
+ 'drawVLine': (args) => this.drawVLine(...args),
126
+ 'getDrawingHeight': () => this.drawingHeight,
127
+ 'getDrawingWidth': () => this.drawingWidth,
128
+ 'getTextHeight': (args) => this.drawTextHeight(...args),
129
+ 'getTextWidth': (args) => this.drawTextWidth(...args),
130
+ 'setDrawingSize': (args) => this.setDrawingSize(...args),
131
+
132
+ // Local storage functions
133
+ 'localStorageGetItem': ([key]) => (
134
+ options !== null && 'localStorage' in options ? options.localStorage.getItem(key) : null
135
+ ),
136
+ 'localStorageSetItem': ([key, value]) => (
137
+ options !== null && 'localStorage' in options ? options.localStorage.setItem(key, value) : null
138
+ ),
139
+ 'localStorageRemoveItem': ([key]) => (
140
+ options !== null && 'localStorage' in options ? options.localStorage.removeItem(key) : null
141
+ ),
142
+ 'localStorageClear': () => (
143
+ options !== null && 'localStorage' in options ? options.localStorage.clear() : null
144
+ ),
145
+
146
+ // Markdown functions
147
+ 'markdownEncode': (args) => encodeMarkdownText(...args),
148
+ 'markdownParse': (lines) => parseMarkdown(MarkdownScriptRuntime.flattenAndSplitLines(lines)),
149
+ 'markdownPrint': (lines) => this.markdownPrint(lines),
150
+ 'markdownTitle': ([markdownModel]) => getMarkdownTitle(markdownModel),
151
+
152
+ // Schema functions
153
+ 'schemaParse': (lines) => MarkdownScriptRuntime.schemaParse(lines),
154
+ 'schemaTypeModel': () => typeModel,
155
+ 'schemaValidate': ([types, typeName, value]) => validateType(types, typeName, value),
156
+ 'schemaValidateTypeModel': ([types]) => validateTypeModel(types),
157
+ 'schemaPrint': ([types, typeName, actionURLs]) => this.schemaPrint(types, typeName, actionURLs),
158
+
159
+ // Session storage functions
160
+ 'sessionStorageGetItem': ([key]) => (
161
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.getItem(key) : null
162
+ ),
163
+ 'sessionStorageSetItem': ([key, value]) => (
164
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.setItem(key, value) : null
165
+ ),
166
+ 'sessionStorageRemoveItem': ([key]) => (
167
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.removeItem(key) : null
168
+ ),
169
+ 'sessionStorageClear': () => (
170
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.clear() : null
171
+ ),
172
+
173
+ // Utility functions
174
+ 'setDocumentTitle': ([title]) => {
175
+ this.documentTitle = title;
176
+ },
177
+ 'setNavigateTimeout': (args) => this.setNavigateTimeout(...args)
178
+ };
179
+
180
+ // The document's title
181
+ this.documentTitle = null;
182
+
183
+ // Element model parts ('drawing', 'markdown')
184
+ this.elementParts = [];
185
+
186
+ // Drawing state
187
+ this.drawingWidth = defaultDrawingWidth;
188
+ this.drawingHeight = defaultDrawingHeight;
189
+ this.drawingPath = [];
190
+
191
+ // Drawing path style
192
+ this.drawingPathStroke = 'black';
193
+ this.drawingPathStrokeWidth = 1;
194
+ this.drawingPathStrokeDashArray = 'none';
195
+ this.drawingPathFill = 'none';
196
+
197
+ // Drawing text style
198
+ this.drawingFontFamily = defaultFontFamily;
199
+ this.drawingFontSizePx = (
200
+ options !== null && 'fontSize' in options && options.fontSize !== null ? options.fontSize * pixelsPerPoint : defaultFontSizePx
201
+ );
202
+ this.drawingFontFill = 'black';
203
+ this.drawingFontBold = false;
204
+ this.drawingFontItalic = false;
205
+ }
206
+
207
+ setDrawing(newDrawing = false) {
208
+ let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
209
+ const isDrawing = part !== null && 'drawing' in part;
210
+ if (!isDrawing || (newDrawing && isDrawing)) {
211
+ part = {
212
+ 'drawing': {
213
+ 'svg': 'svg',
214
+ 'attr': {
215
+ 'width': this.drawingWidth,
216
+ 'height': this.drawingHeight
217
+ },
218
+ 'elem': []
219
+ }
220
+ };
221
+ this.elementParts.push(part);
222
+ }
223
+ return part.drawing;
224
+ }
225
+
226
+ setElements(elements) {
227
+ const part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
228
+ const isDrawing = part !== null && 'drawing' in part;
229
+ if (isDrawing) {
230
+ this.finishDrawingPath();
231
+ }
232
+ this.elementParts.push({'elements': elements});
233
+ }
234
+
235
+ setMarkdown() {
236
+ let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
237
+ const isDrawing = part !== null && 'drawing' in part;
238
+ if (isDrawing) {
239
+ this.finishDrawingPath();
240
+ }
241
+ const isMarkdown = part !== null && 'markdown' in part;
242
+ if (!isMarkdown) {
243
+ part = {'markdown': []};
244
+ this.elementParts.push(part);
245
+ }
246
+ return part.markdown;
247
+ }
248
+
249
+ finishDrawingPath() {
250
+ if (this.drawingPath.length !== 0) {
251
+ this.elementParts[this.elementParts.length - 1].drawing.elem.push({
252
+ 'svg': 'path',
253
+ 'attr': {
254
+ 'fill': this.drawingPathFill,
255
+ 'stroke': this.drawingPathStroke,
256
+ 'stroke-width': this.drawingPathStrokeWidth,
257
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
258
+ 'd': this.drawingPath.join(' ')
259
+ }
260
+ });
261
+ this.drawingPath.length = 0;
262
+ }
263
+ }
264
+
265
+ drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
266
+ this.setDrawing();
267
+ this.drawingPath.push(
268
+ `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
269
+ `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
270
+ );
271
+ }
272
+
273
+ drawCircle(cx, cy, radius) {
274
+ const svg = this.setDrawing();
275
+ this.finishDrawingPath();
276
+ svg.elem.push({
277
+ 'svg': 'circle',
278
+ 'attr': {
279
+ 'fill': this.drawingPathFill,
280
+ 'stroke': this.drawingPathStroke,
281
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
282
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
283
+ 'cx': cx,
284
+ 'cy': cy,
285
+ 'r': radius
286
+ }
287
+ });
288
+ }
289
+
290
+ drawClose() {
291
+ this.setDrawing();
292
+ this.drawingPath.push('Z');
293
+ }
294
+
295
+ drawEllipse(cx, cy, rx, ry) {
296
+ const svg = this.setDrawing();
297
+ this.finishDrawingPath();
298
+ svg.elem.push({
299
+ 'svg': 'ellipse',
300
+ 'attr': {
301
+ 'fill': this.drawingPathFill,
302
+ 'stroke': this.drawingPathStroke,
303
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
304
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
305
+ 'cx': cx,
306
+ 'cy': cy,
307
+ 'rx': rx,
308
+ 'ry': ry
309
+ }
310
+ });
311
+ }
312
+
313
+ drawHLine(px) {
314
+ this.setDrawing();
315
+ this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
316
+ }
317
+
318
+ drawLine(px, py) {
319
+ this.setDrawing();
320
+ this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
321
+ }
322
+
323
+ drawMove(px, py) {
324
+ this.setDrawing();
325
+ this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
326
+ }
327
+
328
+ drawOnClick(callback) {
329
+ const svg = this.setDrawing();
330
+ const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
331
+ clickElement.callback = (element) => {
332
+ element.addEventListener('click', (event) => {
333
+ const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
334
+ callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top]);
335
+ });
336
+ };
337
+ }
338
+
339
+ drawRect(px, py, width, height, rx = null, ry = null) {
340
+ const svg = this.setDrawing();
341
+ this.finishDrawingPath();
342
+ const element = {
343
+ 'svg': 'rect',
344
+ 'attr': {
345
+ 'fill': this.drawingPathFill,
346
+ 'stroke': this.drawingPathStroke,
347
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
348
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
349
+ 'x': px,
350
+ 'y': py,
351
+ 'width': width,
352
+ 'height': height
353
+ }
354
+ };
355
+ if (rx !== null) {
356
+ element.attr.rx = rx;
357
+ }
358
+ if (ry !== null) {
359
+ element.attr.ry = ry;
360
+ }
361
+ svg.elem.push(element);
362
+ }
363
+
364
+ drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
365
+ if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
366
+ strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill) {
367
+ this.finishDrawingPath();
368
+ this.drawingPathStroke = stroke;
369
+ this.drawingPathStrokeWidth = strokeWidth;
370
+ this.drawingPathStrokeDashArray = strokeDashArray;
371
+ this.drawingPathFill = fill;
372
+ }
373
+ }
374
+
375
+ drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
376
+ const svg = this.setDrawing();
377
+ this.finishDrawingPath();
378
+ svg.elem.push({
379
+ 'svg': 'text',
380
+ 'attr': {
381
+ 'fill': this.drawingFontFill,
382
+ 'font-family': this.drawingFontFamily,
383
+ 'font-size': this.drawingFontSizePx.toFixed(svgPrecision),
384
+ 'text-anchor': textAnchor,
385
+ 'dominant-baseline': dominantBaseline,
386
+ 'font-weight': (this.drawingFontBold ? 'bold' : 'normal'),
387
+ 'font-style': (this.drawingFontItalic ? 'italic' : 'normal'),
388
+ 'x': px,
389
+ 'y': py
390
+ },
391
+ 'elem': {'text': text}
392
+ });
393
+ }
394
+
395
+ drawTextHeight(text, width) {
396
+ return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
397
+ }
398
+
399
+ drawTextStyle(fontSizePx = defaultFontSizePx, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
400
+ this.drawingFontSizePx = fontSizePx;
401
+ this.drawingFontFill = textFill;
402
+ this.drawingFontBold = bold;
403
+ this.drawingFontItalic = italic;
404
+ this.drawingFontFamily = fontFamily;
405
+ }
406
+
407
+ drawTextWidth(text) {
408
+ return fontWidthRatio * this.drawiingFontSizePx * text.length;
409
+ }
410
+
411
+ drawVLine(py) {
412
+ this.setDrawing();
413
+ this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
414
+ }
415
+
416
+ markdownPrint(lines) {
417
+ const markdownLines = this.setMarkdown();
418
+ markdownLines.push(...MarkdownScriptRuntime.flattenAndSplitLines(lines));
419
+ }
420
+
421
+ static schemaParse(lines) {
422
+ const parser = new SchemaMarkdownParser();
423
+ parser.parse(MarkdownScriptRuntime.flattenAndSplitLines(lines));
424
+ return parser.types;
425
+ }
426
+
427
+ static flattenAndSplitLines(lines) {
428
+ return lines.flat().reduce(
429
+ (result, line) => {
430
+ result.push(...line.split(rLineSplit));
431
+ return result;
432
+ },
433
+ []
434
+ );
435
+ }
436
+
437
+ schemaPrint(types, typeName, actionURLs = null) {
438
+ const params = (this.options !== null && 'params' in this.options ? encodeQueryString(this.options.params) : null);
439
+ const options = {params};
440
+ if (actionURLs !== null) {
441
+ options.actionURLs = actionURLs;
442
+ }
443
+ this.setElements(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
444
+ }
445
+
446
+ setDrawingSize(width, height) {
447
+ this.finishDrawingPath();
448
+ this.drawingWidth = width;
449
+ this.drawingHeight = height;
450
+ this.setDrawing(true);
451
+ }
452
+
453
+ setNavigateTimeout(url, delay = 0) {
454
+ if (this.options !== null && 'navigateTimeoutFn' in this.options && this.navigateTimeoutFn !== null) {
455
+ this.options.navigateTimeoutFn(url, delay);
456
+ }
457
+ }
458
+ }
459
+
460
+
461
+ // Line-splitting regex
462
+ const rLineSplit = /\r?\n/;
package/lib/util.js ADDED
@@ -0,0 +1,207 @@
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
+ // JSDoc typedefs
11
+
12
+ /**
13
+ * The markdown script code block function options (based on
14
+ * [calc-script's options]{@link https://craigahobbs.github.io/calc-script/module-lib_runtime.html#~ExecuteScriptOptions}).
15
+ *
16
+ * @typedef {Object} MarkdownScriptOptions
17
+ * @property {number} [fontSize] - The chart font size, in points
18
+ * @property {Object} [localStorage] - The localStorage object
19
+ * @property {module:lib/util~NavigateTimeoutFn} [navigateTimeoutFn] - The navigate timeout function
20
+ * @property {Object} [params] - The hash parameters object
21
+ * @property {module:lib/script.MarkdownScriptRuntime} [runtime] - The markdown-script runtime state
22
+ * @property {Object} [sessionStorage] - The sessionStorage object
23
+ * @property {module:lib/util~URLFn} [urlFn] - The URL modifier function
24
+ * @property {Object} [variables] - The map of variable name to chart variable value
25
+ */
26
+
27
+ /**
28
+ * A URL modifier function
29
+ *
30
+ * @callback URLFn
31
+ * @param {string} url - The URL
32
+ * @returns {string} The modified URL
33
+ */
34
+
35
+ /**
36
+ * A navigate timeout function
37
+ *
38
+ * @callback NavigateTimeoutFn
39
+ * @param {string} url - The URL to navigate to
40
+ * @param {number} delay - The navigation delay, in milliseconds
41
+ */
42
+
43
+
44
+ // The categorical color palette
45
+ export const categoricalColors = [
46
+ '#1f77b4',
47
+ '#ff7f0e',
48
+ '#2ca02c',
49
+ '#d62728',
50
+ '#9467bd',
51
+ '#8c564b',
52
+ '#e377c2',
53
+ '#7f7f7f',
54
+ '#bcbd22',
55
+ '#17becf',
56
+ '#aec7e8',
57
+ '#ffbb78',
58
+ '#98df8a',
59
+ '#ff9896',
60
+ '#c5b0d5',
61
+ '#c49c94',
62
+ '#f7b6d2',
63
+ '#c7c7c7',
64
+ '#dbdb8d',
65
+ '#9edae5'
66
+ ];
67
+
68
+
69
+ // Helper function to format labels
70
+ export function formatValue(value, chart) {
71
+ if (value instanceof Date) {
72
+ const isoFormat = value.toISOString();
73
+ if ('datetime' in chart && chart.datetime === 'Year') {
74
+ return isoFormat.slice(0, isoFormat.indexOf('T') - 6);
75
+ } else if ('datetime' in chart && chart.datetime === 'Month') {
76
+ return isoFormat.slice(0, isoFormat.indexOf('T') - 3);
77
+ } else if ('datetime' in chart && chart.datetime === 'Day') {
78
+ return isoFormat.slice(0, isoFormat.indexOf('T'));
79
+ }
80
+ return isoFormat.replace(rDateCleanup, '');
81
+ } else if (typeof value === 'number') {
82
+ const numberFormat = value.toFixed('precision' in chart ? chart.precision : defaultPrecision);
83
+ return numberFormat.replace(rNumberCleanup, '');
84
+ }
85
+ return `${value}`;
86
+ }
87
+
88
+ const defaultPrecision = 2;
89
+ const rNumberCleanup = /\.0*$/;
90
+ const rDateCleanup = /(?:(?:(?:-01)?T00:00)?:00)?\.\d\d\dZ$/;
91
+
92
+
93
+ // Helper function to compare values
94
+ export function compareValues(value1, value2) {
95
+ if (value1 === null) {
96
+ return value2 === null ? 0 : 1;
97
+ } else if (value2 === null) {
98
+ return value1 === null ? 0 : -1;
99
+ } else if (value1 instanceof Date) {
100
+ const time1 = value1.getTime();
101
+ const time2 = value2.getTime();
102
+ return time1 < time2 ? -1 : (time1 === time2 ? 0 : 1);
103
+ }
104
+ return value1 < value2 ? -1 : (value1 === value2 ? 0 : 1);
105
+ }
106
+
107
+
108
+ // Helper function to compute a value's parameter
109
+ export function valueParameter(value, minValue, maxValue) {
110
+ if (minValue === maxValue) {
111
+ return 0;
112
+ }
113
+
114
+ if (minValue instanceof Date) {
115
+ const minDateValue = minValue.valueOf();
116
+ return (value.valueOf() - minDateValue) / (maxValue.valueOf() - minDateValue);
117
+ }
118
+
119
+ return (value - minValue) / (maxValue - minValue);
120
+ }
121
+
122
+
123
+ // Helper function to compute a value from a parameter
124
+ export function parameterValue(param, minValue, maxValue) {
125
+ if (minValue instanceof Date) {
126
+ const minDateValue = minValue.valueOf();
127
+ return new Date(minDateValue + param * (maxValue.valueOf() - minDateValue));
128
+ }
129
+
130
+ return minValue + param * (maxValue - minValue);
131
+ }
132
+
133
+
134
+ // Generic code block helper function
135
+ export function chartCodeBlock(language, lines, options, validationFn, renderFn) {
136
+ // Decode and validate the chart model
137
+ let chartModel;
138
+ try {
139
+ chartModel = validationFn(decodeChartLines(lines));
140
+ } catch ({message}) {
141
+ return {'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': `Error: ${message}`}}};
142
+ }
143
+
144
+ // Render the chart asynchronously
145
+ return {
146
+ 'html': 'p',
147
+ 'elem': !('width' in chartModel) ? null : {
148
+ 'svg': 'svg',
149
+ 'attr': {
150
+ 'width': chartModel.width,
151
+ 'height': chartModel.height
152
+ }
153
+ },
154
+ 'callback': (parent) => {
155
+ renderFn(chartModel, options).
156
+ then((elements) => {
157
+ renderElements(parent, elements);
158
+ }).
159
+ catch(({message}) => {
160
+ renderElements(parent, {'html': 'pre', 'elem': {'text': `Error: ${message}`}});
161
+ });
162
+ }
163
+ };
164
+ }
165
+
166
+
167
+ // Chart code block regular expressions
168
+ const rComment = /^\s*(?:(?:#|\/\/).*)?$/;
169
+ const rKeyValue = /^\s*(?<key>.+?)\s*(:\s*(?<value>.*?)\s*)?$/;
170
+ const rContinuation = /\\\s*$/;
171
+
172
+
173
+ // Helper function to decode chart lines
174
+ function decodeChartLines(lines) {
175
+ // Parse and URI-encode the chart model key/value pairs
176
+ const keyValues = [];
177
+ const lineContinuation = [];
178
+ for (const linePart of lines) {
179
+ // Line continuation?
180
+ const linePartNoContinuation = linePart.replace(rContinuation, '');
181
+ if (lineContinuation.length || linePartNoContinuation !== linePart) {
182
+ lineContinuation.push(linePartNoContinuation);
183
+ }
184
+ if (linePartNoContinuation !== linePart) {
185
+ continue;
186
+ }
187
+ let line;
188
+ if (lineContinuation.length) {
189
+ line = lineContinuation.join('');
190
+ lineContinuation.length = 0;
191
+ } else {
192
+ line = linePart;
193
+ }
194
+
195
+ // Skip comment lines
196
+ if (line.match(rComment) !== null) {
197
+ continue;
198
+ }
199
+
200
+ // Split the key/value
201
+ const {key, value = ''} = line.match(rKeyValue).groups;
202
+ keyValues.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
203
+ }
204
+
205
+ // Decode the chart model
206
+ return decodeQueryString(keyValues.join('&'));
207
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "markdown-up",
4
- "version": "1.6.0",
4
+ "version": "1.7.2",
5
5
  "description": "JavaScript Markdown viewer application",
6
6
  "keywords": [
7
7
  "markdown",
@@ -22,16 +22,16 @@
22
22
  "test": "ava -v test/"
23
23
  },
24
24
  "dependencies": {
25
- "element-app": "~1.1",
26
- "markdown-charts": "~0.9",
25
+ "calc-script": "~0.9",
26
+ "element-model": "~1.1",
27
27
  "markdown-model": "~1.4",
28
28
  "schema-markdown": "~1.1",
29
- "schema-markdown-doc": "~1.3"
29
+ "schema-markdown-doc": "~1.4"
30
30
  },
31
31
  "devDependencies": {
32
- "ava": "~4.0",
32
+ "ava": "~4.2",
33
33
  "c8": "~7.11",
34
- "eslint": "~8.8",
34
+ "eslint": "~8.14",
35
35
  "jsdoc": "~3.6",
36
36
  "jsdom": "~19.0"
37
37
  }