markdown-up 1.7.4 → 1.8.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.
@@ -0,0 +1,756 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ import {addCalculatedField, aggregateData, filterData, joinData, parseCSV, sortData, validateAggregation, validateData} from './data.js';
5
+ import {dataTableElements, validateDataTable} from './dataTable.js';
6
+ import {escapeMarkdownText, markdownHeaderId} from 'markdown-model/lib/elements.js';
7
+ import {getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
8
+ import {lineChartElements, validateLineChart} from './lineChart.js';
9
+ import {validateType, validateTypeModel} from 'schema-markdown/lib/schema.js';
10
+ import {encodeQueryString} from 'schema-markdown/lib/encode.js';
11
+ import {parseSchemaMarkdown} from 'schema-markdown/lib/parser.js';
12
+ import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
13
+ import {typeModel} from 'schema-markdown/lib/typeModel.js';
14
+ import {validateElements} from 'element-model/lib/elementModel.js';
15
+
16
+
17
+ /* eslint-disable id-length */
18
+
19
+
20
+ // Constants
21
+ const defaultFontFamily = 'Arial, Helvetica, sans-serif';
22
+ const fontWidthRatio = 0.6;
23
+ const pixelsPerPoint = 4 / 3;
24
+ const svgPrecision = 8;
25
+
26
+
27
+ // markdown-script library functions
28
+ export const markdownScriptFunctions = {
29
+ //
30
+ // Data and charting functions
31
+ //
32
+
33
+ // $function: dataAggregate
34
+ // $group: Data
35
+ // $doc: Aggregate a data array
36
+ // $arg data: The data array
37
+ // $arg aggregation: The [aggregation model](model.html#var.vName='Aggregation')
38
+ // $return: The aggregated data array
39
+ 'dataAggregate': ([data, aggregation]) => aggregateData(data, validateAggregation(aggregation)),
40
+
41
+ // $function: dataCalculatedField
42
+ // $group: Data
43
+ // $doc: Add a calculated field to a data array
44
+ // $arg data: The data array
45
+ // $arg fieldName: The calculated field name
46
+ // $arg expr: The calculated field expression
47
+ // $arg variables: Optional (default is null). A variables object the expression evaluation.
48
+ // $return: The updated data array
49
+ 'dataCalculatedField': ([data, fieldName, expr, variables = null]) => addCalculatedField(data, fieldName, expr, variables),
50
+
51
+ // $function: dataFilter
52
+ // $group: Data
53
+ // $doc: Filter a data array
54
+ // $arg data: The data array
55
+ // $arg expr: The filter expression
56
+ // $arg variables: Optional (default is null). A variables object the expression evaluation.
57
+ // $return: The filtered data array
58
+ 'dataFilter': ([data, expr, variables = null]) => filterData(data, expr, variables),
59
+
60
+ // $function: dataJoin
61
+ // $group: Data
62
+ // $doc: Join two data arrays
63
+ // $arg leftData: The left data array
64
+ // $arg rightData: The right data array
65
+ // $arg joinExpr: The [join expression](https://craigahobbs.github.io/calc-script/language/#expressions)
66
+ // $arg rightExpr: Optional (default is null).
67
+ // $arg rightExpr: The right [join expression](https://craigahobbs.github.io/calc-script/language/#expressions)
68
+ // $arg isLeftJoin: Optional (default is false). If true, perform a left join (always include left row).
69
+ // $arg variables: Optional (default is null). A variables object for join expression evaluation.
70
+ // $return: The joined data array
71
+ 'dataJoin': ([leftData, rightData, joinExpr, rightExpr = null, isLeftJoin = false, variables = null]) => (
72
+ joinData(leftData, rightData, joinExpr, rightExpr, isLeftJoin, variables)
73
+ ),
74
+
75
+ // $function: dataLineChart
76
+ // $group: Data
77
+ // $doc: Draw a line chart
78
+ // $arg data: The data array
79
+ // $arg lineChart: The [line chart model](model.html#var.vName='LineChart')
80
+ 'dataLineChart': ([data, lineChart], options) => {
81
+ const {runtime} = options;
82
+
83
+ // Render the line chart
84
+ const elements = lineChartElements(data, validateLineChart(lineChart), options);
85
+ runtime.setElements();
86
+ runtime.addElements({'html': 'p', 'elem': elements});
87
+
88
+ // Set the drawing size (the chart is now the active drawing)
89
+ runtime.drawingWidth = elements.attr.width;
90
+ runtime.drawingHeight = elements.attr.height;
91
+ },
92
+
93
+ // $function: dataParseCSV
94
+ // $group: Data
95
+ // $doc: Parse CSV text to a data array
96
+ // $arg text: The CSV text
97
+ // $return: The data array
98
+ 'dataParseCSV': (text) => {
99
+ const data = parseCSV(text);
100
+ validateData(data, true);
101
+ return data;
102
+ },
103
+
104
+ // $function: dataSort
105
+ // $group: Data
106
+ // $doc: Sort a data array
107
+ // $arg data: The data array
108
+ // $arg sorts: The sort field-name/descending-sort tuples
109
+ // $return: The sorted data array
110
+ 'dataSort': ([data, sorts]) => sortData(data, sorts),
111
+
112
+ // $function: dataTable
113
+ // $group: Data
114
+ // $doc: Draw a data table
115
+ // $arg data: The data array
116
+ // $arg dataTable: Optional (default is null). The [data table model](model.html#var.vName='DataTable').
117
+ 'dataTable': ([data, dataTable = null], options) => {
118
+ const {runtime} = options;
119
+ runtime.setElements();
120
+ const dataTableValidated = (dataTable !== null ? validateDataTable(dataTable, options) : null);
121
+ runtime.addElements(dataTableElements(data, dataTableValidated, options));
122
+ },
123
+
124
+ // $function: dataValidate
125
+ // $group: Data
126
+ // $doc: Validate a data array
127
+ // $arg data: The data array
128
+ // $return: The validated data array
129
+ 'dataValidate': ([data]) => {
130
+ validateData(data);
131
+ return data;
132
+ },
133
+
134
+
135
+ //
136
+ // Document functions
137
+ //
138
+
139
+ // $function: documentReset
140
+ // $group: Document
141
+ // $doc: Reset the document. This is useful within callback functions that re-render the document.
142
+ 'documentReset': (unused, options) => {
143
+ const {runtime} = options;
144
+ runtime.isDocumentReset = true;
145
+ },
146
+
147
+ // $function: documentURL
148
+ // $group: Document
149
+ // $doc: Fix-up relative URLs
150
+ // $arg url: The URL
151
+ // $return: The fixed-up URL
152
+ 'documentURL': ([url], options) => options.urlFn(url),
153
+
154
+ // $function: getDocumentFontSize
155
+ // $group: Document
156
+ // $doc: Get the document font size
157
+ // $return: The document font size, in pixels
158
+ 'getDocumentFontSize': (unused, options) => options.fontSize * pixelsPerPoint,
159
+
160
+ // $function: getDocumentInputValue
161
+ // $group: Document
162
+ // $doc: Get an input element's value
163
+ // $arg id: The input element ID
164
+ // $return: The input element value or null if the element does not exist
165
+ 'getDocumentInputValue': ([id], options) => {
166
+ const element = options.window.document.getElementById(id) ?? null;
167
+ return (element !== null ? (element.value ?? null) : null);
168
+ },
169
+
170
+ // $function: getWindowHeight
171
+ // $group: Document
172
+ // $doc: Get the browser window's height
173
+ // $return: The browser window's height
174
+ 'getWindowHeight': (unused, options) => options.window.innerHeight,
175
+
176
+ // $function: getWindowWidth
177
+ // $group: Document
178
+ // $doc: Get the browser window's width
179
+ // $return: The browser window's width
180
+ 'getWindowWidth': (unused, options) => options.window.innerWidth,
181
+
182
+ // $function: setDocumentFocus
183
+ // $group: Document
184
+ // $doc: Set focus to an element
185
+ // $arg id: The element ID
186
+ 'setDocumentFocus': ([id], options) => {
187
+ const {runtime} = options;
188
+ runtime.documentFocus = id;
189
+ },
190
+
191
+ // $function: setDocumentTitle
192
+ // $group: Document
193
+ // $doc: Set the document title
194
+ // $arg title: The document title string
195
+ 'setDocumentTitle': ([title], options) => {
196
+ const {runtime} = options;
197
+ runtime.documentTitle = title;
198
+ },
199
+
200
+ // $function: setWindowLocation
201
+ // $group: Document
202
+ // $doc: Navigate the browser window to a location URL
203
+ // $arg url: The new location URL
204
+ 'setWindowLocation': ([location], options) => {
205
+ const {runtime} = options;
206
+ runtime.windowLocation = options.urlFn(location);
207
+ },
208
+
209
+ // $function: setWindowResize
210
+ // $group: Document
211
+ // $doc: Set the browser window resize event handler
212
+ // $arg callback: The window resize callback function
213
+ 'setWindowResize': ([callback], options) => {
214
+ const {runtime} = options;
215
+ runtime.windowResize = () => {
216
+ options.statementCount = 0;
217
+ callback([], options);
218
+ options.runtimeUpdateFn();
219
+ };
220
+ },
221
+
222
+ // $function: setWindowTimeout
223
+ // $group: Document
224
+ // $doc: Set the browser window timeout event handler
225
+ // $arg callback: The window timeout callback function
226
+ // $arg delay: The delay, in milliseconds, to ellapse before calling the timeout
227
+ 'setWindowTimeout': ([callback, delay], options) => {
228
+ const {runtime} = options;
229
+ runtime.windowTimeout = [
230
+ () => {
231
+ options.statementCount = 0;
232
+ callback([], options);
233
+ options.runtimeUpdateFn();
234
+ },
235
+ delay
236
+ ];
237
+ },
238
+
239
+
240
+ //
241
+ // Drawing functions
242
+ //
243
+
244
+ // $function: drawArc
245
+ // $group: Drawing
246
+ // $doc: Draw an arc curve from the current point to the end point
247
+ // $arg rx: The arc ellipse's x-radius
248
+ // $arg ry: The arc ellipse's y-radius
249
+ // $arg angle: The rotation (in degrees) of the ellipse relative to the x-axis
250
+ // $arg largeArcFlag: Either large arc (1) or small arc (0)
251
+ // $arg sweepFlag: Either clockwise turning arc (1) or counterclockwise turning arc (0)
252
+ // $arg x: The x-coordinate of the end point
253
+ // $arg y: The y-coordinate of the end point
254
+ 'drawArc': ([rx, ry, angle, largeArcFlag, sweepFlag, x, y], options) => {
255
+ const {runtime} = options;
256
+ runtime.setDrawingPath();
257
+ runtime.drawingPath.push(
258
+ `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${angle.toFixed(svgPrecision)} ` +
259
+ `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${x.toFixed(svgPrecision)} ${y.toFixed(svgPrecision)}`
260
+ );
261
+ },
262
+
263
+ // $function: drawCircle
264
+ // $group: Drawing
265
+ // $doc: Draw a circle
266
+ // $arg cx: The x-coordinate of the center of the circle
267
+ // $arg cy: The y-coordinate of the center of the circle
268
+ // $arg r: The radius of the circle
269
+ 'drawCircle': ([cx, cy, r], options) => {
270
+ const {runtime} = options;
271
+ const svg = runtime.setDrawing();
272
+ svg.elem.push({
273
+ 'svg': 'circle',
274
+ 'attr': {
275
+ 'fill': runtime.drawingPathFill,
276
+ 'stroke': runtime.drawingPathStroke,
277
+ 'stroke-width': runtime.drawingPathStrokeWidth.toFixed(svgPrecision),
278
+ 'stroke-dasharray': runtime.drawingPathStrokeDashArray,
279
+ 'cx': cx,
280
+ 'cy': cy,
281
+ 'r': r
282
+ }
283
+ });
284
+ },
285
+
286
+ // $function: drawClose
287
+ // $group: Drawing
288
+ // $doc: Close the current drawing path
289
+ 'drawClose': (unused, options) => {
290
+ const {runtime} = options;
291
+ runtime.setDrawingPath();
292
+ runtime.drawingPath.push('Z');
293
+ },
294
+
295
+ // $function: drawEllipse
296
+ // $group: Drawing
297
+ // $doc: Draw an ellipse
298
+ // $arg cx: The x-coordinate of the center of the ellipse
299
+ // $arg cy: The y-coordinate of the center of the ellipse
300
+ // $arg rx: The x-radius of the ellipse
301
+ // $arg ry: The y-radius of the ellipse
302
+ 'drawEllipse': ([cx, cy, rx, ry], options) => {
303
+ const {runtime} = options;
304
+ const svg = runtime.setDrawing();
305
+ svg.elem.push({
306
+ 'svg': 'ellipse',
307
+ 'attr': {
308
+ 'fill': runtime.drawingPathFill,
309
+ 'stroke': runtime.drawingPathStroke,
310
+ 'stroke-width': runtime.drawingPathStrokeWidth.toFixed(svgPrecision),
311
+ 'stroke-dasharray': runtime.drawingPathStrokeDashArray,
312
+ 'cx': cx,
313
+ 'cy': cy,
314
+ 'rx': rx,
315
+ 'ry': ry
316
+ }
317
+ });
318
+ },
319
+
320
+ // $function: drawHLine
321
+ // $group: Drawing
322
+ // $doc: Draw a horizontal line from the current point to the end point
323
+ // $arg x: The x-coordinate of the end point
324
+ 'drawHLine': ([x], options) => {
325
+ const {runtime} = options;
326
+ runtime.setDrawingPath();
327
+ runtime.drawingPath.push(`H ${x.toFixed(svgPrecision)}`);
328
+ },
329
+
330
+ // $function: drawImage
331
+ // $group: Drawing
332
+ // $doc: Draw an image
333
+ // $arg x: The x-coordinate of the center of the image
334
+ // $arg y: The y-coordinate of the center of the image
335
+ // $arg width: The width of the image
336
+ // $arg height: The height of the image
337
+ // $arg href: The image resource URL
338
+ 'drawImage': ([x, y, width, height, href], options) => {
339
+ const {runtime} = options;
340
+ const svg = runtime.setDrawing();
341
+ svg.elem.push({
342
+ 'svg': 'image',
343
+ 'attr': {
344
+ 'x': x,
345
+ 'y': y,
346
+ 'width': width,
347
+ 'height': height,
348
+ 'href': options.urlFn(href)
349
+ }
350
+ });
351
+ },
352
+
353
+ // $function: drawLine
354
+ // $group: Drawing
355
+ // $doc: Draw a line from the current point to the end point
356
+ // $arg x: The x-coordinate of the end point
357
+ // $arg y: The y-coordinate of the end point
358
+ 'drawLine': ([x, y], options) => {
359
+ const {runtime} = options;
360
+ runtime.setDrawingPath();
361
+ runtime.drawingPath.push(`L ${x.toFixed(svgPrecision)} ${y.toFixed(svgPrecision)}`);
362
+ },
363
+
364
+ // $function: drawMove
365
+ // $group: Drawing
366
+ // $doc: Move the path's drawing point
367
+ // $arg x: The x-coordinate of the new drawing point
368
+ // $arg y: The y-coordinate of the new drawing point
369
+ 'drawMove': ([x, y], options) => {
370
+ const {runtime} = options;
371
+ runtime.setDrawingPath();
372
+ runtime.drawingPath.push(`M ${x.toFixed(svgPrecision)} ${y.toFixed(svgPrecision)}`);
373
+ },
374
+
375
+ // $function: drawOnClick
376
+ // $group: Drawing
377
+ // $doc: Set the most recent drawing object's on-click event handler
378
+ // $arg callback: The on-click event callback function (x, y)
379
+ 'drawOnClick': ([callback], options) => {
380
+ const {runtime} = options;
381
+ const svg = runtime.setDrawing();
382
+ const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
383
+ clickElement.callback = (element) => {
384
+ element.addEventListener('click', (event) => {
385
+ const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
386
+ options.statementCount = 0;
387
+ callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top], options);
388
+ options.runtimeUpdateFn();
389
+ });
390
+ };
391
+ },
392
+
393
+ // $function: drawRect
394
+ // $group: Drawing
395
+ // $doc: Draw a rectangle
396
+ // $arg x: The x-coordinate of the top-left of the rectangle
397
+ // $arg y: The y-coordinate of the top-left of the rectangle
398
+ // $arg width: The width of the rectangle
399
+ // $arg height: The height of the rectangle
400
+ // $arg rx: Optional (default is null). The horizontal corner radius of the rectangle.
401
+ // $arg ry: Optional (default is null). The vertical corner radius of the rectangle.
402
+ 'drawRect': ([x, y, width, height, rx = null, ry = null], options) => {
403
+ const {runtime} = options;
404
+ const svg = runtime.setDrawing();
405
+ const element = {
406
+ 'svg': 'rect',
407
+ 'attr': {
408
+ 'fill': runtime.drawingPathFill,
409
+ 'stroke': runtime.drawingPathStroke,
410
+ 'stroke-width': runtime.drawingPathStrokeWidth.toFixed(svgPrecision),
411
+ 'stroke-dasharray': runtime.drawingPathStrokeDashArray,
412
+ 'x': x,
413
+ 'y': y,
414
+ 'width': width,
415
+ 'height': height
416
+ }
417
+ };
418
+ if (rx !== null) {
419
+ element.attr.rx = rx;
420
+ }
421
+ if (ry !== null) {
422
+ element.attr.ry = ry;
423
+ }
424
+ svg.elem.push(element);
425
+ },
426
+
427
+ // $function: drawStyle
428
+ // $group: Drawing
429
+ // $doc: Set the current drawing styles
430
+ // $arg stroke: Optional (default is 'black'). The stroke color.
431
+ // $arg strokeWidth: Optional (default is 1). The stroke width.
432
+ // $arg fill: Optional (default is 'none'). The fill color.
433
+ // $arg strokeDashArray: Optional (default is 'none'). The stroke
434
+ // $arg strokeDashArray: [dash array](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray#usage_notes).
435
+ 'drawStyle': ([stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none'], options) => {
436
+ const {runtime} = options;
437
+ if (stroke !== runtime.drawingPathStroke || strokeWidth !== runtime.drawingPathStrokeWidth ||
438
+ strokeDashArray !== runtime.drawingPathStrokeDashArray || fill !== runtime.drawingPathFill
439
+ ) {
440
+ runtime.setDrawing();
441
+ runtime.drawingPathStroke = stroke;
442
+ runtime.drawingPathStrokeWidth = strokeWidth;
443
+ runtime.drawingPathStrokeDashArray = strokeDashArray;
444
+ runtime.drawingPathFill = fill;
445
+ }
446
+ },
447
+
448
+ // $function: drawText
449
+ // $group: Drawing
450
+ // $doc: Draw text
451
+ // $arg text: The text to draw
452
+ // $arg x: The x-coordinate of the text
453
+ // $arg y: The y-coordinate of the text
454
+ // $arg textAnchor: Optional (default is 'middle'). The
455
+ // $arg textAnchor: [text anchor](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor#usage_notes) style.
456
+ // $arg dominantBaseline: Optional (default is 'middle'). The
457
+ // $arg dominantBaseline: [dominant baseline](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline#usage_notes)
458
+ // $arg dominantBaseline: style.
459
+ 'drawText': ([text, x, y, textAnchor = 'middle', dominantBaseline = 'middle'], options) => {
460
+ const {runtime} = options;
461
+ const svg = runtime.setDrawing();
462
+ svg.elem.push({
463
+ 'svg': 'text',
464
+ 'attr': {
465
+ 'fill': runtime.drawingFontFill,
466
+ 'font-family': runtime.drawingFontFamily,
467
+ 'font-size': runtime.drawingFontSizePx.toFixed(svgPrecision),
468
+ 'text-anchor': textAnchor,
469
+ 'dominant-baseline': dominantBaseline,
470
+ 'font-weight': (runtime.drawingFontBold ? 'bold' : 'normal'),
471
+ 'font-style': (runtime.drawingFontItalic ? 'italic' : 'normal'),
472
+ 'x': x,
473
+ 'y': y
474
+ },
475
+ 'elem': {'text': text}
476
+ });
477
+ },
478
+
479
+ // $function: drawTextStyle
480
+ // $group: Drawing
481
+ // $doc: Set the current text drawing styles
482
+ // $arg fontSizePx: Optional (default is null, the default font size). The text font size, in pixels.
483
+ // $arg textFill: Optional (default is 'black'). The text fill color.
484
+ // $arg bold: Optional (default is false). If true, text is bold.
485
+ // $arg italic: Optional (default is false). If true, text is italic.
486
+ // $arg fontFamily: Optional (default is null, the default font family). The text font family.
487
+ 'drawTextStyle': ([fontSizePx = null, textFill = 'black', bold = false, italic = false, fontFamily = null], options) => {
488
+ const {runtime} = options;
489
+ runtime.drawingFontSizePx = (fontSizePx !== null ? fontSizePx : options.fontSize * pixelsPerPoint);
490
+ runtime.drawingFontFill = textFill;
491
+ runtime.drawingFontBold = bold;
492
+ runtime.drawingFontItalic = italic;
493
+ runtime.drawingFontFamily = (fontFamily !== null ? fontFamily : defaultFontFamily);
494
+ },
495
+
496
+ // $function: drawVLine
497
+ // $group: Drawing
498
+ // $doc: Draw a vertical line from the current point to the end point
499
+ // $arg y: The y-coordinate of the end point
500
+ 'drawVLine': ([y], options) => {
501
+ const {runtime} = options;
502
+ runtime.setDrawingPath();
503
+ runtime.drawingPath.push(`V ${y.toFixed(svgPrecision)}`);
504
+ },
505
+
506
+ // $function: getDrawingHeight
507
+ // $group: Drawing
508
+ // $doc: Get the current drawing's height
509
+ // $return: The current drawing's height
510
+ 'getDrawingHeight': (unused, options) => options.runtime.drawingHeight,
511
+
512
+ // $function: getDrawingWidth
513
+ // $group: Drawing
514
+ // $doc: Get the current drawing's width
515
+ // $return: The current drawing's width
516
+ 'getDrawingWidth': (unused, options) => options.runtime.drawingWidth,
517
+
518
+ // $function: getTextHeight
519
+ // $group: Drawing
520
+ // $doc: Compute the text's height to fit the width
521
+ // $arg text: The text
522
+ // $arg width: The width of the text. If 0, the default font size (in pixels) is returned.
523
+ // $return: The text's height
524
+ 'getTextHeight': ([text, width], options) => (width > 0 ? width / (fontWidthRatio * text.length) : options.runtime.drawingFontSizePx),
525
+
526
+ // $function: getTextWidth
527
+ // $group: Drawing
528
+ // $doc: Compute the text's width
529
+ // $arg text: The text
530
+ // $arg fontSizePx: The text font size, in pixels
531
+ // $return: The text's width
532
+ 'getTextWidth': ([text, fontSizePx]) => fontWidthRatio * fontSizePx * text.length,
533
+
534
+ // $function: setDrawingSize
535
+ // $group: Drawing
536
+ // $doc: Set the current drawing's size
537
+ // $arg width: The width of the drawing
538
+ // $arg height: The height of the drawing
539
+ 'setDrawingSize': ([width, height], options) => {
540
+ const {runtime} = options;
541
+ runtime.drawingWidth = width;
542
+ runtime.drawingHeight = height;
543
+ runtime.setDrawing(true);
544
+ },
545
+
546
+
547
+ //
548
+ // Element Model functions
549
+ //
550
+
551
+ // $function: elementModelRender
552
+ // $group: Element Model
553
+ // $doc: Render an [element model](https://github.com/craigahobbs/element-model#readme)
554
+ // $arg element: The [element model](https://github.com/craigahobbs/element-model#readme)
555
+ 'elementModelRender': ([elements], options) => {
556
+ const {runtime} = options;
557
+ runtime.setElements();
558
+ elementModelWrapCallbacks(elements, options);
559
+ runtime.addElements(validateElements(elements));
560
+ },
561
+
562
+
563
+ //
564
+ // Local storage functions
565
+ //
566
+
567
+ // $function: localStorageClear
568
+ // $group: Local Storage
569
+ // $doc: Clear all keys from the browser's local storage
570
+ 'localStorageClear': (unused, options) => options.window.localStorage.clear(),
571
+
572
+ // $function: localStorageGet
573
+ // $group: Local Storage
574
+ // $doc: Get a browser local storage key's value
575
+ // $arg key: The key string
576
+ // $return: The local storage value string or null if the key does not exist
577
+ 'localStorageGet': ([key], options) => options.window.localStorage.getItem(key),
578
+
579
+ // $function: localStorageSet
580
+ // $group: Local Storage
581
+ // $doc: Set a browser local storage key's value
582
+ // $arg key: The key string
583
+ // $arg value: The value string
584
+ 'localStorageSet': ([key, value], options) => options.window.localStorage.setItem(key, value),
585
+
586
+ // $function: localStorageRemove
587
+ // $group: Local Storage
588
+ // $doc: Remove a browser local storage key
589
+ // $arg key: The key string
590
+ 'localStorageRemove': ([key], options) => options.window.localStorage.removeItem(key),
591
+
592
+
593
+ //
594
+ // Markdown functions
595
+ //
596
+
597
+ // $function: markdownEscape
598
+ // $group: Markdown
599
+ // $doc: Escape text for inclusion in Markdown text
600
+ // $arg text: The text
601
+ // $return: The escaped text
602
+ 'markdownEscape': ([text]) => escapeMarkdownText(text),
603
+
604
+ // $function: markdownHeaderId
605
+ // $group: Markdown
606
+ // $doc: Compute the Markdown header element ID for some text
607
+ // $arg text: The text
608
+ // $return: The header element ID
609
+ 'markdownHeaderId': ([text]) => markdownHeaderId(text),
610
+
611
+ // $function: markdownParse
612
+ // $group: Markdown
613
+ // $doc: Parse Markdown text
614
+ // $arg lines: The Markdown text lines (may contain nested arrays of un-split lines)
615
+ // $return: The [Markdown model](https://craigahobbs.github.io/markdown-model/model/#var.vName='Markdown')
616
+ 'markdownParse': (lines) => parseMarkdown(lines.flat()),
617
+
618
+ // $function: markdownPrint
619
+ // $group: Markdown
620
+ // $doc: Render Markdown text
621
+ // $arg lines: The Markdown text lines (may contain nested arrays of un-split lines)
622
+ 'markdownPrint': (lines, options) => {
623
+ const {runtime} = options;
624
+ runtime.setMarkdown();
625
+ runtime.addMarkdown(lines);
626
+ },
627
+
628
+ // $function: markdownTitle
629
+ // $group: Markdown
630
+ // $doc: Compute the title of a [Markdown model](https://craigahobbs.github.io/markdown-model/model/#var.vName='Markdown')
631
+ // $arg markdownModel: The [Markdown model](https://craigahobbs.github.io/markdown-model/model/#var.vName='Markdown')
632
+ // $return: The Markdown title or null if there is no title
633
+ 'markdownTitle': ([markdownModel]) => getMarkdownTitle(markdownModel),
634
+
635
+
636
+ //
637
+ // Schema functions
638
+ //
639
+
640
+ // $function: schemaParse
641
+ // $group: Schema
642
+ // $doc: Parse the [Schema Markdown](https://craigahobbs.github.io/schema-markdown/schema-markdown.html) text
643
+ // $arg lines: The [Schema Markdown](https://craigahobbs.github.io/schema-markdown/schema-markdown.html)
644
+ // $arg lines: text lines (may contain nested arrays of un-split lines)
645
+ // $return: The schema's [type model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
646
+ 'schemaParse': (lines) => parseSchemaMarkdown(lines),
647
+
648
+ // $function: schemaPrint
649
+ // $group: Schema
650
+ // $doc: Render a schema type's documentation
651
+ // $arg types: The [type model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
652
+ // $arg typeName: The type name
653
+ // $arg actionURLs: Optional (default is null). The
654
+ // $arg actionURLs: [action URL overrides](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='ActionURL').
655
+ 'schemaPrint': ([types, typeName, actionURLs = null], options) => {
656
+ const {runtime} = options;
657
+ const params = encodeQueryString(options.params);
658
+ const schemaOptions = {params};
659
+ if (actionURLs !== null) {
660
+ schemaOptions.actionURLs = actionURLs;
661
+ }
662
+ runtime.setElements();
663
+ runtime.addElements(schemaMarkdownDoc(types, typeName, schemaOptions));
664
+ },
665
+
666
+ // $function: schemaTypeModel
667
+ // $group: Schema
668
+ // $doc: Get the [Schema Markdown Type Model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
669
+ // $return: The [Schema Markdown Type Model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
670
+ 'schemaTypeModel': () => typeModel,
671
+
672
+ // $function: schemaValidate
673
+ // $group: Schema
674
+ // $doc: Validate an object to a schema type
675
+ // $arg types: The [type model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
676
+ // $arg typeName: The type name
677
+ // $arg value: The object to validate
678
+ // $return: The validated object or null if validation fails
679
+ 'schemaValidate': ([types, typeName, value]) => validateType(types, typeName, value),
680
+
681
+ // $function: schemaValidateTypeModel
682
+ // $group: Schema
683
+ // $doc: Validate a [Schema Markdown Type Model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
684
+ // $arg types: The [type model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types') to validate
685
+ // $return: The validated [type model](https://craigahobbs.github.io/schema-markdown-doc/doc/#var.vName='Types')
686
+ 'schemaValidateTypeModel': ([types]) => validateTypeModel(types),
687
+
688
+
689
+ //
690
+ // Session storage functions
691
+ //
692
+
693
+ // $function: sessionStorageClear
694
+ // $group: Session Storage
695
+ // $doc: Clear all keys from the browser's session storage
696
+ 'sessionStorageClear': (unused, options) => options.window.sessionStorage.clear(),
697
+
698
+ // $function: sessionStorageGet
699
+ // $group: Session Storage
700
+ // $doc: Get a browser session storage key's value
701
+ // $arg key: The key string
702
+ // $return: The session storage value string or null if the key does not exist
703
+ 'sessionStorageGet': ([key], options) => options.window.sessionStorage.getItem(key),
704
+
705
+ // $function: sessionStorageSet
706
+ // $group: Session Storage
707
+ // $doc: Set a browser session storage key's value
708
+ // $arg key: The key string
709
+ // $arg value: The value string
710
+ 'sessionStorageSet': ([key, value], options) => options.window.sessionStorage.setItem(key, value),
711
+
712
+ // $function: sessionStorageRemove
713
+ // $group: Session Storage
714
+ // $doc: Remove a browser session storage key
715
+ // $arg key: The key string
716
+ 'sessionStorageRemove': ([key], options) => options.window.sessionStorage.removeItem(key)
717
+ };
718
+
719
+
720
+ // Helper function for elementModelRender function
721
+ function elementModelWrapCallbacks(elements, options) {
722
+ if (Array.isArray(elements)) {
723
+ for (const childElements of elements) {
724
+ elementModelWrapCallbacks(childElements, options);
725
+ }
726
+ } else if (typeof elements === 'object') {
727
+ if ('elem' in elements) {
728
+ elementModelWrapCallbacks(elements.elem, options);
729
+ }
730
+
731
+ // Element callback attribute must be map of event => callback
732
+ if ('callback' in elements) {
733
+ const elementEvents = elements.callback;
734
+ if (elementEvents !== null && typeof elementEvents === 'object') {
735
+ // Wrap the event handler function
736
+ elements.callback = (element) => {
737
+ // On element render, add a listener for each event
738
+ for (const [elementEvent, elementEventCallback] of Object.entries(elementEvents)) {
739
+ element.addEventListener(elementEvent, (event) => {
740
+ // Determine the event callback args
741
+ const eventArgs = [];
742
+ if (elementEvent === 'keydown' || elementEvent === 'keypress' || elementEvent === 'keyup') {
743
+ eventArgs.push(event.keyCode);
744
+ }
745
+
746
+ // Call the event handler
747
+ options.statementCount = 0;
748
+ elementEventCallback(eventArgs, options);
749
+ options.runtimeUpdateFn();
750
+ });
751
+ }
752
+ };
753
+ }
754
+ }
755
+ }
756
+ }