markdown-up 1.7.2 → 1.7.3

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
@@ -4,71 +4,46 @@
4
4
  /** @module lib/script */
5
5
 
6
6
  import {encodeMarkdownText, getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
7
+ import {markdownElements, markdownHeaderId} from 'markdown-model/lib/elements.js';
7
8
  import {validateType, validateTypeModel} from 'schema-markdown/lib/schema.js';
8
9
  import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
9
10
  import {encodeQueryString} from 'schema-markdown/lib/encode.js';
10
11
  import {executeScriptAsync} from 'calc-script/lib/runtimeAsync.js';
11
- import {markdownElementsAsync} from 'markdown-model/lib/elements.js';
12
12
  import {parseScript} from 'calc-script/lib/parser.js';
13
13
  import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
14
14
  import {typeModel} from 'schema-markdown/lib/typeModel.js';
15
+ import {validateElements} from 'element-model/lib/elementModel.js';
15
16
 
16
17
 
17
18
  /**
18
19
  * markdown-script code block function
19
20
  *
20
21
  * @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
22
+ * @param {object} codeBlock - The code block model
23
+ * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
24
24
  * @returns {Object} The generated element model
25
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
-
26
+ export async function markdownScriptCodeBlock(codeBlock, options) {
34
27
  // Add the options variables to the runtime's globals
35
- if (options !== null && 'variables' in options) {
28
+ const {runtime} = options;
29
+ if ('variables' in options) {
36
30
  Object.assign(runtime.globals, options.variables);
37
31
  }
38
32
 
39
33
  // Execute the calculation script
40
34
  let errorMessage = null;
41
35
  try {
42
- await executeScriptAsync(parseScript(lines), runtime.globals, options);
36
+ await executeScriptAsync(parseScript(codeBlock.lines, codeBlock.startLineNumber + 1), runtime.globals, options);
43
37
  } catch ({message}) {
44
38
  errorMessage = message;
45
- } finally {
46
- runtime.finishDrawingPath();
47
- }
48
-
49
- // Create the markdownElements options
50
- const markdownElementsOptions = {'headerIds': true};
51
- if (options !== null && 'urlFn' in options) {
52
- markdownElementsOptions.urlFn = options.urlFn;
53
- }
54
-
55
- // Render the element model parts
56
- const elements = [];
57
- for (const part of runtime.elementParts) {
58
- if ('drawing' in part) {
59
- elements.push({'html': 'p', 'elem': part.drawing});
60
- } else if ('markdown' in part) {
61
- // eslint-disable-next-line no-await-in-loop
62
- elements.push(await markdownElementsAsync(parseMarkdown(part.markdown), markdownElementsOptions));
63
- } else {
64
- elements.push(part.elements);
65
- }
66
39
  }
67
- runtime.elementParts.length = 0;
40
+
41
+ // Reset the runtime
42
+ let elements = runtime.resetElements();
68
43
 
69
44
  // If an error occurred, render the error message
70
45
  if (errorMessage !== null) {
71
- elements.push({'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': errorMessage}}});
46
+ elements = [elements, {'html': 'pre', 'elem': {'text': errorMessage}}];
72
47
  }
73
48
 
74
49
  return elements;
@@ -82,197 +57,509 @@ const svgPrecision = 8;
82
57
  const fontWidthRatio = 0.6;
83
58
  const pixelsPerPoint = 4 / 3;
84
59
  const defaultFontFamily = 'Arial, Helvetica, sans-serif';
85
- const defaultFontSizePx = 12 * pixelsPerPoint;
86
60
 
87
61
 
88
- /**
89
- * @typedef {Object} ElementPart
90
- * @property {Object} drawing - SVG element model
91
- * @property {string[]} markdown - Markdown text lines
92
- */
62
+ // Line-splitting regex
63
+ const rLineSplit = /\r?\n/;
93
64
 
94
65
 
95
66
  /**
96
67
  * markdown-script runtime state
97
68
  *
98
69
  * @property {Object} globals - The global variables
99
- * @property {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
100
- * @property {module:lib/script~ElementPart[]} elementParts - The element model parts to render
101
- * @property {?string} documentTitle - The document title
70
+ * @property {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
71
+ * @property {?Object[]} elements - The runtime-generated element model
72
+ * @property {?string} documentFocus - The the runtime-set elment ID to set input focus
73
+ * @property {?string} documentTitle - The the runtime-set document title
74
+ * @property {boolean} isDocumentReset - If true, the runtime requested a document-reset
75
+ * @property {?string} windowLocation - The the runtime-set document location
76
+ * @property {?function} windowTimeout - The the runtime-set timeout args (callback, delay)
102
77
  */
103
78
  export class MarkdownScriptRuntime {
104
79
  /**
105
- * @param {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
80
+ * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
106
81
  */
107
- constructor(options = null) {
82
+ constructor(options) {
108
83
  this.options = options;
84
+ this.globals = this.createGlobals();
85
+ this.elements = null;
86
+ this.documentFocus = null;
87
+ this.documentTitle = null;
88
+ this.isDocumentReset = false;
89
+ this.windowLocation = null;
90
+ this.windowResize = null;
91
+ this.windowTimeout = null;
92
+
93
+ // Drawing-path and Markdown function state
94
+ this.drawingPath = null;
95
+ this.markdown = null;
96
+
97
+ // Drawing state
98
+ this.drawingWidth = defaultDrawingWidth;
99
+ this.drawingHeight = defaultDrawingHeight;
100
+
101
+ // Drawing path style
102
+ this.drawingPathStroke = 'black';
103
+ this.drawingPathStrokeWidth = 1;
104
+ this.drawingPathStrokeDashArray = 'none';
105
+ this.drawingPathFill = 'none';
106
+
107
+ // Drawing text style
108
+ this.drawingFontFamily = defaultFontFamily;
109
+ this.drawingFontSizePx = options.fontSize * pixelsPerPoint;
110
+ this.drawingFontFill = 'black';
111
+ this.drawingFontBold = false;
112
+ this.drawingFontItalic = false;
113
+ }
114
+
109
115
 
110
- // The runtime's global variables
111
- this.globals = {
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
+ //
112
179
  // Drawing functions
180
+ //
181
+
182
+ // $function: drawArc
183
+ // $group: Drawing
184
+ // $doc: TODO
113
185
  'drawArc': (args) => this.drawArc(...args),
186
+
187
+ // $function: drawCircle
188
+ // $group: Drawing
189
+ // $doc: TODO
114
190
  'drawCircle': (args) => this.drawCircle(...args),
191
+
192
+ // $function: drawClose
193
+ // $group: Drawing
194
+ // $doc: TODO
115
195
  'drawClose': () => this.drawClose(),
196
+
197
+ // $function: drawEllipse
198
+ // $group: Drawing
199
+ // $doc: TODO
116
200
  'drawEllipse': (args) => this.drawEllipse(...args),
201
+
202
+ // $function: drawHLine
203
+ // $group: Drawing
204
+ // $doc: TODO
117
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
118
215
  'drawLine': (args) => this.drawLine(...args),
216
+
217
+ // $function: drawMove
218
+ // $group: Drawing
219
+ // $doc: TODO
119
220
  'drawMove': (args) => this.drawMove(...args),
221
+
222
+ // $function: drawOnClick
223
+ // $group: Drawing
224
+ // $doc: TODO
120
225
  'drawOnClick': (args) => this.drawOnClick(...args),
226
+
227
+ // $function: drawRect
228
+ // $group: Drawing
229
+ // $doc: TODO
121
230
  'drawRect': (args) => this.drawRect(...args),
231
+
232
+ // $function: drawStyle
233
+ // $group: Drawing
234
+ // $doc: TODO
122
235
  'drawStyle': (args) => this.drawStyle(...args),
236
+
237
+ // $function: drawText
238
+ // $group: Drawing
239
+ // $doc: TODO
123
240
  'drawText': (args) => this.drawText(...args),
241
+
242
+ // $function: drawTextStyle
243
+ // $group: Drawing
244
+ // $doc: TODO
124
245
  'drawTextStyle': (args) => this.drawTextStyle(...args),
246
+
247
+ // $function: drawVLine
248
+ // $group: Drawing
249
+ // $doc: TODO
125
250
  'drawVLine': (args) => this.drawVLine(...args),
251
+
252
+ // $function: getDrawingHeight
253
+ // $group: Drawing
254
+ // $doc: TODO
126
255
  'getDrawingHeight': () => this.drawingHeight,
256
+
257
+ // $function: getDrawingWidth
258
+ // $group: Drawing
259
+ // $doc: TODO
127
260
  'getDrawingWidth': () => this.drawingWidth,
261
+
262
+ // $function: getTextHeight
263
+ // $group: Drawing
264
+ // $doc: TODO
128
265
  'getTextHeight': (args) => this.drawTextHeight(...args),
266
+
267
+ // $function: getTextWidth
268
+ // $group: Drawing
269
+ // $doc: TODO
129
270
  'getTextWidth': (args) => this.drawTextWidth(...args),
271
+
272
+ // $function: setDrawingSize
273
+ // $group: Drawing
274
+ // $doc: TODO
130
275
  'setDrawingSize': (args) => this.setDrawingSize(...args),
131
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
+ //
132
289
  // Local storage functions
133
- 'localStorageGetItem': ([key]) => (
134
- options !== null && 'localStorage' in options ? options.localStorage.getItem(key) : null
135
- ),
136
- 'localStorageSetItem': ([key, value]) => (
137
- options !== null && 'localStorage' in options ? options.localStorage.setItem(key, value) : null
138
- ),
139
- 'localStorageRemoveItem': ([key]) => (
140
- options !== null && 'localStorage' in options ? options.localStorage.removeItem(key) : null
141
- ),
142
- 'localStorageClear': () => (
143
- options !== null && 'localStorage' in options ? options.localStorage.clear() : null
144
- ),
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),
145
306
 
307
+ // $function: localStorageClear
308
+ // $group: Local Storage
309
+ // $doc: TODO
310
+ 'localStorageClear': () => this.options.window.localStorage.clear(),
311
+
312
+
313
+ //
146
314
  // Markdown functions
315
+ //
316
+
317
+ // $function: markdownEncode
318
+ // $group: Markdown
319
+ // $doc: TODO
147
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
148
330
  'markdownParse': (lines) => parseMarkdown(MarkdownScriptRuntime.flattenAndSplitLines(lines)),
331
+
332
+ // $function: markdownPrint
333
+ // $group: Markdown
334
+ // $doc: TODO
149
335
  'markdownPrint': (lines) => this.markdownPrint(lines),
336
+
337
+ // $function: markdownTitle
338
+ // $group: Markdown
339
+ // $doc: TODO
150
340
  'markdownTitle': ([markdownModel]) => getMarkdownTitle(markdownModel),
151
341
 
342
+
343
+ //
152
344
  // Schema functions
345
+ //
346
+
347
+ // $function: schemaParse
348
+ // $group: Schema
349
+ // $doc: TODO
153
350
  'schemaParse': (lines) => MarkdownScriptRuntime.schemaParse(lines),
351
+
352
+ // $function: schemaTypeModel
353
+ // $group: Schema
354
+ // $doc: TODO
154
355
  'schemaTypeModel': () => typeModel,
155
- 'schemaValidate': ([types, typeName, value]) => validateType(types, typeName, value),
156
- 'schemaValidateTypeModel': ([types]) => validateTypeModel(types),
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
157
370
  'schemaPrint': ([types, typeName, actionURLs]) => this.schemaPrint(types, typeName, actionURLs),
158
371
 
372
+
373
+ //
159
374
  // Session storage functions
160
- 'sessionStorageGetItem': ([key]) => (
161
- options !== null && 'sessionStorage' in options ? options.sessionStorage.getItem(key) : null
162
- ),
163
- 'sessionStorageSetItem': ([key, value]) => (
164
- options !== null && 'sessionStorage' in options ? options.sessionStorage.setItem(key, value) : null
165
- ),
166
- 'sessionStorageRemoveItem': ([key]) => (
167
- options !== null && 'sessionStorage' in options ? options.sessionStorage.removeItem(key) : null
168
- ),
169
- 'sessionStorageClear': () => (
170
- options !== null && 'sessionStorage' in options ? options.sessionStorage.clear() : null
171
- ),
172
-
173
- // Utility functions
174
- 'setDocumentTitle': ([title]) => {
175
- this.documentTitle = title;
176
- },
177
- 'setNavigateTimeout': (args) => this.setNavigateTimeout(...args)
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()
178
396
  };
397
+ }
179
398
 
180
- // The document's title
181
- this.documentTitle = null;
182
-
183
- // Element model parts ('drawing', 'markdown')
184
- this.elementParts = [];
185
399
 
186
- // Drawing state
187
- this.drawingWidth = defaultDrawingWidth;
188
- this.drawingHeight = defaultDrawingHeight;
189
- this.drawingPath = [];
400
+ reset() {
401
+ this.documentFocus = null;
402
+ this.documentTitle = null;
403
+ this.isDocumentReset = false;
404
+ this.windowLocation = null;
405
+ this.windowTimeout = null;
406
+ return this.resetElements();
407
+ }
190
408
 
191
- // Drawing path style
192
- this.drawingPathStroke = 'black';
193
- this.drawingPathStrokeWidth = 1;
194
- this.drawingPathStrokeDashArray = 'none';
195
- this.drawingPathFill = 'none';
196
409
 
197
- // Drawing text style
198
- this.drawingFontFamily = defaultFontFamily;
199
- this.drawingFontSizePx = (
200
- options !== null && 'fontSize' in options && options.fontSize !== null ? options.fontSize * pixelsPerPoint : defaultFontSizePx
201
- );
202
- this.drawingFontFill = 'black';
203
- this.drawingFontBold = false;
204
- this.drawingFontItalic = false;
410
+ resetElements() {
411
+ let elements = null;
412
+ if (this.elements !== null) {
413
+ this.setElements();
414
+ ({elements} = this);
415
+ }
416
+ this.elements = null;
417
+ return elements;
205
418
  }
206
419
 
207
- setDrawing(newDrawing = false) {
208
- let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
209
- const isDrawing = part !== null && 'drawing' in part;
210
- if (!isDrawing || (newDrawing && isDrawing)) {
211
- part = {
212
- 'drawing': {
213
- 'svg': 'svg',
214
- 'attr': {
215
- 'width': this.drawingWidth,
216
- 'height': this.drawingHeight
217
- },
218
- 'elem': []
219
- }
220
- };
221
- this.elementParts.push(part);
420
+
421
+ setElements() {
422
+ if (this.elements === null) {
423
+ this.elements = [];
222
424
  }
223
- return part.drawing;
425
+ this.finishDrawingPath();
426
+ this.finishMarkdown();
224
427
  }
225
428
 
226
- setElements(elements) {
227
- const part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
228
- const isDrawing = part !== null && 'drawing' in part;
229
- if (isDrawing) {
230
- this.finishDrawingPath();
231
- }
232
- this.elementParts.push({'elements': elements});
429
+
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;
233
434
  }
234
435
 
235
- setMarkdown() {
236
- let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
237
- const isDrawing = part !== null && 'drawing' in part;
238
- if (isDrawing) {
239
- this.finishDrawingPath();
240
- }
241
- const isMarkdown = part !== null && 'markdown' in part;
242
- if (!isMarkdown) {
243
- part = {'markdown': []};
244
- this.elementParts.push(part);
436
+
437
+ setDrawing(newDrawing = false) {
438
+ this.setElements();
439
+ let svg = this.getDrawingSVG();
440
+ if (svg === null || newDrawing) {
441
+ svg = {
442
+ 'svg': 'svg',
443
+ 'attr': {
444
+ 'width': this.drawingWidth,
445
+ 'height': this.drawingHeight
446
+ },
447
+ 'elem': []
448
+ };
449
+ this.elements.push({'html': 'p', 'elem': svg});
245
450
  }
246
- return part.markdown;
451
+ return svg;
247
452
  }
248
453
 
249
- finishDrawingPath() {
250
- if (this.drawingPath.length !== 0) {
251
- this.elementParts[this.elementParts.length - 1].drawing.elem.push({
454
+
455
+ setDrawingPath() {
456
+ if (this.drawingPath === null) {
457
+ const svg = this.setDrawing();
458
+ svg.elem.push({
252
459
  'svg': 'path',
253
460
  'attr': {
254
461
  'fill': this.drawingPathFill,
255
462
  'stroke': this.drawingPathStroke,
256
463
  'stroke-width': this.drawingPathStrokeWidth,
257
464
  'stroke-dasharray': this.drawingPathStrokeDashArray,
258
- 'd': this.drawingPath.join(' ')
465
+ 'd': ''
259
466
  }
260
467
  });
261
- this.drawingPath.length = 0;
468
+ this.drawingPath = [];
469
+ }
470
+ }
471
+
472
+
473
+ finishDrawingPath() {
474
+ if (this.drawingPath !== null) {
475
+ const svg = this.getDrawingSVG();
476
+ const path = svg.elem[svg.elem.length - 1];
477
+ // eslint-disable-next-line id-length
478
+ path.attr.d = this.drawingPath.join(' ');
479
+ this.drawingPath = null;
480
+ }
481
+ }
482
+
483
+
484
+ setMarkdown() {
485
+ if (this.markdown === null) {
486
+ this.setElements();
487
+ this.markdown = [];
262
488
  }
263
489
  }
264
490
 
491
+
492
+ finishMarkdown() {
493
+ if (this.markdown !== null) {
494
+ const markdownOptions = {'headerIds': true, 'urlFn': this.options.urlFn};
495
+ this.elements.push(markdownElements(parseMarkdown(this.markdown), markdownOptions));
496
+ this.markdown = null;
497
+ }
498
+ }
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
+
265
552
  drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
266
- this.setDrawing();
553
+ this.setDrawingPath();
267
554
  this.drawingPath.push(
268
555
  `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
269
556
  `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
270
557
  );
271
558
  }
272
559
 
560
+
273
561
  drawCircle(cx, cy, radius) {
274
562
  const svg = this.setDrawing();
275
- this.finishDrawingPath();
276
563
  svg.elem.push({
277
564
  'svg': 'circle',
278
565
  'attr': {
@@ -287,14 +574,15 @@ export class MarkdownScriptRuntime {
287
574
  });
288
575
  }
289
576
 
577
+
290
578
  drawClose() {
291
- this.setDrawing();
579
+ this.setDrawingPath();
292
580
  this.drawingPath.push('Z');
293
581
  }
294
582
 
583
+
295
584
  drawEllipse(cx, cy, rx, ry) {
296
585
  const svg = this.setDrawing();
297
- this.finishDrawingPath();
298
586
  svg.elem.push({
299
587
  'svg': 'ellipse',
300
588
  'attr': {
@@ -310,35 +598,56 @@ export class MarkdownScriptRuntime {
310
598
  });
311
599
  }
312
600
 
601
+
313
602
  drawHLine(px) {
314
- this.setDrawing();
603
+ this.setDrawingPath();
315
604
  this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
316
605
  }
317
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
+
318
623
  drawLine(px, py) {
319
- this.setDrawing();
624
+ this.setDrawingPath();
320
625
  this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
321
626
  }
322
627
 
628
+
323
629
  drawMove(px, py) {
324
- this.setDrawing();
630
+ this.setDrawingPath();
325
631
  this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
326
632
  }
327
633
 
634
+
328
635
  drawOnClick(callback) {
329
636
  const svg = this.setDrawing();
330
637
  const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
331
638
  clickElement.callback = (element) => {
332
639
  element.addEventListener('click', (event) => {
333
640
  const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
334
- callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top]);
641
+ this.options.statementCount = 0;
642
+ callback([event.clientX - boundingRect.left, event.clientY - boundingRect.top], this.options);
643
+ this.options.runtimeUpdateFn();
335
644
  });
336
645
  };
337
646
  }
338
647
 
648
+
339
649
  drawRect(px, py, width, height, rx = null, ry = null) {
340
650
  const svg = this.setDrawing();
341
- this.finishDrawingPath();
342
651
  const element = {
343
652
  'svg': 'rect',
344
653
  'attr': {
@@ -361,10 +670,12 @@ export class MarkdownScriptRuntime {
361
670
  svg.elem.push(element);
362
671
  }
363
672
 
673
+
364
674
  drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
365
675
  if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
366
- strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill) {
367
- this.finishDrawingPath();
676
+ strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill
677
+ ) {
678
+ this.setDrawing();
368
679
  this.drawingPathStroke = stroke;
369
680
  this.drawingPathStrokeWidth = strokeWidth;
370
681
  this.drawingPathStrokeDashArray = strokeDashArray;
@@ -372,9 +683,9 @@ export class MarkdownScriptRuntime {
372
683
  }
373
684
  }
374
685
 
686
+
375
687
  drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
376
688
  const svg = this.setDrawing();
377
- this.finishDrawingPath();
378
689
  svg.elem.push({
379
690
  'svg': 'text',
380
691
  'attr': {
@@ -392,38 +703,140 @@ export class MarkdownScriptRuntime {
392
703
  });
393
704
  }
394
705
 
706
+
395
707
  drawTextHeight(text, width) {
396
708
  return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
397
709
  }
398
710
 
399
- drawTextStyle(fontSizePx = defaultFontSizePx, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
400
- this.drawingFontSizePx = fontSizePx;
711
+
712
+ drawTextStyle(fontSizePx = null, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
713
+ this.drawingFontSizePx = (fontSizePx !== null ? fontSizePx : this.options.fontSize);
401
714
  this.drawingFontFill = textFill;
402
715
  this.drawingFontBold = bold;
403
716
  this.drawingFontItalic = italic;
404
717
  this.drawingFontFamily = fontFamily;
405
718
  }
406
719
 
720
+
407
721
  drawTextWidth(text) {
408
722
  return fontWidthRatio * this.drawiingFontSizePx * text.length;
409
723
  }
410
724
 
725
+
411
726
  drawVLine(py) {
412
- this.setDrawing();
727
+ this.setDrawingPath();
413
728
  this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
414
729
  }
415
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
+
416
796
  markdownPrint(lines) {
417
- const markdownLines = this.setMarkdown();
418
- markdownLines.push(...MarkdownScriptRuntime.flattenAndSplitLines(lines));
797
+ this.setMarkdown();
798
+ this.markdown.push(...MarkdownScriptRuntime.flattenAndSplitLines(lines));
419
799
  }
420
800
 
801
+
802
+ //
803
+ // Schema functions
804
+ //
805
+
806
+
421
807
  static schemaParse(lines) {
422
808
  const parser = new SchemaMarkdownParser();
423
809
  parser.parse(MarkdownScriptRuntime.flattenAndSplitLines(lines));
424
810
  return parser.types;
425
811
  }
426
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
+
427
840
  static flattenAndSplitLines(lines) {
428
841
  return lines.flat().reduce(
429
842
  (result, line) => {
@@ -434,29 +847,14 @@ export class MarkdownScriptRuntime {
434
847
  );
435
848
  }
436
849
 
850
+
437
851
  schemaPrint(types, typeName, actionURLs = null) {
438
- const params = (this.options !== null && 'params' in this.options ? encodeQueryString(this.options.params) : null);
852
+ const params = encodeQueryString(this.options.params);
439
853
  const options = {params};
440
854
  if (actionURLs !== null) {
441
855
  options.actionURLs = actionURLs;
442
856
  }
443
- this.setElements(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
444
- }
445
-
446
- setDrawingSize(width, height) {
447
- this.finishDrawingPath();
448
- this.drawingWidth = width;
449
- this.drawingHeight = height;
450
- this.setDrawing(true);
451
- }
452
-
453
- setNavigateTimeout(url, delay = 0) {
454
- if (this.options !== null && 'navigateTimeoutFn' in this.options && this.navigateTimeoutFn !== null) {
455
- this.options.navigateTimeoutFn(url, delay);
456
- }
857
+ this.setElements();
858
+ this.elements.push(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
457
859
  }
458
860
  }
459
-
460
-
461
- // Line-splitting regex
462
- const rLineSplit = /\r?\n/;