@protomaze/demo-engine 0.0.0-stage → 0.1.1

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.
Files changed (71) hide show
  1. package/AGENTS.md +131 -0
  2. package/README.md +192 -2
  3. package/agent/Agent.d.ts +155 -0
  4. package/agent/Agent.js +1 -0
  5. package/agent/Guide.d.ts +2 -0
  6. package/agent/Guide.js +1 -0
  7. package/engine/DemoEngine.d.ts +338 -0
  8. package/engine/DemoEngine.js +1 -0
  9. package/engine/Guided.d.ts +12 -0
  10. package/engine/Guided.js +1 -0
  11. package/engine/Player.d.ts +154 -0
  12. package/engine/Player.js +1 -0
  13. package/engine/Plugin.d.ts +56 -0
  14. package/engine/Plugin.js +1 -0
  15. package/engine/Read.d.ts +5 -0
  16. package/engine/Read.js +1 -0
  17. package/engine/Recorder.d.ts +50 -0
  18. package/engine/Recorder.js +1 -0
  19. package/engine/Settings.d.ts +51 -0
  20. package/engine/Settings.js +1 -0
  21. package/index.d.ts +27 -0
  22. package/index.js +1 -0
  23. package/model/Demo.d.ts +201 -0
  24. package/model/Demo.js +1 -0
  25. package/model/Subtitles.d.ts +12 -0
  26. package/model/Subtitles.js +1 -0
  27. package/model/Timing.d.ts +45 -0
  28. package/model/Timing.js +1 -0
  29. package/model/Validate.d.ts +16 -0
  30. package/model/Validate.js +1 -0
  31. package/package.json +65 -4
  32. package/page/Input.d.ts +67 -0
  33. package/page/Input.js +1 -0
  34. package/page/Overlay.d.ts +110 -0
  35. package/page/Overlay.js +1 -0
  36. package/page/Targets.d.ts +85 -0
  37. package/page/Targets.js +1 -0
  38. package/speech/Music.d.ts +13 -0
  39. package/speech/Music.js +1 -0
  40. package/speech/Pack.d.ts +27 -0
  41. package/speech/Pack.js +1 -0
  42. package/speech/Speech.d.ts +127 -0
  43. package/speech/Speech.js +1 -0
  44. package/speech/Transcribe.d.ts +25 -0
  45. package/speech/Transcribe.js +1 -0
  46. package/speech/Workers.d.ts +22 -0
  47. package/speech/Workers.js +1 -0
  48. package/store/Share.d.ts +19 -0
  49. package/store/Share.js +1 -0
  50. package/store/Store.d.ts +55 -0
  51. package/store/Store.js +1 -0
  52. package/store/Zip.d.ts +9 -0
  53. package/store/Zip.js +1 -0
  54. package/ui/Actions.d.ts +33 -0
  55. package/ui/Actions.js +1 -0
  56. package/ui/EngineUI.d.ts +3 -0
  57. package/ui/EngineUI.js +1 -0
  58. package/ui/Hooks.d.ts +5 -0
  59. package/ui/Hooks.js +1 -0
  60. package/ui/Kit.d.ts +108 -0
  61. package/ui/Kit.js +1 -0
  62. package/ui/Library.d.ts +32 -0
  63. package/ui/Library.js +1 -0
  64. package/ui/Studio.d.ts +10 -0
  65. package/ui/Studio.js +1 -0
  66. package/ui/Styles.d.ts +2 -0
  67. package/ui/Styles.js +1 -0
  68. package/ui/Timeline.d.ts +21 -0
  69. package/ui/Timeline.js +1 -0
  70. package/video/Film.d.ts +61 -0
  71. package/video/Film.js +1 -0
@@ -0,0 +1,110 @@
1
+ import type { Corner, Side } from '../model/Demo';
2
+ import { Cursor } from './Input';
3
+ /** An element an effect follows; read every frame, so it may be found again once the app replaces it. */
4
+ export type Follow = () => Element | undefined;
5
+ export type Effect = {
6
+ kind: 'spotlight';
7
+ element: Follow;
8
+ text?: string;
9
+ padding?: number;
10
+ } | {
11
+ kind: 'ring';
12
+ element: Follow;
13
+ text?: string;
14
+ color?: string;
15
+ shape?: 'box' | 'circle';
16
+ padding?: number;
17
+ } | {
18
+ kind: 'arrow';
19
+ element: Follow;
20
+ text?: string;
21
+ from?: Side;
22
+ color?: string;
23
+ } | {
24
+ kind: 'callout';
25
+ text: string;
26
+ element?: Follow;
27
+ side?: Side;
28
+ corner?: Corner;
29
+ } | {
30
+ kind: 'blur';
31
+ element: Follow;
32
+ } | {
33
+ kind: 'card';
34
+ title: string;
35
+ text?: string;
36
+ } | {
37
+ kind: 'zoom';
38
+ element: Follow;
39
+ scale?: number;
40
+ };
41
+ export type OverlayOptions = {
42
+ /** CSS for the subtitles' distance from the bottom: above the app's own bars. Default '48px'. */
43
+ subtitleBottom?: string;
44
+ /** Subtitles' font size, px. Default 24. */
45
+ subtitleSize?: number;
46
+ /** Highlights' colour. Default '#ffb300'. */
47
+ accent?: string;
48
+ };
49
+ /**
50
+ * What the viewer sees over the app: the stand-in pointer, subtitles, keys pressed, presentation
51
+ * effects, the target picker - and the engine's controls (`ui`). In a shadow root in the top layer:
52
+ * the app's styles and z-indexes don't reach it, nor do demos.
53
+ */
54
+ export declare class Overlay {
55
+ private options;
56
+ readonly host: HTMLElement;
57
+ readonly root: ShadowRoot;
58
+ /** Where the engine's own UI mounts. */
59
+ readonly ui: HTMLElement;
60
+ private layer;
61
+ private cursorNode;
62
+ private subtitleNode;
63
+ private keysNode;
64
+ private shade;
65
+ private shown;
66
+ private tracking;
67
+ private at;
68
+ private keysTimer;
69
+ private picking;
70
+ constructor(options?: OverlayOptions);
71
+ /** Styles for what renders in the shadow root: the engine's UI. */
72
+ addStyles(css: string): void;
73
+ /** On the page; after `body`, so a zoom of the page leaves it as it is. */
74
+ mount(): void;
75
+ unmount(): void;
76
+ /** Back on top of what the app put in the top layer since: its dialogs. */
77
+ raise(): void;
78
+ setOptions(options: OverlayOptions): void;
79
+ private node;
80
+ /** No pointer shown, though it moves: a demo's cleanup, unseen. */
81
+ quiet: boolean;
82
+ readonly cursor: Cursor;
83
+ hideCursor(): void;
84
+ subtitle(text: string | undefined): void;
85
+ /** Keys pressed, shown a moment: 'Control+K' as two caps. */
86
+ keys(chord: string): void;
87
+ /** Shows it until removed, following its element as it moves. */
88
+ show(effect: Effect): () => void;
89
+ /** Every effect taken down. */
90
+ clear(): void;
91
+ get effects(): Effect[];
92
+ /** Every frame while effects show: they follow what moves. */
93
+ private track;
94
+ /** The spotlights' holes in one shade: several light up at once. */
95
+ private updateShade;
96
+ private make;
97
+ /** Rings an element a moment: the editor's "show". */
98
+ flash(element: Element, text?: string): void;
99
+ /**
100
+ * The element the next click on the page names; none on Escape. What a click would mean
101
+ * (`toTarget`) is outlined as the pointer moves, `describe` says how it would be named.
102
+ */
103
+ pick(toTarget: (element: Element) => Element | null, describe: (element: Element) => string): Promise<{
104
+ element: Element;
105
+ x: number;
106
+ y: number;
107
+ } | undefined>;
108
+ /** Stops picking, if it does. */
109
+ cancelPick(): void;
110
+ }
@@ -0,0 +1 @@
1
+ import{nextFrame as t}from"./Input.js";import{IGNORED as e}from"./Targets.js";const i="http://www.w3.org/2000/svg";export class Overlay{constructor(t={}){this.options=t,this.shown=new Set,this.tracking=!1,this.keysTimer=0,this.quiet=!1,this.cursor={move:(t,e)=>{this.at={x:t,y:e},this.cursorNode.style.display=this.quiet?"none":"block",this.cursorNode.style.transform=`translate(${t}px, ${e}px)`},press:t=>this.cursorNode.classList.toggle("down",t),position:()=>this.at},this.host=document.createElement("protomaze-demo-engine"),this.host.setAttribute("data-demo-ignore",""),this.host.setAttribute("popover","manual"),this.host.style.cssText="position:fixed;inset:0;width:100vw;height:100vh;max-width:none;max-height:none;margin:0;padding:0;border:0;background:transparent;overflow:visible;pointer-events:none;z-index:2147483647;display:block;color-scheme:normal;",this.root=this.host.attachShadow({mode:"open"}),this.addStyles("\n:host { all: initial; }\n.layer { position: fixed; inset: 0; pointer-events: none; overflow: hidden; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; }\n.fade { transition: opacity 250ms ease; }\n.gone { opacity: 0 !important; }\n.cursor { position: fixed; left: 0; top: 0; width: 0; height: 0; z-index: 30; display: none; will-change: transform; }\n.cursor svg { position: absolute; left: -2px; top: -1px; filter: drop-shadow(0 1px 2px rgba(0,0,0,.45)); }\n.cursor .press { position: absolute; left: -20px; top: -20px; width: 40px; height: 40px; border-radius: 50%;\n background: var(--accent); opacity: 0; transform: scale(.3); transition: transform 160ms ease, opacity 160ms ease; }\n.cursor.down .press { opacity: .45; transform: scale(1); }\n.subtitle { position: fixed; left: 50%; transform: translateX(-50%); z-index: 20; max-width: min(900px, 84vw); padding: 8px 18px;\n background: rgba(0,0,0,.78); color: #fff; line-height: 1.35; text-align: center; border-radius: 6px; white-space: pre-wrap; }\n.keys { position: fixed; left: 50%; transform: translateX(-50%); z-index: 21; display: flex; gap: 6px; align-items: center; color: #fff; font-size: 15px; }\n.keys kbd { font: 600 15px system-ui, sans-serif; padding: 5px 10px; border-radius: 6px; background: rgba(30,30,30,.92);\n border: 1px solid rgba(255,255,255,.25); box-shadow: 0 2px 0 rgba(255,255,255,.15), 0 4px 12px rgba(0,0,0,.4); }\n.shade { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 1; }\n.ring { position: fixed; z-index: 3; border: 3px solid var(--accent); border-radius: 8px; box-sizing: border-box;\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 24px color-mix(in srgb, var(--accent) 60%, transparent);\n animation: pulse 1.6s ease-in-out infinite; }\n.ring.circle { border-radius: 50%; }\n@keyframes pulse { 50% { box-shadow: 0 0 0 9px color-mix(in srgb, var(--accent) 12%, transparent), 0 0 32px color-mix(in srgb, var(--accent) 70%, transparent); } }\n.blur { position: fixed; z-index: 2; backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); background: rgba(128,128,128,.15); border-radius: 4px; }\n.arrow { position: fixed; z-index: 4; overflow: visible; left: 0; top: 0; width: 1px; height: 1px; }\n.arrow path { fill: none; stroke: var(--accent); stroke-width: 5; stroke-linecap: round; stroke-linejoin: round; filter: drop-shadow(0 2px 3px rgba(0,0,0,.5)); }\n.arrow g { animation: nudge 1.2s ease-in-out infinite; }\n@keyframes nudge { 50% { transform: translate(var(--nx), var(--ny)); } }\n.note { position: fixed; z-index: 5; max-width: 320px; padding: 10px 14px; border-radius: 10px; background: #fff; color: #111;\n font-size: 16px; line-height: 1.4; box-shadow: 0 8px 28px rgba(0,0,0,.35); border-top: 4px solid var(--accent); white-space: pre-wrap; }\n.label { position: fixed; z-index: 5; padding: 4px 10px; border-radius: 6px; background: var(--accent); color: #111; font: 600 14px system-ui, sans-serif;\n white-space: nowrap; box-shadow: 0 4px 14px rgba(0,0,0,.35); }\n.card { position: fixed; inset: 0; z-index: 10; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px;\n background: radial-gradient(circle at 30% 20%, rgba(40,40,60,.86), rgba(5,5,12,.94)); color: #fff; text-align: center; padding: 10vh 10vw;\n backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); }\n.card h1 { margin: 0; font-size: clamp(28px, 5vw, 64px); font-weight: 700; letter-spacing: -.01em; }\n.card p { margin: 0; font-size: clamp(16px, 2vw, 26px); opacity: .85; max-width: 900px; white-space: pre-wrap; }\n.card .bar { width: 80px; height: 5px; border-radius: 3px; background: var(--accent); }\n.pick { position: fixed; z-index: 40; border: 2px dashed var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); border-radius: 4px; }\n.pick-label { position: fixed; z-index: 41; padding: 3px 8px; border-radius: 4px; background: #111; color: #fff; font: 12px ui-monospace, monospace; max-width: 60vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.ui { position: fixed; inset: 0; pointer-events: none; z-index: 50; }\n"),this.layer=this.node("div","layer"),this.layer.style.setProperty("--accent",t.accent??"#ffb300"),this.root.append(this.layer),this.shade=document.createElementNS(i,"svg"),this.shade.classList.add("shade","fade","gone"),this.layer.append(this.shade),this.cursorNode=this.node("div","cursor"),this.cursorNode.innerHTML='<div class="press"></div><svg width="24" height="32" viewBox="0 0 22 30"><path d="M1 1 L1 24 L7 18 L11 28 L15 26 L11 17 L19 17 Z" fill="#fff" stroke="#000" stroke-width="1.5" stroke-linejoin="round"/></svg>',this.subtitleNode=this.node("div","subtitle fade gone"),this.subtitleNode.style.bottom=t.subtitleBottom??"48px",this.subtitleNode.style.fontSize=`${t.subtitleSize??24}px`,this.keysNode=this.node("div","keys fade gone"),this.ui=this.node("div","ui"),this.layer.append(this.cursorNode,this.subtitleNode,this.keysNode,this.ui)}addStyles(t){const e=document.createElement("style");e.textContent=t,this.root.append(e)}mount(){this.host.isConnected||(document.documentElement.append(this.host),this.raise())}unmount(){this.clear(),this.host.remove()}raise(){const t=this.host;if(t.showPopover&&t.isConnected)try{t.matches(":popover-open")&&t.hidePopover(),t.showPopover()}catch{}}setOptions(t){Object.assign(this.options,t),t.accent&&this.layer.style.setProperty("--accent",t.accent),t.subtitleBottom&&(this.subtitleNode.style.bottom=t.subtitleBottom),t.subtitleSize&&(this.subtitleNode.style.fontSize=`${t.subtitleSize}px`)}node(t,e){const i=document.createElement(t);return i.className=e,i}hideCursor(){this.cursorNode.style.display="none",this.at=void 0}subtitle(t){t&&(this.subtitleNode.textContent=t),this.subtitleNode.classList.toggle("gone",!t),this.keysNode.style.bottom=`calc(${this.options.subtitleBottom??"48px"} + ${t?3.5*(this.options.subtitleSize??24):0}px)`}keys(t){this.keysNode.replaceChildren(...t.split(/\+(?!$)/).flatMap((t,e)=>{const i=document.createElement("kbd");return i.textContent=o[t]??t,e?[document.createTextNode("+"),i]:[i]})),this.keysNode.style.bottom=`calc(${this.options.subtitleBottom??"48px"} + ${this.subtitleNode.classList.contains("gone")?0:3.5*(this.options.subtitleSize??24)}px)`,this.keysNode.classList.remove("gone"),window.clearTimeout(this.keysTimer),this.keysTimer=window.setTimeout(()=>this.keysNode.classList.add("gone"),1400)}show(t){const e=this.make(t);return this.shown.add(e),e.update(),e.node.getBoundingClientRect(),e.node.classList.remove("gone"),this.track(),()=>{this.shown.delete(e)&&(e.node.classList.add("gone"),e.remove(),"spotlight"===t.kind&&this.updateShade())}}clear(){[...this.shown].forEach(t=>{this.shown.delete(t),t.node.classList.add("gone"),t.remove()}),this.updateShade()}get effects(){return[...this.shown].map(t=>t.effect)}async track(){if(!this.tracking){for(this.tracking=!0;this.shown.size>0;)this.shown.forEach(t=>t.update()),this.updateShade(),await t();this.updateShade(),this.tracking=!1}}updateShade(){const t=[...this.shown].filter(t=>"spotlight"===t.effect.kind).map(t=>{const e=t.effect,i=r(e.element(),e.padding??8);return i&&`<rect x="${i.left}" y="${i.top}" width="${i.width}" height="${i.height}" rx="10" fill="black"/>`}),e=t.length>0;if(this.shade.classList.toggle("gone",!e),!e)return;const[i,o]=[innerWidth,innerHeight];this.shade.setAttribute("viewBox",`0 0 ${i} ${o}`),this.shade.innerHTML=`<defs><mask id="holes"><rect width="${i}" height="${o}" fill="white"/>${t.filter(Boolean).join("")}</mask></defs><rect width="${i}" height="${o}" fill="rgba(0,0,0,0.62)" mask="url(#holes)"/>`}make(t){const e=(t,e)=>setTimeout(()=>{t.remove(),e?.()},260);switch(t.kind){case"spotlight":{const i=t.text?this.node("div","note fade gone"):this.node("div","fade gone");return t.text&&(i.textContent=t.text),this.layer.append(i),{effect:t,node:i,update:()=>t.text&&d(i,r(t.element(),(t.padding??8)+12)),remove:()=>e(i)}}case"ring":{const i=this.node("div","ring fade gone"+("circle"===t.shape?" circle":""));t.color&&i.style.setProperty("--accent",t.color);const o=t.text?this.node("div","label"):void 0;return o&&(o.textContent=t.text,t.color&&(o.style.background=t.color),i.append(o),o.style.position="absolute",o.style.left="-3px",o.style.bottom="calc(100% + 8px)"),this.layer.append(i),{effect:t,node:i,update:()=>{const e=t.padding??6,o=r(t.element(),e);if(i.style.visibility=o?"visible":"hidden",o)if("circle"===t.shape){const t=Math.max(o.width,o.height);Object.assign(i.style,n({left:o.left+o.width/2-t/2,top:o.top+o.height/2-t/2,width:t,height:t}))}else Object.assign(i.style,n(o))},remove:()=>e(i)}}case"arrow":{const o=document.createElementNS(i,"svg");o.classList.add("arrow","fade","gone"),t.color&&o.style.setProperty("--accent",t.color),o.innerHTML="<g><path/></g>";const d=t.text?this.node("div","label fade gone"):void 0;return d&&(d.textContent=t.text,t.color&&(d.style.background=t.color),this.layer.append(d),d.getBoundingClientRect(),d.classList.remove("gone")),this.layer.append(o),{effect:t,node:o,update:()=>{const e=r(t.element(),6);if(o.style.visibility=e?"visible":"hidden",d&&(d.style.visibility=o.style.visibility),!e)return;const i=t.from??a(e),[l,h]={top:[0,-1],bottom:[0,1],left:[-1,0],right:[1,0]}[i],c=e.left+e.width/2+l*e.width/2,p=e.top+e.height/2+h*e.height/2,f=c+90*l,g=p+90*h,u=16,[m,x]=[c+l*u-h*u*.7,p+h*u-l*u*.7],[b,y]=[c+l*u+h*u*.7,p+h*u+l*u*.7];if(o.querySelector("path").setAttribute("d",`M${f},${g} L${c},${p} M${m},${x} L${c},${p} L${b},${y}`),o.style.setProperty("--nx",10*-l+"px"),o.style.setProperty("--ny",10*-h+"px"),d){const t=d.getBoundingClientRect(),e=f+(0===l?-t.width/2:l>0?6:-t.width-6),i=g+(0===h?-t.height/2:h>0?6:-t.height-6);Object.assign(d.style,n({left:s(e,4,innerWidth-t.width-4),top:s(i,4,innerHeight-t.height-4)}))}},remove:()=>{e(o),d&&(d.classList.add("gone"),e(d))}}}case"callout":{const i=this.node("div","note fade gone");return i.textContent=t.text,this.layer.append(i),{effect:t,node:i,update:()=>{if(t.element){const e=r(t.element(),12);i.style.visibility=e?"visible":"hidden",d(i,e,t.side)}else{const e=t.corner??"top-right";i.style.top=e.startsWith("top")?"24px":"",i.style.bottom=e.startsWith("bottom")?"24px":"",i.style.left=e.endsWith("left")?"24px":"",i.style.right=e.endsWith("right")?"24px":""}},remove:()=>e(i)}}case"blur":{const i=this.node("div","blur fade gone");return this.layer.append(i),{effect:t,node:i,update:()=>{const e=r(t.element(),2);i.style.visibility=e?"visible":"hidden",e&&Object.assign(i.style,n(e))},remove:()=>e(i)}}case"card":{const i=this.node("div","card fade gone"),o=document.createElement("h1");o.textContent=t.title;const n=this.node("div","bar");if(i.append(o,n),t.text){const e=document.createElement("p");e.textContent=t.text,i.append(e)}return this.layer.append(i),{effect:t,node:i,update:()=>{},remove:()=>e(i)}}case"zoom":{const e=function(t,e,i){if(!t)return()=>{};const o=t.getBoundingClientRect(),n={x:innerWidth/(2*e),y:innerHeight/(2*e)},r={x:s(o.left+o.width/2,n.x,innerWidth-n.x),y:s(o.top+o.height/2,n.y,innerHeight-n.y)},a=Array.from(document.body.children).filter(t=>t instanceof HTMLElement&&t!==i&&!["SCRIPT","STYLE","LINK","TEMPLATE"].includes(t.tagName)),d=a.map(t=>({child:t,transform:t.style.transform,origin:t.style.transformOrigin,transition:t.style.transition})),l=document.documentElement,h=l.style.overflow;return l.style.overflow="clip",a.forEach(t=>{const i=t.getBoundingClientRect();t.style.transition="transform 700ms cubic-bezier(.4,0,.2,1)",t.style.transformOrigin=`${r.x-i.left}px ${r.y-i.top}px`,t.style.transform=`translate(${innerWidth/2-r.x}px, ${innerHeight/2-r.y}px) scale(${e})`}),()=>{a.forEach(t=>t.style.transform=d.find(e=>e.child===t).transform||"none"),setTimeout(()=>{d.forEach(({child:t,transform:e,origin:i,transition:o})=>{t.style.transform=e,t.style.transformOrigin=i,t.style.transition=o}),l.style.overflow=h},720)}}(t.element(),t.scale??1.8,this.host),i=this.node("div","");return{effect:t,node:i,update:()=>{},remove:e}}}}flash(t,e){const i=this.show({kind:"ring",element:()=>t,text:e});setTimeout(i,1500)}pick(t,i){return this.picking?.(),new Promise(o=>{const r=this.node("div","pick"),a=this.node("div","pick-label");r.style.display=a.style.display="none",this.layer.append(r,a);let d=null;const l=t=>t.composedPath().includes(this.host),h=(i,o)=>{const n=document.elementsFromPoint(i,o).find(t=>t!==this.host&&!t.closest(e));return n?t(n):null},c=t=>{if(l(t))return;if(d=h(t.clientX,t.clientY),r.style.display=a.style.display=d?"block":"none",!d)return;const e=d.getBoundingClientRect();Object.assign(r.style,n({left:e.left-2,top:e.top-2,width:e.width+4,height:e.height+4})),a.textContent=i(d),Object.assign(a.style,n({left:s(e.left,4,innerWidth-300),top:e.top>28?e.top-26:e.bottom+6}))},p=t=>{l(t)||(t.preventDefault(),t.stopImmediatePropagation())},f=t=>{if(l(t))return;p(t);const e=h(t.clientX,t.clientY);m(e?{element:e,x:t.clientX,y:t.clientY}:void 0)},g=t=>{"Escape"===t.key&&(p(t),m(void 0))},u=["pointerdown","mousedown","pointerup","mouseup","dblclick","contextmenu"],m=t=>{window.removeEventListener("pointermove",c,!0),window.removeEventListener("click",f,!0),window.removeEventListener("keydown",g,!0),u.forEach(t=>window.removeEventListener(t,p,!0)),document.documentElement.style.cursor="",r.remove(),a.remove(),this.picking=void 0,o(t)};window.addEventListener("pointermove",c,!0),window.addEventListener("click",f,!0),window.addEventListener("keydown",g,!0),u.forEach(t=>window.addEventListener(t,p,!0)),document.documentElement.style.cursor="crosshair",this.picking=()=>m(void 0)})}cancelPick(){this.picking?.()}}const o={Control:"Ctrl",Meta:"⌘",ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",Escape:"Esc",Enter:"↵ Enter"," ":"Space"};function n(t){const e={};return Object.entries(t).forEach(([t,i])=>e[t]=`${Math.round(i)}px`),e}function s(t,e,i){return Math.max(e,Math.min(i,t))}function r(t,e){if(!t?.isConnected)return;const i=t.getBoundingClientRect();return 0!==i.width||0!==i.height?{left:i.left-e,top:i.top-e,width:i.width+2*e,height:i.height+2*e}:void 0}function a(t){return[["bottom",innerHeight-t.top-t.height],["top",t.top],["right",innerWidth-t.left-t.width],["left",t.left]].sort((t,e)=>e[1]-t[1])[0][0]}function d(t,e,i){if(!e)return;const o=t.getBoundingClientRect(),r=i??(innerHeight-e.top-e.height>o.height+8?"bottom":e.top>o.height+8?"top":a(e)),d=e.left+e.width/2-o.width/2,l=e.top+e.height/2-o.height/2,h={bottom:{left:d,top:e.top+e.height},top:{left:d,top:e.top-o.height},right:{left:e.left+e.width,top:l},left:{left:e.left-o.width,top:l}}[r];Object.assign(t.style,n({left:s(h.left,8,innerWidth-o.width-8),top:s(h.top,8,innerHeight-o.height-8)}))}
@@ -0,0 +1,85 @@
1
+ import type { DemoTarget, Fraction } from '../model/Demo';
2
+ /** Inside these, nothing is recorded, found or listed: the engine's own UI, the app's dev tools. */
3
+ export declare const IGNORED = "[data-demo-ignore]";
4
+ /**
5
+ * The app's texts back to its locale keys, and keys to texts in the page's language: a target
6
+ * named by key is found in every language. See `dictionaryLabels`.
7
+ */
8
+ export type Labels = {
9
+ keyOf(text: string): string | undefined;
10
+ textOf(key: string): string | undefined;
11
+ };
12
+ export type TargetsOptions = {
13
+ labels?: Labels;
14
+ /** More of what a press lands on: '.MuiSlider-root'. */
15
+ interactive?: string[];
16
+ /** Attributes naming an element, after `data-demo`, its text, `aria-label` and `title`. */
17
+ labelAttributes?: string[];
18
+ /** Classes worth keeping in a target's css: /^Mui\w+-root$/. */
19
+ stableClass?: RegExp;
20
+ };
21
+ /** Digits stand for any, runs of white space for one, and case does not count. */
22
+ export declare function normal(text: string): string;
23
+ /**
24
+ * Labels from the app's own dictionary - its locale file, nested objects of strings - in the page's
25
+ * language: keys whose text is unambiguous. `dictionary` is read again when the language changes.
26
+ */
27
+ export declare function dictionaryLabels(dictionary: () => object, translate?: (key: string) => string | undefined): Labels;
28
+ /** An element as it is listed for whoever builds a demo: an AI, the editor. */
29
+ export type Listed = {
30
+ target: DemoTarget;
31
+ label: string;
32
+ tag: string;
33
+ role?: string;
34
+ /** checked, selected, expanded, disabled, its value. */
35
+ state?: string;
36
+ box: {
37
+ x: number;
38
+ y: number;
39
+ width: number;
40
+ height: number;
41
+ };
42
+ };
43
+ /** Finds and names what demos act on, as a person would point at it. */
44
+ export declare class Targets {
45
+ private options;
46
+ private interactive;
47
+ private attributes;
48
+ constructor(options?: TargetsOptions);
49
+ /**
50
+ * How a person would name it: what it is named for demos, shows, says it is, the icon it is,
51
+ * or - a switch, a field that says nothing itself - the text of the row it is in.
52
+ */
53
+ labelOf(element: Element): string;
54
+ private cssOf;
55
+ /** The label a target looks for, in the page's language. */
56
+ private labelIn;
57
+ /** What a pointer at `element` means: the nearest interactive element; none in the ignored parts. */
58
+ targetElement(element: Element | null): Element | null;
59
+ /** Every element the target names, in page order. */
60
+ matches(target: DemoTarget): Element[];
61
+ /**
62
+ * A target naming the element: by its locale key where its text has one, so it is found in every
63
+ * language; scoped to a named region (`data-demo`, an id) when that makes it the only one.
64
+ */
65
+ describe(element: Element): DemoTarget;
66
+ /** The element as it is now, once it shows; none after `timeout` ms. */
67
+ find(target: DemoTarget, timeout?: number, stopped?: () => boolean): Promise<Element | undefined>;
68
+ /**
69
+ * What can be acted on now, as targets: shown, not ignored, in page order; `within` an element
70
+ * or region (css), `query` in its label.
71
+ */
72
+ list({ within, query, limit }?: {
73
+ within?: string;
74
+ query?: string;
75
+ limit?: number;
76
+ }): Listed[];
77
+ }
78
+ export declare function shown(element: Element): boolean;
79
+ /** Where in it, as fractions of its box. */
80
+ export declare function fractionIn(element: Element, x: number, y: number): Fraction;
81
+ /** A point of an element, in the viewport: `at` fractions of its box, the middle by default. */
82
+ export declare function pointIn(element: Element, at?: Fraction): {
83
+ x: number;
84
+ y: number;
85
+ };
@@ -0,0 +1 @@
1
+ export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,o=new Map,i=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)i(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),o.set(s,n)}});return i(e,""),n={from:e,keys:r,texts:o}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),o=r?t.closest("label"):null,i=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(r?"":e.innerText?.trim())||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||o&&Array.from(o.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||"";if(i.trim())return normal(i);const s=t.querySelector("svg[data-testid], [data-icon]"),a=s?.getAttribute("data-testid")??s?.getAttribute("data-icon");if(a)return normal(a);let l=t.parentElement;for(let t=0;l&&t<4;t++,l=l.parentElement){const t=l.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,o=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(o?`.${CSS.escape(o)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const e=this.labelIn(t);let n;try{n=Array.from(document.querySelectorAll(t.css))}catch{return[]}return n.filter(t=>!t.closest(IGNORED)&&(void 0===e||this.labelOf(t)===e))}describe(t){const r=this.cssOf(t),o=this.labelOf(t),i=o&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(o):void 0,s=t=>({css:t,...i?{key:i}:o?{text:o}:{}}),a=s(r);if(this.matches(a).length<=1)return a;for(let o=t.parentElement;o&&o!==document.body;o=o.parentElement){const i=n(o);if(!i)continue;const a=s(`${i} ${r}`),l=this.matches(a);if(1===l.length)return a;if(l.length>1)return{...a,...e(l,t)}}return{...a,...e(this.matches(a),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const o=t?Array.from(document.querySelectorAll(t)):[document.body],i=new Set,s=[],a=e?normal(e):void 0;for(const t of o)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(i.has(e)||e.closest(IGNORED)||!shown(e))continue;const o=e.parentElement?.closest(this.interactive);if(o&&!o.closest(IGNORED)&&t.contains(o)&&this.labelOf(o)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;i.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...r(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function e(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function n(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;return!(e&&!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0}))&&t.getClientRects().length>0}function r(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),o=t=>Math.round(1e3*t)/1e3;return[o((e-r.left)/(r.width||1)),o((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Music beds the engine composes itself: a few bars of chords, bass and melody, rendered in the
3
+ * browser into a loop that joins seamlessly. Generated from code - no samples, no recordings, no
4
+ * licences - the same every time, nothing to download.
5
+ */
6
+ export type MusicTrack = 'calm' | 'lofi' | 'bright' | 'piano';
7
+ export declare const MUSIC_TRACKS: {
8
+ id: MusicTrack;
9
+ name: string;
10
+ hint: string;
11
+ }[];
12
+ /** The track as a loop, rendered once a session. */
13
+ export declare function renderMusic(track: MusicTrack): Promise<AudioBuffer>;
@@ -0,0 +1 @@
1
+ export const MUSIC_TRACKS=[{id:"calm",name:"Calm",hint:"Ambient pads and soft bells: tutorials, trainings, explanations"},{id:"lofi",name:"Lo-fi",hint:"Warm electric piano on a relaxed beat: tours, walkthroughs"},{id:"bright",name:"Bright",hint:"Upbeat plucks and a light pulse: marketing, launches, booths"},{id:"piano",name:"Piano",hint:"Gentle piano over a soft pad: pitches, stories"}];const e=44100,a=new Map;export function renderMusic(t){let o=a.get(t);return o||(o=async function(a){const t=h[a],o=60/t.bpm,c=4*t.bars*o,i=new OfflineAudioContext(2,Math.ceil((c+4)*e),e),r=i.createBuffer(1,e,e),l=n(101*a.length+3);r.getChannelData(0).forEach((e,a,t)=>t[a]=2*l()-1);const s=i.createBiquadFilter();s.type="lowpass",s.frequency.value=t.warmth??8e3;const u=i.createDynamicsCompressor();u.threshold.value=-20,u.ratio.value=3,u.attack.value=.02,u.release.value=.3,s.connect(u).connect(i.destination);const m=i.createGain();m.connect(s);const p=function(e,a){const t=n(7),o=Math.floor(a*e.sampleRate),c=e.createBuffer(2,o,e.sampleRate);for(let e=0;e<2;e++){const a=c.getChannelData(e);for(let e=0;e<o;e++)a[e]=(2*t()-1)*Math.pow(1-e/o,3.2)}const i=e.createConvolver();return i.buffer=c,i}(i,3),f=i.createGain();f.gain.value=.6,f.connect(p).connect(s),t.play({audio:i,dry:m,wet:f,noise:r,rand:l},o);const g=await i.startRendering(),T=Math.round(c*e),A=new AudioBuffer({numberOfChannels:2,length:T,sampleRate:e});let d=0;for(let e=0;e<2;e++){const a=g.getChannelData(e),t=A.getChannelData(e);for(let e=0;e<T;e++)t[e]=a[e]+(e+T<a.length?a[e+T]:0),d=Math.max(d,Math.abs(t[e]))}const y=d>0?.8/d:1;for(let e=0;e<2;e++){const a=A.getChannelData(e);for(let e=0;e<T;e++)a[e]*=y}return A}(t),o.catch(()=>a.delete(t)),a.set(t,o)),o}const t=e=>440*Math.pow(2,(e-69)/12);function n(e){return()=>{e=(e|=0)+1831565813|0;let a=Math.imul(e^e>>>15,1|e);return a=a+Math.imul(a^a>>>7,61|a)^a,((a^a>>>14)>>>0)/4294967296}}function o(e,a,t,n){const o=e.audio.createGain();if(o.gain.value=t,a.connect(o).connect(e.dry),n>0){const o=e.audio.createGain();o.gain.value=t*n,a.connect(o).connect(e.wet)}}function c(e,a,n,c,i=.045){const{audio:r}=e;a.forEach(a=>{const l=r.createBiquadFilter();l.type="lowpass",l.Q.value=.6,l.frequency.setValueAtTime(700,n),l.frequency.linearRampToValueAtTime(1500,n+.6*c),l.frequency.linearRampToValueAtTime(900,n+c+1.5);const s=r.createGain();s.gain.setValueAtTime(0,n),s.gain.linearRampToValueAtTime(1,n+1.4),s.gain.setValueAtTime(1,n+c),s.gain.linearRampToValueAtTime(0,n+c+1.8),[-7,7].forEach(e=>{const o=r.createOscillator();o.type="sawtooth",o.frequency.value=t(a),o.detune.value=e,o.connect(l),o.start(n),o.stop(n+c+2)}),l.connect(s),o(e,s,i,.7)})}function i(e,a,n,c,i=.16){const{audio:r}=e,l=r.createOscillator();l.type="sine",l.frequency.value=t(a);const s=r.createOscillator();s.type="triangle",s.frequency.value=t(a);const u=r.createGain();u.gain.value=.35,s.connect(u);const m=r.createGain();m.gain.setValueAtTime(0,n),m.gain.linearRampToValueAtTime(1,n+.04),m.gain.setTargetAtTime(.7,n+.05,.4),m.gain.setValueAtTime(.7,n+c),m.gain.linearRampToValueAtTime(0,n+c+.25),l.connect(m),u.connect(m),[l,s].forEach(e=>{e.start(n),e.stop(n+c+.3)}),o(e,m,i,.05)}function r(e,a,n,c=.035){const{audio:i}=e,r=i.createGain();r.gain.setValueAtTime(0,n),r.gain.linearRampToValueAtTime(1,n+.01),r.gain.exponentialRampToValueAtTime(.001,n+2.6),[[1,1],[3.01,.18],[5.4,.05]].forEach(([e,o])=>{const c=i.createOscillator();c.frequency.value=t(a)*e;const l=i.createGain();l.gain.value=o,c.connect(l).connect(r),c.start(n),c.stop(n+2.7)}),o(e,r,c,1.2)}function l(e,a,n,c,i=.05){const{audio:r}=e;a.forEach(a=>{const l=r.createOscillator();l.frequency.value=t(a);const s=r.createOscillator();s.frequency.value=1*t(a);const u=r.createGain();u.gain.setValueAtTime(1.2*t(a),n),u.gain.exponentialRampToValueAtTime(.05*t(a),n+.9),s.connect(u).connect(l.frequency);const m=r.createGain();m.gain.setValueAtTime(0,n),m.gain.linearRampToValueAtTime(1,n+.008),m.gain.setTargetAtTime(.35,n+.01,.6),m.gain.setValueAtTime(.35,n+c),m.gain.linearRampToValueAtTime(0,n+c+.4),l.connect(m),[l,s].forEach(e=>{e.start(n),e.stop(n+c+.5)}),o(e,m,i,.35)})}function s(e,a,n,c=.05){const{audio:i}=e,r=i.createBiquadFilter();r.type="lowpass",r.Q.value=2,r.frequency.setValueAtTime(4200,n),r.frequency.exponentialRampToValueAtTime(500,n+.3);const l=i.createGain();l.gain.setValueAtTime(0,n),l.gain.linearRampToValueAtTime(1,n+.004),l.gain.exponentialRampToValueAtTime(.001,n+.6),[["triangle",1],["square",.25]].forEach(([e,o])=>{const c=i.createOscillator();c.type=e,c.frequency.value=t(a);const l=i.createGain();l.gain.value=o,c.connect(l).connect(r),c.start(n),c.stop(n+.65)}),r.connect(l),o(e,l,c,.45)}function u(e,a,n,c=.06,i=2.4){const{audio:r}=e,l=r.createGain();l.gain.value=1,[[1,1,1],[2,.45,.6],[3,.18,.4],[4,.08,.3]].forEach(([e,o,c])=>{const s=r.createOscillator();s.frequency.value=t(a)*e;const u=r.createGain();u.gain.setValueAtTime(0,n),u.gain.linearRampToValueAtTime(o,n+.006),u.gain.exponentialRampToValueAtTime(8e-4,n+i*c),s.connect(u).connect(l),s.start(n),s.stop(n+i*c+.05)}),o(e,l,c,.5)}function m(e,a,t=.35){const{audio:n}=e,c=n.createOscillator();c.frequency.setValueAtTime(110,a),c.frequency.exponentialRampToValueAtTime(42,a+.12);const i=n.createGain();i.gain.setValueAtTime(1,a),i.gain.exponentialRampToValueAtTime(.001,a+.38),c.connect(i),c.start(a),c.stop(a+.4),o(e,i,t,0)}function p(e,a,t,n){const{audio:c}=e,i=c.createBufferSource();i.buffer=e.noise;const r=c.createBiquadFilter();r.type="hat"===t?"highpass":"bandpass",r.frequency.value="hat"===t?7500:1700,r.Q.value="hat"===t?.7:.9;const l=c.createGain(),s="hat"===t?.06:.2;l.gain.setValueAtTime(1,a),l.gain.exponentialRampToValueAtTime(.001,a+s),i.connect(r).connect(l),i.start(a,.5*e.rand(),s+.02),o(e,l,n,"hat"===t?.1:.3)}const f={Dmaj7:[62,66,69,73],Bm7:[59,62,66,69],Gmaj7:[55,59,62,66],Asus:[57,62,64,69],Gm9:[55,58,62,65,69],C9:[60,64,70,74],Fmaj9:[53,57,60,64,67],Dm9:[50,57,60,64,65],C:[60,64,67],G:[55,59,62,67],Am:[57,60,64,69],F:[53,57,60,65],Em:[52,55,59,64]},h={calm:{bpm:70,bars:8,warmth:5e3,play:(e,a)=>{const t=[74,76,78,81,83,86,88];[f.Dmaj7,f.Bm7,f.Gmaj7,f.Asus].forEach((n,o)=>{const l=8*o*a;c(e,n,l,8*a),i(e,n[0]-24,l,8*a,.12);for(let n=0;n<8;n+=2)e.rand()<.55&&r(e,t[Math.floor(e.rand()*t.length)],l+(n+(e.rand()<.5?0:1))*a)})}},lofi:{bpm:78,bars:8,warmth:3800,play:(e,a)=>{const t=[f.Gm9,f.C9,f.Fmaj9,f.Dm9],n=a/6;for(let o=0;o<8;o++){const c=t[o%4],r=4*o*a;l(e,c,r,1.6*a),l(e,c.slice(1),r+2.5*a+n,1.2*a,.035),i(e,c[0]-12,r,1.5*a),i(e,c[0]-12,r+2.5*a+n,1*a,.12),m(e,r,.3),m(e,r+2.5*a+n,.22),p(e,r+a,"snare",.09),p(e,r+3*a,"snare",.09);for(let t=0;t<8;t++)p(e,r+t/2*a+(t%2?n:0),"hat",t%2?.025:.035)}}},bright:{bpm:104,bars:8,warmth:9e3,play:(e,a)=>{const t=[f.C,f.G,f.Am,f.F],n=[0,1,2,3,2,1,2,3];for(let o=0;o<8;o++){const r=t[o%4],l=4*o*a,u=[...r.slice(0,3),r[0]+12].map(e=>e+12);n.forEach((t,n)=>s(e,u[t],l+n/2*a,n%2?.035:.05)),c(e,r,l,4*a,.018);for(let t=0;t<4;t++)m(e,l+t*a,.22),i(e,r[0]-12,l+(t+.5)*a,.35*a,.1),p(e,l+(t+.5)*a,"hat",.03);p(e,l+a,"snare",.07),p(e,l+3*a,"snare",.07)}}},piano:{bpm:66,bars:8,warmth:7e3,play:(e,a)=>{const t=[f.C,f.Em,f.Am,f.F];for(let n=0;n<8;n++){const o=t[n%4],i=4*n*a;u(e,o[0]-12,i,.07,4);[o[0],o[1],o[2],o[0]+12,o[2],o[1],o[2],o[1]].map(e=>e+12).forEach((t,n)=>u(e,t,i+n/2*a+.02*(e.rand()-.5),0===n?.055:.04)),c(e,o,i,4*a,.012),n%2==1&&e.rand()<.7&&r(e,o[2]+24,i+3*a,.02)}}}};
@@ -0,0 +1,27 @@
1
+ import type { Language } from '../model/Demo';
2
+ /**
3
+ * A demo's narration, made once and kept: `<id>.narration.zip`, checked in beside its
4
+ * `.demo.json`. Played before any voice is asked - no key, no tokens, no model to download -
5
+ * sentence by sentence: what changed since is made by the voice chosen, as ever.
6
+ */
7
+ export type NarrationPack = {
8
+ /** The sentence's audio, if the pack has it, as made. */
9
+ get(text: string, language: Language): PackedSentence | undefined;
10
+ count: number;
11
+ /** Bytes of audio. */
12
+ size: number;
13
+ };
14
+ export type PackedSentence = {
15
+ data: Uint8Array;
16
+ type: string;
17
+ voice: string;
18
+ };
19
+ /** A pack from its zip. */
20
+ export declare function readPack(buffer: ArrayBuffer): Promise<NarrationPack>;
21
+ /** The pack's zip, of these sentences. */
22
+ export declare function writePack(demo: string, sentences: (PackedSentence & {
23
+ language: Language;
24
+ text: string;
25
+ })[]): Blob;
26
+ /** 16-bit PCM WAV of the first channel: what the free voices make, as a file. */
27
+ export declare function toWav(buffer: AudioBuffer): Uint8Array;
package/speech/Pack.js ADDED
@@ -0,0 +1 @@
1
+ import{unzip as e,zip as t}from"../store/Zip.js";const n=(e,t)=>`${t}\n${e.trim()}`;export async function readPack(t){const a=await e(t),r=JSON.parse((new TextDecoder).decode(a.get("index.json")??new Uint8Array));if(1!==r.version||!Array.isArray(r.sentences))throw new Error("Not a narration pack");const i=new Map;let s=0;return r.sentences.forEach(e=>{const t=a.get(e.file);t&&(i.set(n(e.text,e.language),{data:t,type:e.type,voice:e.voice}),s+=t.length)}),{get:(e,t)=>i.get(n(e,t)),count:i.size,size:s}}export function writePack(e,n){const a={version:1,demo:e,made:(new Date).toISOString(),sentences:[]},r=[];return n.forEach((e,t)=>{const n=`${e.language}/${String(t+1).padStart(3,"0")}.${"audio/mpeg"===e.type?"mp3":"wav"}`;a.sentences.push({language:e.language,text:e.text.trim(),voice:e.voice,file:n,type:e.type}),r.push({name:n,data:e.data})}),t([{name:"index.json",data:(new TextEncoder).encode(JSON.stringify(a,null,2))},...r])}export function toWav(e){const t=e.getChannelData(0),n=new DataView(new ArrayBuffer(44+2*t.length)),a=(e,t)=>[...t].forEach((t,a)=>n.setUint8(e+a,t.charCodeAt(0)));return a(0,"RIFF"),n.setUint32(4,36+2*t.length,!0),a(8,"WAVEfmt "),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,1,!0),n.setUint32(24,e.sampleRate,!0),n.setUint32(28,2*e.sampleRate,!0),n.setUint16(32,2,!0),n.setUint16(34,16,!0),a(36,"data"),n.setUint32(40,2*t.length,!0),t.forEach((e,t)=>n.setInt16(44+2*t,32767*Math.max(-1,Math.min(1,e)),!0)),new Uint8Array(n.buffer)}
@@ -0,0 +1,127 @@
1
+ import type { Language } from '../model/Demo';
2
+ import { NarrationPack, PackedSentence } from './Pack';
3
+ /**
4
+ * The narration's voice. Free: neural voices in the page, no key and no server - Kokoro for
5
+ * English, Piper for some forty languages - downloaded once and kept by the browser. ElevenLabs:
6
+ * with one's own key, every sentence paid for once and kept. System: the browser's own voices,
7
+ * instant, but no video hears them. Off: subtitles only, timed to reading.
8
+ */
9
+ export type VoiceKind = 'free' | 'elevenlabs' | 'system' | 'off';
10
+ export type SpeechSettings = {
11
+ voice: VoiceKind;
12
+ /** A free voice per language: 'kokoro:af_heart', 'piper:de_DE-thorsten-medium'. */
13
+ free: Partial<Record<Language, string>>;
14
+ elevenlabs: {
15
+ key: string;
16
+ voice: string;
17
+ model: string;
18
+ };
19
+ /** A system voice per language, by its name. */
20
+ system: Partial<Record<Language, string>>;
21
+ /** Faster above 1, slower below. */
22
+ rate: number;
23
+ };
24
+ export declare const DEFAULT_SPEECH: SpeechSettings;
25
+ export declare const KOKORO_VOICES: {
26
+ id: string;
27
+ name: string;
28
+ }[];
29
+ export type SpeechState = {
30
+ loading?: number;
31
+ error?: string;
32
+ };
33
+ /** Plays what it is given: `done` when ended or stopped. */
34
+ export type Playing = {
35
+ done: Promise<void>;
36
+ stop: () => void;
37
+ };
38
+ /** Speaks narration, and routes it to the speakers and to the video being made (`soundtrack`). */
39
+ export declare class Speech {
40
+ readonly settings: () => SpeechSettings;
41
+ private changed;
42
+ state: SpeechState;
43
+ private audio;
44
+ private recorded;
45
+ private made;
46
+ private lengths;
47
+ private kokoro;
48
+ private piper;
49
+ private kokoroDevice;
50
+ private music;
51
+ private bed;
52
+ /** Sentences being said now: the music ducks under them. */
53
+ private speaking;
54
+ constructor(settings: () => SpeechSettings, changed: () => void);
55
+ private set;
56
+ private loading;
57
+ context(): AudioContext;
58
+ /** From a click: browsers play only what a person asked for. */
59
+ wake(): void;
60
+ /** Whether sound plays: never before a click in this window, which a resume waits for. */
61
+ audible(): Promise<boolean>;
62
+ /** What a video hears: the narration, and what else is connected to it (a microphone). */
63
+ soundtrack(): MediaStreamAudioDestinationNode;
64
+ /** The free voice for a language: chosen, else the default, else none. */
65
+ freeVoice(language: Language): string | undefined;
66
+ /** Who says it: what made audio is kept by. */
67
+ private keyOf;
68
+ /** Who says it now in `language`: 'kokoro:af_heart', 'elevenlabs:<voice>/<model>'; what a pack records. */
69
+ voiceName(language: Language): string;
70
+ private pack;
71
+ /** The demo's narration pack, played before any voice; none to have none. */
72
+ setPack(pack: NarrationPack | undefined): void;
73
+ /** The sentence from the pack, unless there is no voice at all. */
74
+ private packed;
75
+ /**
76
+ * The sentence's audio as a file, for a pack: the pack's own where it has it from the same voice,
77
+ * else made - ElevenLabs' as it came (kept in this browser, so not paid again), free voices' as WAV.
78
+ */
79
+ packable(text: string, language: Language): Promise<PackedSentence>;
80
+ /** Whether the voice makes audio a video hears. */
81
+ get recordable(): boolean;
82
+ /** A sentence's audio, made once a session - or from the pack; none for the system voice or none at all. */
83
+ make(text: string, language: Language): Promise<AudioBuffer> | undefined;
84
+ /** ms it takes to say, once made or said; else unknown. */
85
+ duration(text: string, language: Language): number | undefined;
86
+ /** Every sentence made ahead, so a video has no gaps; `progress` as they come in. */
87
+ prepare(texts: string[], language: Language, progress?: (done: number, total: number) => void): Promise<void>;
88
+ /**
89
+ * Says it: made audio, or the system voice. None for no voice at all, or when its audio is not
90
+ * made within `within` ms - a voice still downloading - so what plays goes on without it.
91
+ */
92
+ say(text: string, language: Language, within?: number): Promise<Playing | undefined>;
93
+ /** Plays it, to the speakers and the soundtrack; the music ducks under it. */
94
+ play(buffer: AudioBuffer): Playing;
95
+ /** The music played under demos (an audio file the browser decodes), `volume` 0 to 1; none to have none. */
96
+ setMusic(file: Blob | undefined, volume?: number): Promise<void>;
97
+ /** The music as audio already made: a composed track (`renderMusic`). */
98
+ setMusicBuffer(buffer: AudioBuffer | undefined, volume?: number): void;
99
+ setMusicVolume(volume: number): void;
100
+ get hasMusic(): boolean;
101
+ /** The music fades in, looped, to the speakers and the soundtrack. */
102
+ startMusic(): void;
103
+ /** The music fades out over `fade` seconds. */
104
+ stopMusic(fade?: number): void;
105
+ private musicLevel;
106
+ private duck;
107
+ pause(): void;
108
+ resume(): void;
109
+ private fromWorker;
110
+ /** Where ElevenLabs is asked, and what its answer is kept as: paid once, by voice, model, speed and text. */
111
+ private elevenLabsUrls;
112
+ private fromElevenLabs;
113
+ private fromSystem;
114
+ }
115
+ /** A Piper voice's model, without its extension: 'de_DE-thorsten-medium' → …/de/de_DE/thorsten/medium/de_DE-thorsten-medium. */
116
+ export declare function piperUrl(id: string): string;
117
+ /** Every Piper voice there is, from its catalogue: language code ('de_DE'), and a name to show. */
118
+ export declare function piperVoices(): Promise<{
119
+ id: string;
120
+ language: string;
121
+ name: string;
122
+ }[]>;
123
+ /** The ElevenLabs account's voices. */
124
+ export declare function elevenLabsVoices(key: string): Promise<{
125
+ id: string;
126
+ name: string;
127
+ }[]>;
@@ -0,0 +1 @@
1
+ import{toWav as e}from"./Pack.js";import{CACHE as t,hasGpu as s,KOKORO_JS as i,KOKORO_MODEL as a,KOKORO_WORKER as n,ORT as o,PHONEMIZE as r,PIPER_VOICES as c,PIPER_WORKER as h,workerOf as l}from"./Workers.js";export const DEFAULT_SPEECH={voice:"free",free:{},elevenlabs:{key:"",voice:"JBFqnCBsd6RMkjVDRZzb",model:"eleven_multilingual_v2"},system:{},rate:1};const u={en:"kokoro:af_heart",de:"piper:de_DE-thorsten-medium",nl:"piper:nl_NL-mls-medium",fr:"piper:fr_FR-siwis-medium",es:"piper:es_ES-davefx-medium",it:"piper:it_IT-paola-medium"};export const KOKORO_VOICES=[{id:"af_heart",name:"Heart (US, f)"},{id:"af_bella",name:"Bella (US, f)"},{id:"af_nicole",name:"Nicole (US, f)"},{id:"af_sarah",name:"Sarah (US, f)"},{id:"am_michael",name:"Michael (US, m)"},{id:"am_fenrir",name:"Fenrir (US, m)"},{id:"am_puck",name:"Puck (US, m)"},{id:"bf_emma",name:"Emma (UK, f)"},{id:"bf_isabella",name:"Isabella (UK, f)"},{id:"bm_george",name:"George (UK, m)"},{id:"bm_fable",name:"Fable (UK, m)"}];export class Speech{constructor(e,t){this.settings=e,this.changed=t,this.state={},this.made=new Map,this.lengths=new Map,this.kokoro=l(n,"module",(e,t)=>this.loading(e,t)),this.piper=l(h,"classic",(e,t)=>this.loading(e,t)),this.speaking=0}set(e){this.state=e,this.changed()}loading(e,t){this.set(e<t?{loading:e/t}:{})}context(){return this.audio??(this.audio=new AudioContext),this.audio}wake(){this.context().resume()}async audible(){return await Promise.race([this.context().resume(),new Promise(e=>setTimeout(e,300))]),"running"===this.context().state}soundtrack(){return this.recorded??(this.recorded=this.context().createMediaStreamDestination()),this.recorded}freeVoice(e){const t=e.toLowerCase().split(/[-_]/)[0];return this.settings().free[e]??this.settings().free[t]??u[t]}keyOf(e,t){if(this.packed(e,t))return["pack",t,e].join("|");const s=this.settings();return[s.voice,this.voiceName(t),s.rate,t,e].join("|")}voiceName(e){const t=this.settings();return"free"===t.voice?this.freeVoice(e)??"free":"elevenlabs"===t.voice?`elevenlabs:${t.elevenlabs.voice}/${t.elevenlabs.model}`:"system"===t.voice?`system:${t.system[e]??""}`:"off"}setPack(e){this.pack=e}packed(e,t){return"off"===this.settings().voice?void 0:this.pack?.get(e,t)}async packable(s,i){const a=this.voiceName(i),n=this.pack?.get(s,i);if(n&&n.voice===a)return n;const o=this.settings();if("free"!==o.voice&&"elevenlabs"!==o.voice)throw new Error("A pack keeps made audio: choose the free voices or ElevenLabs");const r=this.pack;this.pack=void 0;try{const n=await this.make(s,i);if("elevenlabs"===o.voice){const e=await(await caches.open(t)).match(this.elevenLabsUrls(s).keptAs);if(e)return{data:new Uint8Array(await e.arrayBuffer()),type:"audio/mpeg",voice:a}}return{data:e(n),type:"audio/wav",voice:a}}finally{this.pack=r}}get recordable(){const e=this.settings().voice;return"free"===e||"elevenlabs"===e}make(e,t){const s=this.packed(e,t);if(!s&&!this.recordable)return;const i=this.keyOf(e,t);let a=this.made.get(i);return a||(a=s?this.context().decodeAudioData(s.data.slice().buffer):"elevenlabs"===this.settings().voice?this.fromElevenLabs(e):this.fromWorker(e,t),a.then(e=>this.lengths.set(i,1e3*e.duration),e=>{this.made.delete(i),this.set({error:e.message})}),this.made.set(i,a)),a}duration(e,t){if("off"!==this.settings().voice)return this.lengths.get(this.keyOf(e,t))}async prepare(e,t,s=()=>{}){let i=0;await Promise.all(e.map(a=>this.make(a,t)?.catch(()=>{}).then(()=>s(++i,e.length))))}async say(e,t,s=1/0){const i=this.settings().voice;if("off"===i)return;if("system"===i&&!this.packed(e,t))return this.fromSystem(e,t);const a=this.make(e,t)?.catch(()=>{}),n=await(s===1/0?a:Promise.race([a,new Promise(e=>setTimeout(e,s))]));return n&&await this.audible()?this.play(n):void 0}play(e){const t=this.context(),s=t.createBufferSource();s.buffer=e,s.connect(t.destination),this.recorded&&s.connect(this.recorded),this.duck(1);const i=new Promise(e=>s.onended=()=>{this.duck(-1),e()});return s.start(),{done:i,stop:()=>{try{s.stop()}catch{}}}}async setMusic(e,t=.18){this.setMusicBuffer(e?await this.context().decodeAudioData(await e.arrayBuffer()):void 0,t)}setMusicBuffer(e,t=.18){this.stopMusic(0),this.music=e?{buffer:e,volume:t}:void 0}setMusicVolume(e){this.music&&(this.music.volume=e),this.duck(0)}get hasMusic(){return Boolean(this.music)}startMusic(){if(!this.music||this.bed)return;const e=this.context(),t=e.createBufferSource();t.buffer=this.music.buffer,t.loop=!0;const s=e.createGain();s.gain.setValueAtTime(0,e.currentTime),s.gain.linearRampToValueAtTime(this.musicLevel(),e.currentTime+1.5),t.connect(s),s.connect(e.destination),s.connect(this.soundtrack()),t.start(),this.bed={source:t,gain:s}}stopMusic(e=1.5){const t=this.bed;if(!t||!this.audio)return;this.bed=void 0;const s=this.audio.currentTime;t.gain.gain.cancelScheduledValues(s),t.gain.gain.setValueAtTime(t.gain.gain.value,s),t.gain.gain.linearRampToValueAtTime(0,s+e),t.source.stop(s+e+.05)}musicLevel(){return(this.music?.volume??0)*(this.speaking>0?.35:1)}duck(e){if(this.speaking=Math.max(0,this.speaking+e),!this.bed||!this.audio)return;const t=this.audio.currentTime;this.bed.gain.gain.cancelScheduledValues(t),this.bed.gain.gain.setValueAtTime(this.bed.gain.gain.value,t),this.bed.gain.gain.linearRampToValueAtTime(this.musicLevel(),t+(e>0?.25:.8))}pause(){this.audio?.suspend(),"system"===this.settings().voice&&speechSynthesis.pause()}resume(){this.audio?.resume(),"system"===this.settings().voice&&speechSynthesis.resume()}async fromWorker(e,t){const n=this.freeVoice(t);if(!n)throw new Error(`No free voice for "${t}": choose one, or another voice`);const[c,h]=n.split(":"),l=this.settings().rate||1;let u;if("kokoro"===c){this.kokoroDevice??(this.kokoroDevice=s().then(e=>e?"webgpu":"wasm"));const t=await this.kokoroDevice;u=await this.kokoro({text:e,voice:h,speed:l,init:{url:i,model:a,device:t}})}else u=await this.piper({text:e,model:piperUrl(h),speed:l,init:{ort:o,phonemize:r}});const m=this.context().createBuffer(1,u.samples.length,u.rate);return m.copyToChannel(u.samples,0),m}elevenLabsUrls(e){const{voice:t,model:s}=this.settings().elevenlabs,i=`https://api.elevenlabs.io/v1/text-to-speech/${t}?output_format=mp3_44100_128`;return{url:i,keptAs:`${i}&model=${s}&speed=${this.settings().rate||1}&text=${encodeURIComponent(e)}`}}async fromElevenLabs(e){const{key:s,model:i}=this.settings().elevenlabs;if(!s)throw new Error("No ElevenLabs key");const a=this.settings().rate||1,{url:n,keptAs:o}=this.elevenLabsUrls(e),r=await caches.open(t);let c=await r.match(o);if(!c){if(c=await fetch(n,{method:"POST",headers:{"xi-api-key":s,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:i,...1!==a?{voice_settings:{speed:Math.min(1.2,Math.max(.7,a))}}:{}})}),!c.ok)throw new Error(`ElevenLabs: ${c.status} ${await c.text()}`);await r.put(o,c.clone())}return this.context().decodeAudioData(await c.arrayBuffer())}fromSystem(e,t){const s=new SpeechSynthesisUtterance(e);s.lang=t,s.rate=this.settings().rate||1;const i=this.settings().system[t],a=speechSynthesis.getVoices().find(e=>e.name===i)??speechSynthesis.getVoices().find(e=>e.lang.toLowerCase().startsWith(t.toLowerCase()));a&&(s.voice=a);const n=this.keyOf(e,t),o=performance.now();this.duck(1);const r=new Promise(e=>{s.onend=()=>{this.lengths.set(n,performance.now()-o),this.duck(-1),e()},s.onerror=()=>{this.duck(-1),e()}});return speechSynthesis.speak(s),{done:r,stop:()=>speechSynthesis.cancel()}}}export function piperUrl(e){const t=e.split("-"),s=t[0],i=t[t.length-1],a=t.slice(1,-1).join("-");return`${c}${s.split("_")[0]}/${s}/${a}/${i}/${e}`}let m;export function piperVoices(){return m??(m=fetch(`${c}voices.json`).then(e=>e.json()).then(e=>Object.values(e).map(e=>({id:e.key,language:e.language.code,name:`${e.name} (${e.language.name_english}, ${e.language.country_english}, ${e.quality})`})).sort((e,t)=>e.id.localeCompare(t.id)))),m.catch(()=>m=void 0),m}export async function elevenLabsVoices(e){const t=await fetch("https://api.elevenlabs.io/v1/voices",{headers:{"xi-api-key":e}});if(!t.ok)throw new Error(`ElevenLabs: ${t.status}`);const{voices:s}=await t.json();return s.map(e=>({id:e.voice_id,name:e.name}))}
@@ -0,0 +1,25 @@
1
+ import type { Language } from '../model/Demo';
2
+ import type { Subtitle } from '../model/Subtitles';
3
+ /**
4
+ * Speech to text, timed: what a person said while recording, as subtitles and narration. Whisper:
5
+ * in the browser, private, downloaded once. ElevenLabs Scribe: with one's own key.
6
+ */
7
+ export type Transcriber = 'whisper' | 'elevenlabs';
8
+ export type TranscribeOptions = {
9
+ language?: Language;
10
+ with?: Transcriber;
11
+ /** Whisper's size: tiny is quick, small is better. Default base. */
12
+ model?: 'tiny' | 'base' | 'small';
13
+ elevenLabsKey?: string;
14
+ /** Of downloading the model, 0 to 1. */
15
+ progress?: (fraction: number) => void;
16
+ };
17
+ /** Timed segments of what is said in `audio` (any format the browser decodes), ms from its start. */
18
+ export declare function transcribe(audio: Blob, options?: TranscribeOptions): Promise<Subtitle[]>;
19
+ /** Words, or loose pieces, joined into sentences: one subtitle each. */
20
+ export declare function toSentences(pieces: Subtitle[]): Subtitle[];
21
+ /**
22
+ * Narration for steps from what was said: each segment to the step it was said in. `starts`: ms
23
+ * each step began, from the same start as the segments.
24
+ */
25
+ export declare function narrationFor(starts: number[], said: Subtitle[]): string[];
@@ -0,0 +1 @@
1
+ import{sentences as e}from"../model/Demo.js";import{hasGpu as t,TRANSFORMERS as n,WHISPER_WORKER as a,workerOf as r}from"./Workers.js";let o;const s=r(a,"module",(e,t)=>o?.(e/t));let i;export async function transcribe(e,a={}){if("elevenlabs"===a.with)return async function(e,t){if(!t.elevenLabsKey)throw new Error("No ElevenLabs key");const n=new FormData;n.append("file",e,"speech.webm"),n.append("model_id","scribe_v1"),t.language&&n.append("language_code",t.language.split(/[-_]/)[0]);const a=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":t.elevenLabsKey},body:n});if(!a.ok)throw new Error(`ElevenLabs: ${a.status} ${await a.text()}`);const{words:r}=await a.json();return toSentences(r.filter(e=>"audio_event"!==e.type).map(e=>({start:1e3*e.start,end:1e3*e.end,text:e.text})))}(e,a);const r=await async function(e){const t=new OfflineAudioContext(1,1,16e3),n=await t.decodeAudioData(await e.arrayBuffer()),a=Math.ceil(16e3*n.duration);if(0===a)return new Float32Array;const r=new OfflineAudioContext(1,a,16e3),o=r.createBufferSource();return o.buffer=n,o.connect(r.destination),o.start(),(await r.startRendering()).getChannelData(0)}(e);if(0===r.length)return[];o=a.progress,i??(i=t().then(e=>e?"webgpu":"wasm"));const c=await s({url:n,model:`onnx-community/whisper-${a.model??"base"}`,device:await i,language:a.language?.split(/[-_]/)[0],samples:r},[r.buffer]),l=r.length/16e3*1e3;return c.chunks.map(e=>({start:1e3*e.start,end:1e3*(e.end??l/1e3),text:e.text.trim()})).filter(e=>e.text&&!/^\[.*\]$|^\(.*\)$/.test(e.text))}export function toSentences(e){const t=[];let n;for(const a of e)n?(n.text+=a.text,n.end=a.end):n={...a},(/[.!?…]["')\]]*\s*$/.test(n.text)||n.end-n.start>7e3)&&(t.push({...n,text:n.text.trim()}),n=void 0);return n?.text.trim()&&t.push({...n,text:n.text.trim()}),t}export function narrationFor(t,n){const a=t.map(()=>[]);return n.forEach(e=>{let n=0;for(;n+1<t.length&&t[n+1]<=e.start+300;)n++;a[n].push(e.text)}),a.map(t=>e(t.join(" ")).join(" "))}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Neural models in workers, from a CDN, kept by the browser after the first download: no key, no
3
+ * server. Each reads one request at a time and says how its downloads go.
4
+ */
5
+ export type Progress = (loaded: number, total: number) => void;
6
+ /** A worker made from `source`; `call` posts a request and resolves with its answer. */
7
+ export declare function workerOf(source: string, type: WorkerType, progress: Progress): <T extends object>(request: object, transfer?: Transferable[]) => Promise<T>;
8
+ export declare function hasGpu(): Promise<boolean>;
9
+ export declare const KOKORO_JS = "https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/dist/kokoro.web.js";
10
+ export declare const KOKORO_MODEL = "onnx-community/Kokoro-82M-v1.0-ONNX";
11
+ export declare const ORT = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/";
12
+ export declare const PHONEMIZE = "https://cdn.jsdelivr.net/npm/@diffusionstudio/piper-wasm@1.0.0/build/";
13
+ export declare const PIPER_VOICES = "https://huggingface.co/rhasspy/piper-voices/resolve/main/";
14
+ export declare const TRANSFORMERS = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.6";
15
+ /** Where models and voices are kept, in the browser's Cache Storage. */
16
+ export declare const CACHE = "protomaze-demo-engine";
17
+ /** Kokoro-82M (Apache 2.0): English, American and British voices. */
18
+ export declare const KOKORO_WORKER = "\nlet tts;\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n if (!tts) {\n const { KokoroTTS } = await import(data.init.url);\n tts = await KokoroTTS.from_pretrained(data.init.model, {\n device: data.init.device,\n dtype: data.init.device === 'webgpu' ? 'fp32' : 'q8',\n progress_callback: (p) => p.total && self.postMessage({ progress: p.file, loaded: p.loaded, total: p.total }),\n });\n }\n const audio = await tts.generate(data.text, { voice: data.voice, speed: data.speed || 1 });\n self.postMessage({ id: data.id, samples: audio.audio, rate: audio.sampling_rate }, [audio.audio.buffer]);\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };";
19
+ /** Piper (MIT): voices in some forty languages, each its own model. */
20
+ export declare const PIPER_WORKER = "\nconst sessions = new Map();\nlet espeak;\nlet printed = [];\nasync function kept(url, track) {\n const cache = await caches.open('protomaze-demo-engine');\n const hit = await cache.match(url);\n if (hit) return hit.arrayBuffer();\n const response = await fetch(url);\n if (!response.ok) throw new Error('Could not download ' + url);\n const total = Number(response.headers.get('content-length')) || 0;\n const reader = response.body.getReader();\n const chunks = [];\n let loaded = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n loaded += value.length;\n if (track && total) self.postMessage({ progress: url, loaded, total });\n }\n const buffer = await new Blob(chunks).arrayBuffer();\n await cache.put(url, new Response(buffer));\n return buffer;\n}\nasync function phonemizer(init) {\n if (espeak) return espeak;\n importScripts(init.ort + 'ort.min.js', init.phonemize + 'piper_phonemize.js');\n ort.env.wasm.wasmPaths = init.ort;\n ort.env.wasm.numThreads = 1;\n const [wasm, data] = await Promise.all([\n kept(init.phonemize + 'piper_phonemize.wasm', true),\n kept(init.phonemize + 'piper_phonemize.data', true),\n ]);\n espeak = await createPiperPhonemize({\n print: (line) => printed.push(line), printErr: () => {}, noInitialRun: true,\n wasmBinary: wasm, getPreloadedPackage: () => data.slice(0),\n });\n return espeak;\n}\nasync function voice(init, model) {\n let made = sessions.get(model);\n if (!made) {\n made = (async () => {\n await phonemizer(init);\n const [config, onnx] = await Promise.all([\n kept(model + '.onnx.json').then((b) => JSON.parse(new TextDecoder().decode(b))),\n kept(model + '.onnx', true),\n ]);\n const session = await ort.InferenceSession.create(onnx, { executionProviders: ['wasm'] });\n return { config, session };\n })();\n made.catch(() => sessions.delete(model));\n sessions.set(model, made);\n }\n return made;\n}\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n const { config, session } = await voice(data.init, data.model);\n printed = [];\n espeak.callMain(['-l', config.espeak.voice, '--input', JSON.stringify([{ text: data.text }]), '--espeak_data', '/espeak-ng-data']);\n const ids = printed.flatMap((line) => JSON.parse(line).phoneme_ids ?? []);\n const i = config.inference;\n const feeds = {\n input: new ort.Tensor('int64', BigInt64Array.from(ids.map(BigInt)), [1, ids.length]),\n input_lengths: new ort.Tensor('int64', BigInt64Array.from([BigInt(ids.length)]), [1]),\n scales: new ort.Tensor('float32', Float32Array.from([i.noise_scale, i.length_scale / (data.speed || 1), i.noise_w]), [3]),\n };\n if ((config.num_speakers ?? 1) > 1) feeds.sid = new ort.Tensor('int64', BigInt64Array.from([BigInt(data.speaker ?? 0)]), [1]);\n const result = await session.run(feeds);\n const samples = new Float32Array(result.output.data);\n self.postMessage({ id: data.id, samples, rate: config.audio.sample_rate }, [samples.buffer]);\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };";
21
+ /** Whisper (MIT), through transformers.js: speech to text with timestamps, in the browser. */
22
+ export declare const WHISPER_WORKER = "\nconst pipes = new Map();\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n let made = pipes.get(data.model);\n if (!made) {\n made = (async () => {\n const { pipeline } = await import(data.url);\n return pipeline('automatic-speech-recognition', data.model, {\n device: data.device,\n dtype: data.device === 'webgpu' ? { encoder_model: 'fp32', decoder_model_merged: 'q4' } : 'q8',\n progress_callback: (p) => p.total && self.postMessage({ progress: p.file, loaded: p.loaded, total: p.total }),\n });\n })();\n made.catch(() => pipes.delete(data.model));\n pipes.set(data.model, made);\n }\n const transcribe = await made;\n const options = { return_timestamps: true, chunk_length_s: 30, stride_length_s: 5, task: 'transcribe' };\n let result;\n try {\n result = await transcribe(data.samples, data.language ? { ...options, language: data.language } : options);\n } catch (error) {\n if (!data.language) throw error;\n result = await transcribe(data.samples, options);\n }\n const chunks = (result.chunks ?? []).map((c) => ({ start: c.timestamp[0], end: c.timestamp[1], text: c.text }));\n self.postMessage({ id: data.id, text: result.text, chunks });\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };";
@@ -0,0 +1 @@
1
+ export function workerOf(e,n,t){let a,s=0;const r=new Map,o=new Map;return async(i,d=[])=>{if(!a){const s=URL.createObjectURL(new Blob([e],{type:"text/javascript"}));a=new Worker(s,{type:n}),a.onmessage=({data:e})=>{if(e.progress){o.set(e.progress,[e.loaded,e.total]);let n=0,a=0;return o.forEach(([e,t])=>(n+=e,a+=t)),void t(n,a)}r.get(e.id)?.(e),r.delete(e.id)},a.onerror=e=>{r.forEach(n=>n({id:0,error:e.message||"The worker failed"})),r.clear(),a=void 0}}const p=++s,c=await new Promise(e=>{r.set(p,e),a.postMessage({id:p,...i},d)});if(c.error)throw new Error(c.error);return c}}export async function hasGpu(){try{const e=navigator.gpu;return Boolean(e&&await e.requestAdapter())}catch{return!1}}export const KOKORO_JS="https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/dist/kokoro.web.js";export const KOKORO_MODEL="onnx-community/Kokoro-82M-v1.0-ONNX";export const ORT="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/";export const PHONEMIZE="https://cdn.jsdelivr.net/npm/@diffusionstudio/piper-wasm@1.0.0/build/";export const PIPER_VOICES="https://huggingface.co/rhasspy/piper-voices/resolve/main/";export const TRANSFORMERS="https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.6";export const CACHE="protomaze-demo-engine";export const KOKORO_WORKER="\nlet tts;\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n if (!tts) {\n const { KokoroTTS } = await import(data.init.url);\n tts = await KokoroTTS.from_pretrained(data.init.model, {\n device: data.init.device,\n dtype: data.init.device === 'webgpu' ? 'fp32' : 'q8',\n progress_callback: (p) => p.total && self.postMessage({ progress: p.file, loaded: p.loaded, total: p.total }),\n });\n }\n const audio = await tts.generate(data.text, { voice: data.voice, speed: data.speed || 1 });\n self.postMessage({ id: data.id, samples: audio.audio, rate: audio.sampling_rate }, [audio.audio.buffer]);\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };";export const PIPER_WORKER=`\nconst sessions = new Map();\nlet espeak;\nlet printed = [];\nasync function kept(url, track) {\n const cache = await caches.open('${CACHE}');\n const hit = await cache.match(url);\n if (hit) return hit.arrayBuffer();\n const response = await fetch(url);\n if (!response.ok) throw new Error('Could not download ' + url);\n const total = Number(response.headers.get('content-length')) || 0;\n const reader = response.body.getReader();\n const chunks = [];\n let loaded = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n loaded += value.length;\n if (track && total) self.postMessage({ progress: url, loaded, total });\n }\n const buffer = await new Blob(chunks).arrayBuffer();\n await cache.put(url, new Response(buffer));\n return buffer;\n}\nasync function phonemizer(init) {\n if (espeak) return espeak;\n importScripts(init.ort + 'ort.min.js', init.phonemize + 'piper_phonemize.js');\n ort.env.wasm.wasmPaths = init.ort;\n ort.env.wasm.numThreads = 1;\n const [wasm, data] = await Promise.all([\n kept(init.phonemize + 'piper_phonemize.wasm', true),\n kept(init.phonemize + 'piper_phonemize.data', true),\n ]);\n espeak = await createPiperPhonemize({\n print: (line) => printed.push(line), printErr: () => {}, noInitialRun: true,\n wasmBinary: wasm, getPreloadedPackage: () => data.slice(0),\n });\n return espeak;\n}\nasync function voice(init, model) {\n let made = sessions.get(model);\n if (!made) {\n made = (async () => {\n await phonemizer(init);\n const [config, onnx] = await Promise.all([\n kept(model + '.onnx.json').then((b) => JSON.parse(new TextDecoder().decode(b))),\n kept(model + '.onnx', true),\n ]);\n const session = await ort.InferenceSession.create(onnx, { executionProviders: ['wasm'] });\n return { config, session };\n })();\n made.catch(() => sessions.delete(model));\n sessions.set(model, made);\n }\n return made;\n}\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n const { config, session } = await voice(data.init, data.model);\n printed = [];\n espeak.callMain(['-l', config.espeak.voice, '--input', JSON.stringify([{ text: data.text }]), '--espeak_data', '/espeak-ng-data']);\n const ids = printed.flatMap((line) => JSON.parse(line).phoneme_ids ?? []);\n const i = config.inference;\n const feeds = {\n input: new ort.Tensor('int64', BigInt64Array.from(ids.map(BigInt)), [1, ids.length]),\n input_lengths: new ort.Tensor('int64', BigInt64Array.from([BigInt(ids.length)]), [1]),\n scales: new ort.Tensor('float32', Float32Array.from([i.noise_scale, i.length_scale / (data.speed || 1), i.noise_w]), [3]),\n };\n if ((config.num_speakers ?? 1) > 1) feeds.sid = new ort.Tensor('int64', BigInt64Array.from([BigInt(data.speaker ?? 0)]), [1]);\n const result = await session.run(feeds);\n const samples = new Float32Array(result.output.data);\n self.postMessage({ id: data.id, samples, rate: config.audio.sample_rate }, [samples.buffer]);\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };`;export const WHISPER_WORKER="\nconst pipes = new Map();\n// One at a time: the model runs one request, others wait their turn.\nlet queue = Promise.resolve();\nself.onmessage = ({ data }) => { queue = queue.then(async () => {\n try {\n let made = pipes.get(data.model);\n if (!made) {\n made = (async () => {\n const { pipeline } = await import(data.url);\n return pipeline('automatic-speech-recognition', data.model, {\n device: data.device,\n dtype: data.device === 'webgpu' ? { encoder_model: 'fp32', decoder_model_merged: 'q4' } : 'q8',\n progress_callback: (p) => p.total && self.postMessage({ progress: p.file, loaded: p.loaded, total: p.total }),\n });\n })();\n made.catch(() => pipes.delete(data.model));\n pipes.set(data.model, made);\n }\n const transcribe = await made;\n const options = { return_timestamps: true, chunk_length_s: 30, stride_length_s: 5, task: 'transcribe' };\n let result;\n try {\n result = await transcribe(data.samples, data.language ? { ...options, language: data.language } : options);\n } catch (error) {\n if (!data.language) throw error;\n result = await transcribe(data.samples, options);\n }\n const chunks = (result.chunks ?? []).map((c) => ({ start: c.timestamp[0], end: c.timestamp[1], text: c.text }));\n self.postMessage({ id: data.id, text: result.text, chunks });\n } catch (error) {\n self.postMessage({ id: data.id, error: String(error?.message ?? error) });\n }\n}); };";
@@ -0,0 +1,19 @@
1
+ import type { Demo } from '../model/Demo';
2
+ /**
3
+ * A link that opens the app on a demo, the demo itself in it - compressed, after `#demo=` - so a
4
+ * demo recorded or edited here travels without being checked in. `start`: the query that brings
5
+ * the app to the demo's start (`DemoEngineOptions.start.url`).
6
+ */
7
+ export declare function linkTo(demo: Demo, base?: string): Promise<string>;
8
+ /** The demo a link brought, taken out of the address; none without one. */
9
+ export declare function demoFromLink(): Promise<Demo | undefined>;
10
+ export declare function pack(value: object): Promise<string>;
11
+ export declare function unpack(text: string): Promise<unknown>;
12
+ /** Saved by the browser, as a file. */
13
+ export declare function download(content: Blob | string, name: string, type?: string): void;
14
+ /** Through the system's share sheet, where there is one that takes these files. */
15
+ export declare function shareFiles(files: File[], title: string, text?: string): Promise<boolean>;
16
+ /** A file's name from a title. */
17
+ export declare function fileName(title: string, extension: string): string;
18
+ /** Text picked by the person: a demo's JSON, from disk. */
19
+ export declare function pickFile(accept?: string): Promise<File | undefined>;
package/store/Share.js ADDED
@@ -0,0 +1 @@
1
+ const e=/^#demo=(.+)$/;export async function linkTo(e,t=window.location.href){const n=new URL(t);return n.hash="demo="+await pack(e),n.toString()}export async function demoFromLink(){const t=window.location.hash.match(e);if(t){window.history.replaceState(window.history.state,"",window.location.pathname+window.location.search);try{return await unpack(t[1])}catch{return}}}export async function pack(e){const t=new Blob([JSON.stringify(e)]).stream().pipeThrough(new CompressionStream("deflate-raw")),n=new Uint8Array(await new Response(t).arrayBuffer());let o="";return n.forEach(e=>o+=String.fromCharCode(e)),btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}export async function unpack(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=Uint8Array.from(t,e=>e.charCodeAt(0)),o=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return JSON.parse(await new Response(o).text())}export function download(e,t,n="text/plain"){const o="string"==typeof e?new Blob([e],{type:`${n};charset=utf-8`}):e,r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download=t,a.style.display="none",document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export async function shareFiles(e,t,n){const o={files:e,title:t,...n?{text:n}:{}};if(!navigator.canShare?.(o))return!1;try{return await navigator.share(o),!0}catch{return!1}}export function fileName(e,t){return`${e.replace(/[\\/:*?"<>|]+/g,"").replace(/\s+/g," ").trim()||"demo"}.${t}`}export function pickFile(e=".json,application/json"){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept=e,n.onchange=()=>t(n.files?.[0]),n.addEventListener("cancel",()=>t(void 0)),n.click()})}