markdown-up 1.7.1 → 1.7.4

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,70 +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
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
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
39
  }
48
40
 
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
- elements.push(markdownElements(parseMarkdown(part.markdown), markdownElementsOptions));
62
- } else {
63
- elements.push(part.elements);
64
- }
65
- }
66
- runtime.elementParts.length = 0;
41
+ // Reset the runtime
42
+ let elements = runtime.resetElements();
67
43
 
68
44
  // If an error occurred, render the error message
69
45
  if (errorMessage !== null) {
70
- elements.push({'html': 'p', 'elem': {'html': 'pre', 'elem': {'text': errorMessage}}});
46
+ elements = [elements, {'html': 'pre', 'elem': {'text': errorMessage}}];
71
47
  }
72
48
 
73
49
  return elements;
@@ -81,204 +57,509 @@ const svgPrecision = 8;
81
57
  const fontWidthRatio = 0.6;
82
58
  const pixelsPerPoint = 4 / 3;
83
59
  const defaultFontFamily = 'Arial, Helvetica, sans-serif';
84
- const defaultFontSizePx = 12 * pixelsPerPoint;
85
60
 
86
61
 
87
- /**
88
- * @typedef {Object} ElementPart
89
- * @property {Object} drawing - SVG element model
90
- * @property {string[]} markdown - Markdown text lines
91
- */
62
+ // Line-splitting regex
63
+ const rLineSplit = /\r?\n/;
92
64
 
93
65
 
94
66
  /**
95
67
  * markdown-script runtime state
96
68
  *
97
69
  * @property {Object} globals - The global variables
98
- * @property {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
99
- * @property {module:lib/script~ElementPart[]} elementParts - The element model parts to render
100
- * @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)
101
77
  */
102
78
  export class MarkdownScriptRuntime {
103
79
  /**
104
- * @param {module:lib/util~MarkdownScriptOptions} [options = null] - Markdown script options
80
+ * @param {Object} options - The [markdown-script options]{@link module:lib/util~MarkdownScriptOptions}
105
81
  */
106
- constructor(options = null) {
82
+ constructor(options) {
107
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
+
108
115
 
109
- // The runtime's global variables
110
- 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
+ //
111
179
  // Drawing functions
180
+ //
181
+
182
+ // $function: drawArc
183
+ // $group: Drawing
184
+ // $doc: TODO
112
185
  'drawArc': (args) => this.drawArc(...args),
186
+
187
+ // $function: drawCircle
188
+ // $group: Drawing
189
+ // $doc: TODO
113
190
  'drawCircle': (args) => this.drawCircle(...args),
191
+
192
+ // $function: drawClose
193
+ // $group: Drawing
194
+ // $doc: TODO
114
195
  'drawClose': () => this.drawClose(),
196
+
197
+ // $function: drawEllipse
198
+ // $group: Drawing
199
+ // $doc: TODO
115
200
  'drawEllipse': (args) => this.drawEllipse(...args),
201
+
202
+ // $function: drawHLine
203
+ // $group: Drawing
204
+ // $doc: TODO
116
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
117
215
  'drawLine': (args) => this.drawLine(...args),
216
+
217
+ // $function: drawMove
218
+ // $group: Drawing
219
+ // $doc: TODO
118
220
  'drawMove': (args) => this.drawMove(...args),
221
+
222
+ // $function: drawOnClick
223
+ // $group: Drawing
224
+ // $doc: TODO
119
225
  'drawOnClick': (args) => this.drawOnClick(...args),
226
+
227
+ // $function: drawRect
228
+ // $group: Drawing
229
+ // $doc: TODO
120
230
  'drawRect': (args) => this.drawRect(...args),
231
+
232
+ // $function: drawStyle
233
+ // $group: Drawing
234
+ // $doc: TODO
121
235
  'drawStyle': (args) => this.drawStyle(...args),
236
+
237
+ // $function: drawText
238
+ // $group: Drawing
239
+ // $doc: TODO
122
240
  'drawText': (args) => this.drawText(...args),
241
+
242
+ // $function: drawTextStyle
243
+ // $group: Drawing
244
+ // $doc: TODO
123
245
  'drawTextStyle': (args) => this.drawTextStyle(...args),
246
+
247
+ // $function: drawVLine
248
+ // $group: Drawing
249
+ // $doc: TODO
124
250
  'drawVLine': (args) => this.drawVLine(...args),
251
+
252
+ // $function: getDrawingHeight
253
+ // $group: Drawing
254
+ // $doc: TODO
125
255
  'getDrawingHeight': () => this.drawingHeight,
256
+
257
+ // $function: getDrawingWidth
258
+ // $group: Drawing
259
+ // $doc: TODO
126
260
  'getDrawingWidth': () => this.drawingWidth,
261
+
262
+ // $function: getTextHeight
263
+ // $group: Drawing
264
+ // $doc: TODO
127
265
  'getTextHeight': (args) => this.drawTextHeight(...args),
266
+
267
+ // $function: getTextWidth
268
+ // $group: Drawing
269
+ // $doc: TODO
128
270
  'getTextWidth': (args) => this.drawTextWidth(...args),
271
+
272
+ // $function: setDrawingSize
273
+ // $group: Drawing
274
+ // $doc: TODO
129
275
  'setDrawingSize': (args) => this.setDrawingSize(...args),
130
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
+ //
131
289
  // Local storage functions
132
- 'localStorageGetItem': ([key]) => (
133
- options !== null && 'localStorage' in options ? options.localStorage.getItem(key) : null
134
- ),
135
- 'localStorageSetItem': ([key, value]) => (
136
- options !== null && 'localStorage' in options ? options.localStorage.setItem(key, value) : null
137
- ),
138
- 'localStorageRemoveItem': ([key]) => (
139
- options !== null && 'localStorage' in options ? options.localStorage.removeItem(key) : null
140
- ),
141
- 'localStorageClear': () => (
142
- options !== null && 'localStorage' in options ? options.localStorage.clear() : null
143
- ),
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
+
144
312
 
313
+ //
145
314
  // Markdown functions
315
+ //
316
+
317
+ // $function: markdownEncode
318
+ // $group: Markdown
319
+ // $doc: TODO
146
320
  'markdownEncode': (args) => encodeMarkdownText(...args),
147
- 'markdownPrint': (args) => this.markdownPrint(args),
148
- 'markdownTitle': ([text]) => getMarkdownTitle(parseMarkdown(text)),
149
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
+ //
150
344
  // Schema functions
151
- 'schemaParse': (args) => {
152
- const parser = new SchemaMarkdownParser();
153
- parser.parse(args);
154
- return parser.types;
155
- },
156
- 'schemaParseString': ([text]) => {
157
- const parser = new SchemaMarkdownParser(text);
158
- return parser.types;
159
- },
160
- 'schemaTypeModel': () => typeModel.types,
161
- 'schemaValidate': ([types, typeName, value]) => validateType(types, typeName, value),
162
- 'schemaValidateTypeModel': ([types]) => validateTypeModelTypes(types),
163
- 'schemaPrint': ([types, typeName]) => this.schemaPrint(types, typeName),
345
+ //
164
346
 
165
- // Session storage functions
166
- 'sessionStorageGetItem': ([key]) => (
167
- options !== null && 'sessionStorage' in options ? options.sessionStorage.getItem(key) : null
168
- ),
169
- 'sessionStorageSetItem': ([key, value]) => (
170
- options !== null && 'sessionStorage' in options ? options.sessionStorage.setItem(key, value) : null
171
- ),
172
- 'sessionStorageRemoveItem': ([key]) => (
173
- options !== null && 'sessionStorage' in options ? options.sessionStorage.removeItem(key) : null
174
- ),
175
- 'sessionStorageClear': () => (
176
- options !== null && 'sessionStorage' in options ? options.sessionStorage.clear() : null
177
- ),
178
-
179
- // Utility functions
180
- 'setDocumentTitle': ([title]) => {
181
- this.documentTitle = title;
182
- },
183
- 'setNavigateTimeout': (args) => this.setNavigateTimeout(...args)
184
- };
347
+ // $function: schemaParse
348
+ // $group: Schema
349
+ // $doc: TODO
350
+ 'schemaParse': (lines) => MarkdownScriptRuntime.schemaParse(lines),
185
351
 
186
- // The document's title
187
- this.documentTitle = null;
352
+ // $function: schemaTypeModel
353
+ // $group: Schema
354
+ // $doc: TODO
355
+ 'schemaTypeModel': () => typeModel,
188
356
 
189
- // Element model parts ('drawing', 'markdown')
190
- this.elementParts = [];
357
+ // $function: schemaValidate
358
+ // $group: Schema
359
+ // $doc: TODO
360
+ 'schemaValidate': ([types, typeName, value]) => this.schemaValidate(types, typeName, value),
191
361
 
192
- // Drawing state
193
- this.drawingWidth = defaultDrawingWidth;
194
- this.drawingHeight = defaultDrawingHeight;
195
- this.drawingPath = [];
362
+ // $function: schemaValidateTypeModel
363
+ // $group: Schema
364
+ // $doc: TODO
365
+ 'schemaValidateTypeModel': ([types]) => this.schemaValidateTypeModel(types),
196
366
 
197
- // Drawing path style
198
- this.drawingPathStroke = 'black';
199
- this.drawingPathStrokeWidth = 1;
200
- this.drawingPathStrokeDashArray = 'none';
201
- this.drawingPathFill = 'none';
367
+ // $function: schemaPrint
368
+ // $group: Schema
369
+ // $doc: TODO
370
+ 'schemaPrint': ([types, typeName, actionURLs]) => this.schemaPrint(types, typeName, actionURLs),
202
371
 
203
- // Drawing text style
204
- this.drawingFontFamily = defaultFontFamily;
205
- this.drawingFontSizePx = (
206
- options !== null && 'fontSize' in options && options.fontSize !== null ? options.fontSize * pixelsPerPoint : defaultFontSizePx
207
- );
208
- this.drawingFontFill = 'black';
209
- this.drawingFontBold = false;
210
- this.drawingFontItalic = false;
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
+ };
211
397
  }
212
398
 
213
- setDrawing(newDrawing = false) {
214
- let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
215
- const isDrawing = part !== null && 'drawing' in part;
216
- if (!isDrawing || (newDrawing && isDrawing)) {
217
- part = {
218
- 'drawing': {
219
- 'svg': 'svg',
220
- 'attr': {
221
- 'width': this.drawingWidth,
222
- 'height': this.drawingHeight
223
- },
224
- 'elem': []
225
- }
226
- };
227
- this.elementParts.push(part);
228
- }
229
- return part.drawing;
399
+
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();
230
407
  }
231
408
 
232
- setElements(elements) {
233
- const part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
234
- const isDrawing = part !== null && 'drawing' in part;
235
- if (isDrawing) {
236
- this.finishDrawingPath();
409
+
410
+ resetElements() {
411
+ let elements = null;
412
+ if (this.elements !== null) {
413
+ this.setElements();
414
+ ({elements} = this);
237
415
  }
238
- this.elementParts.push({'elements': elements});
416
+ this.elements = null;
417
+ return elements;
239
418
  }
240
419
 
241
- setMarkdown() {
242
- let part = this.elementParts.length !== 0 ? this.elementParts[this.elementParts.length - 1] : null;
243
- const isDrawing = part !== null && 'drawing' in part;
244
- if (isDrawing) {
245
- this.finishDrawingPath();
420
+
421
+ setElements() {
422
+ if (this.elements === null) {
423
+ this.elements = [];
246
424
  }
247
- const isMarkdown = part !== null && 'markdown' in part;
248
- if (!isMarkdown) {
249
- part = {'markdown': []};
250
- this.elementParts.push(part);
425
+ this.finishDrawingPath();
426
+ this.finishMarkdown();
427
+ }
428
+
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;
434
+ }
435
+
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});
251
450
  }
252
- return part.markdown;
451
+ return svg;
253
452
  }
254
453
 
255
- finishDrawingPath() {
256
- if (this.drawingPath.length !== 0) {
257
- 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({
258
459
  'svg': 'path',
259
460
  'attr': {
260
461
  'fill': this.drawingPathFill,
261
462
  'stroke': this.drawingPathStroke,
262
463
  'stroke-width': this.drawingPathStrokeWidth,
263
464
  'stroke-dasharray': this.drawingPathStrokeDashArray,
264
- 'd': this.drawingPath.join(' ')
465
+ 'd': ''
265
466
  }
266
467
  });
267
- 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;
268
480
  }
269
481
  }
270
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
+
271
552
  drawArc(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, px, py) {
272
- this.setDrawing();
553
+ this.setDrawingPath();
273
554
  this.drawingPath.push(
274
555
  `A ${rx.toFixed(svgPrecision)} ${ry.toFixed(svgPrecision)} ${xAxisRotation.toFixed(svgPrecision)} ` +
275
556
  `${largeArcFlag ? 1 : 0} ${sweepFlag ? 1 : 0} ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`
276
557
  );
277
558
  }
278
559
 
560
+
279
561
  drawCircle(cx, cy, radius) {
280
562
  const svg = this.setDrawing();
281
- this.finishDrawingPath();
282
563
  svg.elem.push({
283
564
  'svg': 'circle',
284
565
  'attr': {
@@ -293,14 +574,15 @@ export class MarkdownScriptRuntime {
293
574
  });
294
575
  }
295
576
 
577
+
296
578
  drawClose() {
297
- this.setDrawing();
579
+ this.setDrawingPath();
298
580
  this.drawingPath.push('Z');
299
581
  }
300
582
 
583
+
301
584
  drawEllipse(cx, cy, rx, ry) {
302
585
  const svg = this.setDrawing();
303
- this.finishDrawingPath();
304
586
  svg.elem.push({
305
587
  'svg': 'ellipse',
306
588
  'attr': {
@@ -316,35 +598,56 @@ export class MarkdownScriptRuntime {
316
598
  });
317
599
  }
318
600
 
601
+
319
602
  drawHLine(px) {
320
- this.setDrawing();
603
+ this.setDrawingPath();
321
604
  this.drawingPath.push(`H ${px.toFixed(svgPrecision)}`);
322
605
  }
323
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
+
324
623
  drawLine(px, py) {
325
- this.setDrawing();
624
+ this.setDrawingPath();
326
625
  this.drawingPath.push(`L ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
327
626
  }
328
627
 
628
+
329
629
  drawMove(px, py) {
330
- this.setDrawing();
630
+ this.setDrawingPath();
331
631
  this.drawingPath.push(`M ${px.toFixed(svgPrecision)} ${py.toFixed(svgPrecision)}`);
332
632
  }
333
633
 
634
+
334
635
  drawOnClick(callback) {
335
636
  const svg = this.setDrawing();
336
637
  const clickElement = svg.elem.length === 0 ? svg : svg.elem[svg.elem.length - 1];
337
638
  clickElement.callback = (element) => {
338
639
  element.addEventListener('click', (event) => {
339
640
  const boundingRect = event.target.ownerSVGElement.getBoundingClientRect();
340
- 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();
341
644
  });
342
645
  };
343
646
  }
344
647
 
648
+
345
649
  drawRect(px, py, width, height, rx = null, ry = null) {
346
650
  const svg = this.setDrawing();
347
- this.finishDrawingPath();
348
651
  const element = {
349
652
  'svg': 'rect',
350
653
  'attr': {
@@ -367,10 +670,12 @@ export class MarkdownScriptRuntime {
367
670
  svg.elem.push(element);
368
671
  }
369
672
 
673
+
370
674
  drawStyle(stroke = 'black', strokeWidth = 1, fill = 'none', strokeDashArray = 'none') {
371
675
  if (stroke !== this.drawingPathStroke || strokeWidth !== this.drawingPathStrokeWidth ||
372
- strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill) {
373
- this.finishDrawingPath();
676
+ strokeDashArray !== this.drawingPathStrokeDashArray || fill !== this.drawingPathFill
677
+ ) {
678
+ this.setDrawing();
374
679
  this.drawingPathStroke = stroke;
375
680
  this.drawingPathStrokeWidth = strokeWidth;
376
681
  this.drawingPathStrokeDashArray = strokeDashArray;
@@ -378,9 +683,9 @@ export class MarkdownScriptRuntime {
378
683
  }
379
684
  }
380
685
 
686
+
381
687
  drawText(text, px, py, textAnchor = 'middle', dominantBaseline = 'middle') {
382
688
  const svg = this.setDrawing();
383
- this.finishDrawingPath();
384
689
  svg.elem.push({
385
690
  'svg': 'text',
386
691
  'attr': {
@@ -398,50 +703,158 @@ export class MarkdownScriptRuntime {
398
703
  });
399
704
  }
400
705
 
706
+
401
707
  drawTextHeight(text, width) {
402
708
  return width > 0 ? width / (fontWidthRatio * text.length) : this.drawingFontSizePx;
403
709
  }
404
710
 
405
- drawTextStyle(fontSizePx = defaultFontSizePx, textFill = 'black', bold = false, italic = false, fontFamily = defaultFontFamily) {
406
- 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);
407
714
  this.drawingFontFill = textFill;
408
715
  this.drawingFontBold = bold;
409
716
  this.drawingFontItalic = italic;
410
717
  this.drawingFontFamily = fontFamily;
411
718
  }
412
719
 
720
+
413
721
  drawTextWidth(text) {
414
722
  return fontWidthRatio * this.drawiingFontSizePx * text.length;
415
723
  }
416
724
 
725
+
417
726
  drawVLine(py) {
418
- this.setDrawing();
727
+ this.setDrawingPath();
419
728
  this.drawingPath.push(`V ${py.toFixed(svgPrecision)}`);
420
729
  }
421
730
 
422
- markdownPrint(lines) {
423
- const markdownLines = this.setMarkdown();
424
- markdownLines.push(...lines);
425
- }
426
-
427
- schemaPrint(types, typeName) {
428
- const params = (
429
- this.options !== null && 'params' in this.options && this.params !== null ? encodeQueryString(this.options.params) : null
430
- );
431
- const elements = schemaMarkdownDoc(types, typeName, {'params': params});
432
- this.setElements(elements);
433
- }
434
731
 
435
732
  setDrawingSize(width, height) {
436
- this.finishDrawingPath();
437
733
  this.drawingWidth = width;
438
734
  this.drawingHeight = height;
439
735
  this.setDrawing(true);
440
736
  }
441
737
 
442
- setNavigateTimeout(url, delay = 0) {
443
- if (this.options !== null && 'navigateTimeoutFn' in this.options && this.navigateTimeoutFn !== null) {
444
- 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;
445
856
  }
857
+ this.setElements();
858
+ this.elements.push(schemaMarkdownDoc(types, typeName, {params, actionURLs}));
446
859
  }
447
860
  }