@protomaze/demo-engine 0.1.7 → 0.1.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protomaze/demo-engine",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Protomaze Demo Engine: record, edit, narrate, play and film demos of a web app, in the browser",
5
5
  "repository": {
6
6
  "type": "git",
package/page/Input.d.ts CHANGED
@@ -23,7 +23,18 @@ export declare class Hand {
23
23
  private cursor;
24
24
  private speed;
25
25
  private hovered;
26
+ /** Script focus as the browser decides it again: see `pointing`. */
27
+ private unpatchFocus;
26
28
  constructor(cursor: Cursor, speed?: () => number);
29
+ /**
30
+ * From the hand's press on, the app's own script focus - a menu focusing its list, handing focus
31
+ * back when it closes - is not :focus-visible, as after a real click. The browser cannot tell: it
32
+ * has seen no trusted pointer input, so it takes script focus for keyboard focus, and MUI's
33
+ * tooltips open on it and stay. Until the hand presses a key, or is reset.
34
+ */
35
+ private pointing;
36
+ /** Keys pressed: script focus may show again, as a keyboard's does. */
37
+ private keyboard;
27
38
  private wait;
28
39
  /** The stand-in pointer, moved there along an eased path; longer ways take longer. */
29
40
  moveTo(x: number, y: number): Promise<void>;
package/page/Input.js CHANGED
@@ -1 +1 @@
1
- export function nextFrame(){return new Promise(t=>{const e=()=>{cancelAnimationFrame(n),clearTimeout(o),t()},n=requestAnimationFrame(e),o=setTimeout(e,40)})}export class Hand{constructor(t,e=()=>1){this.cursor=t,this.speed=e}wait(t){return(t=>new Promise(e=>setTimeout(e,t)))(t/this.speed())}async moveTo(t,e){const n=this.cursor.position()??{x:innerWidth/2,y:innerHeight/2},o=Math.hypot(t-n.x,e-n.y),s=Math.min(900,250+.6*o)/this.speed(),i=performance.now();for(;;){const o=Math.min(1,(performance.now()-i)/(s||1)),r=o<.5?4*o*o*o:1-Math.pow(-2*o+2,3)/2;if(this.cursor.move(n.x+(t-n.x)*r,n.y+(e-n.y)*r),o>=1)break;await nextFrame()}}hit(t,e,n){const o=document.elementFromPoint(t,e);return n?o&&n.contains(o)?o:n:o??document.body}over(t,n,o){if(this.hovered!==t){const s=this.hovered;this.leave(t),e(t,"pointerover",n,o,{relatedTarget:s??null}),e(t,"mouseover",n,o,{relatedTarget:s??null});const i=[];for(let e=t;e&&(!s||!e.contains(s));e=e.parentElement)i.unshift(e);i.forEach(t=>{e(t,"pointerenter",n,o,{bubbles:!1,relatedTarget:s??null}),e(t,"mouseenter",n,o,{bubbles:!1,relatedTarget:s??null})}),this.hovered=t}e(t,"pointermove",n,o),e(t,"mousemove",n,o)}leave(t){const n=this.hovered;if(n){e(n,"pointerout",0,0,{relatedTarget:t??null}),e(n,"mouseout",0,0,{relatedTarget:t??null});for(let o=n;o&&!o.contains(t??null);o=o.parentElement)e(o,"pointerleave",0,0,{bubbles:!1,relatedTarget:t??null}),e(o,"mouseleave",0,0,{bubbles:!1,relatedTarget:t??null});this.hovered=void 0}}async point(t,e){await this.moveTo(e.x,e.y),this.over(this.hit(e.x,e.y,t),e.x,e.y)}async click(o,s,{double:i=!1,right:r=!1,...a}={}){await this.point(o,s);const c=this.hit(s.x,s.y,o),l=t(a),u=r?2:0;for(let t=0;t<(i?2:1);t++)this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:u,buttons:r?2:1,...l}),e(c,"mousedown",s.x,s.y,{button:u,buttons:r?2:1,...l,detail:t+1}),n(c),await this.wait(60),e(c,"pointerup",s.x,s.y,{button:u,buttons:0,...l}),e(c,"mouseup",s.x,s.y,{button:u,buttons:0,...l,detail:t+1}),r?e(c,"contextmenu",s.x,s.y,{button:u,buttons:0,...l}):e(c,"click",s.x,s.y,{button:u,buttons:0,...l,detail:t+1}),setTimeout(()=>this.cursor.press(!1),160/this.speed()),i&&await this.wait(80);i&&e(c,"dblclick",s.x,s.y,{button:u,buttons:0,...l,detail:2})}async drag(o,s,i,r={}){if(o instanceof HTMLInputElement&&"range"===o.type)return this.slide(o,s,i);await this.point(o,s);const a=t(r),c=this.hit(s.x,s.y,o);this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:0,buttons:1,...a}),e(c,"mousedown",s.x,s.y,{button:0,buttons:1,...a}),n(c);const l=Math.max(8,Math.round(Math.hypot(i.x-s.x,i.y-s.y)/12));for(let t=1;t<=l;t++){const n=t/l,o=s.x+(i.x-s.x)*n,r=s.y+(i.y-s.y)*n;this.cursor.move(o,r);const u=document.elementFromPoint(o,r)??c;e(u,"pointermove",o,r,{buttons:1,...a}),e(u,"mousemove",o,r,{buttons:1,...a}),await this.wait(16)}const u=document.elementFromPoint(i.x,i.y)??c;e(u,"pointerup",i.x,i.y,{button:0,buttons:0,...a}),e(u,"mouseup",i.x,i.y,{button:0,buttons:0,...a}),(u===c||c.contains(u))&&e(u,"click",i.x,i.y,{button:0,buttons:0,...a}),this.cursor.press(!1),this.over(u,i.x,i.y)}async slide(t,e,n){await this.point(t,e),this.cursor.press(!0);const s=t.getBoundingClientRect(),[i,r]=[Number(t.min||0),Number(t.max||100)],a="any"===t.step?0:Number(t.step||1);for(let c=1;c<=12;c++){const l=e.x+(n.x-e.x)*(c/12);this.cursor.move(l,e.y+(n.y-e.y)*(c/12));let u=i+Math.min(1,Math.max(0,(l-s.left)/(s.width||1)))*(r-i);a&&(u=Math.round((u-i)/a)*a+i),o(t,String(u)),t.dispatchEvent(new Event("input",{bubbles:!0})),await this.wait(25)}t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async type(t,n){const s=t;s.focus?.({preventScroll:!0});const i=t.isContentEditable;for(let r=0===n.length?0:1;r<=n.length;r++){const a=n.slice(0,r),c=n[r-1];c&&e(t,"keydown",0,0,{key:c}),i?t.textContent=a:o(s,a),t.dispatchEvent(new InputEvent("input",{bubbles:!0,data:c??null,inputType:c?"insertText":"deleteContentBackward"})),c&&e(t,"keyup",0,0,{key:c}),await this.wait(55)}t.dispatchEvent(new Event("change",{bubbles:!0}))}key(t,e){const n=e??document.activeElement??document.body,{key:o,...s}=parseChord(t),r={key:o,code:i(o),bubbles:!0,cancelable:!0,composed:!0,...s},a=new KeyboardEvent("keydown",r),c=!n.dispatchEvent(a);n.dispatchEvent(new KeyboardEvent("keyup",r));const l=n.form;!c&&"Enter"===o&&l&&n instanceof HTMLInputElement&&l.requestSubmit()}async select(t,e,n){await this.point(t,n),this.cursor.press(!0);const s=e.trim().toLowerCase(),i=Array.from(t.options).find(t=>t.value===e||t.text.trim().toLowerCase()===s);if(!i)throw new Error(`No option "${e}"`);await this.wait(250),o(t,i.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async scroll(t,e){e?(t??window).scrollBy({left:e[0],top:e[1],behavior:this.speed()>1?"auto":"smooth"}):t?.scrollIntoView({block:"center",inline:"nearest",behavior:this.speed()>1?"auto":"smooth"}),await this.wait(500)}reset(){this.leave()}}export function at(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}function t(t){return{shiftKey:Boolean(t.shift),ctrlKey:Boolean(t.ctrl),altKey:Boolean(t.alt),metaKey:Boolean(t.meta)}}function e(t,e,n,o,s={}){const i={bubbles:!0,cancelable:!0,composed:!0,clientX:n,clientY:o,screenX:n,screenY:o,view:window,pointerId:1,pointerType:"mouse",isPrimary:!0,...s};let r;r=e.startsWith("key")?new KeyboardEvent(e,{bubbles:!0,cancelable:!0,composed:!0,...s}):e.startsWith("pointer")?new PointerEvent(e,i):new MouseEvent(e,i),t.dispatchEvent(r)}function n(t){const e=t.closest('button, a[href], input, textarea, select, summary, [tabindex], [contenteditable=""], [contenteditable="true"]');e?.focus({preventScroll:!0})}function o(t,e){const n=Object.getPrototypeOf(t),o=Object.getOwnPropertyDescriptor(n,"value")?.set;o?o.call(t,e):t.value=e}const s={control:"ctrl",ctrl:"ctrl",shift:"shift",alt:"alt",option:"alt",meta:"meta",cmd:"meta",command:"meta"};export function parseChord(t){const e=t.length>1&&t.endsWith("++"),n=(e?t.slice(0,-2):t).split("+").map(t=>t.trim()).filter(Boolean),o=e?"+":n.pop()??"",i=new Set(n.map(t=>s[t.toLowerCase()]).filter(Boolean));return{key:1===o.length&&i.size?o.toLowerCase():o,ctrlKey:i.has("ctrl"),shiftKey:i.has("shift"),altKey:i.has("alt"),metaKey:i.has("meta")}}function i(t){return/^[a-z]$/i.test(t)?`Key${t.toUpperCase()}`:/^\d$/.test(t)?`Digit${t}`:" "===t?"Space":t}
1
+ export function nextFrame(){return new Promise(t=>{const e=()=>{cancelAnimationFrame(o),clearTimeout(n),t()},o=requestAnimationFrame(e),n=setTimeout(e,40)})}export class Hand{constructor(t,e=()=>1){this.cursor=t,this.speed=e}pointing(){if(this.unpatchFocus)return;const t=[];for(const e of[HTMLElement.prototype,SVGElement.prototype]){const o=e.focus,n=function(t){return o.call(this,t&&"focusVisible"in t?t:{...t,focusVisible:!1})};e.focus=n,t.push({prototype:e,original:o,focus:n})}this.unpatchFocus=()=>{for(const{prototype:e,original:o,focus:n}of t)e.focus===n&&(e.focus=o);this.unpatchFocus=void 0}}keyboard(){this.unpatchFocus?.()}wait(t){return(t=>new Promise(e=>setTimeout(e,t)))(t/this.speed())}async moveTo(t,e){const o=this.cursor.position()??{x:innerWidth/2,y:innerHeight/2},n=Math.hypot(t-o.x,e-o.y),s=Math.min(900,250+.6*n)/this.speed(),i=performance.now();for(;;){const n=Math.min(1,(performance.now()-i)/(s||1)),r=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2;if(this.cursor.move(o.x+(t-o.x)*r,o.y+(e-o.y)*r),n>=1)break;await nextFrame()}}hit(t,e,o){const n=document.elementFromPoint(t,e);return o?n&&o.contains(n)?n:o:n??document.body}over(t,o,n){if(this.hovered!==t){const s=this.hovered;this.leave(t),e(t,"pointerover",o,n,{relatedTarget:s??null}),e(t,"mouseover",o,n,{relatedTarget:s??null});const i=[];for(let e=t;e&&(!s||!e.contains(s));e=e.parentElement)i.unshift(e);i.forEach(t=>{e(t,"pointerenter",o,n,{bubbles:!1,relatedTarget:s??null}),e(t,"mouseenter",o,n,{bubbles:!1,relatedTarget:s??null})}),this.hovered=t}e(t,"pointermove",o,n),e(t,"mousemove",o,n)}leave(t){const o=this.hovered;if(o){e(o,"pointerout",0,0,{relatedTarget:t??null}),e(o,"mouseout",0,0,{relatedTarget:t??null});for(let n=o;n&&!n.contains(t??null);n=n.parentElement)e(n,"pointerleave",0,0,{bubbles:!1,relatedTarget:t??null}),e(n,"mouseleave",0,0,{bubbles:!1,relatedTarget:t??null});this.hovered=void 0}}async point(t,e){await this.moveTo(e.x,e.y),this.over(this.hit(e.x,e.y,t),e.x,e.y)}async click(n,s,{double:i=!1,right:r=!1,...a}={}){await this.point(n,s);const c=this.hit(s.x,s.y,n),u=t(a),l=r?2:0;this.pointing();for(let t=0;t<(i?2:1);t++)this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:l,buttons:r?2:1,...u}),e(c,"mousedown",s.x,s.y,{button:l,buttons:r?2:1,...u,detail:t+1}),o(c),await this.wait(60),e(c,"pointerup",s.x,s.y,{button:l,buttons:0,...u}),e(c,"mouseup",s.x,s.y,{button:l,buttons:0,...u,detail:t+1}),r?e(c,"contextmenu",s.x,s.y,{button:l,buttons:0,...u}):e(c,"click",s.x,s.y,{button:l,buttons:0,...u,detail:t+1}),setTimeout(()=>this.cursor.press(!1),160/this.speed()),i&&await this.wait(80);i&&e(c,"dblclick",s.x,s.y,{button:l,buttons:0,...u,detail:2})}async drag(n,s,i,r={}){if(n instanceof HTMLInputElement&&"range"===n.type)return this.slide(n,s,i);await this.point(n,s);const a=t(r),c=this.hit(s.x,s.y,n);this.pointing(),this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:0,buttons:1,...a}),e(c,"mousedown",s.x,s.y,{button:0,buttons:1,...a}),o(c);const u=Math.max(8,Math.round(Math.hypot(i.x-s.x,i.y-s.y)/12));for(let t=1;t<=u;t++){const o=t/u,n=s.x+(i.x-s.x)*o,r=s.y+(i.y-s.y)*o;this.cursor.move(n,r);const l=document.elementFromPoint(n,r)??c;e(l,"pointermove",n,r,{buttons:1,...a}),e(l,"mousemove",n,r,{buttons:1,...a}),await this.wait(16)}const l=document.elementFromPoint(i.x,i.y)??c;e(l,"pointerup",i.x,i.y,{button:0,buttons:0,...a}),e(l,"mouseup",i.x,i.y,{button:0,buttons:0,...a}),(l===c||c.contains(l))&&e(l,"click",i.x,i.y,{button:0,buttons:0,...a}),this.cursor.press(!1),this.over(l,i.x,i.y)}async slide(t,e,o){await this.point(t,e),this.cursor.press(!0);const s=t.getBoundingClientRect(),[i,r]=[Number(t.min||0),Number(t.max||100)],a="any"===t.step?0:Number(t.step||1);for(let c=1;c<=12;c++){const u=e.x+(o.x-e.x)*(c/12);this.cursor.move(u,e.y+(o.y-e.y)*(c/12));let l=i+Math.min(1,Math.max(0,(u-s.left)/(s.width||1)))*(r-i);a&&(l=Math.round((l-i)/a)*a+i),n(t,String(l)),t.dispatchEvent(new Event("input",{bubbles:!0})),await this.wait(25)}t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async type(t,o){this.keyboard();const s=t;s.focus?.({preventScroll:!0});const i=t.isContentEditable;for(let r=0===o.length?0:1;r<=o.length;r++){const a=o.slice(0,r),c=o[r-1];c&&e(t,"keydown",0,0,{key:c}),i?t.textContent=a:n(s,a),t.dispatchEvent(new InputEvent("input",{bubbles:!0,data:c??null,inputType:c?"insertText":"deleteContentBackward"})),c&&e(t,"keyup",0,0,{key:c}),await this.wait(55)}t.dispatchEvent(new Event("change",{bubbles:!0}))}key(t,e){this.keyboard();const o=e??document.activeElement??document.body,{key:n,...s}=parseChord(t),r={key:n,code:i(n),bubbles:!0,cancelable:!0,composed:!0,...s},a=new KeyboardEvent("keydown",r),c=!o.dispatchEvent(a);o.dispatchEvent(new KeyboardEvent("keyup",r));const u=o.form;!c&&"Enter"===n&&u&&o instanceof HTMLInputElement&&u.requestSubmit()}async select(t,e,o){await this.point(t,o),this.pointing(),this.cursor.press(!0);const s=e.trim().toLowerCase(),i=Array.from(t.options).find(t=>t.value===e||t.text.trim().toLowerCase()===s);if(!i)throw new Error(`No option "${e}"`);await this.wait(250),n(t,i.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async scroll(t,e){e?(t??window).scrollBy({left:e[0],top:e[1],behavior:this.speed()>1?"auto":"smooth"}):t?.scrollIntoView({block:"center",inline:"nearest",behavior:this.speed()>1?"auto":"smooth"}),await this.wait(500)}reset(){this.leave(),this.unpatchFocus?.()}}export function at(t,e=[.5,.5]){const o=t.getBoundingClientRect();return{x:o.left+e[0]*o.width,y:o.top+e[1]*o.height}}function t(t){return{shiftKey:Boolean(t.shift),ctrlKey:Boolean(t.ctrl),altKey:Boolean(t.alt),metaKey:Boolean(t.meta)}}function e(t,e,o,n,s={}){const i={bubbles:!0,cancelable:!0,composed:!0,clientX:o,clientY:n,screenX:o,screenY:n,view:window,pointerId:1,pointerType:"mouse",isPrimary:!0,...s};let r;r=e.startsWith("key")?new KeyboardEvent(e,{bubbles:!0,cancelable:!0,composed:!0,...s}):e.startsWith("pointer")?new PointerEvent(e,i):new MouseEvent(e,i),t.dispatchEvent(r)}function o(t){const e=t.closest('button, a[href], input, textarea, select, summary, [tabindex], [contenteditable=""], [contenteditable="true"]');e?.focus({preventScroll:!0,focusVisible:!1})}function n(t,e){const o=Object.getPrototypeOf(t),n=Object.getOwnPropertyDescriptor(o,"value")?.set;n?n.call(t,e):t.value=e}const s={control:"ctrl",ctrl:"ctrl",shift:"shift",alt:"alt",option:"alt",meta:"meta",cmd:"meta",command:"meta"};export function parseChord(t){const e=t.length>1&&t.endsWith("++"),o=(e?t.slice(0,-2):t).split("+").map(t=>t.trim()).filter(Boolean),n=e?"+":o.pop()??"",i=new Set(o.map(t=>s[t.toLowerCase()]).filter(Boolean));return{key:1===n.length&&i.size?n.toLowerCase():n,ctrlKey:i.has("ctrl"),shiftKey:i.has("shift"),altKey:i.has("alt"),metaKey:i.has("meta")}}function i(t){return/^[a-z]$/i.test(t)?`Key${t.toUpperCase()}`:/^\d$/.test(t)?`Digit${t}`:" "===t?"Space":t}
@@ -11,10 +11,12 @@ export type SpeechSettings = {
11
11
  voice: VoiceKind;
12
12
  /** A free voice per language: 'kokoro:af_heart', 'piper:de_DE-thorsten-medium'. */
13
13
  free: Partial<Record<Language, string>>;
14
+ /** `voice` for every language without its own in `voices`: the multilingual model speaks them all. */
14
15
  elevenlabs: {
15
16
  key: string;
16
17
  voice: string;
17
18
  model: string;
19
+ voices?: Partial<Record<Language, string>>;
18
20
  };
19
21
  /** A system voice per language, by its name. */
20
22
  system: Partial<Record<Language, string>>;
@@ -63,6 +65,8 @@ export declare class Speech {
63
65
  soundtrack(): MediaStreamAudioDestinationNode;
64
66
  /** The free voice for a language: chosen, else the default, else none. */
65
67
  freeVoice(language: Language): string | undefined;
68
+ /** The ElevenLabs voice for a language: its own, else the one for all. */
69
+ elevenLabsVoice(language: Language): string;
66
70
  /** Who says it: what made audio is kept by. */
67
71
  private keyOf;
68
72
  /** Who says it now in `language`: 'kokoro:af_heart', 'elevenlabs:<voice>/<model>'; what a pack records. */
@@ -120,8 +124,10 @@ export declare function piperVoices(): Promise<{
120
124
  language: string;
121
125
  name: string;
122
126
  }[]>;
123
- /** The ElevenLabs account's voices. */
124
- export declare function elevenLabsVoices(key: string): Promise<{
127
+ export type ElevenLabsVoice = {
125
128
  id: string;
126
- name: string;
127
- }[]>;
129
+ name: string; /** Checked for these, as 'de', 'en': base codes. */
130
+ languages: string[];
131
+ };
132
+ /** The ElevenLabs account's voices, with the languages each is checked for. */
133
+ export declare function elevenLabsVoices(key: string): Promise<ElevenLabsVoice[]>;
package/speech/Speech.js CHANGED
@@ -1 +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}))}
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]}elevenLabsVoice(e){const{voice:t,voices:s={}}=this.settings().elevenlabs;return s[e]||s[e.toLowerCase().split(/[-_]/)[0]]||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:${this.elevenLabsVoice(e)}/${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,i).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,t):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,t){const{model:s}=this.settings().elevenlabs,i=`https://api.elevenlabs.io/v1/text-to-speech/${this.elevenLabsVoice(t)}?output_format=mp3_44100_128`;return{url:i,keptAs:`${i}&model=${s}&speed=${this.settings().rate||1}&text=${encodeURIComponent(e)}`}}async fromElevenLabs(e,s){const{key:i,model:a}=this.settings().elevenlabs;if(!i)throw new Error("No ElevenLabs key");const n=this.settings().rate||1,{url:o,keptAs:r}=this.elevenLabsUrls(e,s),c=await caches.open(t);let h=await c.match(r);if(!h){if(h=await fetch(o,{method:"POST",headers:{"xi-api-key":i,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:a,...1!==n?{voice_settings:{speed:Math.min(1.2,Math.max(.7,n))}}:{}})}),!h.ok)throw new Error(`ElevenLabs: ${h.status} ${await h.text()}`);await c.put(r,h.clone())}return this.context().decodeAudioData(await h.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={"xi-api-key":e};let s=await fetch("https://api.elevenlabs.io/v2/voices?page_size=100",{headers:t});if(s.ok||(s=await fetch("https://api.elevenlabs.io/v1/voices",{headers:t})),!s.ok)throw new Error(`ElevenLabs: ${s.status}`);const{voices:i}=await s.json(),a=e=>(e??"").toLowerCase().split(/[-_]/)[0];return i.map(e=>({id:e.voice_id,name:e.name,languages:[...new Set([...(e.verified_languages??[]).flatMap(e=>[a(e.language),a(e.locale)]),a(e.labels?.language)].filter(Boolean))]}))}
package/ui/Library.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as o}from"react";import{createPortal as l}from"react-dom";import{clock as i}from"../model/Timing.js";import{elevenLabsVoices as s,KOKORO_VOICES as r,piperVoices as c}from"../speech/Speech.js";import{pickFile as m}from"../store/Share.js";import{useDemos as d,useEngine as p}from"./Hooks.js";import{Button as g,Check as h,Icon as u,Labelled as E,Menu as b,Segmented as k,useTheme as v}from"./Kit.js";import{Flagged as y}from"./Flag.js";import{VideoLook as w}from"./Dialogs.js";import{UI_CSS as f}from"./Styles.js";const N=[["free","Free","Neural voices in the browser, no key: Kokoro for English, Piper for ~40 languages. Downloaded once (80-330 MB), then kept."],["elevenlabs","ElevenLabs","Premium voices with your own key. Each sentence is paid for once, then kept in this browser."],["system","System","The browser's own voices: instant, but videos don't hear them."],["off","Off","Subtitles only, timed to reading."]];export function DemoLibrary({engine:t,theme:a}){const n=v(a??t.options.theme??"auto");return e.createElement(Shadow,null,e.createElement(Library,{engine:t,theme:n}))}export function Shadow({children:t}){const i=n(null),[s,r]=o();return a(()=>{const e=i.current,t=e.shadowRoot??e.attachShadow({mode:"open"});if(!t.querySelector("style[data-pde]")){const a=e.ownerDocument.createElement("style");a.setAttribute("data-pde",""),a.textContent=f,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&l(t,s))}export function Library({engine:t,theme:a,floating:n}){const o=p(t),l=d(t),i="idle"!==o.session.mode,s=o.library??"demos",r=async e=>{const{demo:a,problems:n}=t.parse(e);if(!a)return t.say(`Not a demo: ${n.slice(0,3).map(e=>`${e.path||"demo"} ${e.message}`).join("; ")}`,!0);await t.save(a),t.openStudio(a)};return"settings"===s?e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement(g,{icon:"back",kind:"bare",title:"Back to the demos",onClick:()=>t.showLibrary(n?"demos":void 0)}),e.createElement("h2",{className:"grow"},"Settings")),e.createElement(Settings,{engine:t})):e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement("h2",{className:"grow"},"Demos"),o.loop&&e.createElement(g,{small:!0,icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"),e.createElement(b,{title:"Make a demo",icon:"add",label:"New",items:[{label:"Record one: do it on the page",icon:"record",disabled:i,onClick:()=>t.openDialog({kind:"record"})},{label:"Start empty, in the studio",icon:"edit",onClick:()=>t.openStudio(t.create())},{label:"Import a .demo.json",icon:"upload",onClick:()=>{m().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},{label:"Paste its JSON",icon:"copy",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}}]}),e.createElement(g,{icon:"tune",kind:"bare",title:"Settings: voices, languages, subtitles",onClick:()=>t.openSettings()})),o.message&&e.createElement("div",{className:"small "+(o.message.error?"error":"muted")},o.message.text),0===l.length&&e.createElement("div",{className:"small muted"},"None yet: record one (New), or ask an AI to make one (it starts with demoEngine.help())."),l.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),l.length>1&&e.createElement(g,{kind:"bare",icon:"loop",disabled:i,onClick:()=>t.openDialog({kind:"loop",demos:l.map(e=>e.demo)})},"Loop them all at a booth…"))}function S({engine:t,entry:a,busy:n}){const{demo:o,origin:l,video:s}=a,r=i(t.timing(o).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:o.description},o.title),"app"!==l&&e.createElement("span",{className:"badge"},"edited"===l?"edited here":"made here")),o.description&&e.createElement("div",{className:"small muted"},o.description),e.createElement("div",{className:"small muted"},o.steps.length," steps · ~",r,t.languagesOf(o).length?` · ${t.languagesOf(o).join(", ")}`:""),e.createElement("div",{className:"row"},e.createElement(g,{icon:"play",small:!0,kind:"primary",disabled:n,onClick:()=>{t.play(o)}},"Play"),e.createElement(g,{icon:"present",small:!0,disabled:n,title:"Step by step, the presenter’s screen beside it",onClick:()=>t.present(o)},"Present"),e.createElement(g,{icon:"guide",small:!0,disabled:n,title:"The viewer does each step: a tutorial",onClick:()=>{t.guide(o)}},"Guide"),e.createElement("span",{className:"grow"}),e.createElement(g,{icon:"edit",small:!0,kind:"bare",title:"Edit in the studio",onClick:()=>t.openStudio(o)}),e.createElement(b,{title:"More",items:[{label:"Film a video…",icon:"film",disabled:n,onClick:()=>t.openDialog({kind:"film",demo:o})},{label:"Loop at a booth…",icon:"loop",disabled:n,onClick:()=>t.openDialog({kind:"loop",demos:[o]})},s&&{label:"The video’s subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,o.title,"srt")},s&&{label:"Share the video…",icon:"share",onClick:()=>{t.shareVideo(s,o.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Share the demo"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(o).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(o)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...o,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(o)}},{heading:"This demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...JSON.parse(JSON.stringify(o)),id:t.create(o.title).id,title:`${o.title} (copy)`})},"edited"===l&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(o.id)},"here"===l&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${o.title}"?`)&&void t.remove(o.id)}]})),s&&e.createElement("div",{className:"row video-line"},e.createElement(u,{name:"film"}),e.createElement(w,{video:s}),e.createElement("span",{className:"grow small muted ellipsis",title:new Date(s.at).toLocaleString()},new Date(s.at).toLocaleDateString(),s.json!==JSON.stringify(o)&&s.json!==JSON.stringify({...o,scenario:void 0})?" · older version":""),e.createElement(g,{icon:"play",small:!0,kind:"bare",title:"Watch",onClick:()=>t.openDialog({kind:"video",demo:o,video:s})}),e.createElement(g,{icon:"download",small:!0,kind:"bare",title:s.look?.subtitles?"Download":"Download, with its subtitles beside it",onClick:()=>{t.downloadVideo(s,o.title),s.look?.subtitles||t.downloadVideo(s,o.title,"vtt")}}),e.createElement(g,{icon:"delete",small:!0,kind:"bare",title:"Delete the video",onClick:()=>{window.confirm("Delete this video?")&&t.store.deleteVideo(s.id)}})))}export function Settings({engine:t}){const{settings:a,speech:n}=p(t),o=a.speech.voice,l=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement(e.Fragment,null,e.createElement("section",{className:"section"},e.createElement("h3",null,"Voice"),e.createElement(k,{value:o,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),"free"===o&&e.createElement(C,{engine:t}),"elevenlabs"===o&&e.createElement(D,{engine:t}),"system"===o&&e.createElement(L,{engine:t,language:l}),e.createElement(E,{label:`Speed ${a.speech.rate.toFixed(2)}×`},e.createElement("input",{type:"range",min:.7,max:1.4,step:.05,value:a.speech.rate,onChange:e=>i({rate:Number(e.target.value)})})),void 0!==n.loading&&e.createElement("div",{className:"col",style:{gap:2}},e.createElement("span",{className:"small muted"},"Downloading a model: ",Math.round(100*n.loading)," %"),e.createElement("div",{className:"progress"},e.createElement("div",{style:{width:100*n.loading+"%"}}))),n.error&&e.createElement("div",{className:"small error"},"Voice: ",n.error)),e.createElement("section",{className:"section"},e.createElement("h3",null,"Language and subtitles"),e.createElement(E,{label:"Narration in"},e.createElement(k,{value:a.language,onChange:e=>t.changeSettings({language:e}),options:[["page",e.createElement(y,{key:"page",language:"page"},"The page's"),`The page's language: ${t.options.language?.()??l} now`],...t.languages().map(t=>[t,e.createElement(y,{key:t,language:t})])]})),e.createElement(h,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(h,{label:"A demo's narration pack, where it has one",title:"Its audio made once and checked in: no key, no download; what changed since, the voice says",checked:a.usePacks,onChange:e=>t.changeSettings({usePacks:e})})),e.createElement("section",{className:"section"},e.createElement("h3",null,"Playing from a step"),e.createElement(h,{label:"Earlier steps first, quickly: the app where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9 a step, Esc stops. Videos, recordings, booths and presentations ask what they need as they start."))}function C({engine:a}){const{settings:n}=p(a),[l,i]=o([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const o=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=l.filter(e=>e.language.split("_")[0]===i);return e.createElement(E,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:o,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!o&&e.createElement("option",{value:""},"None: choose one"),"en"===i&&e.createElement("optgroup",{label:"Kokoro"},r.map(t=>e.createElement("option",{key:t.id,value:`kokoro:${t.id}`},t.name))),e.createElement("optgroup",{label:"Piper"},o.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===o)&&e.createElement("option",{value:o},o.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function D({engine:a}){const{settings:n}=p(a),{key:l,voice:i}=n.speech.elevenlabs,[r,c]=o([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});return t(()=>{l&&s(l).then(c,()=>c([]))},[l]),e.createElement("div",{className:"row"},e.createElement(E,{label:"API key, kept in this browser",className:"grow"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:l,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&e.createElement(E,{label:"Voice",className:"grow"},e.createElement("select",{className:"field",value:r.some(e=>e.id===i)?i:"",onChange:e=>m({voice:e.target.value})},r.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}function L({engine:a,language:n}){const{settings:l}=p(a),[i,s]=o(()=>speechSynthesis.getVoices());t(()=>{const e=()=>s(speechSynthesis.getVoices());return speechSynthesis.addEventListener("voiceschanged",e),()=>speechSynthesis.removeEventListener("voiceschanged",e)},[]);const r=i.filter(e=>e.lang.toLowerCase().startsWith(n.toLowerCase().split("-")[0]));return e.createElement(E,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:l.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...l.speech,system:{...l.speech.system,[n]:e.target.value}}})},e.createElement("option",{value:""},"The default"),r.map(t=>e.createElement("option",{key:t.name,value:t.name},t.name))))}
1
+ import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as o}from"react";import{createPortal as l}from"react-dom";import{clock as i}from"../model/Timing.js";import{elevenLabsVoices as s,KOKORO_VOICES as r,piperVoices as c}from"../speech/Speech.js";import{pickFile as m}from"../store/Share.js";import{useDemos as d,useEngine as p}from"./Hooks.js";import{Button as g,Check as h,Icon as u,Labelled as E,Menu as v,Segmented as b,useTheme as k}from"./Kit.js";import{Flagged as y}from"./Flag.js";import{VideoLook as w}from"./Dialogs.js";import{UI_CSS as f}from"./Styles.js";const N=[["free","Free","Neural voices in the browser, no key: Kokoro for English, Piper for ~40 languages. Downloaded once (80-330 MB), then kept."],["elevenlabs","ElevenLabs","Premium voices with your own key. Each sentence is paid for once, then kept in this browser."],["system","System","The browser's own voices: instant, but videos don't hear them."],["off","Off","Subtitles only, timed to reading."]];export function DemoLibrary({engine:t,theme:a}){const n=k(a??t.options.theme??"auto");return e.createElement(Shadow,null,e.createElement(Library,{engine:t,theme:n}))}export function Shadow({children:t}){const i=n(null),[s,r]=o();return a(()=>{const e=i.current,t=e.shadowRoot??e.attachShadow({mode:"open"});if(!t.querySelector("style[data-pde]")){const a=e.ownerDocument.createElement("style");a.setAttribute("data-pde",""),a.textContent=f,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&l(t,s))}export function Library({engine:t,theme:a,floating:n}){const o=p(t),l=d(t),i="idle"!==o.session.mode,s=o.library??"demos",r=async e=>{const{demo:a,problems:n}=t.parse(e);if(!a)return t.say(`Not a demo: ${n.slice(0,3).map(e=>`${e.path||"demo"} ${e.message}`).join("; ")}`,!0);await t.save(a),t.openStudio(a)};return"settings"===s?e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement(g,{icon:"back",kind:"bare",title:"Back to the demos",onClick:()=>t.showLibrary(n?"demos":void 0)}),e.createElement("h2",{className:"grow"},"Settings")),e.createElement(Settings,{engine:t})):e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement("h2",{className:"grow"},"Demos"),o.loop&&e.createElement(g,{small:!0,icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"),e.createElement(v,{title:"Make a demo",icon:"add",label:"New",items:[{label:"Record one: do it on the page",icon:"record",disabled:i,onClick:()=>t.openDialog({kind:"record"})},{label:"Start empty, in the studio",icon:"edit",onClick:()=>t.openStudio(t.create())},{label:"Import a .demo.json",icon:"upload",onClick:()=>{m().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},{label:"Paste its JSON",icon:"copy",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}}]}),e.createElement(g,{icon:"tune",kind:"bare",title:"Settings: voices, languages, subtitles",onClick:()=>t.openSettings()})),o.message&&e.createElement("div",{className:"small "+(o.message.error?"error":"muted")},o.message.text),0===l.length&&e.createElement("div",{className:"small muted"},"None yet: record one (New), or ask an AI to make one (it starts with demoEngine.help())."),l.map(a=>e.createElement(C,{key:a.demo.id,engine:t,entry:a,busy:i})),l.length>1&&e.createElement(g,{kind:"bare",icon:"loop",disabled:i,onClick:()=>t.openDialog({kind:"loop",demos:l.map(e=>e.demo)})},"Loop them all at a booth…"))}function C({engine:t,entry:a,busy:n}){const{demo:o,origin:l,video:s}=a,r=i(t.timing(o).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:o.description},o.title),"app"!==l&&e.createElement("span",{className:"badge"},"edited"===l?"edited here":"made here")),o.description&&e.createElement("div",{className:"small muted"},o.description),e.createElement("div",{className:"small muted"},o.steps.length," steps · ~",r,t.languagesOf(o).length?` · ${t.languagesOf(o).join(", ")}`:""),e.createElement("div",{className:"row"},e.createElement(g,{icon:"play",small:!0,kind:"primary",disabled:n,onClick:()=>{t.play(o)}},"Play"),e.createElement(g,{icon:"present",small:!0,disabled:n,title:"Step by step, the presenter’s screen beside it",onClick:()=>t.present(o)},"Present"),e.createElement(g,{icon:"guide",small:!0,disabled:n,title:"The viewer does each step: a tutorial",onClick:()=>{t.guide(o)}},"Guide"),e.createElement("span",{className:"grow"}),e.createElement(g,{icon:"edit",small:!0,kind:"bare",title:"Edit in the studio",onClick:()=>t.openStudio(o)}),e.createElement(v,{title:"More",items:[{label:"Film a video…",icon:"film",disabled:n,onClick:()=>t.openDialog({kind:"film",demo:o})},{label:"Loop at a booth…",icon:"loop",disabled:n,onClick:()=>t.openDialog({kind:"loop",demos:[o]})},s&&{label:"The video’s subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,o.title,"srt")},s&&{label:"Share the video…",icon:"share",onClick:()=>{t.shareVideo(s,o.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Share the demo"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(o).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(o)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...o,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(o)}},{heading:"This demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...JSON.parse(JSON.stringify(o)),id:t.create(o.title).id,title:`${o.title} (copy)`})},"edited"===l&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(o.id)},"here"===l&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${o.title}"?`)&&void t.remove(o.id)}]})),s&&e.createElement("div",{className:"row video-line"},e.createElement(u,{name:"film"}),e.createElement(w,{video:s}),e.createElement("span",{className:"grow small muted ellipsis",title:new Date(s.at).toLocaleString()},new Date(s.at).toLocaleDateString(),s.json!==JSON.stringify(o)&&s.json!==JSON.stringify({...o,scenario:void 0})?" · older version":""),e.createElement(g,{icon:"play",small:!0,kind:"bare",title:"Watch",onClick:()=>t.openDialog({kind:"video",demo:o,video:s})}),e.createElement(g,{icon:"download",small:!0,kind:"bare",title:s.look?.subtitles?"Download":"Download, with its subtitles beside it",onClick:()=>{t.downloadVideo(s,o.title),s.look?.subtitles||t.downloadVideo(s,o.title,"vtt")}}),e.createElement(g,{icon:"delete",small:!0,kind:"bare",title:"Delete the video",onClick:()=>{window.confirm("Delete this video?")&&t.store.deleteVideo(s.id)}})))}export function Settings({engine:t}){const{settings:a,speech:n}=p(t),o=a.speech.voice,l=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement(e.Fragment,null,e.createElement("section",{className:"section"},e.createElement("h3",null,"Voice"),e.createElement(b,{value:o,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),"free"===o&&e.createElement(S,{engine:t}),"elevenlabs"===o&&e.createElement(D,{engine:t}),"system"===o&&e.createElement(L,{engine:t,language:l}),e.createElement(E,{label:`Speed ${a.speech.rate.toFixed(2)}×`},e.createElement("input",{type:"range",min:.7,max:1.4,step:.05,value:a.speech.rate,onChange:e=>i({rate:Number(e.target.value)})})),void 0!==n.loading&&e.createElement("div",{className:"col",style:{gap:2}},e.createElement("span",{className:"small muted"},"Downloading a model: ",Math.round(100*n.loading)," %"),e.createElement("div",{className:"progress"},e.createElement("div",{style:{width:100*n.loading+"%"}}))),n.error&&e.createElement("div",{className:"small error"},"Voice: ",n.error)),e.createElement("section",{className:"section"},e.createElement("h3",null,"Language and subtitles"),e.createElement(E,{label:"Narration in"},e.createElement(b,{value:a.language,onChange:e=>t.changeSettings({language:e}),options:[["page",e.createElement(y,{key:"page",language:"page"},"The page's"),`The page's language: ${t.options.language?.()??l} now`],...t.languages().map(t=>[t,e.createElement(y,{key:t,language:t})])]})),e.createElement(h,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(h,{label:"A demo's narration pack, where it has one",title:"Its audio made once and checked in: no key, no download; what changed since, the voice says",checked:a.usePacks,onChange:e=>t.changeSettings({usePacks:e})})),e.createElement("section",{className:"section"},e.createElement("h3",null,"Playing from a step"),e.createElement(h,{label:"Earlier steps first, quickly: the app where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9 a step, Esc stops. Videos, recordings, booths and presentations ask what they need as they start."))}function S({engine:a}){const{settings:n}=p(a),[l,i]=o([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const o=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=l.filter(e=>e.language.split("_")[0]===i);return e.createElement(E,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:o,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!o&&e.createElement("option",{value:""},"None: choose one"),"en"===i&&e.createElement("optgroup",{label:"Kokoro"},r.map(t=>e.createElement("option",{key:t.id,value:`kokoro:${t.id}`},t.name))),e.createElement("optgroup",{label:"Piper"},o.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===o)&&e.createElement("option",{value:o},o.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function D({engine:a}){const{settings:n}=p(a),{key:l,voices:i={}}=n.speech.elevenlabs,[r,c]=o([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});t(()=>{l&&s(l).then(c,()=>c([]))},[l]);const d=a.languages();return e.createElement("div",{className:"col"},e.createElement(E,{label:"API key, kept in this browser"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:l,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&d.map((t,n)=>{const o=a.speech.elevenLabsVoice(t),l=t.toLowerCase().split(/[-_]/)[0],s=r.filter(e=>e.languages.includes(l)),c=r.filter(e=>!e.languages.includes(l)),d=function(e){try{return new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{return e}}(l);return e.createElement(E,{key:t,label:`Voice for ${d}`},e.createElement("select",{className:"field",value:o,onChange:e=>m({voices:{...i,[t]:e.target.value},...0===n?{voice:e.target.value}:{}})},!r.some(e=>e.id===o)&&e.createElement("option",{value:o},o),s.length>0&&e.createElement("optgroup",{label:`Checked for ${d}`},s.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name))),e.createElement("optgroup",{label:s.length>0?"Other voices: they speak it too":`Every voice speaks ${d}`},c.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}))}function L({engine:a,language:n}){const{settings:l}=p(a),[i,s]=o(()=>speechSynthesis.getVoices());t(()=>{const e=()=>s(speechSynthesis.getVoices());return speechSynthesis.addEventListener("voiceschanged",e),()=>speechSynthesis.removeEventListener("voiceschanged",e)},[]);const r=i.filter(e=>e.lang.toLowerCase().startsWith(n.toLowerCase().split("-")[0]));return e.createElement(E,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:l.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...l.speech,system:{...l.speech.system,[n]:e.target.value}}})},e.createElement("option",{value:""},"The default"),r.map(t=>e.createElement("option",{key:t.name,value:t.name},t.name))))}