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/app.js CHANGED
@@ -3,39 +3,39 @@
3
3
 
4
4
  /** @module lib/app */
5
5
 
6
- import {ElementApplication, encodeHashID, getHashID} from 'element-app/lib/app.js';
7
6
  import {MarkdownScriptRuntime, markdownScriptCodeBlock} from './script.js';
8
7
  import {decodeQueryString, encodeQueryString} from 'schema-markdown/lib/encode.js';
9
8
  import {getBaseURL, isRelativeURL, markdownElementsAsync} from 'markdown-model/lib/elements.js';
10
9
  import {getMarkdownTitle, parseMarkdown} from 'markdown-model/lib/parser.js';
10
+ import {SchemaMarkdownParser} from 'schema-markdown/lib/parser.js';
11
11
  import {barChartCodeBlock} from './barChart.js';
12
12
  import {dataTableCodeBlock} from './dataTable.js';
13
13
  import {evaluateExpression} from 'calc-script/lib/runtime.js';
14
14
  import {lineChartCodeBlock} from './lineChart.js';
15
15
  import {parseExpression} from 'calc-script/lib/parser.js';
16
+ import {renderElements} from 'element-model/lib/elementModel.js';
16
17
  import {schemaMarkdownDoc} from 'schema-markdown-doc/lib/schemaMarkdownDoc.js';
18
+ import {validateType} from 'schema-markdown/lib/schema.js';
17
19
 
18
20
 
19
21
  // The application's hash parameter type model
20
- const markdownUpHashTypes = `\
22
+ const markdownUpTypesSmd = `\
21
23
  #
22
- # **markdown-up** is a Markdown viewer application. Click the following link to learn more.
23
- #
24
- # [markdown-up](https://github.com/craigahobbs/markdown-up#readme)
24
+ # [MarkdownUp](https://craigahobbs.github.io/markdown-up/) is a Markdown viewer application.
25
25
  #
26
26
  # ## Hash Parameters
27
27
  #
28
- # The markdown-up application recognizes the following hash parameters:
28
+ # MarkdownUp recognizes the following hash parameters:
29
29
  #
30
30
  struct MarkdownUp
31
31
 
32
32
  # The resource URL
33
- optional string(len > 0) url
33
+ optional string url
34
34
 
35
35
  # Optional command
36
36
  optional Command cmd
37
37
 
38
- # The menu visibility (default is hidden)
38
+ # The menu visibility (default is collapsed)
39
39
  optional int(== 1) menu
40
40
 
41
41
  # The font size
@@ -51,95 +51,125 @@ struct MarkdownUp
51
51
  optional int(== 1) debug
52
52
 
53
53
 
54
- # Field value union
55
- union FieldValue
56
-
57
- # A datetime value
58
- datetime(nullable) datetime
59
-
60
- # A number value
61
- float(nullable) number
62
-
63
- # A string value
64
- string(nullable) string
65
-
66
-
67
- # Application command union
54
+ # A MarkdownUp application command
68
55
  union Command
69
56
 
70
- # Display the application's hash parameter documentation
57
+ # Display the hash parameters documentation
71
58
  int(== 1) help
72
59
 
73
- # Show the URL's Markdown text
60
+ # Show the resource's Markdown text
74
61
  int(== 1) markdown
75
62
  `;
63
+ const markdownUpTypes = new SchemaMarkdownParser(markdownUpTypesSmd).types;
76
64
 
77
65
 
78
66
  /**
79
- * A markdown-up application options object
67
+ * The MarkdownUp application options
80
68
  *
81
69
  * @typedef {Object} MarkdownUpOptions
82
- * @param {number} [options.fontSize = 12] - The font size, in points
83
- * @param {number} [options.lineHeight = 1.2] - The line height, in em
84
- * @param {boolean} [options.menu = true] - If true, show the menu
85
- * @param {string} [options.url = 'README.md'] - The resource URL
70
+ * @param {number} [fontSize = 12] - The font size, in points
71
+ * @param {number} [lineHeight = 1.2] - The line height, in em
72
+ * @param {string} [markdownText = null] - The markdown text
73
+ * @param {boolean} [menu = true] - If true, show the menu
74
+ * @param {string} [url = 'README.md'] - The resource URL
86
75
  */
87
76
 
88
77
 
89
78
  /**
90
- * MarkdownUp, a web application for viewing Markdown files
91
- *
92
- * The MarkdownUp class extends the element-app
93
- * [ElementApplication]{@link https://craigahobbs.github.io/element-app/module-lib_app.ElementApplication.html}
94
- * class.
79
+ * MarkdownUp, a Markdown viewer
95
80
  *
96
- * @extends ElementApplication
81
+ * @property {Object} window - The web browser window object
82
+ * @property {?Object} params - The validated hash parameters object
97
83
  * @property {number} fontSize - The font size, in points
98
84
  * @property {number} lineHeight - The line height, in em
99
85
  * @property {string} markdownText - The markdown text
100
86
  * @property {boolean} menu - If true, show the menu
101
87
  * @property {string} url - The resource URL
102
- * @property {number} [setNavigateTimeoutId = null] - The navigate timeout ID
88
+ * @property {?number} runtimeTimeoutId - The runtime-set timeout ID
103
89
  */
104
- export class MarkdownUp extends ElementApplication {
90
+ export class MarkdownUp {
105
91
  /**
106
92
  * Create an application instance
107
93
  *
108
94
  * @param {Object} window - The web browser window object
109
- * @property {module:lib/app~MarkdownUpOptions} [options] - The markdown-up application options
95
+ * @property {Object} [options] - The [application options]{@link module:lib/app~MarkdownUpOptions}
110
96
  */
111
97
  constructor(window, {fontSize = 12, lineHeight = 1.2, markdownText = null, menu = true, url = 'README.md'} = {}) {
112
- super(window, null, 'MarkdownUp', markdownUpHashTypes);
98
+ this.window = window;
99
+ this.params = null;
113
100
  this.fontSize = fontSize;
114
101
  this.lineHeight = lineHeight;
115
102
  this.markdownText = markdownText;
116
103
  this.menu = menu;
117
104
  this.url = url;
118
- this.setNavigateTimeoutId = null;
105
+ this.runtimeWindowResize = null;
106
+ this.runtimeTimeoutId = null;
119
107
  }
120
108
 
109
+
121
110
  /**
122
- * ElementApplication.render override to clear the navigate timeout
111
+ * Run the application. This method calls render and subscribes to any hash parameter changes to
112
+ * re-render on any hash parameter change.
123
113
  */
124
- async render() {
125
- // Clear the navigate timeout ID, if one is set
126
- if (this.setNavigateTimeoutId !== null) {
127
- this.window.clearTimeout(this.setNavigateTimeoutId);
128
- this.setNavigateTimeoutId = null;
129
- }
130
-
131
- // Call the base class implementation
132
- await super.render();
114
+ async run() {
115
+ await this.render();
116
+ this.window.addEventListener('hashchange', () => this.render(), false);
133
117
  }
134
118
 
119
+
135
120
  /**
136
- * The [Element Application pre-render callback]{@link
137
- * https://craigahobbs.github.io/element-app/module-lib_app.ElementApplication.html#preRender}.
138
- * The callback is used to set the document font size and line height.
139
- *
140
- * @override
121
+ * Render the application
141
122
  */
142
- preRender() {
123
+ async render() {
124
+ // Clear the runtime timeout ID, if one is set
125
+ if (this.runtimeTimeoutId !== null) {
126
+ this.window.clearTimeout(this.runtimeTimeoutId);
127
+ this.runtimeTimeoutId = null;
128
+ }
129
+
130
+ // Clear the window resize event handler
131
+ if (this.runtimeWindowResize !== null) {
132
+ this.window.removeEventListener('resize', this.runtimeWindowResize);
133
+ this.runtimeWindowResize = null;
134
+ }
135
+
136
+ // Parse the hash parameters and render the application element model
137
+ let result;
138
+ let isError = false;
139
+ try {
140
+ // Validate hash parameters
141
+ const paramsPrev = this.params;
142
+ this.updateParams();
143
+
144
+ // Skip the render if the page params haven't changed
145
+ if (paramsPrev !== null && JSON.stringify(paramsPrev) === JSON.stringify(this.params)) {
146
+ return;
147
+ }
148
+
149
+ // Call the application main and validate the result
150
+ result = await this.main();
151
+ } catch ({message}) {
152
+ result = {'elements': {'html': 'p', 'elem': {'text': `Error: ${message}`}}};
153
+ isError = true;
154
+ }
155
+
156
+ // Set the window title
157
+ const title = result.title ?? null;
158
+ if (title !== null) {
159
+ this.window.document.title = title;
160
+ }
161
+
162
+ // Timeout?
163
+ if ('timeout' in result) {
164
+ this.runtimeTimeoutId = this.window.setTimeout(...result.timeout);
165
+ }
166
+
167
+ // Window resize event handler?
168
+ if ('resize' in result) {
169
+ this.runtimeWindowResize = result.resize;
170
+ this.window.addEventListener('resize', result.resize);
171
+ }
172
+
143
173
  // Set the font size
144
174
  const fontSize = this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize;
145
175
  this.window.document.documentElement.style.setProperty('--markdown-model-font-size', `${fontSize}pt`);
@@ -147,223 +177,353 @@ export class MarkdownUp extends ElementApplication {
147
177
  // Set the line height
148
178
  const lineHeight = this.params !== null && 'lineHeight' in this.params ? this.params.lineHeight : this.lineHeight;
149
179
  this.window.document.documentElement.style.setProperty('--markdown-model-line-height', `${lineHeight}em`);
150
- }
151
180
 
152
- /**
153
- * The [Element Application main entry point]{@link
154
- * https://craigahobbs.github.io/element-app/module-lib_app.ElementApplication.html#main}.
155
- *
156
- * @override
157
- * @returns {Object} [MainResult]{@link https://craigahobbs.github.io/element-app/module-lib_app.html#~MainResult}
158
- */
159
- async main() {
160
- // Load the text resource
161
- const url = 'url' in this.params ? this.params.url : this.url;
162
- let markdownText = null;
163
- let markdownModel = null;
164
- let markdownTitle = null;
165
- if (!('cmd' in this.params) || 'markdown' in this.params.cmd) {
166
- if (this.markdownText !== null && !('url' in this.params)) {
167
- ({markdownText} = this);
168
- } else {
169
- const response = await this.window.fetch(url);
170
- if (!response.ok) {
171
- const status = response.statusText;
172
- throw new Error(`Could not fetch "${url}"${status === '' ? '' : `, ${JSON.stringify(status)}`}`);
181
+ // Render the element model
182
+ renderElements(this.window.document.body, result.elements);
183
+
184
+ // Focus?
185
+ if ('focus' in result) {
186
+ const element = this.window.document.getElementById(result.focus);
187
+ if (element !== null) {
188
+ element.focus();
189
+ if ('selectionStart' in element) {
190
+ element.selectionStart = element.value.length;
191
+ element.selectionEnd = element.value.length;
173
192
  }
174
- markdownText = await response.text();
175
193
  }
176
- markdownModel = parseMarkdown(markdownText);
177
- markdownTitle = getMarkdownTitle(markdownModel);
178
194
  }
179
195
 
180
- // Command?
181
- let cmdElements = null;
182
- if ('cmd' in this.params) {
183
- // Display markdown?
184
- if ('markdown' in this.params.cmd) {
185
- cmdElements = {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': markdownText}};
186
-
187
- // Help
188
- } else {
189
- cmdElements = schemaMarkdownDoc(this.hashTypes, this.hashType, {'params': encodeQueryString(this.params)});
190
- }
196
+ // Navigate?
197
+ // Note: This is done after render since it may have no effect (in which case we want to render).
198
+ if ('location' in result && result.location !== null) {
199
+ this.window.location.href = result.location;
200
+ return;
191
201
  }
192
202
 
193
- // Helper function to create a cycle link
194
- const linkCycle = (paramName, defaultValue, delta, fixed = null) => {
195
- const value = paramName in this.params ? this.params[paramName] : defaultValue;
196
- const {attr} = this.hashTypes.MarkdownUp.struct.members.find((member) => member.name === paramName);
197
- let valueNew = value + delta;
198
- if (valueNew > attr.lte) {
199
- valueNew = attr.gte;
200
- }
201
- valueNew = Math.max(attr.gte, Math.min(attr.lte, valueNew));
202
- const params = {...this.params};
203
- params[paramName] = fixed === null ? `${valueNew}` : `${valueNew.toFixed(fixed)}`;
204
- return `#${encodeQueryString(params)}`;
205
- };
203
+ // If there is a URL hash ID, re-navigate to go there since it was just rendered. After the
204
+ // first render, re-render is short-circuited by the unchanged hash param check above.
205
+ if (!isError && getHashID(this.window.location.hash) !== null) {
206
+ this.window.location.href = this.window.location.hash;
207
+ }
208
+ }
206
209
 
207
- // Helper function to create a toggle link
208
- const linkCommandToggle = (command, value) => {
209
- const params = {...this.params};
210
- if ('cmd' in this.params && command in this.params.cmd) {
211
- delete params.cmd;
212
- } else {
213
- params.cmd = {};
214
- params.cmd[command] = `${value}`;
215
- }
216
- return `#${encodeQueryString(params)}`;
217
- };
218
210
 
219
- // Helper function to create a value-toggle link
220
- const linkValueToggle = (name, value) => {
221
- const params = {...this.params};
222
- if (!(name in this.params)) {
223
- params[name] = value;
224
- } else {
225
- delete params[name];
226
- }
227
- return `#${encodeQueryString(params)}`;
228
- };
211
+ /**
212
+ * Parse and validate the hash parameters
213
+ *
214
+ * @param {?string} paramString - Optional parameter string for testing
215
+ */
216
+ updateParams(paramString = null) {
217
+ // Clear, then validate the hash parameters (may throw)
218
+ this.params = null;
229
219
 
230
- // The URL modifier function
231
- const urlFn = (rawURL) => {
232
- // Hash URL?
233
- if (rawURL.startsWith('#')) {
234
- // Fixup the "url" param if its relative
235
- const hashParams = decodeQueryString(rawURL.slice(1));
236
- if ('url' in hashParams && isRelativeURL(hashParams.url)) {
237
- hashParams.url = `${getBaseURL(url)}${hashParams.url}`;
238
- }
220
+ // Decode the params string
221
+ const params = decodeQueryString(paramString !== null ? paramString : this.window.location.hash.slice(1));
239
222
 
240
- // Return the combined hash URL
241
- return encodeHashID({...this.params, ...hashParams}, getHashID(rawURL));
242
- }
223
+ // Validate the params
224
+ this.params = validateType(markdownUpTypes, 'MarkdownUp', params);
225
+ }
243
226
 
244
- // Relative URL?
245
- if (isRelativeURL(rawURL)) {
246
- return `${getBaseURL(url)}${rawURL}`;
247
- }
248
227
 
249
- return rawURL;
250
- };
228
+ /**
229
+ * The application's main entry point
230
+ *
231
+ * @returns {Object}
232
+ */
233
+ async main() {
234
+ // Help?
235
+ if ('cmd' in this.params && 'help' in this.params.cmd) {
236
+ return {
237
+ 'title': 'MarkdownUp',
238
+ 'elements': [
239
+ schemaMarkdownDoc(markdownUpTypes, 'MarkdownUp', {'params': encodeQueryString(this.params)}),
240
+ this.burgerElements()
241
+ ]
242
+ };
243
+ }
251
244
 
252
- // The log function
253
- const logFn = (text) => {
254
- if ('debug' in this.params) {
255
- this.window.console.log(text);
245
+ // Get the Markdown text
246
+ const urlOverride = 'url' in this.params && this.params.url !== '';
247
+ const url = urlOverride ? this.params.url : this.url;
248
+ let markdownText = null;
249
+ if (this.markdownText !== null && !urlOverride) {
250
+ ({markdownText} = this);
251
+ } else {
252
+ // Fetch the Markdown text resource URL
253
+ const response = await this.window.fetch(url);
254
+ if (!response.ok) {
255
+ const status = response.statusText;
256
+ return {
257
+ 'title': 'MarkdownUp',
258
+ 'elements': {
259
+ 'html': 'p',
260
+ 'elem': {'text': `Error: Could not fetch "${url}"${status === '' ? '' : ` - ${JSON.stringify(status)}`}`}
261
+ }
262
+ };
256
263
  }
257
- };
258
-
259
- // The fetch function
260
- // eslint-disable-next-line require-await
261
- const fetchFn = async (fetchURL, init) => this.window.fetch(urlFn(fetchURL), init);
264
+ markdownText = await response.text();
265
+ }
262
266
 
263
- // The navigate timeout function
264
- const navigateTimeoutFn = (navigateURL, delay) => {
265
- const timeoutCallback = () => {
266
- this.window.location.href = urlFn(navigateURL);
267
+ // Parse the Markdown and get the title
268
+ const markdownModel = parseMarkdown(markdownText);
269
+ const markdownTitle = getMarkdownTitle(markdownModel);
270
+
271
+ // Display the Markdown?
272
+ if ('cmd' in this.params && 'markdown' in this.params.cmd) {
273
+ return {
274
+ 'title': markdownTitle,
275
+ 'elements': [
276
+ {'html': 'div', 'attr': {'class': 'markdown'}, 'elem': {'text': markdownText}},
277
+ this.burgerElements()
278
+ ]
267
279
  };
268
- this.setNavigateTimeoutId = this.window.setTimeout(timeoutCallback, delay);
269
- };
270
- // eslint-disable-next-line lines-around-comment
271
-
272
- // Render the text as Markdown
273
- const fontSize = 0.9 * (this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize);
274
- const scriptOptions = {
275
- fetchFn,
276
- fontSize,
277
- 'localStorage': this.window.localStorage,
278
- logFn,
279
- navigateTimeoutFn,
280
- 'params': this.params,
281
- 'sessionStorage': this.window.sessionStorage,
282
- urlFn
283
- };
284
- if ('var' in this.params) {
285
- scriptOptions.variables = {};
286
- for (const varName of Object.keys(this.params.var)) {
287
- const varExpr = parseExpression(this.params.var[varName]);
288
- scriptOptions.variables[varName] = evaluateExpression(varExpr, scriptOptions.variables);
289
- }
290
280
  }
291
- scriptOptions.runtime = new MarkdownScriptRuntime(scriptOptions);
281
+
282
+ // Render the Markdown
283
+ const scriptOptions = this.createScriptOptions(url);
292
284
  const result = {
293
285
  'title': markdownTitle,
294
286
  'elements': [
295
- // Command?
296
- cmdElements !== null ? cmdElements : null,
297
-
298
287
  // Add a top hash ID, if necessary
299
- cmdElements !== null || Object.keys(this.params).length === 0
288
+ Object.keys(this.params).length === 0
300
289
  ? null : {'html': 'div', 'attr': {'id': encodeQueryString(this.params), 'style': 'display=none'}},
301
290
 
302
291
  // Render the markdown
303
- cmdElements !== null ? null : await markdownElementsAsync(markdownModel, {
292
+ await markdownElementsAsync(markdownModel, {
304
293
  'codeBlocks': {
305
- 'bar-chart': (language, lines) => barChartCodeBlock(language, lines, scriptOptions),
306
- 'data-table': (language, lines) => dataTableCodeBlock(language, lines, scriptOptions),
307
- 'line-chart': (language, lines) => lineChartCodeBlock(language, lines, scriptOptions),
308
- 'markdown-script': (language, lines) => markdownScriptCodeBlock(language, lines, scriptOptions)
294
+ 'bar-chart': (codeBlock) => barChartCodeBlock(codeBlock, scriptOptions),
295
+ 'data-table': (codeBlock) => dataTableCodeBlock(codeBlock, scriptOptions),
296
+ 'line-chart': (codeBlock) => lineChartCodeBlock(codeBlock, scriptOptions),
297
+ 'markdown-script': (codeBlock) => markdownScriptCodeBlock(codeBlock, scriptOptions)
309
298
  },
310
- urlFn,
299
+ 'urlFn': (urlRaw) => this.modifyURL(urlRaw, url),
311
300
  'headerIds': true
312
301
  }),
313
302
 
314
303
  // Popup menu burger
315
- !this.menu ? null : {
316
- 'html': 'div',
317
- 'attr': {'class': 'menu-burger'},
318
- 'elem': [
319
- {
320
- 'html': 'a',
321
- 'attr': {'href': linkValueToggle('menu', '1'), 'aria-label': 'Menu'},
322
- 'elem': menuSVGElements
323
- }
324
- ]
325
- },
326
-
327
- // Popup menu
328
- !this.menu || !('menu' in this.params) ? null : {
329
- 'html': 'div',
330
- 'attr': {'class': 'menu'},
331
- 'elem': [
332
- {
333
- 'html': 'a',
334
- 'attr': {'href': linkCommandToggle('markdown', '1'), 'aria-label': 'Show Markdown'},
335
- 'elem': markdownSVGElements
336
- },
337
- {
338
- 'html': 'a',
339
- 'attr': {'href': linkCycle('fontSize', this.fontSize, 2), 'aria-label': 'Font size'},
340
- 'elem': fontSizeSVGElements
341
- },
342
- {
343
- 'html': 'a',
344
- 'attr': {'href': linkCycle('lineHeight', this.lineHeight, 0.2, 1), 'aria-label': 'Line height'},
345
- 'elem': lineHeightSVGElements
346
- },
347
- {
348
- 'html': 'a',
349
- 'attr': {'href': linkCommandToggle('help', '1'), 'aria-label': 'Help'},
350
- 'elem': helpSVGElements
351
- }
352
- ]
353
- }
304
+ this.burgerElements()
354
305
  ]
355
306
  };
356
307
 
357
- // Set document title?
308
+ // Set any runtime side-effects
309
+ if (scriptOptions.runtime.windowLocation !== null) {
310
+ result.location = scriptOptions.runtime.windowLocation;
311
+ }
312
+ if (scriptOptions.runtime.documentFocus !== null) {
313
+ result.focus = scriptOptions.runtime.documentFocus;
314
+ }
358
315
  if (scriptOptions.runtime.documentTitle !== null) {
359
316
  result.title = scriptOptions.runtime.documentTitle;
360
317
  }
318
+ if (scriptOptions.runtime.windowTimeout !== null) {
319
+ result.timeout = scriptOptions.runtime.windowTimeout;
320
+ }
321
+ if (scriptOptions.runtime.windowResize !== null) {
322
+ result.resize = scriptOptions.runtime.windowResize;
323
+ }
361
324
 
362
325
  return result;
363
326
  }
327
+
328
+
329
+ createScriptOptions(resourceURL) {
330
+ // Create the script options object
331
+ const scriptOptions = {
332
+ // eslint-disable-next-line require-await
333
+ 'fetchFn': async (fetchURL, init) => this.window.fetch(fetchURL, init),
334
+ 'fontSize': this.params !== null && 'fontSize' in this.params ? this.params.fontSize : this.fontSize,
335
+ 'params': this.params,
336
+ 'urlFn': (url) => this.modifyURL(url, resourceURL),
337
+ 'window': this.window
338
+ };
339
+
340
+ // Add log function, if debugging
341
+ if ('debug' in this.params) {
342
+ scriptOptions.logFn = (text) => {
343
+ this.window.console.log(text);
344
+ };
345
+ }
346
+
347
+ // Add hash parameter variables, if any
348
+ if ('var' in this.params) {
349
+ scriptOptions.variables = {};
350
+ for (const varName of Object.keys(this.params.var)) {
351
+ const varExpr = parseExpression(this.params.var[varName]);
352
+ scriptOptions.variables[varName] = evaluateExpression(varExpr, scriptOptions.variables);
353
+ }
354
+ }
355
+
356
+ // Create the markdown-script runtime
357
+ const runtime = new MarkdownScriptRuntime(scriptOptions);
358
+ scriptOptions.runtime = runtime;
359
+ scriptOptions.runtimeUpdateFn = () => {
360
+ // Did script set the document title?
361
+ if (runtime.documentTitle !== null) {
362
+ this.window.document.title = runtime.documentTitle;
363
+ }
364
+
365
+ // Did the script set a timeout?
366
+ if (runtime.windowTimeout !== null) {
367
+ if (this.runtimeTimeoutId !== null) {
368
+ this.window.clearTimeout(this.runtimeTimeoutId);
369
+ }
370
+ this.runtimeTimeoutId = this.window.setTimeout(...runtime.windowTimeout);
371
+ }
372
+
373
+ // Reset the runtime
374
+ const {isDocumentReset} = runtime;
375
+ const {windowLocation} = runtime;
376
+ const documentElements = runtime.reset();
377
+
378
+ // Render the elment model
379
+ renderElements(
380
+ this.window.document.body,
381
+ [
382
+ documentElements,
383
+ isDocumentReset ? this.burgerElements() : null
384
+ ],
385
+ isDocumentReset
386
+ );
387
+
388
+ // Focus?
389
+ if (runtime.documentFocus !== null) {
390
+ const element = this.window.document.getElementById(runtime.documentFocus);
391
+ if (element !== null) {
392
+ element.focus();
393
+ if ('selectionStart' in element) {
394
+ element.selectionStart = element.value.length;
395
+ element.selectionEnd = element.value.length;
396
+ }
397
+ }
398
+ }
399
+
400
+ // Navigate?
401
+ // Note: This is done after render since it may have no effect (in which case we want to render).
402
+ if (windowLocation !== null) {
403
+ this.window.location.href = windowLocation;
404
+ }
405
+ };
406
+
407
+ return scriptOptions;
408
+ }
409
+
410
+
411
+ modifyURL(url, resourceURL) {
412
+ // Hash URL?
413
+ if (url.startsWith('#')) {
414
+ // Fixup the "url" param if its relative
415
+ const hashParams = decodeQueryString(url.slice(1));
416
+ if ('url' in hashParams && hashParams.url !== '' && isRelativeURL(hashParams.url)) {
417
+ hashParams.url = `${getBaseURL(resourceURL)}${hashParams.url}`;
418
+ }
419
+
420
+ // Encode hash parameters with a hash ID
421
+ const paramString = encodeQueryString({...this.params, ...hashParams});
422
+ const hashID = getHashID(url);
423
+ return `#${paramString}${hashID !== null && paramString !== '' ? '&' : ''}${hashID !== null ? hashID : ''}`;
424
+ }
425
+
426
+ // Relative URL?
427
+ if (isRelativeURL(url)) {
428
+ return `${getBaseURL(resourceURL)}${url}`;
429
+ }
430
+
431
+ return url;
432
+ }
433
+
434
+
435
+ burgerElements() {
436
+ return !this.menu ? null : [
437
+ {
438
+ 'html': 'div',
439
+ 'attr': {'class': 'menu-burger'},
440
+ 'elem': [
441
+ {
442
+ 'html': 'a',
443
+ 'attr': {'href': this.linkValueToggle('menu', '1'), 'aria-label': 'Menu'},
444
+ 'elem': menuSVGElements
445
+ }
446
+ ]
447
+ },
448
+
449
+ // Popup menu
450
+ !('menu' in this.params) ? null : {
451
+ 'html': 'div',
452
+ 'attr': {'class': 'menu'},
453
+ 'elem': [
454
+ {
455
+ 'html': 'a',
456
+ 'attr': {'href': this.linkCommandToggle('markdown', '1'), 'aria-label': 'Show Markdown'},
457
+ 'elem': markdownSVGElements
458
+ },
459
+ {
460
+ 'html': 'a',
461
+ 'attr': {'href': this.linkCycle('fontSize', this.fontSize, 2), 'aria-label': 'Font size'},
462
+ 'elem': fontSizeSVGElements
463
+ },
464
+ {
465
+ 'html': 'a',
466
+ 'attr': {'href': this.linkCycle('lineHeight', this.lineHeight, 0.2, 1), 'aria-label': 'Line height'},
467
+ 'elem': lineHeightSVGElements
468
+ },
469
+ {
470
+ 'html': 'a',
471
+ 'attr': {'href': this.linkCommandToggle('help', '1'), 'aria-label': 'Help'},
472
+ 'elem': helpSVGElements
473
+ }
474
+ ]
475
+ }
476
+ ];
477
+ }
478
+
479
+
480
+ linkCycle(paramName, defaultValue, delta, fixed = null) {
481
+ const value = paramName in this.params ? this.params[paramName] : defaultValue;
482
+ const {attr} = markdownUpTypes.MarkdownUp.struct.members.find((member) => member.name === paramName);
483
+ let valueNew = value + delta;
484
+ if (valueNew > attr.lte) {
485
+ valueNew = attr.gte;
486
+ }
487
+ valueNew = Math.max(attr.gte, Math.min(attr.lte, valueNew));
488
+ const params = {...this.params};
489
+ params[paramName] = fixed === null ? `${valueNew}` : `${valueNew.toFixed(fixed)}`;
490
+ return `#${encodeQueryString(params)}`;
491
+ }
492
+
493
+
494
+ linkCommandToggle(command, value) {
495
+ const params = {...this.params};
496
+ if ('cmd' in this.params && command in this.params.cmd) {
497
+ delete params.cmd;
498
+ } else {
499
+ params.cmd = {};
500
+ params.cmd[command] = `${value}`;
501
+ }
502
+ return `#${encodeQueryString(params)}`;
503
+ }
504
+
505
+
506
+ linkValueToggle(name, value) {
507
+ const params = {...this.params};
508
+ if (!(name in this.params)) {
509
+ params[name] = value;
510
+ } else {
511
+ delete params[name];
512
+ }
513
+ return `#${encodeQueryString(params)}`;
514
+ }
364
515
  }
365
516
 
366
517
 
518
+ // Get a URL's hash ID
519
+ function getHashID(url) {
520
+ const matchId = url.match(rHashId);
521
+ return matchId !== null ? matchId[1] : null;
522
+ }
523
+
524
+ const rHashId = /[#&]([^=]+)$/;
525
+
526
+
367
527
  // Icon sizes
368
528
  const burgerSize = '24';
369
529
  const iconSize = '36';