markdown-up 1.7.0 → 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,69 +4,46 @@
4
4
  /** @module lib/script */
5
5
 
6
6
  import {encodeMarkdownText, getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
7
- import {validateType, validateTypeModelTypes} from 'schema-markdown/lib/schema.js';
7
+ import {markdownElements, markdownHeaderId} from 'markdown-model/lib/elements.js';
8
+ import {validateType, validateTypeModel} from 'schema-markdown/lib/schema.js';
8
9
  import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
9
- import {UserTypeElements} from 'schema-markdown-doc/lib/userTypeElements.js';
10
+ import {encodeQueryString} from 'schema-markdown/lib/encode.js';
10
11
  import {executeScriptAsync} from 'calc-script/lib/runtimeAsync.js';
11
- import {markdownElements} from 'markdown-model/lib/elements.js';
12
12
  import {parseScript} from 'calc-script/lib/parser.js';
13
+ import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
13
14
  import {typeModel} from 'schema-markdown/lib/typeModel.js';
15
+ import {validateElements} from 'element-model/lib/elementModel.js';
14
16
 
15
17
 
16
18
  /**
17
19
  * markdown-script code block function
18
20
  *
19
21
  * @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
22
+ * @param {object} codeBlock - The code block model
23
+ * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
23
24
  * @returns {Object} The generated element model
24
25
  */
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
-
26
+ export async function markdownScriptCodeBlock(codeBlock, options) {
33
27
  // Add the options variables to the runtime's globals
34
- if (options !== null && 'variables' in options) {
28
+ const {runtime} = options;
29
+ if ('variables' in options) {
35
30
  Object.assign(runtime.globals, options.variables);
36
31
  }
37
32
 
38
33
  // Execute the calculation script
39
34
  let errorMessage = null;
40
35
  try {
41
- await executeScriptAsync(parseScript(lines), runtime.globals, options);
36
+ await executeScriptAsync(parseScript(codeBlock.lines, codeBlock.startLineNumber + 1), runtime.globals, options);
42
37
  } catch ({message}) {
43
38
  errorMessage = message;
44
- } finally {
45
- runtime.finishDrawingPath();
46
39
  }
47
40
 
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;
41
+ // Reset the runtime
42
+ let elements = runtime.resetElements();
66
43
 
67
44
  // If an error occurred, render the error message
68
45
  if (errorMessage !== null) {
69
- elements.push({'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': errorMessage}}});
46
+ elements = [elements, {'html': 'pre', 'elem': {'text': errorMessage}}];
70
47
  }
71
48
 
72
49
  return elements;
@@ -80,197 +57,509 @@ const svgPrecision = 8;
80
57
  const fontWidthRatio = 0.6;
81
58
  const pixelsPerPoint = 4 / 3;
82
59
  const defaultFontFamily = 'Arial, Helvetica, sans-serif';
83
- const defaultFontSizePx = 12 * pixelsPerPoint;
84
60
 
85
61
 
86
- /**
87
- * @typedef {Object} ElementPart
88
- * @property {Object} drawing - SVG element model
89
- * @property {string[]} markdown - Markdown text lines
90
- */
62
+ // Line-splitting regex
63
+ const rLineSplit = /\r?\n/;
91
64
 
92
65
 
93
66
  /**
94
67
  * markdown-script runtime state
95
68
  *
96
69
  * @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
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)
99
77
  */
100
78
  export class MarkdownScriptRuntime {
101
79
  /**
102
- * @param {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
80
+ * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
103
81
  */
104
- constructor(options = null) {
82
+ constructor(options) {
105
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;
106
96
 
107
- // The runtime's global variables
108
- this.globals = {
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
+
115
+
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
+ //
109
179
  // Drawing functions
180
+ //
181
+
182
+ // $function: drawArc
183
+ // $group: Drawing
184
+ // $doc: TODO
110
185
  'drawArc': (args) => this.drawArc(...args),
186
+
187
+ // $function: drawCircle
188
+ // $group: Drawing
189
+ // $doc: TODO
111
190
  'drawCircle': (args) => this.drawCircle(...args),
191
+
192
+ // $function: drawClose
193
+ // $group: Drawing
194
+ // $doc: TODO
112
195
  'drawClose': () => this.drawClose(),
196
+
197
+ // $function: drawEllipse
198
+ // $group: Drawing
199
+ // $doc: TODO
113
200
  'drawEllipse': (args) => this.drawEllipse(...args),
201
+
202
+ // $function: drawHLine
203
+ // $group: Drawing
204
+ // $doc: TODO
114
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
115
215
  'drawLine': (args) => this.drawLine(...args),
216
+
217
+ // $function: drawMove
218
+ // $group: Drawing
219
+ // $doc: TODO
116
220
  'drawMove': (args) => this.drawMove(...args),
221
+
222
+ // $function: drawOnClick
223
+ // $group: Drawing
224
+ // $doc: TODO
117
225
  'drawOnClick': (args) => this.drawOnClick(...args),
226
+
227
+ // $function: drawRect
228
+ // $group: Drawing
229
+ // $doc: TODO
118
230
  'drawRect': (args) => this.drawRect(...args),
231
+
232
+ // $function: drawStyle
233
+ // $group: Drawing
234
+ // $doc: TODO
119
235
  'drawStyle': (args) => this.drawStyle(...args),
236
+
237
+ // $function: drawText
238
+ // $group: Drawing
239
+ // $doc: TODO
120
240
  'drawText': (args) => this.drawText(...args),
241
+
242
+ // $function: drawTextStyle
243
+ // $group: Drawing
244
+ // $doc: TODO
121
245
  'drawTextStyle': (args) => this.drawTextStyle(...args),
246
+
247
+ // $function: drawVLine
248
+ // $group: Drawing
249
+ // $doc: TODO
122
250
  'drawVLine': (args) => this.drawVLine(...args),
251
+
252
+ // $function: getDrawingHeight
253
+ // $group: Drawing
254
+ // $doc: TODO
123
255
  'getDrawingHeight': () => this.drawingHeight,
256
+
257
+ // $function: getDrawingWidth
258
+ // $group: Drawing
259
+ // $doc: TODO
124
260
  'getDrawingWidth': () => this.drawingWidth,
261
+
262
+ // $function: getTextHeight
263
+ // $group: Drawing
264
+ // $doc: TODO
125
265
  'getTextHeight': (args) => this.drawTextHeight(...args),
266
+
267
+ // $function: getTextWidth
268
+ // $group: Drawing
269
+ // $doc: TODO
126
270
  'getTextWidth': (args) => this.drawTextWidth(...args),
271
+
272
+ // $function: setDrawingSize
273
+ // $group: Drawing
274
+ // $doc: TODO
127
275
  'setDrawingSize': (args) => this.setDrawingSize(...args),
128
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
+ //
129
289
  // 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
- ),
290
+ //
142
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
+ //
143
314
  // Markdown functions
315
+ //
316
+
317
+ // $function: markdownEncode
318
+ // $group: Markdown
319
+ // $doc: TODO
144
320
  'markdownEncode': (args) => encodeMarkdownText(...args),
145
- 'markdownPrint': (args) => this.markdownPrint(args),
146
- 'markdownTitle': ([text]) => getMarkdownTitle(parseMarkdown(text)),
147
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
+ //
148
344
  // 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),
345
+ //
162
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
+ //
163
374
  // 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)
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()
179
396
  };
397
+ }
180
398
 
181
- // Element model parts ('drawing', 'markdown')
182
- this.elementParts = [];
183
399
 
184
- // Drawing state
185
- this.drawingWidth = defaultDrawingWidth;
186
- this.drawingHeight = defaultDrawingHeight;
187
- 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
+ }
188
408
 
189
- // Drawing path style
190
- this.drawingPathStroke = 'black';
191
- this.drawingPathStrokeWidth = 1;
192
- this.drawingPathStrokeDashArray = 'none';
193
- this.drawingPathFill = 'none';
194
409
 
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;
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;
203
418
  }
204
419
 
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);
420
+
421
+ setElements() {
422
+ if (this.elements === null) {
423
+ this.elements = [];
220
424
  }
221
- return part.drawing;
425
+ this.finishDrawingPath();
426
+ this.finishMarkdown();
222
427
  }
223
428
 
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});
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;
231
434
  }
232
435
 
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);
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});
243
450
  }
244
- return part.markdown;
451
+ return svg;
245
452
  }
246
453
 
247
- finishDrawingPath() {
248
- if (this.drawingPath.length !== 0) {
249
- 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({
250
459
  'svg': 'path',
251
460
  'attr': {
252
461
  'fill': this.drawingPathFill,
253
462
  'stroke': this.drawingPathStroke,
254
463
  'stroke-width': this.drawingPathStrokeWidth,
255
464
  'stroke-dasharray': this.drawingPathStrokeDashArray,
256
- 'd': this.drawingPath.join(' ')
465
+ 'd': ''
257
466
  }
258
467
  });
259
- this.drawingPath.length = 0;
468
+ this.drawingPath = [];
260
469
  }
261
470
  }
262
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 = [];
488
+ }
489
+ }
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
+
263
552
  drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
264
- this.setDrawing();
553
+ this.setDrawingPath();
265
554
  this.drawingPath.push(
266
555
  `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
267
556
  `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
268
557
  );
269
558
  }
270
559
 
560
+
271
561
  drawCircle(cx, cy, radius) {
272
562
  const svg = this.setDrawing();
273
- this.finishDrawingPath();
274
563
  svg.elem.push({
275
564
  'svg': 'circle',
276
565
  'attr': {
@@ -285,14 +574,15 @@ export class MarkdownScriptRuntime {
285
574
  });
286
575
  }
287
576
 
577
+
288
578
  drawClose() {
289
- this.setDrawing();
579
+ this.setDrawingPath();
290
580
  this.drawingPath.push('Z');
291
581
  }
292
582
 
583
+
293
584
  drawEllipse(cx, cy, rx, ry) {
294
585
  const svg = this.setDrawing();
295
- this.finishDrawingPath();
296
586
  svg.elem.push({
297
587
  'svg': 'ellipse',
298
588
  'attr': {
@@ -308,35 +598,56 @@ export class MarkdownScriptRuntime {
308
598
  });
309
599
  }
310
600
 
601
+
311
602
  drawHLine(px) {
312
- this.setDrawing();
603
+ this.setDrawingPath();
313
604
  this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
314
605
  }
315
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
+
316
623
  drawLine(px, py) {
317
- this.setDrawing();
624
+ this.setDrawingPath();
318
625
  this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
319
626
  }
320
627
 
628
+
321
629
  drawMove(px, py) {
322
- this.setDrawing();
630
+ this.setDrawingPath();
323
631
  this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
324
632
  }
325
633
 
634
+
326
635
  drawOnClick(callback) {
327
636
  const svg = this.setDrawing();
328
637
  const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
329
638
  clickElement.callback = (element) => {
330
639
  element.addEventListener('click', (event) => {
331
640
  const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
332
- 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();
333
644
  });
334
645
  };
335
646
  }
336
647
 
648
+
337
649
  drawRect(px, py, width, height, rx = null, ry = null) {
338
650
  const svg = this.setDrawing();
339
- this.finishDrawingPath();
340
651
  const element = {
341
652
  'svg': 'rect',
342
653
  'attr': {
@@ -359,10 +670,12 @@ export class MarkdownScriptRuntime {
359
670
  svg.elem.push(element);
360
671
  }
361
672
 
673
+
362
674
  drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
363
675
  if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
364
- strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill) {
365
- this.finishDrawingPath();
676
+ strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill
677
+ ) {
678
+ this.setDrawing();
366
679
  this.drawingPathStroke = stroke;
367
680
  this.drawingPathStrokeWidth = strokeWidth;
368
681
  this.drawingPathStrokeDashArray = strokeDashArray;
@@ -370,9 +683,9 @@ export class MarkdownScriptRuntime {
370
683
  }
371
684
  }
372
685
 
686
+
373
687
  drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
374
688
  const svg = this.setDrawing();
375
- this.finishDrawingPath();
376
689
  svg.elem.push({
377
690
  'svg': 'text',
378
691
  'attr': {
@@ -390,48 +703,158 @@ export class MarkdownScriptRuntime {
390
703
  });
391
704
  }
392
705
 
706
+
393
707
  drawTextHeight(text, width) {
394
708
  return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
395
709
  }
396
710
 
397
- drawTextStyle(fontSizePx = defaultFontSizePx, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
398
- 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);
399
714
  this.drawingFontFill = textFill;
400
715
  this.drawingFontBold = bold;
401
716
  this.drawingFontItalic = italic;
402
717
  this.drawingFontFamily = fontFamily;
403
718
  }
404
719
 
720
+
405
721
  drawTextWidth(text) {
406
722
  return fontWidthRatio * this.drawiingFontSizePx * text.length;
407
723
  }
408
724
 
725
+
409
726
  drawVLine(py) {
410
- this.setDrawing();
727
+ this.setDrawingPath();
411
728
  this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
412
729
  }
413
730
 
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
731
 
425
732
  setDrawingSize(width, height) {
426
- this.finishDrawingPath();
427
733
  this.drawingWidth = width;
428
734
  this.drawingHeight = height;
429
735
  this.setDrawing(true);
430
736
  }
431
737
 
432
- setNavigateTimeout(url, delay = 0) {
433
- if (this.options !== null && 'navigateTimeoutFn' in this.options && this.navigateTimeoutFn !== null) {
434
- this.options.navigateTimeoutFn(url, delay);
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;
435
856
  }
857
+ this.setElements();
858
+ this.elements.push(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
436
859
  }
437
860
  }