markdown-up 1.5.1 → 1.7.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/script.js ADDED
@@ -0,0 +1,447 @@
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, validateTypeModelTypes} 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 {markdownElements} 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
+ elements.push(markdownElements(parseMarkdown(part.markdown), markdownElementsOptions));
62
+ } else {
63
+ elements.push(part.elements);
64
+ }
65
+ }
66
+ runtime.elementParts.length = 0;
67
+
68
+ // If an error occurred, render the error message
69
+ if (errorMessage !== null) {
70
+ elements.push({'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': errorMessage}}});
71
+ }
72
+
73
+ return elements;
74
+ }
75
+
76
+
77
+ // markdown-script runtime constants
78
+ const defaultDrawingWidth = 300;
79
+ const defaultDrawingHeight = 200;
80
+ const svgPrecision = 8;
81
+ const fontWidthRatio = 0.6;
82
+ const pixelsPerPoint = 4 / 3;
83
+ const defaultFontFamily = 'Arial, Helvetica, sans-serif';
84
+ const defaultFontSizePx = 12 * pixelsPerPoint;
85
+
86
+
87
+ /**
88
+ * @typedef {Object} ElementPart
89
+ * @property {Object} drawing - SVG element model
90
+ * @property {string[]} markdown - Markdown text lines
91
+ */
92
+
93
+
94
+ /**
95
+ * markdown-script runtime state
96
+ *
97
+ * @property {Object} globals - The global variables
98
+ * @property {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
99
+ * @property {module:lib/script~ElementPart[]} elementParts - The element model parts to render
100
+ * @property {?string} documentTitle - The document title
101
+ */
102
+ export class MarkdownScriptRuntime {
103
+ /**
104
+ * @param {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
105
+ */
106
+ constructor(options = null) {
107
+ this.options = options;
108
+
109
+ // The runtime's global variables
110
+ this.globals = {
111
+ // Drawing functions
112
+ 'drawArc': (args) => this.drawArc(...args),
113
+ 'drawCircle': (args) => this.drawCircle(...args),
114
+ 'drawClose': () => this.drawClose(),
115
+ 'drawEllipse': (args) => this.drawEllipse(...args),
116
+ 'drawHLine': (args) => this.drawHLine(...args),
117
+ 'drawLine': (args) => this.drawLine(...args),
118
+ 'drawMove': (args) => this.drawMove(...args),
119
+ 'drawOnClick': (args) => this.drawOnClick(...args),
120
+ 'drawRect': (args) => this.drawRect(...args),
121
+ 'drawStyle': (args) => this.drawStyle(...args),
122
+ 'drawText': (args) => this.drawText(...args),
123
+ 'drawTextStyle': (args) => this.drawTextStyle(...args),
124
+ 'drawVLine': (args) => this.drawVLine(...args),
125
+ 'getDrawingHeight': () => this.drawingHeight,
126
+ 'getDrawingWidth': () => this.drawingWidth,
127
+ 'getTextHeight': (args) => this.drawTextHeight(...args),
128
+ 'getTextWidth': (args) => this.drawTextWidth(...args),
129
+ 'setDrawingSize': (args) => this.setDrawingSize(...args),
130
+
131
+ // Local storage functions
132
+ 'localStorageGetItem': ([key]) => (
133
+ options !== null && 'localStorage' in options ? options.localStorage.getItem(key) : null
134
+ ),
135
+ 'localStorageSetItem': ([key, value]) => (
136
+ options !== null && 'localStorage' in options ? options.localStorage.setItem(key, value) : null
137
+ ),
138
+ 'localStorageRemoveItem': ([key]) => (
139
+ options !== null && 'localStorage' in options ? options.localStorage.removeItem(key) : null
140
+ ),
141
+ 'localStorageClear': () => (
142
+ options !== null && 'localStorage' in options ? options.localStorage.clear() : null
143
+ ),
144
+
145
+ // Markdown functions
146
+ 'markdownEncode': (args) => encodeMarkdownText(...args),
147
+ 'markdownPrint': (args) => this.markdownPrint(args),
148
+ 'markdownTitle': ([text]) => getMarkdownTitle(parseMarkdown(text)),
149
+
150
+ // Schema functions
151
+ 'schemaParse': (args) => {
152
+ const parser = new SchemaMarkdownParser();
153
+ parser.parse(args);
154
+ return parser.types;
155
+ },
156
+ 'schemaParseString': ([text]) => {
157
+ const parser = new SchemaMarkdownParser(text);
158
+ return parser.types;
159
+ },
160
+ 'schemaTypeModel': () => typeModel.types,
161
+ 'schemaValidate': ([types, typeName, value]) => validateType(types, typeName, value),
162
+ 'schemaValidateTypeModel': ([types]) => validateTypeModelTypes(types),
163
+ 'schemaPrint': ([types, typeName]) => this.schemaPrint(types, typeName),
164
+
165
+ // Session storage functions
166
+ 'sessionStorageGetItem': ([key]) => (
167
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.getItem(key) : null
168
+ ),
169
+ 'sessionStorageSetItem': ([key, value]) => (
170
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.setItem(key, value) : null
171
+ ),
172
+ 'sessionStorageRemoveItem': ([key]) => (
173
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.removeItem(key) : null
174
+ ),
175
+ 'sessionStorageClear': () => (
176
+ options !== null && 'sessionStorage' in options ? options.sessionStorage.clear() : null
177
+ ),
178
+
179
+ // Utility functions
180
+ 'setDocumentTitle': ([title]) => {
181
+ this.documentTitle = title;
182
+ },
183
+ 'setNavigateTimeout': (args) => this.setNavigateTimeout(...args)
184
+ };
185
+
186
+ // The document's title
187
+ this.documentTitle = null;
188
+
189
+ // Element model parts ('drawing', 'markdown')
190
+ this.elementParts = [];
191
+
192
+ // Drawing state
193
+ this.drawingWidth = defaultDrawingWidth;
194
+ this.drawingHeight = defaultDrawingHeight;
195
+ this.drawingPath = [];
196
+
197
+ // Drawing path style
198
+ this.drawingPathStroke = 'black';
199
+ this.drawingPathStrokeWidth = 1;
200
+ this.drawingPathStrokeDashArray = 'none';
201
+ this.drawingPathFill = 'none';
202
+
203
+ // Drawing text style
204
+ this.drawingFontFamily = defaultFontFamily;
205
+ this.drawingFontSizePx = (
206
+ options !== null && 'fontSize' in options && options.fontSize !== null ? options.fontSize * pixelsPerPoint : defaultFontSizePx
207
+ );
208
+ this.drawingFontFill = 'black';
209
+ this.drawingFontBold = false;
210
+ this.drawingFontItalic = false;
211
+ }
212
+
213
+ setDrawing(newDrawing = false) {
214
+ let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
215
+ const isDrawing = part !== null && 'drawing' in part;
216
+ if (!isDrawing || (newDrawing && isDrawing)) {
217
+ part = {
218
+ 'drawing': {
219
+ 'svg': 'svg',
220
+ 'attr': {
221
+ 'width': this.drawingWidth,
222
+ 'height': this.drawingHeight
223
+ },
224
+ 'elem': []
225
+ }
226
+ };
227
+ this.elementParts.push(part);
228
+ }
229
+ return part.drawing;
230
+ }
231
+
232
+ setElements(elements) {
233
+ const part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
234
+ const isDrawing = part !== null && 'drawing' in part;
235
+ if (isDrawing) {
236
+ this.finishDrawingPath();
237
+ }
238
+ this.elementParts.push({'elements': elements});
239
+ }
240
+
241
+ setMarkdown() {
242
+ let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
243
+ const isDrawing = part !== null && 'drawing' in part;
244
+ if (isDrawing) {
245
+ this.finishDrawingPath();
246
+ }
247
+ const isMarkdown = part !== null && 'markdown' in part;
248
+ if (!isMarkdown) {
249
+ part = {'markdown': []};
250
+ this.elementParts.push(part);
251
+ }
252
+ return part.markdown;
253
+ }
254
+
255
+ finishDrawingPath() {
256
+ if (this.drawingPath.length !== 0) {
257
+ this.elementParts[this.elementParts.length - 1].drawing.elem.push({
258
+ 'svg': 'path',
259
+ 'attr': {
260
+ 'fill': this.drawingPathFill,
261
+ 'stroke': this.drawingPathStroke,
262
+ 'stroke-width': this.drawingPathStrokeWidth,
263
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
264
+ 'd': this.drawingPath.join(' ')
265
+ }
266
+ });
267
+ this.drawingPath.length = 0;
268
+ }
269
+ }
270
+
271
+ drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
272
+ this.setDrawing();
273
+ this.drawingPath.push(
274
+ `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
275
+ `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
276
+ );
277
+ }
278
+
279
+ drawCircle(cx, cy, radius) {
280
+ const svg = this.setDrawing();
281
+ this.finishDrawingPath();
282
+ svg.elem.push({
283
+ 'svg': 'circle',
284
+ 'attr': {
285
+ 'fill': this.drawingPathFill,
286
+ 'stroke': this.drawingPathStroke,
287
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
288
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
289
+ 'cx': cx,
290
+ 'cy': cy,
291
+ 'r': radius
292
+ }
293
+ });
294
+ }
295
+
296
+ drawClose() {
297
+ this.setDrawing();
298
+ this.drawingPath.push('Z');
299
+ }
300
+
301
+ drawEllipse(cx, cy, rx, ry) {
302
+ const svg = this.setDrawing();
303
+ this.finishDrawingPath();
304
+ svg.elem.push({
305
+ 'svg': 'ellipse',
306
+ 'attr': {
307
+ 'fill': this.drawingPathFill,
308
+ 'stroke': this.drawingPathStroke,
309
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
310
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
311
+ 'cx': cx,
312
+ 'cy': cy,
313
+ 'rx': rx,
314
+ 'ry': ry
315
+ }
316
+ });
317
+ }
318
+
319
+ drawHLine(px) {
320
+ this.setDrawing();
321
+ this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
322
+ }
323
+
324
+ drawLine(px, py) {
325
+ this.setDrawing();
326
+ this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
327
+ }
328
+
329
+ drawMove(px, py) {
330
+ this.setDrawing();
331
+ this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
332
+ }
333
+
334
+ drawOnClick(callback) {
335
+ const svg = this.setDrawing();
336
+ const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
337
+ clickElement.callback = (element) => {
338
+ element.addEventListener('click', (event) => {
339
+ const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
340
+ callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top]);
341
+ });
342
+ };
343
+ }
344
+
345
+ drawRect(px, py, width, height, rx = null, ry = null) {
346
+ const svg = this.setDrawing();
347
+ this.finishDrawingPath();
348
+ const element = {
349
+ 'svg': 'rect',
350
+ 'attr': {
351
+ 'fill': this.drawingPathFill,
352
+ 'stroke': this.drawingPathStroke,
353
+ 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
354
+ 'stroke-dasharray': this.drawingPathStrokeDashArray,
355
+ 'x': px,
356
+ 'y': py,
357
+ 'width': width,
358
+ 'height': height
359
+ }
360
+ };
361
+ if (rx !== null) {
362
+ element.attr.rx = rx;
363
+ }
364
+ if (ry !== null) {
365
+ element.attr.ry = ry;
366
+ }
367
+ svg.elem.push(element);
368
+ }
369
+
370
+ drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
371
+ if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
372
+ strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill) {
373
+ this.finishDrawingPath();
374
+ this.drawingPathStroke = stroke;
375
+ this.drawingPathStrokeWidth = strokeWidth;
376
+ this.drawingPathStrokeDashArray = strokeDashArray;
377
+ this.drawingPathFill = fill;
378
+ }
379
+ }
380
+
381
+ drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
382
+ const svg = this.setDrawing();
383
+ this.finishDrawingPath();
384
+ svg.elem.push({
385
+ 'svg': 'text',
386
+ 'attr': {
387
+ 'fill': this.drawingFontFill,
388
+ 'font-family': this.drawingFontFamily,
389
+ 'font-size': this.drawingFontSizePx.toFixed(svgPrecision),
390
+ 'text-anchor': textAnchor,
391
+ 'dominant-baseline': dominantBaseline,
392
+ 'font-weight': (this.drawingFontBold ? 'bold' : 'normal'),
393
+ 'font-style': (this.drawingFontItalic ? 'italic' : 'normal'),
394
+ 'x': px,
395
+ 'y': py
396
+ },
397
+ 'elem': {'text': text}
398
+ });
399
+ }
400
+
401
+ drawTextHeight(text, width) {
402
+ return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
403
+ }
404
+
405
+ drawTextStyle(fontSizePx = defaultFontSizePx, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
406
+ this.drawingFontSizePx = fontSizePx;
407
+ this.drawingFontFill = textFill;
408
+ this.drawingFontBold = bold;
409
+ this.drawingFontItalic = italic;
410
+ this.drawingFontFamily = fontFamily;
411
+ }
412
+
413
+ drawTextWidth(text) {
414
+ return fontWidthRatio * this.drawiingFontSizePx * text.length;
415
+ }
416
+
417
+ drawVLine(py) {
418
+ this.setDrawing();
419
+ this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
420
+ }
421
+
422
+ markdownPrint(lines) {
423
+ const markdownLines = this.setMarkdown();
424
+ markdownLines.push(...lines);
425
+ }
426
+
427
+ schemaPrint(types, typeName) {
428
+ const params = (
429
+ this.options !== null && 'params' in this.options && this.params !== null ? encodeQueryString(this.options.params) : null
430
+ );
431
+ const elements = schemaMarkdownDoc(types, typeName, {'params': params});
432
+ this.setElements(elements);
433
+ }
434
+
435
+ setDrawingSize(width, height) {
436
+ this.finishDrawingPath();
437
+ this.drawingWidth = width;
438
+ this.drawingHeight = height;
439
+ this.setDrawing(true);
440
+ }
441
+
442
+ setNavigateTimeout(url, delay = 0) {
443
+ if (this.options !== null && 'navigateTimeoutFn' in this.options && this.navigateTimeoutFn !== null) {
444
+ this.options.navigateTimeoutFn(url, delay);
445
+ }
446
+ }
447
+ }
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.5.1",
4
+ "version": "1.7.1",
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
+ "calc-script": "~0.9",
25
26
  "element-app": "~1.1",
26
- "markdown-charts": "~0.9",
27
- "markdown-model": "~1.3",
27
+ "markdown-model": "~1.4",
28
28
  "schema-markdown": "~1.1",
29
- "schema-markdown-doc": "~1.2"
29
+ "schema-markdown-doc": "~1.4"
30
30
  },
31
31
  "devDependencies": {
32
- "ava": "^4.0.0-rc.1",
33
- "c8": "~7.10",
34
- "eslint": "~8.4",
32
+ "ava": "~4.2",
33
+ "c8": "~7.11",
34
+ "eslint": "~8.14",
35
35
  "jsdoc": "~3.6",
36
36
  "jsdom": "~19.0"
37
37
  }