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.
package/lib/script.js CHANGED
@@ -1,45 +1,63 @@
1
1
  // Licensed under the MIT License
2
2
  // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
3
 
4
- /** @module lib/script */
5
-
6
- import {encodeMarkdownText, getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
7
- import {markdownElements, markdownHeaderId} from 'markdown-model/lib/elements.js';
8
- import {validateType, validateTypeModel} from 'schema-markdown/lib/schema.js';
9
- import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
10
- import {encodeQueryString} from 'schema-markdown/lib/encode.js';
11
4
  import {executeScriptAsync} from 'calc-script/lib/runtimeAsync.js';
5
+ import {markdownElements} from 'markdown-model/lib/elements.js';
6
+ import {parseMarkdown} from 'markdown-model/lib/parser.js';
12
7
  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
- import {validateElements} from 'element-model/lib/elementModel.js';
16
8
 
17
9
 
18
10
  /**
19
- * markdown-script code block function
11
+ * The markdown-script code block function options (based on
12
+ * [calc-script's options]{@link https://craigahobbs.github.io/calc-script/module-lib_runtime.html#~ExecuteScriptOptions}).
13
+ *
14
+ * @typedef {Object} MarkdownScriptOptions
15
+ * @property {number} fontSize - The font size, in points
16
+ * @property {Object} params - The [hash parameters object]{@link https://craigahobbs.github.io/markdown-up/#cmd.help=1}
17
+ * @property {Object} runtime - The [markdown-script runtime state]{@link module:lib/script.MarkdownScriptRuntime}
18
+ * @property {Object} [variables] - The map of variable name to variable value
19
+ * @property {Object} window - The web browser window object
20
+ * @property {function} runtimeUpdateFn - The [runtime update callback function]{@link module:lib/util~MarkdownScriptRuntimeUpdateFn}
21
+ *
22
+ * @ignore
23
+ */
24
+
25
+
26
+ /**
27
+ * A runtime update callback function
28
+ *
29
+ * @callback MarkdownScriptRuntimeUpdateFn
30
+ *
31
+ * @ignore
32
+ */
33
+
34
+
35
+ /**
36
+ * The markdown-script code block function
20
37
  *
21
38
  * @async
22
39
  * @param {object} codeBlock - The code block model
23
- * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
40
+ * @param {Object} options - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
24
41
  * @returns {Object} The generated element model
42
+ *
43
+ * @ignore
25
44
  */
26
45
  export async function markdownScriptCodeBlock(codeBlock, options) {
27
46
  // Add the options variables to the runtime's globals
28
- const {runtime} = options;
29
47
  if ('variables' in options) {
30
- Object.assign(runtime.globals, options.variables);
48
+ Object.assign(options.globals, options.variables);
31
49
  }
32
50
 
33
51
  // Execute the calculation script
34
52
  let errorMessage = null;
35
53
  try {
36
- await executeScriptAsync(parseScript(codeBlock.lines, codeBlock.startLineNumber + 1), runtime.globals, options);
54
+ await executeScriptAsync(parseScript(codeBlock.lines, codeBlock.startLineNumber + 1), options);
37
55
  } catch ({message}) {
38
56
  errorMessage = message;
39
57
  }
40
58
 
41
59
  // Reset the runtime
42
- let elements = runtime.resetElements();
60
+ let elements = options.runtime.resetElements();
43
61
 
44
62
  // If an error occurred, render the error message
45
63
  if (errorMessage !== null) {
@@ -50,38 +68,33 @@ export async function markdownScriptCodeBlock(codeBlock, options) {
50
68
  }
51
69
 
52
70
 
53
- // markdown-script runtime constants
71
+ // Constants
54
72
  const defaultDrawingWidth = 300;
55
73
  const defaultDrawingHeight = 200;
56
- const svgPrecision = 8;
57
- const fontWidthRatio = 0.6;
58
- const pixelsPerPoint = 4 / 3;
59
74
  const defaultFontFamily = 'Arial, Helvetica, sans-serif';
60
-
61
-
62
- // Line-splitting regex
63
- const rLineSplit = /\r?\n/;
75
+ const pixelsPerPoint = 4 / 3;
64
76
 
65
77
 
66
78
  /**
67
- * markdown-script runtime state
79
+ * The markdown-script runtime state
68
80
  *
69
- * @property {Object} globals - The global variables
70
- * @property {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
81
+ * @property {Object} options - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
71
82
  * @property {?Object[]} elements - The runtime-generated element model
72
- * @property {?string} documentFocus - The the runtime-set elment ID to set input focus
83
+ * @property {?string} documentFocus - The the runtime-set element ID to set input focus
73
84
  * @property {?string} documentTitle - The the runtime-set document title
74
85
  * @property {boolean} isDocumentReset - If true, the runtime requested a document-reset
75
86
  * @property {?string} windowLocation - The the runtime-set document location
76
- * @property {?function} windowTimeout - The the runtime-set timeout args (callback, delay)
87
+ * @property {?function} windowResize - The the runtime-set resize callback
88
+ * @property {?Array} windowTimeout - The the runtime-set timeout args (callback, delay)
89
+ *
90
+ * @ignore
77
91
  */
78
92
  export class MarkdownScriptRuntime {
79
93
  /**
80
- * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
94
+ * @param {Object} options - The [markdown-script options]{@link module:lib/script~MarkdownScriptOptions}
81
95
  */
82
96
  constructor(options) {
83
97
  this.options = options;
84
- this.globals = this.createGlobals();
85
98
  this.elements = null;
86
99
  this.documentFocus = null;
87
100
  this.documentTitle = null;
@@ -113,300 +126,19 @@ export class MarkdownScriptRuntime {
113
126
  }
114
127
 
115
128
 
116
- createGlobals() {
117
- return {
118
- //
119
- // Document functions
120
- //
121
-
122
- // $function: documentReset
123
- // $group: Document
124
- // $doc: Reset the document. This is useful to call within callback functions that re-render the document.
125
- 'documentReset': () => this.documentReset(),
126
-
127
- // $function: documentURL
128
- // $group: Document
129
- // $doc: TODO
130
- 'documentURL': ([url]) => this.options.urlFn(url),
131
-
132
- // $function: getDocumentInputValue
133
- // $group: Document
134
- // $doc: TODO
135
- 'getDocumentInputValue': ([id]) => this.options.window.document.getElementById(id).value,
136
-
137
- // $function: getDocumentFontSize
138
- // $group: Document
139
- // $doc: TODO
140
- 'getDocumentFontSize': () => this.options.fontSize * pixelsPerPoint,
141
-
142
- // $function: getWindowHeight
143
- // $group: Document
144
- // $doc: TODO
145
- 'getWindowHeight': () => this.options.window.innerHeight,
146
-
147
- // $function: getWindowWidth
148
- // $group: Document
149
- // $doc: TODO
150
- 'getWindowWidth': () => this.options.window.innerWidth,
151
-
152
- // $function: setDocumentFocus
153
- // $group: Document
154
- // $doc: TODO
155
- 'setDocumentFocus': ([id]) => this.setDocumentFocus(id),
156
-
157
- // $function: setDocumentTitle
158
- // $group: Document
159
- // $doc: TODO
160
- 'setDocumentTitle': ([title]) => this.setDocumentTitle(title),
161
-
162
- // $function: setWindowLocation
163
- // $group: Document
164
- // $doc: TODO
165
- 'setWindowLocation': ([location]) => this.setWindowLocation(location),
166
-
167
- // $function: setWindowResize
168
- // $group: Document
169
- // $doc: TODO
170
- 'setWindowResize': ([callback]) => this.setWindowResize(callback),
171
-
172
- // $function: setWindowTimeout
173
- // $group: Document
174
- // $doc: TODO
175
- 'setWindowTimeout': ([callback, delay]) => this.setWindowTimeout(callback, delay),
176
-
177
-
178
- //
179
- // Drawing functions
180
- //
181
-
182
- // $function: drawArc
183
- // $group: Drawing
184
- // $doc: TODO
185
- 'drawArc': (args) => this.drawArc(...args),
186
-
187
- // $function: drawCircle
188
- // $group: Drawing
189
- // $doc: TODO
190
- 'drawCircle': (args) => this.drawCircle(...args),
191
-
192
- // $function: drawClose
193
- // $group: Drawing
194
- // $doc: TODO
195
- 'drawClose': () => this.drawClose(),
196
-
197
- // $function: drawEllipse
198
- // $group: Drawing
199
- // $doc: TODO
200
- 'drawEllipse': (args) => this.drawEllipse(...args),
201
-
202
- // $function: drawHLine
203
- // $group: Drawing
204
- // $doc: TODO
205
- 'drawHLine': (args) => this.drawHLine(...args),
206
-
207
- // $function: drawImage
208
- // $group: Drawing
209
- // $doc: TODO
210
- 'drawImage': (args) => this.drawImage(...args),
211
-
212
- // $function: drawLine
213
- // $group: Drawing
214
- // $doc: TODO
215
- 'drawLine': (args) => this.drawLine(...args),
216
-
217
- // $function: drawMove
218
- // $group: Drawing
219
- // $doc: TODO
220
- 'drawMove': (args) => this.drawMove(...args),
221
-
222
- // $function: drawOnClick
223
- // $group: Drawing
224
- // $doc: TODO
225
- 'drawOnClick': (args) => this.drawOnClick(...args),
226
-
227
- // $function: drawRect
228
- // $group: Drawing
229
- // $doc: TODO
230
- 'drawRect': (args) => this.drawRect(...args),
231
-
232
- // $function: drawStyle
233
- // $group: Drawing
234
- // $doc: TODO
235
- 'drawStyle': (args) => this.drawStyle(...args),
236
-
237
- // $function: drawText
238
- // $group: Drawing
239
- // $doc: TODO
240
- 'drawText': (args) => this.drawText(...args),
241
-
242
- // $function: drawTextStyle
243
- // $group: Drawing
244
- // $doc: TODO
245
- 'drawTextStyle': (args) => this.drawTextStyle(...args),
246
-
247
- // $function: drawVLine
248
- // $group: Drawing
249
- // $doc: TODO
250
- 'drawVLine': (args) => this.drawVLine(...args),
251
-
252
- // $function: getDrawingHeight
253
- // $group: Drawing
254
- // $doc: TODO
255
- 'getDrawingHeight': () => this.drawingHeight,
256
-
257
- // $function: getDrawingWidth
258
- // $group: Drawing
259
- // $doc: TODO
260
- 'getDrawingWidth': () => this.drawingWidth,
261
-
262
- // $function: getTextHeight
263
- // $group: Drawing
264
- // $doc: TODO
265
- 'getTextHeight': (args) => this.drawTextHeight(...args),
266
-
267
- // $function: getTextWidth
268
- // $group: Drawing
269
- // $doc: TODO
270
- 'getTextWidth': (args) => this.drawTextWidth(...args),
271
-
272
- // $function: setDrawingSize
273
- // $group: Drawing
274
- // $doc: TODO
275
- 'setDrawingSize': (args) => this.setDrawingSize(...args),
276
-
277
-
278
- //
279
- // Element Model functions
280
- //
281
-
282
- // $function: elementModelRender
283
- // $group: Element Model
284
- // $doc: TODO
285
- 'elementModelRender': ([elements]) => this.elementModelRender(elements),
286
-
287
-
288
- //
289
- // Local storage functions
290
- //
291
-
292
- // $function: localStorageGet
293
- // $group: Local Storage
294
- // $doc: TODO
295
- 'localStorageGet': ([key]) => this.options.window.localStorage.getItem(key),
296
-
297
- // $function: localStorageSet
298
- // $group: Local Storage
299
- // $doc: TODO
300
- 'localStorageSet': ([key, value]) => this.options.window.localStorage.setItem(key, value),
301
-
302
- // $function: localStorageRemove
303
- // $group: Local Storage
304
- // $doc: TODO
305
- 'localStorageRemove': ([key]) => this.options.window.localStorage.removeItem(key),
306
-
307
- // $function: localStorageClear
308
- // $group: Local Storage
309
- // $doc: TODO
310
- 'localStorageClear': () => this.options.window.localStorage.clear(),
311
-
312
-
313
- //
314
- // Markdown functions
315
- //
316
-
317
- // $function: markdownEncode
318
- // $group: Markdown
319
- // $doc: TODO
320
- 'markdownEncode': (args) => encodeMarkdownText(...args),
321
-
322
- // $function: markdownHeaderId
323
- // $group: Markdown
324
- // $doc: TODO
325
- 'markdownHeaderId': ([text]) => markdownHeaderId(text),
326
-
327
- // $function: markdownParse
328
- // $group: Markdown
329
- // $doc: TODO
330
- 'markdownParse': (lines) => parseMarkdown(MarkdownScriptRuntime.flattenAndSplitLines(lines)),
331
-
332
- // $function: markdownPrint
333
- // $group: Markdown
334
- // $doc: TODO
335
- 'markdownPrint': (lines) => this.markdownPrint(lines),
336
-
337
- // $function: markdownTitle
338
- // $group: Markdown
339
- // $doc: TODO
340
- 'markdownTitle': ([markdownModel]) => getMarkdownTitle(markdownModel),
341
-
342
-
343
- //
344
- // Schema functions
345
- //
346
-
347
- // $function: schemaParse
348
- // $group: Schema
349
- // $doc: TODO
350
- 'schemaParse': (lines) => MarkdownScriptRuntime.schemaParse(lines),
351
-
352
- // $function: schemaTypeModel
353
- // $group: Schema
354
- // $doc: TODO
355
- 'schemaTypeModel': () => typeModel,
356
-
357
- // $function: schemaValidate
358
- // $group: Schema
359
- // $doc: TODO
360
- 'schemaValidate': ([types, typeName, value]) => this.schemaValidate(types, typeName, value),
361
-
362
- // $function: schemaValidateTypeModel
363
- // $group: Schema
364
- // $doc: TODO
365
- 'schemaValidateTypeModel': ([types]) => this.schemaValidateTypeModel(types),
366
-
367
- // $function: schemaPrint
368
- // $group: Schema
369
- // $doc: TODO
370
- 'schemaPrint': ([types, typeName, actionURLs]) => this.schemaPrint(types, typeName, actionURLs),
371
-
372
-
373
- //
374
- // Session storage functions
375
- //
376
-
377
- // $function: sessionStorageGet
378
- // $group: Session Storage
379
- // $doc: TODO
380
- 'sessionStorageGet': ([key]) => this.options.window.sessionStorage.getItem(key),
381
-
382
- // $function: sessionStorageSet
383
- // $group: Session Storage
384
- // $doc: TODO
385
- 'sessionStorageSet': ([key, value]) => this.options.window.sessionStorage.setItem(key, value),
386
-
387
- // $function: sessionStorageRemove
388
- // $group: Session Storage
389
- // $doc: TODO
390
- 'sessionStorageRemove': ([key]) => this.options.window.sessionStorage.removeItem(key),
391
-
392
- // $function: sessionStorageClear
393
- // $group: Session Storage
394
- // $doc: TODO
395
- 'sessionStorageClear': () => this.options.window.sessionStorage.clear()
396
- };
397
- }
398
-
399
-
129
+ // Reset the runtime state
400
130
  reset() {
401
131
  this.documentFocus = null;
402
132
  this.documentTitle = null;
403
133
  this.isDocumentReset = false;
404
134
  this.windowLocation = null;
135
+ this.windowResize = null;
405
136
  this.windowTimeout = null;
406
137
  return this.resetElements();
407
138
  }
408
139
 
409
140
 
141
+ // Reset the runtime elements
410
142
  resetElements() {
411
143
  let elements = null;
412
144
  if (this.elements !== null) {
@@ -418,6 +150,7 @@ export class MarkdownScriptRuntime {
418
150
  }
419
151
 
420
152
 
153
+ // Helper method to prepare runtime for adding elements
421
154
  setElements() {
422
155
  if (this.elements === null) {
423
156
  this.elements = [];
@@ -427,13 +160,13 @@ export class MarkdownScriptRuntime {
427
160
  }
428
161
 
429
162
 
430
- getDrawingSVG() {
431
- const par = (this.elements.length !== 0 ? this.elements[this.elements.length - 1] : null);
432
- const svg = (par !== null && par.html === 'p' && 'elem' in par ? par.elem : null);
433
- return svg !== null && svg.svg === 'svg' ? svg : null;
163
+ // Helper method to add runtime elements
164
+ addElements(elements) {
165
+ this.elements.push(elements);
434
166
  }
435
167
 
436
168
 
169
+ // Helper method to start an SVG drawing
437
170
  setDrawing(newDrawing = false) {
438
171
  this.setElements();
439
172
  let svg = this.getDrawingSVG();
@@ -452,6 +185,15 @@ export class MarkdownScriptRuntime {
452
185
  }
453
186
 
454
187
 
188
+ // Helper method to get the current SVG drawing element
189
+ getDrawingSVG() {
190
+ const par = (this.elements.length !== 0 ? this.elements[this.elements.length - 1] : null);
191
+ const svg = (par !== null && par.html === 'p' && 'elem' in par ? par.elem : null);
192
+ return svg !== null && svg.svg === 'svg' ? svg : null;
193
+ }
194
+
195
+
196
+ // Helper method to start an SVG drawing path
455
197
  setDrawingPath() {
456
198
  if (this.drawingPath === null) {
457
199
  const svg = this.setDrawing();
@@ -470,6 +212,7 @@ export class MarkdownScriptRuntime {
470
212
  }
471
213
 
472
214
 
215
+ // Helper method to finish the current SVG drawing path
473
216
  finishDrawingPath() {
474
217
  if (this.drawingPath !== null) {
475
218
  const svg = this.getDrawingSVG();
@@ -481,6 +224,7 @@ export class MarkdownScriptRuntime {
481
224
  }
482
225
 
483
226
 
227
+ // Helper method to start a Markdown block
484
228
  setMarkdown() {
485
229
  if (this.markdown === null) {
486
230
  this.setElements();
@@ -489,372 +233,18 @@ export class MarkdownScriptRuntime {
489
233
  }
490
234
 
491
235
 
236
+ // Helper method to flatten and add Markdown text lines
237
+ addMarkdown(lines) {
238
+ this.markdown.push(...lines.flat());
239
+ }
240
+
241
+
242
+ // Helper method to finish the current Markdown block and add its elements
492
243
  finishMarkdown() {
493
244
  if (this.markdown !== null) {
494
245
  const markdownOptions = {'headerIds': true, 'urlFn': this.options.urlFn};
495
- this.elements.push(markdownElements(parseMarkdown(this.markdown), markdownOptions));
246
+ this.addElements(markdownElements(parseMarkdown(this.markdown), markdownOptions));
496
247
  this.markdown = null;
497
248
  }
498
249
  }
499
-
500
-
501
- //
502
- // Document functions
503
- //
504
-
505
-
506
- documentReset() {
507
- this.isDocumentReset = true;
508
- }
509
-
510
-
511
- setDocumentFocus(id) {
512
- this.documentFocus = id;
513
- }
514
-
515
-
516
- setDocumentTitle(title) {
517
- this.documentTitle = title;
518
- }
519
-
520
-
521
- setWindowLocation(location) {
522
- this.windowLocation = this.options.urlFn(location);
523
- }
524
-
525
-
526
- setWindowResize(callback) {
527
- this.windowResize = () => {
528
- this.options.statementCount = 0;
529
- callback([], this.options);
530
- this.options.runtimeUpdateFn();
531
- };
532
- }
533
-
534
-
535
- setWindowTimeout(callback, delay) {
536
- this.windowTimeout = [
537
- () => {
538
- this.options.statementCount = 0;
539
- callback([], this.options);
540
- this.options.runtimeUpdateFn();
541
- },
542
- delay
543
- ];
544
- }
545
-
546
-
547
- //
548
- // Drawing functions
549
- //
550
-
551
-
552
- drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
553
- this.setDrawingPath();
554
- this.drawingPath.push(
555
- `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
556
- `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
557
- );
558
- }
559
-
560
-
561
- drawCircle(cx, cy, radius) {
562
- const svg = this.setDrawing();
563
- svg.elem.push({
564
- 'svg': 'circle',
565
- 'attr': {
566
- 'fill': this.drawingPathFill,
567
- 'stroke': this.drawingPathStroke,
568
- 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
569
- 'stroke-dasharray': this.drawingPathStrokeDashArray,
570
- 'cx': cx,
571
- 'cy': cy,
572
- 'r': radius
573
- }
574
- });
575
- }
576
-
577
-
578
- drawClose() {
579
- this.setDrawingPath();
580
- this.drawingPath.push('Z');
581
- }
582
-
583
-
584
- drawEllipse(cx, cy, rx, ry) {
585
- const svg = this.setDrawing();
586
- svg.elem.push({
587
- 'svg': 'ellipse',
588
- 'attr': {
589
- 'fill': this.drawingPathFill,
590
- 'stroke': this.drawingPathStroke,
591
- 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
592
- 'stroke-dasharray': this.drawingPathStrokeDashArray,
593
- 'cx': cx,
594
- 'cy': cy,
595
- 'rx': rx,
596
- 'ry': ry
597
- }
598
- });
599
- }
600
-
601
-
602
- drawHLine(px) {
603
- this.setDrawingPath();
604
- this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
605
- }
606
-
607
-
608
- drawImage(px, py, width, height, href) {
609
- const svg = this.setDrawing();
610
- svg.elem.push({
611
- 'svg': 'image',
612
- 'attr': {
613
- 'x': px,
614
- 'y': py,
615
- 'width': width,
616
- 'height': height,
617
- 'href': this.options.urlFn(href)
618
- }
619
- });
620
- }
621
-
622
-
623
- drawLine(px, py) {
624
- this.setDrawingPath();
625
- this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
626
- }
627
-
628
-
629
- drawMove(px, py) {
630
- this.setDrawingPath();
631
- this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
632
- }
633
-
634
-
635
- drawOnClick(callback) {
636
- const svg = this.setDrawing();
637
- const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
638
- clickElement.callback = (element) => {
639
- element.addEventListener('click', (event) => {
640
- const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
641
- this.options.statementCount = 0;
642
- callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top], this.options);
643
- this.options.runtimeUpdateFn();
644
- });
645
- };
646
- }
647
-
648
-
649
- drawRect(px, py, width, height, rx = null, ry = null) {
650
- const svg = this.setDrawing();
651
- const element = {
652
- 'svg': 'rect',
653
- 'attr': {
654
- 'fill': this.drawingPathFill,
655
- 'stroke': this.drawingPathStroke,
656
- 'stroke-width': this.drawingPathStrokeWidth.toFixed(svgPrecision),
657
- 'stroke-dasharray': this.drawingPathStrokeDashArray,
658
- 'x': px,
659
- 'y': py,
660
- 'width': width,
661
- 'height': height
662
- }
663
- };
664
- if (rx !== null) {
665
- element.attr.rx = rx;
666
- }
667
- if (ry !== null) {
668
- element.attr.ry = ry;
669
- }
670
- svg.elem.push(element);
671
- }
672
-
673
-
674
- drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
675
- if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
676
- strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill
677
- ) {
678
- this.setDrawing();
679
- this.drawingPathStroke = stroke;
680
- this.drawingPathStrokeWidth = strokeWidth;
681
- this.drawingPathStrokeDashArray = strokeDashArray;
682
- this.drawingPathFill = fill;
683
- }
684
- }
685
-
686
-
687
- drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
688
- const svg = this.setDrawing();
689
- svg.elem.push({
690
- 'svg': 'text',
691
- 'attr': {
692
- 'fill': this.drawingFontFill,
693
- 'font-family': this.drawingFontFamily,
694
- 'font-size': this.drawingFontSizePx.toFixed(svgPrecision),
695
- 'text-anchor': textAnchor,
696
- 'dominant-baseline': dominantBaseline,
697
- 'font-weight': (this.drawingFontBold ? 'bold' : 'normal'),
698
- 'font-style': (this.drawingFontItalic ? 'italic' : 'normal'),
699
- 'x': px,
700
- 'y': py
701
- },
702
- 'elem': {'text': text}
703
- });
704
- }
705
-
706
-
707
- drawTextHeight(text, width) {
708
- return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
709
- }
710
-
711
-
712
- drawTextStyle(fontSizePx = null, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
713
- this.drawingFontSizePx = (fontSizePx !== null ? fontSizePx : this.options.fontSize);
714
- this.drawingFontFill = textFill;
715
- this.drawingFontBold = bold;
716
- this.drawingFontItalic = italic;
717
- this.drawingFontFamily = fontFamily;
718
- }
719
-
720
-
721
- drawTextWidth(text) {
722
- return fontWidthRatio * this.drawiingFontSizePx * text.length;
723
- }
724
-
725
-
726
- drawVLine(py) {
727
- this.setDrawingPath();
728
- this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
729
- }
730
-
731
-
732
- setDrawingSize(width, height) {
733
- this.drawingWidth = width;
734
- this.drawingHeight = height;
735
- this.setDrawing(true);
736
- }
737
-
738
-
739
- //
740
- // Element Model functions
741
- //
742
-
743
-
744
- elementModelRender(elements) {
745
- this.setElements();
746
- this.elementModelWrapCallbacks(elements);
747
- this.elements.push(validateElements(elements));
748
- }
749
-
750
-
751
- elementModelWrapCallbacks(elements) {
752
- if (Array.isArray(elements)) {
753
- for (const childElements of elements) {
754
- this.elementModelWrapCallbacks(childElements);
755
- }
756
- } else if (typeof elements === 'object') {
757
- if ('elem' in elements) {
758
- this.elementModelWrapCallbacks(elements.elem);
759
- }
760
-
761
- // Element callback attribute must be map of event => callback
762
- if ('callback' in elements) {
763
- const elementEvents = elements.callback;
764
- if (typeof elementEvents !== 'object') {
765
- elements.callback = null;
766
- } else {
767
- // Wrap the event handler function
768
- elements.callback = (element) => {
769
- // On element render, add a listener for each event
770
- for (const [elementEvent, elementEventCallback] of Object.entries(elementEvents)) {
771
- element.addEventListener(elementEvent, (event) => {
772
- // Determine the event callback args
773
- const eventArgs = [];
774
- if (elementEvent === 'keydown' || elementEvent === 'keypress' || elementEvent === 'keyup') {
775
- eventArgs.push(event.keyCode);
776
- }
777
-
778
- // Call the event handler
779
- this.options.statementCount = 0;
780
- elementEventCallback(eventArgs, this.options);
781
- this.options.runtimeUpdateFn();
782
- });
783
- }
784
- };
785
- }
786
- }
787
- }
788
- }
789
-
790
-
791
- //
792
- // Markdown functions
793
- //
794
-
795
-
796
- markdownPrint(lines) {
797
- this.setMarkdown();
798
- this.markdown.push(...MarkdownScriptRuntime.flattenAndSplitLines(lines));
799
- }
800
-
801
-
802
- //
803
- // Schema functions
804
- //
805
-
806
-
807
- static schemaParse(lines) {
808
- const parser = new SchemaMarkdownParser();
809
- parser.parse(MarkdownScriptRuntime.flattenAndSplitLines(lines));
810
- return parser.types;
811
- }
812
-
813
-
814
- schemaValidate(types, typeName, value) {
815
- try {
816
- return validateType(types, typeName, value);
817
- } catch ({message}) {
818
- if ('logFn' in this.options) {
819
- this.options.logFn(`Error: schemaValidate failed for type "${typeName}" with error: ${message}`);
820
- }
821
- return null;
822
- }
823
- }
824
-
825
-
826
- schemaValidateTypeModel(types) {
827
- try {
828
- return validateTypeModel(types);
829
- } catch ({message}) {
830
- if ('logFn' in this.options) {
831
- this.options.logFn(
832
- `Error: schemaValidateTypeModel failed with error: ${message}`
833
- );
834
- }
835
- return null;
836
- }
837
- }
838
-
839
-
840
- static flattenAndSplitLines(lines) {
841
- return lines.flat().reduce(
842
- (result, line) => {
843
- result.push(...line.split(rLineSplit));
844
- return result;
845
- },
846
- []
847
- );
848
- }
849
-
850
-
851
- schemaPrint(types, typeName, actionURLs = null) {
852
- const params = encodeQueryString(this.options.params);
853
- const options = {params};
854
- if (actionURLs !== null) {
855
- options.actionURLs = actionURLs;
856
- }
857
- this.setElements();
858
- this.elements.push(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
859
- }
860
250
  }