markdown-up 5.2.1 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/app.js CHANGED
@@ -4,10 +4,12 @@
4
4
  /** @module lib/app */
5
5
 
6
6
  import {MarkdownScriptRuntime, markdownScriptCodeBlock} from './script.js';
7
+ import {MarkdownUpVoice, voiceElementsParagraphs} from './voice.js';
7
8
  import {barescriptParseExpression, evaluateExpression} from 'bare-script/lib/runtime.js';
8
9
  import {elementModelWrapCallbacks, markdownScriptFunctions} from './scriptLibrary.js';
9
10
  import {
10
- markdownElementsAsync, markdownParse, markdownTitle, schemaParse, schemaValidate, urlDecodeQueryString, urlEncodeQueryString
11
+ markdownElements, markdownElementsAsync, markdownParse, markdownTitle, schemaParse, schemaValidate, urlDecodeQueryString,
12
+ urlEncodeQueryString
11
13
  } from 'bare-script/lib/include.js';
12
14
  import {renderElements} from 'element-model/lib/elementModel.js';
13
15
  import {valueJSON} from 'bare-script/lib/value.js';
@@ -40,6 +42,12 @@ struct MarkdownUpLocal
40
42
  # The line height
41
43
  optional float(>= 1, <= 10) lineHeight
42
44
 
45
+ # The voice playback voice
46
+ optional string(len > 0) voice
47
+
48
+ # The voice playback speaking rate
49
+ optional float(>= 0.5, <= 2) voiceRate
50
+
43
51
 
44
52
  # The MarkdownUp session storage JSON schema
45
53
  struct MarkdownUpSession
@@ -69,6 +77,9 @@ enum MarkdownUpView
69
77
  * @property {?boolean} [darkMode = false] - If true, use dark mode by default
70
78
  * @property {?number} [fontSize = 12] - The font size, in points
71
79
  * @property {?Object} [globals = null] - Global script runtime variables
80
+ * @property {?string} [hashURL = 'sameOrigin'] - The "url" hash parameter policy. A resource's scripts run with the
81
+ * page's origin access (e.g., fetch, local storage), so by default only same-origin resource URLs are allowed
82
+ * ("sameOrigin"). Use "any" to allow any resource URL or "none" to disallow the "url" hash parameter.
72
83
  * @property {?string} [helpURL] - The help URL
73
84
  * @property {?number} [lineHeight = 1.3] - The line height, in em
74
85
  * @property {?string} [markdownText = null] - The default Markdown text
@@ -81,6 +92,38 @@ enum MarkdownUpView
81
92
  const defaultHelpURL = 'https://craigahobbs.github.io/markdown-up-py/';
82
93
 
83
94
 
95
+ // The menu's font sizes (pt) and line heights (em)
96
+ const menuFontSizes = [8, 10, 12, 14, 18, 24];
97
+ const menuLineHeights = [1.2, 1.3, 1.5, 1.7, 2];
98
+
99
+
100
+ // The ID of the element the voice playback bar is rendered in, if the page has one - otherwise, the bar is rendered in
101
+ // its own element (with the default ID) at the bottom of the window
102
+ const voiceBarId = 'markdownUpVoice';
103
+ const voiceBarDefaultId = 'markdownUpVoiceDefault';
104
+
105
+
106
+ // The menu and voice playback bar icon paths (24 x 24)
107
+ const icons = {
108
+ 'burger': 'M3,5 L21,5 M3,12 L21,12 M3,19 L21,19',
109
+ 'close': 'M7,7 L17,17 M17,7 L7,17',
110
+ 'darkMode': 'M16,3 A10,10,0,1,1,3,18 A14,14,0,0,0,17,3 Z',
111
+ 'debug': 'M12,5 A4,7,0,1,0,12,19 A4,7,0,1,0,12,5 M9,9 L15,9 M9,9 L4,6 M9,12 L3,12 M9,15 L4,18 ' +
112
+ 'M15,9 L20,6 M15,12 L21,12 M15,15 L20,18',
113
+ 'fontSize': 'M4,21 L12,3 L20,21 M7.5,14 L16.5,14',
114
+ 'help': 'M12,2 A10,10,0,1,0,12,22 A10,10,0,1,0,12,2 M9,9.5 A3,3,0,1,1,12,12.5 L12,14.5 M12,17.5 L12,18',
115
+ 'lineHeight': 'M11,5 L21,5 M11,12 L21,12 M11,19 L21,19 M5,4 L5,20 M2.5,6.5 L5,4 L7.5,6.5 M2.5,17.5 L5,20 L7.5,17.5',
116
+ 'link': 'M9,5 L19,5 L19,15 M19,5 L6,18',
117
+ 'markdown': 'M5,2 L19,2 L19,22 L5,22 Z M8,7.5 L16,7.5 M8,12 L16,12 M8,16.5 L16,16.5',
118
+ 'pause': 'M8,6 H11 V18 H8 Z M13,6 H16 V18 H13 Z',
119
+ 'play': 'M9,6 L18,12 L9,18 Z',
120
+ 'readAloud': 'M3,9 L7,9 L12,5 L12,19 L7,15 L3,15 Z M16,9 A4,4,0,0,1,16,15 M18.5,6 A8,8,0,0,1,18.5,18',
121
+ 'rewind': 'M5,6 H8 V18 H5 Z M19,6 L10,12 L19,18 Z',
122
+ 'skipBack': 'M12,6 L3,12 L12,18 Z M21,6 L12,12 L21,18 Z',
123
+ 'skipForward': 'M3,6 L12,12 L3,18 Z M12,6 L21,12 L12,18 Z'
124
+ };
125
+
126
+
84
127
  /**
85
128
  * The MarkdownUp application
86
129
  */
@@ -101,6 +144,7 @@ export class MarkdownUp {
101
144
  (this.window.matchMedia && this.window.matchMedia('(prefers-color-scheme: dark)').matches);
102
145
  this.fontSize = (options !== null ? options.fontSize : null) ?? 12;
103
146
  this.globals = (options !== null ? options.globals : null) ?? null;
147
+ this.hashURL = (options !== null ? options.hashURL : null) ?? 'sameOrigin';
104
148
  this.helpURL = (options !== null ? options.helpURL : null) ?? defaultHelpURL;
105
149
  this.lineHeight = (options !== null ? options.lineHeight : null) ?? 1.3;
106
150
  this.markdownText = (options !== null ? options.markdownText : null) ?? null;
@@ -111,6 +155,18 @@ export class MarkdownUp {
111
155
  this.runtimeTimeoutId = null;
112
156
  this.runtimeCount = 0;
113
157
 
158
+ // The page's content element model, as last rendered (for reading the page aloud)
159
+ this.pageElements = null;
160
+
161
+ // The voice playback. It's either the page read aloud (the menu's "Read aloud") or a script's (voiceSpeak) -
162
+ // voiceScript is the script's Markdown text and final arguments.
163
+ this.voice = new MarkdownUpVoice(window, () => this.renderVoice(true));
164
+ this.voiceReadAloud = false;
165
+ this.voiceScript = null;
166
+
167
+ // The voice playback bar's own element, if any (the page has no voice playback bar element)
168
+ this.voiceBar = null;
169
+
114
170
  // The shared Web Audio state (for windowPlaySound), created on first use. The noise buffer is
115
171
  // a one-second white-noise buffer reused for drum and explosion sounds.
116
172
  this.audioContext = null;
@@ -126,6 +182,13 @@ export class MarkdownUp {
126
182
  this.keyState[code] = false;
127
183
  }
128
184
  });
185
+
186
+ // The escape key closes the menu
187
+ this.window.addEventListener('keydown', (event) => {
188
+ if (event.key === 'Escape' && this.menu && this.paramsSession !== null && 'menu' in this.paramsSession) {
189
+ this.menuSessionToggle('menu');
190
+ }
191
+ });
129
192
  }
130
193
 
131
194
 
@@ -176,6 +239,7 @@ export class MarkdownUp {
176
239
  // Parse the hash parameters and render the application element model
177
240
  let result;
178
241
  let isError = false;
242
+ const urlPrev = this.params !== null ? (this.params.url ?? null) : null;
179
243
  try {
180
244
  // Validate hash parameters
181
245
  const paramsPrev = this.params;
@@ -193,6 +257,14 @@ export class MarkdownUp {
193
257
  isError = true;
194
258
  }
195
259
 
260
+ // A new page ends the reading of the page aloud, a new document ends a script's voice playback, and rendering
261
+ // the page anew ends its voice lines
262
+ const url = this.params !== null ? (this.params.url ?? null) : null;
263
+ if (!forceRender && (this.voiceReadAloud || url !== urlPrev)) {
264
+ this.voice.close();
265
+ }
266
+ this.voice.sayStop();
267
+
196
268
  // Set the colors
197
269
  const isDarkMode = this.paramsLocal.darkMode ?? this.darkMode;
198
270
  this.window.document.documentElement.style.colorScheme = isDarkMode ? 'dark' : 'light';
@@ -208,6 +280,7 @@ export class MarkdownUp {
208
280
  // Call the application main and validate the result
209
281
  this.runtimeCount += 1;
210
282
  this.clearRuntimeCallbacks();
283
+ this.pageElements = null;
211
284
  if (!isError) {
212
285
  result = await this.main();
213
286
  }
@@ -229,10 +302,9 @@ export class MarkdownUp {
229
302
  this.window.addEventListener('resize', result.resize);
230
303
  }
231
304
 
232
- // Set the document keydown handler?
305
+ // Set the document keydown handler? (clearRuntimeCallbacks removes it)
233
306
  if ('keyDown' in result) {
234
- this.runtimeDocumentKeyDown = result.keyDown;
235
- this.window.document.addEventListener('keydown', async (event) => {
307
+ this.runtimeDocumentKeyDown = async (event) => {
236
308
  // Is the active element something that wants this event?
237
309
  const {activeElement} = this.window.document;
238
310
  if (activeElement instanceof this.window.HTMLElement &&
@@ -250,11 +322,13 @@ export class MarkdownUp {
250
322
 
251
323
  // Call the document keydown handler
252
324
  await result.keyDown(event);
253
- });
325
+ };
326
+ this.window.document.addEventListener('keydown', this.runtimeDocumentKeyDown);
254
327
  }
255
328
 
256
329
  // Render the element model
257
- renderElements(this.window.document.body, result.elements);
330
+ this.renderPage(result.elements);
331
+ this.renderVoice();
258
332
 
259
333
  // Navigate?
260
334
  // Note: This is done after render since it may have no effect (in which case we need to render)
@@ -344,12 +418,13 @@ export class MarkdownUp {
344
418
 
345
419
  async main() {
346
420
  const url = this.getResourceURL();
421
+ const isHashURL = 'url' in this.params && this.params.url !== '';
347
422
  const scriptOptions = this.createScriptOptions();
348
423
 
349
424
  // Get the Markdown text
350
425
  let markdownText;
351
426
  let timeBegin;
352
- if (this.markdownText !== null && !('url' in this.params && this.params.url !== '')) {
427
+ if (this.markdownText !== null && !isHashURL) {
353
428
  ({markdownText} = this);
354
429
 
355
430
  // Log Markdown render begin
@@ -358,6 +433,11 @@ export class MarkdownUp {
358
433
  scriptOptions.logFn('MarkdownUp: ===== Rendering Markdown text');
359
434
  }
360
435
  } else {
436
+ // Is the "url" hash parameter's resource URL allowed?
437
+ if (isHashURL && !this.isHashURLAllowed(url)) {
438
+ return hashURLError(url);
439
+ }
440
+
361
441
  // Log Markdown render begin
362
442
  if (scriptOptions.debug) {
363
443
  scriptOptions.logFn(`MarkdownUp: ===== Rendering Markdown document "${url}"`);
@@ -372,6 +452,13 @@ export class MarkdownUp {
372
452
 
373
453
  // Fetch the Markdown text resource URL
374
454
  const response = await this.window.fetch(url);
455
+
456
+ // Was the "url" hash parameter's resource URL redirected to a resource URL that's not allowed?
457
+ const responseURL = response.url ?? '';
458
+ if (isHashURL && responseURL !== '' && !this.isHashURLAllowed(responseURL)) {
459
+ return hashURLError(responseURL);
460
+ }
461
+
375
462
  if (!response.ok) {
376
463
  const status = response.statusText;
377
464
  return {
@@ -398,6 +485,7 @@ export class MarkdownUp {
398
485
 
399
486
  // Display the Markdown?
400
487
  if (this.params.view === 'markdown') {
488
+ this.pageElements = markdownElements(markdownModel);
401
489
  return {
402
490
  'title': title,
403
491
  'elements': [
@@ -415,6 +503,7 @@ export class MarkdownUp {
415
503
  // Render the Markdown
416
504
  const contentElements = await markdownElementsAsync(markdownModel, scriptMarkdownOptions);
417
505
  elementModelWrapCallbacks(contentElements, scriptOptions);
506
+ this.pageElements = contentElements;
418
507
  const result = {
419
508
  'title': title,
420
509
  'elements': [
@@ -467,6 +556,24 @@ export class MarkdownUp {
467
556
  }
468
557
 
469
558
 
559
+ // Is the "url" hash parameter's resource URL allowed? The resource's scripts run with the page's origin access.
560
+ isHashURLAllowed(url) {
561
+ if (this.hashURL === 'any') {
562
+ return true;
563
+ } else if (this.hashURL !== 'sameOrigin') {
564
+ return false;
565
+ }
566
+
567
+ // Same-origin? Resolve the URL as fetch does - this also excludes "data:" and "blob:" URLs.
568
+ try {
569
+ const {protocol, host} = new URL(url, this.window.document.baseURI);
570
+ return protocol === this.window.location.protocol && host === this.window.location.host;
571
+ } catch {
572
+ return false;
573
+ }
574
+ }
575
+
576
+
470
577
  createScriptOptions() {
471
578
  // Create the markdown options object
472
579
  const markdownOptions = {
@@ -493,6 +600,15 @@ export class MarkdownUp {
493
600
  markdownOptions,
494
601
  'params': this.params,
495
602
  'urlFn': (url) => this.modifyURL(url),
603
+ 'voice': {
604
+ 'close': () => this.voiceScriptClose(),
605
+ 'load': () => this.voice.prepare(),
606
+ 'ready': () => this.voice.ready(),
607
+ 'say': (text, voice, style, rate) => this.voice.say(text, voice, style, rate),
608
+ 'setText': (text, final) => this.voiceScriptSetText(text, final),
609
+ 'speak': (text, final, key) => this.voiceScriptSpeak(text, final, key),
610
+ 'state': () => this.voiceScriptState()
611
+ },
496
612
  'window': this.window
497
613
  };
498
614
 
@@ -542,13 +658,16 @@ export class MarkdownUp {
542
658
  if (elements !== null) {
543
659
  const {body} = this.window.document;
544
660
  if (runtime.documentReset === null) {
545
- renderElements(body, [this.burgerElements(), elements]);
661
+ this.renderPage([this.burgerElements(), elements]);
662
+ this.pageElements = elements;
546
663
  } else {
547
- while (body.lastChild !== null && body.lastChild.id !== runtime.documentReset) {
664
+ while (body.lastChild !== null && body.lastChild !== this.voiceBar && body.lastChild.id !== runtime.documentReset) {
548
665
  body.lastChild.remove();
549
666
  }
550
667
  renderElements(body, [elements], false);
668
+ this.pageElements = [pageElementsReset(this.pageElements, runtime.documentReset), elements];
551
669
  }
670
+ this.renderVoice();
552
671
  }
553
672
 
554
673
  // Navigate?
@@ -599,46 +718,56 @@ export class MarkdownUp {
599
718
  burgerElements() {
600
719
  const paramString = urlEncodeQueryString(this.params);
601
720
  const topHeaderId = `${paramString}${paramString !== '' ? '&' : ''}_top`;
721
+ const isMenu = 'menu' in this.paramsSession;
602
722
  return [
603
723
  !this.menu ? null : [
724
+ // Menu "burger" button
604
725
  {
605
726
  'html': 'div',
606
727
  'attr': {'class': 'menu-burger'},
607
- 'elem': this.menuValueToggle('menu', {
608
- 'size': 32,
609
- 'noCheck': true,
610
- 'path': 'M3,5 L21,5 M3,12 L21,12 M3,19 L21,19'
611
- })
728
+ 'elem': {
729
+ 'html': 'button',
730
+ 'attr': {'type': 'button', 'class': 'menu-button', 'aria-label': 'Menu', 'aria-expanded': `${isMenu}`},
731
+ 'elem': iconElements(icons.burger, 22),
732
+ 'callback': clickCallback(() => this.menuSessionToggle('menu'))
733
+ }
612
734
  },
613
735
 
614
- // Popup menu
615
- !('menu' in this.paramsSession) ? null : {
616
- 'html': 'div',
617
- 'attr': {'class': 'menu'},
618
- 'elem': [
619
- this.menuViewToggle('markdown', {
620
- 'path': 'M4,2 L20,2 L20,22 L4,22 Z',
621
- 'path2': 'M7,7.5 L17,7.5 M7,12 L17,12 M7,16.5 L17,16.5'
622
- }),
623
- this.menuDarkModeToggle({
624
- 'path': 'M16,3 A10,10,0,1,1,3,18 A14,14,0,0,0,17,3'
625
- }),
626
- this.menuValueCycle('fontSize', 12, [8, 10, 12, 14, 18, 24], (value) => `${value}pt`, {
627
- 'path': 'M4,22 L10,2 L14,2 L20,22 M6,12.5 L18,12.5',
628
- 'strokeWidth': 4
629
- }),
630
- this.menuValueCycle('lineHeight', 1.3, [1.2, 1.3, 1.5, 1.7, 2.0], null, {
631
- 'path2': 'M2,3 L22,3 M2,9 L22,9 M2,15 L22,15 M2,21 L22,21'
632
- }),
633
- this.menuValueToggle('debug', {
634
- 'path': 'M12,5 A4,7,0,1,0,12,19 A4,7,0,1,0,12,5 M9,9 L15,9 M9,9 L4,6 M9,12 L3,12 M9,15 L4,18 ' +
635
- 'M15,9 L20,6 M15,12 L21,12 M15,15 L20,18'
636
- }),
637
- this.menuLink(this.helpURL, {
638
- 'path': 'M7,9 L7,4 L17,4 L17,12 L12,12 L12,16 M12,19 L12,22'
639
- })
640
- ]
641
- }
736
+ // Popup menu - a click outside of it (on its backdrop) closes it
737
+ !isMenu ? null : [
738
+ {
739
+ 'html': 'div',
740
+ 'attr': {'class': 'menu-backdrop'},
741
+ 'callback': clickCallback(() => this.menuSessionToggle('menu'))
742
+ },
743
+ {
744
+ 'html': 'div',
745
+ 'attr': {'class': 'menu', 'role': 'menu'},
746
+ 'elem': [
747
+ menuItemElements('Read aloud', icons.readAloud, null, () => this.menuReadAloud()),
748
+ menuSeparatorElements(),
749
+ menuItemElements(
750
+ 'Dark mode', icons.darkMode, !!(this.paramsLocal.darkMode ?? this.darkMode), () => this.menuDarkModeToggle()
751
+ ),
752
+ this.menuStepperElements('Font size', icons.fontSize, 'fontSize', this.fontSize, menuFontSizes, 'pt'),
753
+ this.menuStepperElements('Line height', icons.lineHeight, 'lineHeight', this.lineHeight, menuLineHeights, ''),
754
+ menuSeparatorElements(),
755
+ menuItemElements(
756
+ 'Markdown source', icons.markdown, this.params.view === 'markdown', () => this.menuViewToggle('markdown')
757
+ ),
758
+ menuItemElements('Debug', icons.debug, 'debug' in this.paramsSession, () => this.menuSessionToggle('debug')),
759
+ {
760
+ 'html': 'a',
761
+ 'attr': {'class': 'menu-item', 'role': 'menuitem', 'href': this.helpURL},
762
+ 'elem': [
763
+ iconElements(icons.help),
764
+ {'html': 'span', 'attr': {'class': 'menu-label'}, 'elem': {'text': 'Help'}},
765
+ iconElements(icons.link, 14)
766
+ ]
767
+ }
768
+ ]
769
+ }
770
+ ]
642
771
  ],
643
772
 
644
773
  // The top header ID
@@ -647,168 +776,318 @@ export class MarkdownUp {
647
776
  }
648
777
 
649
778
 
650
- menuLink(url, icon) {
651
- return this.menuButton(
652
- () => {
653
- this.window.location.href = url;
779
+ // Create a menu stepper's element model - a local storage value with buttons to step it down and up through its values
780
+ menuStepperElements(label, icon, valueName, valueDefault, values, unit) {
781
+ const value = this.paramsLocal[valueName] ?? valueDefault;
782
+ const stepElements = (stepLabel, stepText, valueNew) => ({
783
+ 'html': 'button',
784
+ 'attr': {
785
+ 'type': 'button',
786
+ 'class': 'menu-step',
787
+ 'aria-label': `${label} ${stepLabel}`,
788
+ 'disabled': valueNew === null ? 'disabled' : null
654
789
  },
655
- icon
656
- );
657
- }
658
-
659
-
660
- menuValueToggle(valueName, icon) {
661
- icon.checked = valueName in this.paramsSession;
662
- return this.menuButton(
663
- () => {
664
- if (valueName in this.paramsSession) {
665
- delete this.paramsSession[valueName];
790
+ 'elem': {'text': stepText},
791
+ 'callback': valueNew === null ? null : clickCallback(() => {
792
+ if (valueNew === valueDefault) {
793
+ delete this.paramsLocal[valueName];
666
794
  } else {
667
- this.paramsSession[valueName] = 1;
795
+ this.paramsLocal[valueName] = valueNew;
668
796
  }
669
- this.window.sessionStorage.setItem('MarkdownUp', JSON.stringify(this.paramsSession));
797
+ this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
670
798
  this.render(true);
671
- },
672
- icon
673
- );
799
+ })
800
+ });
801
+ return {
802
+ 'html': 'div',
803
+ 'attr': {'class': 'menu-item menu-stepper'},
804
+ 'elem': [
805
+ iconElements(icon),
806
+ {'html': 'span', 'attr': {'class': 'menu-label'}, 'elem': {'text': label}},
807
+ stepElements('down', '−', values.findLast((valueOther) => valueOther < value) ?? null),
808
+ {'html': 'span', 'attr': {'class': 'menu-value'}, 'elem': {'text': `${value}${unit}`}},
809
+ stepElements('up', '+', values.find((valueOther) => valueOther > value) ?? null)
810
+ ]
811
+ };
674
812
  }
675
813
 
676
814
 
677
- menuViewToggle(viewValue, icon) {
678
- icon.checked = this.params.view === viewValue;
679
- return this.menuButton(
680
- () => {
681
- const params = {...this.params};
682
- if (params.view === viewValue) {
683
- delete params.view;
684
- } else {
685
- params.view = viewValue;
686
- }
687
- this.window.location.href = `#${urlEncodeQueryString(params)}`;
688
- },
689
- icon
690
- );
815
+ // Toggle a session storage value (e.g., the menu) and render
816
+ menuSessionToggle(valueName) {
817
+ if (valueName in this.paramsSession) {
818
+ delete this.paramsSession[valueName];
819
+ } else {
820
+ this.paramsSession[valueName] = 1;
821
+ }
822
+ this.window.sessionStorage.setItem('MarkdownUp', JSON.stringify(this.paramsSession));
823
+ this.render(true);
691
824
  }
692
825
 
693
826
 
694
- menuDarkModeToggle(icon) {
827
+ // Toggle a view (e.g., the Markdown text view)
828
+ menuViewToggle(viewValue) {
829
+ const params = {...this.params};
830
+ if (params.view === viewValue) {
831
+ delete params.view;
832
+ } else {
833
+ params.view = viewValue;
834
+ }
835
+ this.window.location.href = `#${urlEncodeQueryString(params)}`;
836
+ }
837
+
838
+
839
+ // Toggle dark mode and render
840
+ menuDarkModeToggle() {
695
841
  const isDarkMode = this.paramsLocal.darkMode ?? this.darkMode;
696
- icon.checked = isDarkMode;
697
- return this.menuButton(
698
- () => {
699
- if (isDarkMode !== this.darkMode) {
700
- delete this.paramsLocal.darkMode;
701
- } else {
702
- this.paramsLocal.darkMode = !isDarkMode;
703
- }
704
- this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
705
- this.render(true);
706
- },
707
- icon
708
- );
842
+ if (isDarkMode !== this.darkMode) {
843
+ delete this.paramsLocal.darkMode;
844
+ } else {
845
+ this.paramsLocal.darkMode = !isDarkMode;
846
+ }
847
+ this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
848
+ this.render(true);
709
849
  }
710
850
 
711
851
 
712
- menuValueCycle(valueName, valueDefault, values, textFn, icon) {
713
- const valueCurrent = this.paramsLocal[valueName] ?? valueDefault;
714
- let ixNew = values.indexOf(valueCurrent) + 1;
715
- if (ixNew >= values.length) {
716
- ixNew = 0;
852
+ // Read the page aloud - the page as it's rendered now, if it has anything to read - and close the menu
853
+ menuReadAloud() {
854
+ const paragraphs = voiceElementsParagraphs(this.pageElements, true);
855
+ if (paragraphs.length !== 0) {
856
+ this.voiceReadAloud = true;
857
+ this.voiceScript = null;
858
+ this.voiceSettings();
859
+ this.voice.speak(paragraphs, true, null);
717
860
  }
718
- const valueNew = values[ixNew];
719
- icon.text = (textFn !== null ? textFn(valueCurrent) : valueCurrent);
720
- return this.menuButton(
721
- () => {
722
- this.paramsLocal[valueName] = valueNew;
723
- this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
724
- this.render(true);
725
- },
726
- icon
727
- );
861
+ this.menuSessionToggle('menu');
728
862
  }
729
863
 
730
864
 
731
- menuButton(onClick, {checked = false, noCheck = false, path = null, path2 = null, strokeWidth = 3, size = 48, text = null}) {
732
- const isDarkMode = this.paramsLocal.darkMode ?? this.darkMode;
733
- const stroke = (isDarkMode ? (checked && !noCheck ? 'black' : 'white') : (checked && !noCheck ? 'white' : 'black'));
734
- const background = (stroke === 'black' ? 'white' : 'black');
735
- const borderSize = (0.125 * size).toFixed(3);
736
- const innerSize = (0.75 * size).toFixed(3);
737
-
738
- // Compute the text block geometry
739
- const textStrokeWidth = Math.round(1000 * 0.05 * size) / 1000;
740
- const textLeft = 0.5 * textStrokeWidth;
741
- const textRight = 12.5 * textStrokeWidth;
742
- const textTop = size - 6.5 * textStrokeWidth;
743
- const textBottom = size - 0.5 * textStrokeWidth;
744
- const textBoxX = 0.5 * (textLeft + textRight);
745
- const textBoxY = 0.5 * (textTop + textBottom);
746
- const textBoxSize = (textBottom - textTop) - 1.75 * textStrokeWidth;
865
+ // Set the voice playback's voice and speaking rate to the preferred voice and speaking rate
866
+ voiceSettings() {
867
+ this.voice.voice = this.paramsLocal.voice ?? null;
868
+ this.voice.rate = this.paramsLocal.voiceRate ?? 1;
869
+ }
870
+
871
+
872
+ // The script library's voiceSpeak - start reading Markdown text aloud
873
+ voiceScriptSpeak(text, final, key) {
874
+ this.voiceReadAloud = false;
875
+ this.voiceScript = [text, final];
876
+ this.voiceSettings();
877
+ this.voice.speak(voiceMarkdownParagraphs(text), final, key);
878
+ }
879
+
880
+
881
+ // The script library's voiceSetText - set the Markdown text of the script's voice playback, if any
882
+ voiceScriptSetText(text, final) {
883
+ if (this.voiceScriptState() !== null && (text !== this.voiceScript[0] || final !== this.voiceScript[1])) {
884
+ this.voiceScript = [text, final];
885
+ this.voice.setText(voiceMarkdownParagraphs(text), final);
886
+ }
887
+ }
888
+
889
+
890
+ // The script library's voiceState - the state of the script's voice playback, if any (not the page read aloud)
891
+ voiceScriptState() {
892
+ return this.voiceReadAloud ? null : this.voice.state();
893
+ }
894
+
895
+
896
+ // The script library's voiceClose - close the script's voice playback, if any (not the page read aloud), and stop
897
+ // the voice lines
898
+ voiceScriptClose() {
899
+ this.voice.sayStop();
900
+ if (!this.voiceReadAloud) {
901
+ this.voice.close();
902
+ }
903
+ }
904
+
905
+
906
+ // Render the page's element model in the document body. The voice playback bar's own element, if any, is left in
907
+ // place (it's the body's first element) - an element that's replaced as it's clicked gets no click, so the bar's
908
+ // controls would fail while an application renders.
909
+ renderPage(elements) {
910
+ const {body} = this.window.document;
911
+ if (this.voiceBar === null) {
912
+ renderElements(body, elements);
913
+ } else {
914
+ while (body.lastChild !== this.voiceBar) {
915
+ body.lastChild.remove();
916
+ }
917
+ renderElements(body, elements, false);
918
+ }
919
+ }
920
+
921
+
922
+ // Render the voice playback bar, if there's a voice playback - in the page's voice playback bar element, if it has
923
+ // one, or in the bar's own element at the bottom of the window. Unless the playback changed, a rendered bar is left
924
+ // as it is.
925
+ renderVoice(changed = false) {
926
+ const {document} = this.window;
927
+ const isPlayback = this.voice.state() !== null;
928
+ const pageBar = document.getElementById(voiceBarId);
929
+
930
+ // Remove the bar's own element when it isn't needed
931
+ if (this.voiceBar !== null && (pageBar !== null || !isPlayback)) {
932
+ this.voiceBar.remove();
933
+ this.voiceBar = null;
934
+ }
935
+
936
+ // No playback? Clear the page's voice playback bar element, if any.
937
+ if (!isPlayback) {
938
+ if (pageBar !== null && pageBar.firstChild !== null) {
939
+ pageBar.replaceChildren();
940
+ }
941
+ return;
942
+ }
943
+
944
+ // Create the bar's own element, if necessary - the body's first element, where rendering the page leaves it
945
+ if (pageBar === null && this.voiceBar === null) {
946
+ this.voiceBar = document.createElement('div');
947
+ this.voiceBar.id = voiceBarDefaultId;
948
+ this.voiceBar.className = 'voice-default';
949
+ document.body.prepend(this.voiceBar);
950
+ }
951
+
952
+ // Render the bar
953
+ const bar = pageBar ?? this.voiceBar;
954
+ if (changed || bar.firstChild === null) {
955
+ renderElements(bar, this.voiceElements());
956
+ }
957
+ }
958
+
747
959
 
960
+ // Create the voice playback bar's element model
961
+ voiceElements() {
962
+ const {voice} = this;
963
+ const {playing} = voice.state();
964
+ const textButtonElements = (label, text, onClick) => ({
965
+ 'html': 'button',
966
+ 'attr': {'type': 'button', 'class': 'voice-text', 'aria-label': label},
967
+ 'elem': {'text': text},
968
+ 'callback': clickCallback(onClick)
969
+ });
748
970
  return {
749
971
  'html': 'div',
750
- 'attr': {'style': 'cursor: pointer; user-select: none;'},
751
- 'elem': {
752
- 'svg': 'svg',
753
- 'attr': {'width': size, 'height': size},
754
- 'elem': [
755
- !checked || noCheck ? null : {
756
- 'svg': 'rect',
757
- 'attr': {'fill': (isDarkMode ? 'white' : 'black'), 'stroke': 'none', 'width': size, 'height': size}
758
- },
759
- {
760
- 'svg': 'g',
761
- 'attr': {'transform': `translate(${borderSize}, ${borderSize})`},
762
- 'elem': {
763
- 'svg': 'svg',
764
- 'attr': {'width': innerSize, 'height': innerSize, 'viewBox': '0 0 24 24'},
765
- 'elem': [
766
- path === null ? null : {
767
- 'svg': 'path',
768
- 'attr': {'fill': 'none', 'stroke': stroke, 'stroke-width': strokeWidth, 'd': path}
769
- },
770
- path2 === null ? null : {
771
- 'svg': 'path',
772
- 'attr': {'fill': 'none', 'stroke': stroke, 'stroke-width': strokeWidth - 1, 'd': path2}
773
- }
774
- ]
775
- }
776
- },
777
- (text === null ? null : {
778
- 'svg': 'rect',
779
- 'attr': {
780
- 'fill': background,
781
- 'stroke': stroke,
782
- 'stroke-width': textStrokeWidth,
783
- 'x': textLeft.toFixed(3),
784
- 'y': textTop.toFixed(3),
785
- 'width': (textRight - textLeft).toFixed(3),
786
- 'height': (textBottom - textTop).toFixed(3)
787
- }
788
- }),
789
- (text === null ? null : {
790
- 'svg': 'text',
791
- 'attr': {
792
- 'fill': stroke,
793
- 'x': textBoxX.toFixed(3),
794
- 'y': textBoxY.toFixed(3),
795
- 'text-anchor': 'middle',
796
- 'dominant-baseline': 'middle',
797
- 'font-size': `${textBoxSize.toFixed(3)}px`,
798
- 'font-weight': 'bold'
799
- },
800
- 'elem': {'text': text}
801
- })
802
- ]
803
- },
804
- 'callback': (element) => {
805
- element.addEventListener('click', onClick);
806
- }
972
+ 'attr': {'class': 'voice', 'role': 'group', 'aria-label': 'Read aloud'},
973
+ 'elem': [
974
+ voiceButtonElements('Rewind', icons.rewind, true, () => voice.rewind()),
975
+ voiceButtonElements('Skip back', icons.skipBack, true, () => voice.skipBack()),
976
+ (playing
977
+ ? voiceButtonElements('Pause', icons.pause, true, () => voice.pause(), true)
978
+ : voiceButtonElements('Play', icons.play, true, () => voice.play(), true)),
979
+ voiceButtonElements('Skip forward', icons.skipForward, true, () => voice.skipForward()),
980
+ textButtonElements('Voice', voice.voiceLabel(), () => {
981
+ const voiceNext = voice.voiceNext();
982
+ if (voiceNext !== null) {
983
+ this.paramsLocal.voice = voiceNext;
984
+ this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
985
+ voice.setVoice(voiceNext);
986
+ }
987
+ }),
988
+ {'html': 'span', 'attr': {'class': 'voice-separator'}, 'elem': {'text': '|'}},
989
+ textButtonElements('Speaking rate', `${voice.rate}x`, () => {
990
+ const rateNext = voice.rateNext();
991
+ this.paramsLocal.voiceRate = rateNext;
992
+ this.window.localStorage.setItem('MarkdownUp', JSON.stringify(this.paramsLocal));
993
+ voice.setRate(rateNext);
994
+ }),
995
+ voiceButtonElements('Close', icons.close, false, () => voice.close())
996
+ ]
807
997
  };
808
998
  }
809
999
  }
810
1000
 
811
1001
 
1002
+ // Create an element model callback that adds an element's click event handler
1003
+ function clickCallback(onClick) {
1004
+ return (element) => {
1005
+ element.addEventListener('click', onClick);
1006
+ };
1007
+ }
1008
+
1009
+
1010
+ // Create an icon's element model - an icon is drawn with lines or filled
1011
+ function iconElements(path, size = 18, fill = false) {
1012
+ return {
1013
+ 'svg': 'svg',
1014
+ 'attr': {'width': size, 'height': size, 'viewBox': '0 0 24 24', 'aria-hidden': 'true'},
1015
+ 'elem': {
1016
+ 'svg': 'path',
1017
+ 'attr': {
1018
+ 'fill': fill ? 'currentColor' : 'none',
1019
+ 'stroke': fill ? 'none' : 'currentColor',
1020
+ 'stroke-width': 2,
1021
+ 'stroke-linecap': 'round',
1022
+ 'stroke-linejoin': 'round',
1023
+ 'd': path
1024
+ }
1025
+ }
1026
+ };
1027
+ }
1028
+
1029
+
1030
+ // Create a menu item's element model - if checked isn't null, the item is a toggle
1031
+ function menuItemElements(label, icon, checked, onClick) {
1032
+ const isToggle = checked !== null;
1033
+ return {
1034
+ 'html': 'button',
1035
+ 'attr': {
1036
+ 'type': 'button',
1037
+ 'class': 'menu-item',
1038
+ 'role': isToggle ? 'menuitemcheckbox' : 'menuitem',
1039
+ 'aria-checked': isToggle ? `${checked}` : null
1040
+ },
1041
+ 'elem': [
1042
+ iconElements(icon),
1043
+ {'html': 'span', 'attr': {'class': 'menu-label'}, 'elem': {'text': label}},
1044
+ !isToggle ? null : {'html': 'span', 'attr': {'class': 'menu-switch'}}
1045
+ ],
1046
+ 'callback': clickCallback(onClick)
1047
+ };
1048
+ }
1049
+
1050
+
1051
+ // Create a menu separator's element model
1052
+ function menuSeparatorElements() {
1053
+ return {'html': 'div', 'attr': {'class': 'menu-separator', 'role': 'separator'}};
1054
+ }
1055
+
1056
+
1057
+ // Create a voice playback bar button's element model
1058
+ function voiceButtonElements(label, icon, fill, onClick, isPrimary = false) {
1059
+ return {
1060
+ 'html': 'button',
1061
+ 'attr': {'type': 'button', 'class': `voice-button${isPrimary ? ' voice-primary' : ''}`, 'aria-label': label},
1062
+ 'elem': iconElements(icon, isPrimary ? 22 : 18, fill),
1063
+ 'callback': clickCallback(onClick)
1064
+ };
1065
+ }
1066
+
1067
+
1068
+ // Get Markdown text's paragraphs to read aloud
1069
+ function voiceMarkdownParagraphs(text) {
1070
+ return voiceElementsParagraphs(markdownElements(markdownParse(text)));
1071
+ }
1072
+
1073
+
1074
+ // Get the page elements that remain after a document reset - the top-level elements through the reset ID's element
1075
+ function pageElementsReset(pageElements, resetId) {
1076
+ const elements = [pageElements].flat(Infinity).filter((element) => element !== null);
1077
+ const ixReset = elements.findIndex((element) => (element.attr ?? null) !== null && element.attr.id === resetId);
1078
+ return elements.slice(0, ixReset + 1);
1079
+ }
1080
+
1081
+
1082
+ // Create the main result for a "url" hash parameter resource URL that's not allowed
1083
+ function hashURLError(url) {
1084
+ return {
1085
+ 'title': 'MarkdownUp',
1086
+ 'elements': {'html': 'p', 'elem': {'text': `Error: The "url" hash parameter resource URL "${url}" is not allowed`}}
1087
+ };
1088
+ }
1089
+
1090
+
812
1091
  // Get a URL's header ID
813
1092
  function getHeaderId(url) {
814
1093
  const matchId = url.match(rHeaderId);