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