@protomaze/demo-engine 0.1.0 → 0.1.2

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.
@@ -1 +1 @@
1
- import{copyOf as e,languagesOf as t,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as d,estimate as p}from"../model/Timing.js";import{parseDemo as l,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as S,download as k,fileName as b,linkTo as E,shareFiles as j}from"../store/Share.js";import{extensionOf as x,recordMicrophone as P,startFilming as T,videoSize as R}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{Player as $}from"./Player.js";import{Recorder as K}from"./Recorder.js";import{readAction as L}from"./Read.js";import{mountUI as N}from"../ui/EngineUI.js";import{agentTools as B}from"../agent/Agent.js";import{DEFAULT_SETTINGS as D,loadSettings as O,saveSettings as F}from"./Settings.js";const I=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new u({...e.targets,labels:e.labels}),this.overlay=new g(e.overlay),this.hand=new m(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:O(this.settingsKey),speech:{}},this.speech=new y(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new v(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e())}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e())}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};F(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return L(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=N(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);I.forEach(e=>window.addEventListener(e,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=!1===this.options.agent?void 0:this.options.agent??"demoEngine";i&&(window[i]=B(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),I.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await S();if(t){const e=c(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else{if("ArrowLeft"!==e.key&&"PageUp"!==e.key)return;o.player.again()}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=c(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return l(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]),n=new $(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}again(){const e=this.state.session;"playing"===e.mode&&e.player.again()}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),d=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},p=["pointerdown","keydown","wheel","touchstart"];p.forEach(e=>window.addEventListener(e,d,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,p.forEach(e=>window.removeEventListener(e,d,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const l=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const d=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(d.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await l(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await l(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=c(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};if(!1!==t.fromStart&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const i=await this.run(e,{...t,speed:t.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),o=i.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!i.error&&0===o.length,error:i.error,failures:o,problems:s,duration:i.timing.duration}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:p(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??d(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await T({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:d,voice:p}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let l=r.timing.cues;p&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),l=await this.transcribe(p,s).catch(()=>l),this.setSession({mode:"idle"}));const c={id:e.id,blob:d,at:Date.now(),json:JSON.stringify(e),vtt:h(l),timing:r.timing,language:s,...p?{voice:p}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${e.title}": ${Math.round(d.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:R(s,i)}:{}}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return w(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await T({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await P())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const d=this.options.start?.current(),p=new K(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const l=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>p.nextStep(),this.sayRecording=e=>p.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=p.stop(c),g=performance.now()-l;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),p=i??o?.voice;let l=[];if(p){this.updateSession("preparing",{text:"Transcribing what was said"});try{l=await this.transcribe(p,n);const e=f(m.stepStarts,l);m.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const c=m.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",d),steps:[]},y=t.after??u.steps.length-1,w={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===w.steps.length&&w.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:w.id,blob:o.video,at:Date.now(),json:JSON.stringify(w),vtt:h(l),language:n,timing:{duration:g,steps:m.stepStarts.map((e,t)=>({step:t,start:e,end:m.stepStarts[t+1]??g})),cues:l.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${c.length} step${1===c.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return E(e)}downloadDemo(e,t="json"){if("md"===t)return k(e.scenario??o(e,this.language()),b(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;k(JSON.stringify(n,null,2)+"\n",b(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?k(e.vtt,b(t,"vtt"),"text/vtt"):"srt"===s?k(r(a(e.vtt)),b(t,"srt"),"application/x-subrip"):void k(e.blob,b(t,x(e.blob)))}shareVideo(e,t){return j([new File([e.blob],b(t,x(e.blob)),{type:e.blob.type}),new File([e.vtt],b(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{D as DEFAULT_SETTINGS};
1
+ import{copyOf as e,languagesOf as t,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as d}from"../model/Timing.js";import{parseDemo as c,validate as l}from"../model/Validate.js";import{Hand as g}from"../page/Input.js";import{Overlay as m}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as k,download as b,fileName as S,linkTo as P,shareFiles as x}from"../store/Share.js";import{extensionOf as T,recordMicrophone as j,startFilming as E,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as R,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as L}from"./Recorder.js";import{readAction as B}from"./Read.js";import{mountUI as D}from"../ui/EngineUI.js";import{agentTools as F}from"../agent/Agent.js";import{openPresenter as I}from"../ui/Presenter.js";import{DEFAULT_SETTINGS as O,loadSettings as A,saveSettings as C}from"./Settings.js";const J=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new u({...e.targets,labels:e.labels}),this.overlay=new m(e.overlay),this.hand=new g(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:A(this.settingsKey),speech:{}},this.speech=new y(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new v(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e())}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e())}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};C(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return B(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=D(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);J.forEach(e=>window.addEventListener(e,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=!1===this.options.agent?void 0:this.options.agent??"demoEngine";i&&(window[i]=F(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),J.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await k();if(t){const e=l(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=l(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return c(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new N(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}openPresenter(e={}){return I(this,e)}presenterKey(e){this.key(e)}present(e,t={}){const s=this.play(e,{...t,waitForPresenter:!0});return this.openPresenter(),s}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return R(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?R(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=K(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));b(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},d=["pointerdown","keydown","wheel","touchstart"];d.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,d.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const c=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await c(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await c(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=l(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};if(!1!==t.fromStart&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const i=await this.run(e,{...t,speed:t.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),o=i.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!i.error&&0===o.length,error:i.error,failures:o,problems:s,duration:i.timing.duration}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:d(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await E({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:d}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let c=r.timing.cues;d&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),c=await this.transcribe(d,s).catch(()=>c),this.setSession({mode:"idle"}));const l={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(c),timing:r.timing,language:s,...d?{voice:d}:{}};return await this.store.saveVideo(l),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),l}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:$(s,i)}:{}}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return w(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await E({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await j())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),d=new L(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const c=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>d.nextStep(),this.sayRecording=e=>d.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const l=Boolean(r||a&&o.microphone),g=d.stop(l),m=performance.now()-c;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),d=i??o?.voice;let c=[];if(d){this.updateSession("preparing",{text:"Transcribing what was said"});try{c=await this.transcribe(d,n);const e=f(g.stepStarts,c);g.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const l=g.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,w={...u,steps:[...u.steps.slice(0,y+1),...l,...u.steps.slice(y+1)]};0===w.steps.length&&w.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:w.id,blob:o.video,at:Date.now(),json:JSON.stringify(w),vtt:h(c),language:n,timing:{duration:m,steps:g.stepStarts.map((e,t)=>({step:t,start:e,end:g.stepStarts[t+1]??m})),cues:c.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${l.length} step${1===l.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return P(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),S(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",S(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,S(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),S(t,"srt"),"application/x-subrip"):void b(e.blob,S(t,T(e.blob)))}shareVideo(e,t){return x([new File([e.blob],S(t,T(e.blob)),{type:e.blob.type}),new File([e.vtt],S(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{O as DEFAULT_SETTINGS};
@@ -39,6 +39,8 @@ export type PlayResult = {
39
39
  index: number;
40
40
  error: string;
41
41
  }[];
42
+ /** Gone forward or back by the presenter: its timing is not the demo's. */
43
+ navigated?: boolean;
42
44
  };
43
45
  export type PlayState = {
44
46
  step: number;
@@ -61,6 +63,8 @@ export type PlayerContext = {
61
63
  ready?: () => Promise<void> | void;
62
64
  /** An action as an instruction to the viewer: 'Click "Save"'. */
63
65
  read(action: DemoAction, element?: Element): string;
66
+ /** The app back at the demo's start (`DemoStart.go`): going back a step replays from there. False if it cannot. */
67
+ reset?: () => Promise<boolean>;
64
68
  update(state: Partial<PlayState>): void;
65
69
  };
66
70
  /** Plays one demo: each step's narration - spoken, a sentence a subtitle - while its actions run. */
@@ -76,8 +80,14 @@ export declare class Player {
76
80
  private speed;
77
81
  /** On to the next step: what is left of this one quickly, silently. */
78
82
  private hurrying;
79
- /** The step's narration again, while waiting for the presenter. */
80
- private repeating;
83
+ /** A step to go to, asked for by the presenter. */
84
+ private jump;
85
+ /** Going back: what is left of this step is dropped, not done. */
86
+ private dropping;
87
+ private navigated;
88
+ private stepNow;
89
+ private stepStart;
90
+ private last;
81
91
  /** Guided: the viewer's turn given up, the demo does it. */
82
92
  private skipViewer;
83
93
  /** Whether the viewer did the last guided action, so the demo leaves it. */
@@ -101,8 +111,23 @@ export declare class Player {
101
111
  * step - what is left of this one done quickly, so the app is where the next one expects it.
102
112
  */
103
113
  next(): void;
104
- /** The presenter's back (left arrow, PageUp): waiting after a step, its narration again. */
105
- again(): void;
114
+ /**
115
+ * The presenter's back (left arrow, PageUp): this step again from its start - or, pressed in its
116
+ * first seconds, the one before.
117
+ */
118
+ back(): void;
119
+ /**
120
+ * To a step: forward, what is left of this one done quickly and the steps between caught up
121
+ * under a card; back, the app reset to the demo's start (its cleanup, then `reset`) and caught
122
+ * up to the step. False where it cannot: filmed, a video would show it.
123
+ */
124
+ goTo(step: number): boolean;
125
+ /** The step playing, 0-based. */
126
+ get step(): number;
127
+ /** ms played when the step playing started. */
128
+ get stepStartedAt(): number;
129
+ private get waiting();
130
+ private waitingNow;
106
131
  /** Guided: the demo does what the viewer was to do. */
107
132
  doItForMe(): void;
108
133
  /** ms of play, less while paused; sooner when stopped or hurried. */
@@ -119,7 +144,11 @@ export declare class Player {
119
144
  private viewerDoes;
120
145
  /** The demo's cleanup, quick and unseen, whatever fails: the app as the demo found it. */
121
146
  private cleanup;
122
- /** Earlier steps' interactions, quick and silent: the app where the step expects it. */
147
+ /** Under a card naming the step: what the audience need not see happen. */
148
+ private covered;
149
+ /** Back to a step: the app as the demo found it - its cleanup, its start - then caught up to the step. */
150
+ private rewind;
151
+ /** Steps' interactions from `from` until `until`, quick and silent: the app where the step expects it. */
123
152
  private catchUp;
124
153
  /** Does it; a presentation effect returns how to take it down. */
125
154
  private perform;
package/engine/Player.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as a}from"../model/Demo.js";import{readingTime as o}from"../model/Timing.js";import{at as n}from"../page/Input.js";import{pointIn as r}from"../page/Targets.js";import{isGuided as h,waitForViewer as c}from"./Guided.js";const p=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.hurrying=!1,this.repeating=!1,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying;){if(void 0!==this.pausedAt){await p(50);continue}const t=Math.min(e,50),s=performance.now();await p(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(void 0!==this.pausedAt)return this.resume();this.hurrying=!0,this.silence(),this.skipViewer()}again(){void 0!==this.pausedAt&&(this.repeating=!0,this.resume())}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await p(50)}async find(t){const e=await this.context.targets.find(t,1e4,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,c=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{d>0&&!1!==n.catchUp&&await this.catchUp(d);const f=e.steps.map((t,e)=>e<d||e>l||u?[]:a(i(t,c)));f.flat().forEach(t=>r.speech.make(t,c)?.catch(()=>{}));const y=f.flat().map(t=>r.speech.make(t,c))[0]?.catch(()=>{});y&&await Promise.race([y,p(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();for(let i=d;i<=l&&!this.stopped;i++){const a=e.steps[i];r.update({step:i,caption:""}),r.overlay.raise();const p=this.elapsed(),y=[],x=f[i].map((t,e)=>new Promise(t=>y[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[i].entries()){if(await this.whilePaused(),this.stopped||this.hurrying)break;const s=await r.speech.say(e,c,n.filming?1/0:0===t&&i===d?0:1500);await this.whilePaused();const a=this.elapsed();y[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(o(e)),w.cues.push({step:i,start:a,end:this.elapsed(),text:e})}v=!0,y.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},A=async()=>{for(const[e,o]of a.actions.entries()){if(this.stopped)break;if(void 0===o.cue||v||u||await(x[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped)break;if(this.hurrying&&s(o))continue;const a=this.elapsed(),r={step:i,index:e,start:a,end:a};w.actions.push(r);try{const t=n.guided&&h(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,c);if(r.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),r.end=this.elapsed())};m.add(t);const s=o.for;void 0!==s&&this.sleep(s).then(t)}"clear"===o.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(r.end=this.elapsed(),r.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${i+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:i,index:e,error:s})}}};if(await Promise.all([$(),A()]),a.hold&&await this.sleep(a.hold),[...m].forEach(t=>t()),w.steps.push({step:i,start:p,end:this.elapsed()}),this.hurrying=!1,(a.pause||n.waitForPresenter)&&i<l&&!this.stopped&&!u)for(;this.pause(!0),await this.whilePaused(),this.repeating&&!this.stopped;)this.repeating=!1,await $(),this.hurrying=!1}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const a=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const o=c(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,o.cancel()},await o.done,this.target=void 0,this.skipViewer=()=>{},a.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,a]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(a,12),this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,[this.stopped,this.speed]=[i,a]}}async catchUp(e){const i=this.speed;this.speed=Math.max(i,12),this.context.update({catchingUp:!0});try{for(let i=0;i<e&&!this.stopped;i++){this.context.update({step:i});for(const e of this.demo.steps[i].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${i+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=i,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:a}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const o={hand:i,overlay:a,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,o)}const o=t=>a.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&a.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),a=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(a,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??1e4);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await p(100)}return}case"clear":return void a.clear();case"card":return o({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return o({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return o({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return o({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return o({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return o({kind:"blur",element:s});case"zoom":{const e=o({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
1
+ import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as a}from"../model/Demo.js";import{readingTime as o}from"../model/Timing.js";import{at as n}from"../page/Input.js";import{pointIn as r}from"../page/Targets.js";import{isGuided as h,waitForViewer as p}from"./Guided.js";const c=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await c(50);continue}const t=Math.min(e,50),s=performance.now();await c(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.waitingNow=t,this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(this.waiting)return this.resume();this.goTo(this.stepNow+1)}back(){const t=!this.waiting&&this.elapsed()-this.stepStart<3e3;this.goTo(t?this.stepNow-1:this.stepNow)}goTo(t){if(this.options.filming||this.stopped)return!1;const e=Math.max(0,Math.min(t,this.last));return!(e>this.stepNow&&this.stepNow===this.last)&&(this.jump=e,this.navigated=!0,e>this.stepNow?this.hurrying=!0:this.dropping=!0,this.silence(),this.skipViewer(),this.resume(),!0)}get step(){return this.stepNow}get stepStartedAt(){return this.stepStart}get waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,1e4,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]:a(i(t,p))),y=[...f.slice(d),...f.slice(0,d)].flat();y.forEach(t=>r.speech.make(t,p)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,p))[0]?.catch(()=>{});v&&await Promise.race([v,c(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();let x=d;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const a=this.elapsed();this.stepStart=a;const c=[],y=f[x].map((t,e)=>new Promise(t=>c[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[x].entries()){if(await this.whilePaused(),this.stopped||this.hurrying||this.dropping)break;const s=await r.speech.say(e,p,n.filming?1/0:0===t&&x===d?0:1500);await this.whilePaused();const i=this.elapsed();c[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(o(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,c.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},N=async()=>{for(const[e,a]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===a.cue||v||u||await(y[a.cue]??b),await this.sleep(a.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(a))continue;const i=this.elapsed(),o={step:x,index:e,start:i,end:i};w.actions.push(o);try{const t=n.guided&&h(a)&&!this.hurrying;t&&await this.viewerDoes(a);const e=t&&this.viewerDid?void 0:await this.perform(a,p);if(o.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),o.end=this.elapsed())};m.add(t);const s=a.for;void 0!==s&&this.sleep(s).then(t)}"clear"===a.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(o.end=this.elapsed(),o.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${a.do}): ${s}`);g.push({step:x,index:e,error:s})}}};if(await Promise.all([$(),N()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:a,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||n.waitForPresenter)&&x<l&&!this.stopped&&!u&&(this.pause(!0),await this.whilePaused()),this.stopped)break;if(void 0!==this.jump){const t=this.jump;this.jump=void 0,this.dropping=!1,t<=x?await this.rewind(t):t>x+1&&await this.covered(t,()=>this.catchUp(x+1,t)),x=t;continue}x++}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g,...this.navigated?{navigated:!0}:{}}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const a=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const o=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,o.cancel()},await o.done,this.target=void 0,this.skipViewer=()=>{},a.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,a]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(a,12),this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,[this.stopped,this.speed]=[i,a]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await c(250),i()}}async rewind(t){await this.covered(t,async()=>{this.context.overlay.clear(),await this.cleanup(),await(this.context.reset?.()),await this.catchUp(0,t)})}async catchUp(e,i){const a=this.speed;this.speed=Math.max(a,12),this.context.update({catchingUp:!0});try{for(let a=e;a<i&&!this.stopped;a++){this.context.update({step:a});for(const e of this.demo.steps[a].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${a+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=a,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:a}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const o={hand:i,overlay:a,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,o)}const o=t=>a.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&a.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),a=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(a,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??1e4);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void a.clear();case"card":return o({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return o({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return o({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return o({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return o({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return o({kind:"blur",element:s});case"zoom":{const e=o({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
@@ -43,6 +43,8 @@ export type DemoSettings = {
43
43
  };
44
44
  /** Expo booth: after a visitor's last touch, ms till the loop plays again. */
45
45
  loopIdle: number;
46
+ /** A demo's narration pack, where it has one, before any voice: made once, played by everyone. */
47
+ usePacks: boolean;
46
48
  };
47
49
  export declare const DEFAULT_SETTINGS: DemoSettings;
48
50
  export declare function loadSettings(key: string): DemoSettings;
@@ -1 +1 @@
1
- import{DEFAULT_SPEECH as e}from"../speech/Speech.js";export const DEFAULT_SETTINGS={speech:e,language:"page",subtitles:!0,waitForPresenter:!1,catchUp:!0,microphone:!1,filmRecording:!1,transcriber:"whisper",whisperModel:"base",music:{on:!1,volume:.18,track:"calm"},film:{frameRate:30,bitrate:8,lines:1080,aspect:"16:9",fit:"fit"},loopIdle:3e4};export function loadSettings(t){try{const s=JSON.parse(localStorage.getItem(t)??"{}");return{...DEFAULT_SETTINGS,...s,speech:{...e,...s.speech,elevenlabs:{...e.elevenlabs,...s.speech?.elevenlabs}},music:{...DEFAULT_SETTINGS.music,...s.music?.name?{track:"file"}:{},...s.music},film:{...DEFAULT_SETTINGS.film,...s.film}}}catch{return DEFAULT_SETTINGS}}export function saveSettings(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}
1
+ import{DEFAULT_SPEECH as e}from"../speech/Speech.js";export const DEFAULT_SETTINGS={speech:e,language:"page",subtitles:!0,waitForPresenter:!1,catchUp:!0,microphone:!1,filmRecording:!1,transcriber:"whisper",whisperModel:"base",music:{on:!1,volume:.18,track:"calm"},film:{frameRate:30,bitrate:8,lines:1080,aspect:"16:9",fit:"fit"},loopIdle:3e4,usePacks:!0};export function loadSettings(t){try{const s=JSON.parse(localStorage.getItem(t)??"{}");return{...DEFAULT_SETTINGS,...s,speech:{...e,...s.speech,elevenlabs:{...e.elevenlabs,...s.speech?.elevenlabs}},music:{...DEFAULT_SETTINGS.music,...s.music?.name?{track:"file"}:{},...s.music},film:{...DEFAULT_SETTINGS.film,...s.film}}}catch{return DEFAULT_SETTINGS}}export function saveSettings(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}
package/index.d.ts CHANGED
@@ -12,6 +12,9 @@ export * from './page/Input';
12
12
  export * from './page/Overlay';
13
13
  export * from './speech/Speech';
14
14
  export * from './speech/Transcribe';
15
+ export * from './speech/Pack';
16
+ export * from './speech/Music';
17
+ export * from './store/Zip';
15
18
  export * from './video/Film';
16
19
  export * from './store/Store';
17
20
  export * from './store/Share';
@@ -20,5 +23,6 @@ export { GUIDE } from './agent/Guide';
20
23
  export { DemoLibrary, Library, Narration, Recording, Shadow } from './ui/Library';
21
24
  export { Studio } from './ui/Studio';
22
25
  export { Timeline } from './ui/Timeline';
26
+ export { openPresenter, mountPresenter } from './ui/Presenter';
23
27
  export { useEngine, useDemos } from './ui/Hooks';
24
28
  export { UI_CSS } from './ui/Styles';
package/index.js CHANGED
@@ -1 +1 @@
1
- export*from"./model/Demo.js";export*from"./model/Timing.js";export*from"./model/Subtitles.js";export*from"./model/Validate.js";export*from"./engine/DemoEngine.js";export*from"./engine/Player.js";export*from"./engine/Recorder.js";export*from"./engine/Plugin.js";export*from"./engine/Settings.js";export*from"./page/Targets.js";export*from"./page/Input.js";export*from"./page/Overlay.js";export*from"./speech/Speech.js";export*from"./speech/Transcribe.js";export*from"./video/Film.js";export*from"./store/Store.js";export*from"./store/Share.js";export*from"./agent/Agent.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Narration,Recording,Shadow}from"./ui/Library.js";export{Studio}from"./ui/Studio.js";export{Timeline}from"./ui/Timeline.js";export{useEngine,useDemos}from"./ui/Hooks.js";export{UI_CSS}from"./ui/Styles.js";
1
+ export*from"./model/Demo.js";export*from"./model/Timing.js";export*from"./model/Subtitles.js";export*from"./model/Validate.js";export*from"./engine/DemoEngine.js";export*from"./engine/Player.js";export*from"./engine/Recorder.js";export*from"./engine/Plugin.js";export*from"./engine/Settings.js";export*from"./page/Targets.js";export*from"./page/Input.js";export*from"./page/Overlay.js";export*from"./speech/Speech.js";export*from"./speech/Transcribe.js";export*from"./speech/Pack.js";export*from"./speech/Music.js";export*from"./store/Zip.js";export*from"./video/Film.js";export*from"./store/Store.js";export*from"./store/Share.js";export*from"./agent/Agent.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Narration,Recording,Shadow}from"./ui/Library.js";export{Studio}from"./ui/Studio.js";export{Timeline}from"./ui/Timeline.js";export{openPresenter,mountPresenter}from"./ui/Presenter.js";export{useEngine,useDemos}from"./ui/Hooks.js";export{UI_CSS}from"./ui/Styles.js";
package/model/Demo.d.ts CHANGED
@@ -28,6 +28,8 @@ export type DemoStep = {
28
28
  hold?: number;
29
29
  /** Wait for the presenter (→, Enter or Continue) once the step is done. */
30
30
  pause?: boolean;
31
+ /** For the presenter's screen only: never said, never shown to the audience. */
32
+ notes?: string;
31
33
  };
32
34
  /**
33
35
  * The `index`th element matching `css` whose label (`labelOf`) is the locale `key`'s text in the
package/model/Validate.js CHANGED
@@ -1 +1 @@
1
- import{BUILT_IN_KINDS as t,isTarget as e}from"./Demo.js";const o={click:["target"],hover:["target"],type:["target","text"],key:["key"],select:["target","option"],drag:["target","to"],scroll:[],waitFor:["target"],spotlight:["target"],ring:["target"],arrow:["target"],callout:["text"],blur:["target"],card:["title"],zoom:["target"],clear:[]},r=new Set(["target"]),n=["top","right","bottom","left"],a=["top-left","top-right","bottom-left","bottom-right"];export function validate(i,c=[]){const d=[],f=(t,e)=>d.push({path:t,message:e});if("object"!=typeof i||null===i)return[{path:"",message:"not an object"}];const g=i;if("string"==typeof g.id&&g.id||f("id","needs a string"),"string"==typeof g.title&&g.title||f("title","needs a string"),void 0!==g.description&&"string"!=typeof g.description&&f("description","is a string"),void 0===g.start||"object"==typeof g.start&&!Object.values(g.start).some(t=>"string"!=typeof t)||f("start","is an object of strings"),!Array.isArray(g.steps))return f("steps","needs an array"),d;const l=[...t,...c];return g.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?f(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?f(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&f(`${o}.say.${t}`,"is a string")}),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>p(t,`${o}.actions[${e}]`)):f(`${o}.actions`,"needs an array, [] for none"))}),void 0!==g.cleanup&&(Array.isArray(g.cleanup)?g.cleanup.forEach((t,e)=>p(t,`cleanup[${e}]`)):f("cleanup","needs an array of actions")),d;function p(t,i){if("object"!=typeof t||null===t)return f(i,"not an object");if(!l.includes(t.do))return f(`${i}.do`,`unknown action "${t.do}": one of ${l.join(", ")}`);for(const n of o[t.do]??[]){const o=t[n];void 0===o||""===o&&"text"!==n?f(`${i}.${n}`,"is required"):r.has(n)&&!e(o)&&f(`${i}.${n}`,"needs { css, text?, key?, index? }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&f(`${i}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&f(`${i}.cue`,"is a sentence's index, 0 or more");const c=t;if(void 0===c.at||s(c.at)||f(`${i}.at`,"is [x, y], fractions of the box"),void 0===c.from||n.includes(c.from)||f(`${i}.from`,`one of ${n.join(", ")}`),void 0===c.side||n.includes(c.side)||f(`${i}.side`,`one of ${n.join(", ")}`),void 0===c.corner||a.includes(c.corner)||f(`${i}.corner`,`one of ${a.join(", ")}`),"drag"===t.do){const t=c.to;t&&void 0!==t.target&&!e(t.target)&&f(`${i}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!s(t.at)&&f(`${i}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&f(`${i}.to`,"needs a target, an at, or both")}}}function s(t){return Array.isArray(t)&&2===t.length&&t.every(t=>"number"==typeof t&&Number.isFinite(t))}export function parseDemo(t,e=[]){let o;try{o=JSON.parse(t)}catch(t){return{problems:[{path:"",message:t.message}]}}const r=validate(o,e);return r.length?{problems:r}:{demo:o,problems:r}}
1
+ import{BUILT_IN_KINDS as t,isTarget as e}from"./Demo.js";const o={click:["target"],hover:["target"],type:["target","text"],key:["key"],select:["target","option"],drag:["target","to"],scroll:[],waitFor:["target"],spotlight:["target"],ring:["target"],arrow:["target"],callout:["text"],blur:["target"],card:["title"],zoom:["target"],clear:[]},r=new Set(["target"]),n=["top","right","bottom","left"],a=["top-left","top-right","bottom-left","bottom-right"];export function validate(i,c=[]){const d=[],f=(t,e)=>d.push({path:t,message:e});if("object"!=typeof i||null===i)return[{path:"",message:"not an object"}];const g=i;if("string"==typeof g.id&&g.id||f("id","needs a string"),"string"==typeof g.title&&g.title||f("title","needs a string"),void 0!==g.description&&"string"!=typeof g.description&&f("description","is a string"),void 0===g.start||"object"==typeof g.start&&!Object.values(g.start).some(t=>"string"!=typeof t)||f("start","is an object of strings"),!Array.isArray(g.steps))return f("steps","needs an array"),d;const l=[...t,...c];return g.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?f(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?f(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&f(`${o}.say.${t}`,"is a string")}),void 0!==t.notes&&"string"!=typeof t.notes&&f(`${o}.notes`,"is a string"),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>p(t,`${o}.actions[${e}]`)):f(`${o}.actions`,"needs an array, [] for none"))}),void 0!==g.cleanup&&(Array.isArray(g.cleanup)?g.cleanup.forEach((t,e)=>p(t,`cleanup[${e}]`)):f("cleanup","needs an array of actions")),d;function p(t,i){if("object"!=typeof t||null===t)return f(i,"not an object");if(!l.includes(t.do))return f(`${i}.do`,`unknown action "${t.do}": one of ${l.join(", ")}`);for(const n of o[t.do]??[]){const o=t[n];void 0===o||""===o&&"text"!==n?f(`${i}.${n}`,"is required"):r.has(n)&&!e(o)&&f(`${i}.${n}`,"needs { css, text?, key?, index? }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&f(`${i}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&f(`${i}.cue`,"is a sentence's index, 0 or more");const c=t;if(void 0===c.at||s(c.at)||f(`${i}.at`,"is [x, y], fractions of the box"),void 0===c.from||n.includes(c.from)||f(`${i}.from`,`one of ${n.join(", ")}`),void 0===c.side||n.includes(c.side)||f(`${i}.side`,`one of ${n.join(", ")}`),void 0===c.corner||a.includes(c.corner)||f(`${i}.corner`,`one of ${a.join(", ")}`),"drag"===t.do){const t=c.to;t&&void 0!==t.target&&!e(t.target)&&f(`${i}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!s(t.at)&&f(`${i}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&f(`${i}.to`,"needs a target, an at, or both")}}}function s(t){return Array.isArray(t)&&2===t.length&&t.every(t=>"number"==typeof t&&Number.isFinite(t))}export function parseDemo(t,e=[]){let o;try{o=JSON.parse(t)}catch(t){return{problems:[{path:"",message:t.message}]}}const r=validate(o,e);return r.length?{problems:r}:{demo:o,problems:r}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protomaze/demo-engine",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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",
@@ -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)}
@@ -1,4 +1,5 @@
1
1
  import type { Language } from '../model/Demo';
2
+ import { NarrationPack, PackedSentence } from './Pack';
2
3
  /**
3
4
  * The narration's voice. Free: neural voices in the page, no key and no server - Kokoro for
4
5
  * English, Piper for some forty languages - downloaded once and kept by the browser. ElevenLabs:
@@ -64,9 +65,21 @@ export declare class Speech {
64
65
  freeVoice(language: Language): string | undefined;
65
66
  /** Who says it: what made audio is kept by. */
66
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>;
67
80
  /** Whether the voice makes audio a video hears. */
68
81
  get recordable(): boolean;
69
- /** A sentence's audio, made once a session; none for the system voice or none at all. */
82
+ /** A sentence's audio, made once a session - or from the pack; none for the system voice or none at all. */
70
83
  make(text: string, language: Language): Promise<AudioBuffer> | undefined;
71
84
  /** ms it takes to say, once made or said; else unknown. */
72
85
  duration(text: string, language: Language): number | undefined;
@@ -94,6 +107,8 @@ export declare class Speech {
94
107
  pause(): void;
95
108
  resume(): void;
96
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;
97
112
  private fromElevenLabs;
98
113
  private fromSystem;
99
114
  }
package/speech/Speech.js CHANGED
@@ -1 +1 @@
1
- import{CACHE as e,hasGpu as t,KOKORO_JS as i,KOKORO_MODEL as s,KOKORO_WORKER as n,ORT as a,PHONEMIZE as o,PIPER_VOICES as r,PIPER_WORKER as c,workerOf as h}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=h(n,"module",(e,t)=>this.loading(e,t)),this.piper=h(c,"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){const i=this.settings(),s="free"===i.voice?this.freeVoice(t):"elevenlabs"===i.voice?`${i.elevenlabs.voice}/${i.elevenlabs.model}`:i.system[t];return[i.voice,s,i.rate,t,e].join("|")}get recordable(){const e=this.settings().voice;return"free"===e||"elevenlabs"===e}make(e,t){if(!this.recordable)return;const i=this.keyOf(e,t);let s=this.made.get(i);return s||(s="elevenlabs"===this.settings().voice?this.fromElevenLabs(e):this.fromWorker(e,t),s.then(e=>this.lengths.set(i,1e3*e.duration),e=>{this.made.delete(i),this.set({error:e.message})}),this.made.set(i,s)),s}duration(e,t){if("off"!==this.settings().voice)return this.lengths.get(this.keyOf(e,t))}async prepare(e,t,i=()=>{}){let s=0;await Promise.all(e.map(n=>this.make(n,t)?.catch(()=>{}).then(()=>i(++s,e.length))))}async say(e,t,i=1/0){const s=this.settings().voice;if("off"===s)return;if("system"===s)return this.fromSystem(e,t);const n=this.make(e,t)?.catch(()=>{}),a=await(i===1/0?n:Promise.race([n,new Promise(e=>setTimeout(e,i))]));return a&&await this.audible()?this.play(a):void 0}play(e){const t=this.context(),i=t.createBufferSource();i.buffer=e,i.connect(t.destination),this.recorded&&i.connect(this.recorded),this.duck(1);const s=new Promise(e=>i.onended=()=>{this.duck(-1),e()});return i.start(),{done:s,stop:()=>{try{i.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 i=e.createGain();i.gain.setValueAtTime(0,e.currentTime),i.gain.linearRampToValueAtTime(this.musicLevel(),e.currentTime+1.5),t.connect(i),i.connect(e.destination),i.connect(this.soundtrack()),t.start(),this.bed={source:t,gain:i}}stopMusic(e=1.5){const t=this.bed;if(!t||!this.audio)return;this.bed=void 0;const i=this.audio.currentTime;t.gain.gain.cancelScheduledValues(i),t.gain.gain.setValueAtTime(t.gain.gain.value,i),t.gain.gain.linearRampToValueAtTime(0,i+e),t.source.stop(i+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,n){const r=this.freeVoice(n);if(!r)throw new Error(`No free voice for "${n}": choose one, or another voice`);const[c,h]=r.split(":"),u=this.settings().rate||1;let m;if("kokoro"===c){this.kokoroDevice??(this.kokoroDevice=t().then(e=>e?"webgpu":"wasm"));const n=await this.kokoroDevice;m=await this.kokoro({text:e,voice:h,speed:u,init:{url:i,model:s,device:n}})}else m=await this.piper({text:e,model:piperUrl(h),speed:u,init:{ort:a,phonemize:o}});const l=this.context().createBuffer(1,m.samples.length,m.rate);return l.copyToChannel(m.samples,0),l}async fromElevenLabs(t){const{key:i,voice:s,model:n}=this.settings().elevenlabs;if(!i)throw new Error("No ElevenLabs key");const a=`https://api.elevenlabs.io/v1/text-to-speech/${s}?output_format=mp3_44100_128`,o=this.settings().rate||1,r=`${a}&model=${n}&speed=${o}&text=${encodeURIComponent(t)}`,c=await caches.open(e);let h=await c.match(r);if(!h){if(h=await fetch(a,{method:"POST",headers:{"xi-api-key":i,"Content-Type":"application/json"},body:JSON.stringify({text:t,model_id:n,...1!==o?{voice_settings:{speed:Math.min(1.2,Math.max(.7,o))}}:{}})}),!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 i=new SpeechSynthesisUtterance(e);i.lang=t,i.rate=this.settings().rate||1;const s=this.settings().system[t],n=speechSynthesis.getVoices().find(e=>e.name===s)??speechSynthesis.getVoices().find(e=>e.lang.toLowerCase().startsWith(t.toLowerCase()));n&&(i.voice=n);const a=this.keyOf(e,t),o=performance.now();this.duck(1);const r=new Promise(e=>{i.onend=()=>{this.lengths.set(a,performance.now()-o),this.duck(-1),e()},i.onerror=()=>{this.duck(-1),e()}});return speechSynthesis.speak(i),{done:r,stop:()=>speechSynthesis.cancel()}}}export function piperUrl(e){const t=e.split("-"),i=t[0],s=t[t.length-1],n=t.slice(1,-1).join("-");return`${r}${i.split("_")[0]}/${i}/${n}/${s}/${e}`}let m;export function piperVoices(){return m??(m=fetch(`${r}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:i}=await t.json();return i.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]}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}))}
package/store/Zip.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** Zip files, as narration packs are kept: stored, not compressed (audio is already). Read either way. */
2
+ export type ZipEntry = {
3
+ name: string;
4
+ data: Uint8Array;
5
+ };
6
+ /** A zip of these files, stored. */
7
+ export declare function zip(files: ZipEntry[]): Blob;
8
+ /** The files in a zip, by name: stored or deflated (a zip made again elsewhere). */
9
+ export declare function unzip(buffer: ArrayBuffer): Promise<Map<string, Uint8Array>>;
package/store/Zip.js ADDED
@@ -0,0 +1 @@
1
+ let t;function e(e){if(!t){t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++)n=1&n?3988292384^n>>>1:n>>>1;t[e]=n>>>0}}let n=4294967295;for(let i=0;i<e.length;i++)n=t[255&(n^e[i])]^n>>>8;return(4294967295^n)>>>0}export function zip(t){const n=new TextEncoder,i=[],r=[];let a=0;for(const s of t){const t=n.encode(s.name),U=e(s.data),o=new DataView(new ArrayBuffer(30));o.setUint32(0,67324752,!0),o.setUint16(4,20,!0),o.setUint16(6,2048,!0),o.setUint16(12,33,!0),o.setUint32(14,U,!0),o.setUint32(18,s.data.length,!0),o.setUint32(22,s.data.length,!0),o.setUint16(26,t.length,!0),i.push(new Uint8Array(o.buffer),t,s.data);const w=new DataView(new ArrayBuffer(46));w.setUint32(0,33639248,!0),w.setUint16(4,20,!0),w.setUint16(6,20,!0),w.setUint16(8,2048,!0),w.setUint16(14,33,!0),w.setUint32(16,U,!0),w.setUint32(20,s.data.length,!0),w.setUint32(24,s.data.length,!0),w.setUint16(28,t.length,!0),w.setUint32(42,a,!0),r.push(new Uint8Array(w.buffer),t),a+=30+t.length+s.data.length}const s=r.reduce((t,e)=>t+e.length,0),U=new DataView(new ArrayBuffer(22));return U.setUint32(0,101010256,!0),U.setUint16(8,t.length,!0),U.setUint16(10,t.length,!0),U.setUint32(12,s,!0),U.setUint32(16,a,!0),new Blob([...i,...r,new Uint8Array(U.buffer)],{type:"application/zip"})}export async function unzip(t){const e=new DataView(t);let n=t.byteLength-22;for(;n>=0&&101010256!==e.getUint32(n,!0);)n--;if(n<0)throw new Error("Not a zip");const i=e.getUint16(n+10,!0);let r=e.getUint32(n+16,!0);const a=new TextDecoder,s=new Map;for(let n=0;n<i;n++){if(33639248!==e.getUint32(r,!0))throw new Error("A broken zip");const n=e.getUint16(r+10,!0),i=e.getUint32(r+20,!0),U=e.getUint16(r+28,!0),o=e.getUint16(r+30,!0),w=e.getUint16(r+32,!0),f=e.getUint32(r+42,!0),l=a.decode(new Uint8Array(t,r+46,U)),g=f+30+e.getUint16(f+26,!0)+e.getUint16(f+28,!0),c=new Uint8Array(t,g,i);if(0===n)s.set(l,c.slice());else if(8===n){const t=new Blob([c.slice()]).stream().pipeThrough(new DecompressionStream("deflate-raw"));s.set(l,new Uint8Array(await new Response(t).arrayBuffer()))}r+=46+U+o+w}return s}
package/ui/EngineUI.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useState as a}from"react";import{createRoot as n}from"react-dom/client";import{useEngine as i}from"./Hooks.js";import{Button as l,Icon as o,useTheme as s}from"./Kit.js";import{Library as r}from"./Library.js";import{Studio as m}from"./Studio.js";import{UI_CSS as c}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(c);const a=n(t.overlay.ui);return a.render(e.createElement(d,{engine:t})),()=>a.unmount()}function d({engine:t}){const n=i(t),c=s(t.options.theme??"dark"),[d,g]=a(!1),{session:h}=n,E="playing"===h.mode&&(h.filming&&!h.paused||h.looping)||"recording"===h.mode&&h.filming;return e.createElement(e.Fragment,null,"ready"===h.mode&&e.createElement("div",{className:"pde ready","data-theme":c,onClick:e=>e.target===e.currentTarget&&h.cancel()},e.createElement("div",{className:"box"},e.createElement(l,{icon:"Film"===h.verb?"film":"Record"===h.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:h.go},h.verb," “",h.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===h.verb?"":" and be filmed","."),e.createElement(l,{kind:"bare",onClick:h.cancel},"Cancel"))),"preparing"===h.mode&&e.createElement("div",{className:"pde bar","data-theme":c},e.createElement("span",null,h.title),e.createElement("span",{className:"muted"},h.text),void 0!==n.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*n.speech.loading)," %"),e.createElement(l,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===h.mode&&!h.checking&&!E&&e.createElement("div",{className:"pde bar","data-theme":c},h.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},h.title),e.createElement("span",{className:"muted"},h.catchingUp?`catching up · ${h.step+1}`:`${h.step+1} / ${h.steps}`),void 0!==n.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*n.speech.loading)," %"),n.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},n.hint),h.paused&&!h.waiting&&!n.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),h.guided&&h.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},h.instruction),h.guided&&h.instruction&&e.createElement(l,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),h.waiting&&e.createElement(l,{icon:"back",title:"Say it again (←, PageUp)",onClick:()=>t.again()}),e.createElement(l,{icon:h.paused?"play":"pause",kind:h.paused?"primary":void 0,title:"Space",onClick:()=>h.waiting?t.next():t.togglePause()},h.waiting?"Continue":h.paused?"Resume":"Pause"),!h.waiting&&!h.guided&&e.createElement(l,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),e.createElement(l,{icon:"stop",title:"Esc",onClick:()=>t.stop()},h.guided?"Exit":"Stop")),n.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":c,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(o,{name:"loop"}),e.createElement("span",{className:"small muted"},"The demo plays again after ",Math.round(t.getState().settings.loopIdle/1e3)," s without input"),e.createElement(l,{icon:"stop",small:!0,kind:"bare",title:"Stop the loop (Ctrl+Shift+L)",onClick:()=>t.stopLoop()})),"recording"===h.mode&&e.createElement(p,{engine:t,theme:c,filmed:h.filming}),n.message&&"idle"===h.mode&&e.createElement(u,{engine:t,theme:c,text:n.message.text,error:n.message.error}),n.studio&&!E&&e.createElement(m,{key:n.studio.opened,engine:t,theme:c}),t.options.launcher&&"idle"===h.mode&&!n.loop&&!n.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":c},e.createElement(l,{kind:d?"primary":void 0,onClick:()=>g(!d)},e.createElement(o,{name:"demos"}),"Demos")),d&&e.createElement(r,{engine:t,theme:c,floating:!0})))}function p({engine:t,theme:a,filmed:n}){const{session:o}=i(t);return"recording"!==o.mode?null:n?e.createElement("div",{className:"pde bar","data-theme":a,style:{top:"auto",bottom:12,padding:"4px 6px 4px 10px"}},e.createElement("span",{className:"dot"}),e.createElement("span",{className:"small muted"},"Step ",o.step+1),e.createElement(l,{icon:"right",small:!0,kind:"bare",title:"Next step (Alt+N)",onClick:()=>t.nextStep()}),e.createElement(l,{icon:"stop",small:!0,kind:"bare",title:"Stop (Esc)",onClick:()=>{t.finishRecording()}})):e.createElement("div",{className:"pde bar","data-theme":a},e.createElement("span",{className:"dot"}),e.createElement("span",null,"Step ",o.step+1),e.createElement("span",{className:"muted small"},o.actions," action",1===o.actions?"":"s",o.microphone?" · 🎙 listening":""),!o.microphone&&e.createElement("input",{className:"field",style:{width:340},placeholder:"This step's narration (or leave it for later)",value:o.caption,onChange:e=>t.narrate(e.target.value)}),e.createElement(l,{icon:"right",title:"Alt+N",onClick:()=>t.nextStep()},"Next step"),e.createElement(l,{icon:"stop",kind:"primary",title:"Esc",onClick:()=>{t.finishRecording()}},"Stop"),e.createElement("span",{className:"small muted"},"Alt+H: hover here"))}function u({engine:a,theme:n,text:i,error:o}){return t(()=>{if(o)return;const e=setTimeout(()=>a.say(void 0),6e3);return()=>clearTimeout(e)},[i]),e.createElement("div",{className:"pde toast"+(o?" error":""),"data-theme":n,style:{bottom:a.getState().studio?"auto":24,top:a.getState().studio?70:"auto"}},e.createElement("span",{className:"grow"},i),e.createElement(l,{icon:"close",small:!0,kind:"bare",title:"Close",onClick:()=>a.say(void 0)}))}
1
+ import e,{useEffect as t,useState as a}from"react";import{createRoot as n}from"react-dom/client";import{useEngine as l}from"./Hooks.js";import{Button as i,Icon as o,Menu as s,useTheme as r}from"./Kit.js";import{Library as m}from"./Library.js";import{Studio as c}from"./Studio.js";import{UI_CSS as d}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(d);const a=n(t.overlay.ui);return a.render(e.createElement(p,{engine:t})),()=>a.unmount()}function p({engine:t}){const n=l(t),d=r(t.options.theme??"dark"),[p,h]=a(!1),{session:E}=n,f="playing"===E.mode&&(E.filming&&!E.paused||E.looping)||"recording"===E.mode&&E.filming;return e.createElement(e.Fragment,null,"ready"===E.mode&&e.createElement("div",{className:"pde ready","data-theme":d,onClick:e=>e.target===e.currentTarget&&E.cancel()},e.createElement("div",{className:"box"},e.createElement(i,{icon:"Film"===E.verb?"film":"Record"===E.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:E.go},E.verb," “",E.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===E.verb?"":" and be filmed","."),e.createElement(i,{kind:"bare",onClick:E.cancel},"Cancel"))),"preparing"===E.mode&&e.createElement("div",{className:"pde bar","data-theme":d},e.createElement("span",null,E.title),e.createElement("span",{className:"muted"},E.text),void 0!==n.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*n.speech.loading)," %"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===E.mode&&!E.checking&&!f&&e.createElement("div",{className:"pde bar","data-theme":d},E.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},E.title),!E.filming&&e.createElement(i,{icon:"back",small:!0,kind:"bare",title:"Back: this step again; pressed early, the one before (←, PageUp)",onClick:()=>t.back()}),E.filming?e.createElement("span",{className:"muted"},`${E.step+1} / ${E.steps}`):e.createElement(s,{title:"Go to a step (1-9, Home, End)",icon:"expand",label:e.createElement("span",{className:"muted"},E.catchingUp?`… ${E.step+1}`:`${E.step+1} / ${E.steps}`),align:"left",items:E.demo.steps.map((a,n)=>({label:e.createElement("span",{style:{fontWeight:n===E.step?700:400}},`${n+1}. ${a.title??(Object.values(a.say).find(Boolean)??"").slice(0,48)}`),onClick:()=>t.goTo(n)}))}),void 0!==n.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*n.speech.loading)," %"),n.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},n.hint),E.paused&&!E.waiting&&!n.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),E.guided&&E.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},E.instruction),E.guided&&E.instruction&&e.createElement(i,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),e.createElement(i,{icon:E.paused?"play":"pause",kind:E.paused?"primary":void 0,title:"Space",onClick:()=>E.waiting?t.next():t.togglePause()},E.waiting?"Continue":E.paused?"Resume":"Pause"),!E.waiting&&e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),e.createElement(i,{icon:"present",kind:"bare",title:"The presenter's screen, in a window of its own",onClick:()=>{t.openPresenter()}}),e.createElement(i,{icon:"stop",title:"Esc",onClick:()=>t.stop()},E.guided?"Exit":"Stop")),n.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":d,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(o,{name:"loop"}),e.createElement("span",{className:"small muted"},"The demo plays again after ",Math.round(t.getState().settings.loopIdle/1e3)," s without input"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop the loop (Ctrl+Shift+L)",onClick:()=>t.stopLoop()})),"recording"===E.mode&&e.createElement(u,{engine:t,theme:d,filmed:E.filming}),n.message&&"idle"===E.mode&&e.createElement(g,{engine:t,theme:d,text:n.message.text,error:n.message.error}),n.studio&&!f&&e.createElement(c,{key:n.studio.opened,engine:t,theme:d}),t.options.launcher&&"idle"===E.mode&&!n.loop&&!n.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":d},e.createElement(i,{kind:p?"primary":void 0,onClick:()=>h(!p)},e.createElement(o,{name:"demos"}),"Demos")),p&&e.createElement(m,{engine:t,theme:d,floating:!0})))}function u({engine:t,theme:a,filmed:n}){const{session:o}=l(t);return"recording"!==o.mode?null:n?e.createElement("div",{className:"pde bar","data-theme":a,style:{top:"auto",bottom:12,padding:"4px 6px 4px 10px"}},e.createElement("span",{className:"dot"}),e.createElement("span",{className:"small muted"},"Step ",o.step+1),e.createElement(i,{icon:"right",small:!0,kind:"bare",title:"Next step (Alt+N)",onClick:()=>t.nextStep()}),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop (Esc)",onClick:()=>{t.finishRecording()}})):e.createElement("div",{className:"pde bar","data-theme":a},e.createElement("span",{className:"dot"}),e.createElement("span",null,"Step ",o.step+1),e.createElement("span",{className:"muted small"},o.actions," action",1===o.actions?"":"s",o.microphone?" · 🎙 listening":""),!o.microphone&&e.createElement("input",{className:"field",style:{width:340},placeholder:"This step's narration (or leave it for later)",value:o.caption,onChange:e=>t.narrate(e.target.value)}),e.createElement(i,{icon:"right",title:"Alt+N",onClick:()=>t.nextStep()},"Next step"),e.createElement(i,{icon:"stop",kind:"primary",title:"Esc",onClick:()=>{t.finishRecording()}},"Stop"),e.createElement("span",{className:"small muted"},"Alt+H: hover here"))}function g({engine:a,theme:n,text:l,error:o}){return t(()=>{if(o)return;const e=setTimeout(()=>a.say(void 0),6e3);return()=>clearTimeout(e)},[l]),e.createElement("div",{className:"pde toast"+(o?" error":""),"data-theme":n,style:{bottom:a.getState().studio?"auto":24,top:a.getState().studio?70:"auto"}},e.createElement("span",{className:"grow"},l),e.createElement(i,{icon:"close",small:!0,kind:"bare",title:"Close",onClick:()=>a.say(void 0)}))}
package/ui/Library.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as l}from"react";import{createPortal as o}from"react-dom";import{clock as i}from"../model/Timing.js";import{elevenLabsVoices as r,KOKORO_VOICES as s,piperVoices as c}from"../speech/Speech.js";import{MUSIC_TRACKS as m}from"../speech/Music.js";import{videoSize as d}from"../video/Film.js";import{pickFile as p}from"../store/Share.js";import{useDemos as h,useEngine as g}from"./Hooks.js";import{Button as u,Check as E,Icon as v,Labelled as b,Menu as f,Segmented as w,useTheme as y}from"./Kit.js";import{UI_CSS as k}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=y(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),[r,s]=l();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=k,t.append(a)}s(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},r&&o(t,r))}export function Library({engine:t,theme:a,floating:n}){const l=g(t),o=h(t),i="idle"!==l.session.mode,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 e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},l.message&&e.createElement("div",{className:"small "+(l.message.error?"error":"muted")},l.message.text),e.createElement("section",{className:"section"},e.createElement("h3",null,"Demos"),0===o.length&&e.createElement("div",{className:"small muted"},"None yet: record one, or ask an AI to make one (demoEngine.help())."),o.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},l.loop?e.createElement(u,{icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"):e.createElement(u,{icon:"loop",disabled:i||0===o.length,title:"Every demo, one after the other, again and again: an expo booth",onClick:()=>{t.loop(o.map(e=>e.demo))}},"Loop all"),e.createElement(u,{icon:"record",disabled:i,onClick:()=>{t.record()},style:{color:"var(--danger)"}},"Record"),e.createElement(u,{icon:"add",disabled:i,onClick:()=>t.openStudio(t.create())},"New"),e.createElement(u,{icon:"upload",onClick:()=>{p().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},"Import"),e.createElement(u,{icon:"copy",title:"Paste a demo’s JSON",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}},"Paste"))),e.createElement(Narration,{engine:t}),e.createElement(Production,{engine:t}),e.createElement(Recording,{engine:t}))}export function Production({engine:t}){const{settings:a}=g(t),{music:n,film:o}=a,[i,r]=l(),s=n.on?n.track:"none",c=o.lines?d(o.lines,o.aspect):void 0,h={width:Math.round(innerWidth*devicePixelRatio),height:Math.round(innerHeight*devicePixelRatio)};return e.createElement("section",{className:"section"},e.createElement("h3",null,"Production"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10,alignItems:"flex-end"}},e.createElement(b,{label:"Music"},e.createElement("select",{className:"field",value:s,onChange:e=>(e=>{if(i?.(),r(void 0),"none"===e)return t.changeSettings({music:{...n,on:!1}});"pick"!==e?t.changeSettings({music:{...n,on:!0,track:e}}):p("audio/*").then(e=>e&&t.setMusic(e))})(e.target.value)},e.createElement("option",{value:"none"},"None"),m.map(t=>e.createElement("option",{key:t.id,value:t.id,title:t.hint},t.name)),n.name&&e.createElement("option",{value:"file"},n.name),e.createElement("option",{value:"pick"},"Your own file…"))),e.createElement(u,{small:!0,icon:i?"stop":"listen",disabled:!n.on,onClick:()=>{(async()=>{if(i)return i(),r(void 0);const e=await t.listenToMusic(20);r(()=>e),setTimeout(()=>r(void 0),2e4)})()}},i?"Stop":"Listen"),e.createElement(b,{label:`Volume ${Math.round(100*n.volume)} %`},e.createElement("input",{type:"range",min:.02,max:.6,step:.01,value:n.volume,disabled:!n.on,onChange:e=>{t.changeSettings({music:{...n,volume:Number(e.target.value)}}),t.speech.setMusicVolume(Number(e.target.value))}}))),e.createElement("div",{className:"small muted"},n.on&&"file"!==n.track?`${m.find(e=>e.id===n.track)?.hint}. Composed by the engine: free to use anywhere. `:"","Under the narration, quieter while it speaks; in videos too."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Video size"},e.createElement("select",{className:"field",value:o.lines,onChange:e=>t.changeSettings({film:{...o,lines:Number(e.target.value)}})},e.createElement("option",{value:0},"The tab's own (",h.width,"×",h.height,")"),[720,1080,1440,2160].map(t=>{const{width:a,height:n}=d(t,o.aspect);return e.createElement("option",{key:t,value:t},2160===t?"4K":`${t}p`," (",a,"×",n,")")}))),o.lines>0&&e.createElement(e.Fragment,null,e.createElement(b,{label:"Shape"},e.createElement("select",{className:"field",value:o.aspect,onChange:e=>t.changeSettings({film:{...o,aspect:e.target.value}})},e.createElement("option",{value:"16:9"},"16:9 landscape"),e.createElement("option",{value:"9:16"},"9:16 portrait"),e.createElement("option",{value:"1:1"},"1:1 square"))),e.createElement(b,{label:"The tab"},e.createElement("select",{className:"field",value:o.fit,onChange:e=>t.changeSettings({film:{...o,fit:e.target.value}})},e.createElement("option",{value:"fit"},"Whole, with bars"),e.createElement("option",{value:"fill"},"Filling it, edges cut")))),e.createElement(b,{label:"Frames"},e.createElement("select",{className:"field",value:o.frameRate,onChange:e=>t.changeSettings({film:{...o,frameRate:Number(e.target.value)}})},e.createElement("option",{value:30},"30 a second"),e.createElement("option",{value:60},"60 a second"))),e.createElement(b,{label:"Quality"},e.createElement("select",{className:"field",value:o.bitrate,onChange:e=>t.changeSettings({film:{...o,bitrate:Number(e.target.value)}})},e.createElement("option",{value:4},"Small (4 Mb/s)"),e.createElement("option",{value:8},"Good (8 Mb/s)"),e.createElement("option",{value:16},"High (16 Mb/s)"),e.createElement("option",{value:25},"Master (25 Mb/s)")))),c&&(c.width>1.05*h.width||c.height>1.05*h.height)&&e.createElement("div",{className:"small muted"},"The tab is ",h.width,"×",h.height,": a ",c.width,"×",c.height," video scales it up, a little soft. A bigger window, or a screen with more pixels, keeps it sharp."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Loop: plays again after"},e.createElement("select",{className:"field",value:a.loopIdle,onChange:e=>t.changeSettings({loopIdle:Number(e.target.value)})},[10,20,30,60,120].map(t=>e.createElement("option",{key:t,value:1e3*t},t," s idle"))))))}function S({engine:t,entry:a,busy:n}){const{demo:l,origin:o,video:r}=a,s=i(t.timing(l).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:l.description},l.title),"app"!==o&&e.createElement("span",{className:"badge"},"edited"===o?"edited here":"made here"),r&&e.createElement("span",{className:"badge accent",title:`Filmed ${new Date(r.at).toLocaleString()}`},"video")),l.description&&e.createElement("div",{className:"small muted"},l.description),e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted grow"},l.steps.length," steps · ~",s," · ",t.languagesOf(l).join(", ")||"no narration"),e.createElement(u,{icon:"play",small:!0,kind:"primary",title:"Play",disabled:n,onClick:()=>{t.play(l)}}),e.createElement(u,{icon:"film",small:!0,title:"Film: a video with narration and subtitles",disabled:n,onClick:()=>{t.film(l)}}),e.createElement(u,{icon:"edit",small:!0,title:"Open in the studio",onClick:()=>t.openStudio(l)}),e.createElement(f,{title:"More",items:[{heading:"Play"},{label:"Present: waits after each step",icon:"present",disabled:n,onClick:()=>{t.play(l,{waitForPresenter:!0})}},{label:"Guide: the viewer does it",icon:"guide",disabled:n,onClick:()=>{t.guide(l)}},{label:"Loop it: an expo booth",icon:"loop",disabled:n,onClick:()=>{t.loop([l])}},{heading:"Share"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(l).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(l)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...l,scenario:a.scenario},"md")},r&&{heading:"Video"},r&&{label:"Download the video",icon:"film",onClick:()=>t.downloadVideo(r,l.title)},r&&{label:"Subtitles .vtt",icon:"subtitles",onClick:()=>t.downloadVideo(r,l.title,"vtt")},r&&{label:"Subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(r,l.title,"srt")},r&&{label:"Share…",icon:"share",onClick:()=>{t.shareVideo(r,l.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...t.create(`${l.title} (copy)`),...JSON.parse(JSON.stringify(l)),id:t.create(l.title).id,title:`${l.title} (copy)`})},"edited"===o&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(l.id)},"here"===o&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${l.title}"?`)&&void t.remove(l.id)}]})))}export function Narration({engine:t}){const{settings:a,speech:n}=g(t),l=a.speech.voice,o=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement("section",{className:"section"},e.createElement("h3",null,"Narration"),e.createElement(w,{value:l,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),e.createElement("div",{className:"small muted"},N.find(([e])=>e===l)?.[2]),"free"===l&&e.createElement(C,{engine:t}),"elevenlabs"===l&&e.createElement(x,{engine:t}),"system"===l&&e.createElement(M,{engine:t,language:o}),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(b,{label:"Language"},e.createElement("select",{className:"field",value:a.language,onChange:e=>t.changeSettings({language:e.target.value})},e.createElement("option",{value:"page"},"The page's (",t.options.language?.()??o,")"),t.languages().map(t=>e.createElement("option",{key:t,value:t},t)))),e.createElement(b,{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)})}))),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(E,{label:"Wait for the presenter after each step",checked:a.waitForPresenter,onChange:e=>t.changeSettings({waitForPresenter:e})}),e.createElement(E,{label:"From a step: catch up first",title:"Earlier steps' actions quickly, so the app is 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 says it again, Esc stops: a presenter's clicker works."),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))}function C({engine:a}){const{settings:n}=g(a),[o,i]=l([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const l=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],r=o.filter(e=>e.language.split("_")[0]===i);return e.createElement(b,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:l,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!l&&e.createElement("option",{value:""},"None: choose one"),"en"===i&&e.createElement("optgroup",{label:"Kokoro"},s.map(t=>e.createElement("option",{key:t.id,value:`kokoro:${t.id}`},t.name))),e.createElement("optgroup",{label:"Piper"},l.startsWith("piper:")&&!r.some(e=>`piper:${e.id}`===l)&&e.createElement("option",{value:l},l.slice(6)),r.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function x({engine:a}){const{settings:n}=g(a),{key:o,voice:i}=n.speech.elevenlabs,[s,c]=l([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});return t(()=>{o&&r(o).then(c,()=>c([]))},[o]),e.createElement("div",{className:"row"},e.createElement(b,{label:"API key, kept in this browser",className:"grow"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:o,onChange:e=>m({key:e.target.value.trim()})})),s.length>0&&e.createElement(b,{label:"Voice",className:"grow"},e.createElement("select",{className:"field",value:s.some(e=>e.id===i)?i:"",onChange:e=>m({voice:e.target.value})},s.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}function M({engine:a,language:n}){const{settings:o}=g(a),[i,r]=l(()=>speechSynthesis.getVoices());t(()=>{const e=()=>r(speechSynthesis.getVoices());return speechSynthesis.addEventListener("voiceschanged",e),()=>speechSynthesis.removeEventListener("voiceschanged",e)},[]);const s=i.filter(e=>e.lang.toLowerCase().startsWith(n.toLowerCase().split("-")[0]));return e.createElement(b,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:o.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...o.speech,system:{...o.speech.system,[n]:e.target.value}}})},e.createElement("option",{value:""},"The default"),s.map(t=>e.createElement("option",{key:t.name,value:t.name},t.name))))}export function Recording({engine:t}){const{settings:a}=g(t);return e.createElement("section",{className:"section"},e.createElement("h3",null,"Recording"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"mic"})," Microphone: what I say becomes the narration"),checked:a.microphone,onChange:e=>t.changeSettings({microphone:e})}),e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"film"})," Film it too"),checked:a.filmRecording,onChange:e=>t.changeSettings({filmRecording:e})})),a.microphone&&e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},e.createElement(b,{label:"Speech to text"},e.createElement("select",{className:"field",value:a.transcriber,onChange:e=>t.changeSettings({transcriber:e.target.value})},e.createElement("option",{value:"whisper"},"Whisper, in the browser (private, free)"),e.createElement("option",{value:"elevenlabs"},"ElevenLabs Scribe (your key)"))),"whisper"===a.transcriber&&e.createElement(b,{label:"Model"},e.createElement("select",{className:"field",value:a.whisperModel,onChange:e=>t.changeSettings({whisperModel:e.target.value})},e.createElement("option",{value:"tiny"},"tiny: quick"),e.createElement("option",{value:"base"},"base"),e.createElement("option",{value:"small"},"small: best")))),e.createElement("div",{className:"small muted"},"Recording: Alt+N starts the next step, Alt+H records a hover where the pointer is, Esc stops."))}
1
+ import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as l}from"react";import{createPortal as o}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{MUSIC_TRACKS as m}from"../speech/Music.js";import{videoSize as d}from"../video/Film.js";import{pickFile as p}from"../store/Share.js";import{useDemos as h,useEngine as g}from"./Hooks.js";import{Button as u,Check as E,Icon as v,Labelled as b,Menu as f,Segmented as w,useTheme as y}from"./Kit.js";import{UI_CSS as k}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=y(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]=l();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=k,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&o(t,s))}export function Library({engine:t,theme:a,floating:n}){const l=g(t),o=h(t),i="idle"!==l.session.mode,s=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 e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},l.message&&e.createElement("div",{className:"small "+(l.message.error?"error":"muted")},l.message.text),e.createElement("section",{className:"section"},e.createElement("h3",null,"Demos"),0===o.length&&e.createElement("div",{className:"small muted"},"None yet: record one, or ask an AI to make one (demoEngine.help())."),o.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},l.loop?e.createElement(u,{icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"):e.createElement(u,{icon:"loop",disabled:i||0===o.length,title:"Every demo, one after the other, again and again: an expo booth",onClick:()=>{t.loop(o.map(e=>e.demo))}},"Loop all"),e.createElement(u,{icon:"record",disabled:i,onClick:()=>{t.record()},style:{color:"var(--danger)"}},"Record"),e.createElement(u,{icon:"add",disabled:i,onClick:()=>t.openStudio(t.create())},"New"),e.createElement(u,{icon:"upload",onClick:()=>{p().then(e=>e?.text()).then(e=>{if(e)return s(e)})}},"Import"),e.createElement(u,{icon:"copy",title:"Paste a demo’s JSON",onClick:()=>{navigator.clipboard.readText().then(s,()=>t.say("Could not read the clipboard",!0))}},"Paste"))),e.createElement(Narration,{engine:t}),e.createElement(Production,{engine:t}),e.createElement(Recording,{engine:t}))}export function Production({engine:t}){const{settings:a}=g(t),{music:n,film:o}=a,[i,s]=l(),r=n.on?n.track:"none",c=o.lines?d(o.lines,o.aspect):void 0,h={width:Math.round(innerWidth*devicePixelRatio),height:Math.round(innerHeight*devicePixelRatio)};return e.createElement("section",{className:"section"},e.createElement("h3",null,"Production"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10,alignItems:"flex-end"}},e.createElement(b,{label:"Music"},e.createElement("select",{className:"field",value:r,onChange:e=>(e=>{if(i?.(),s(void 0),"none"===e)return t.changeSettings({music:{...n,on:!1}});"pick"!==e?t.changeSettings({music:{...n,on:!0,track:e}}):p("audio/*").then(e=>e&&t.setMusic(e))})(e.target.value)},e.createElement("option",{value:"none"},"None"),m.map(t=>e.createElement("option",{key:t.id,value:t.id,title:t.hint},t.name)),n.name&&e.createElement("option",{value:"file"},n.name),e.createElement("option",{value:"pick"},"Your own file…"))),e.createElement(u,{small:!0,icon:i?"stop":"listen",disabled:!n.on,onClick:()=>{(async()=>{if(i)return i(),s(void 0);const e=await t.listenToMusic(20);s(()=>e),setTimeout(()=>s(void 0),2e4)})()}},i?"Stop":"Listen"),e.createElement(b,{label:`Volume ${Math.round(100*n.volume)} %`},e.createElement("input",{type:"range",min:.02,max:.6,step:.01,value:n.volume,disabled:!n.on,onChange:e=>{t.changeSettings({music:{...n,volume:Number(e.target.value)}}),t.speech.setMusicVolume(Number(e.target.value))}}))),e.createElement("div",{className:"small muted"},n.on&&"file"!==n.track?`${m.find(e=>e.id===n.track)?.hint}. Composed by the engine: free to use anywhere. `:"","Under the narration, quieter while it speaks; in videos too."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Video size"},e.createElement("select",{className:"field",value:o.lines,onChange:e=>t.changeSettings({film:{...o,lines:Number(e.target.value)}})},e.createElement("option",{value:0},"The tab's own (",h.width,"×",h.height,")"),[720,1080,1440,2160].map(t=>{const{width:a,height:n}=d(t,o.aspect);return e.createElement("option",{key:t,value:t},2160===t?"4K":`${t}p`," (",a,"×",n,")")}))),o.lines>0&&e.createElement(e.Fragment,null,e.createElement(b,{label:"Shape"},e.createElement("select",{className:"field",value:o.aspect,onChange:e=>t.changeSettings({film:{...o,aspect:e.target.value}})},e.createElement("option",{value:"16:9"},"16:9 landscape"),e.createElement("option",{value:"9:16"},"9:16 portrait"),e.createElement("option",{value:"1:1"},"1:1 square"))),e.createElement(b,{label:"The tab"},e.createElement("select",{className:"field",value:o.fit,onChange:e=>t.changeSettings({film:{...o,fit:e.target.value}})},e.createElement("option",{value:"fit"},"Whole, with bars"),e.createElement("option",{value:"fill"},"Filling it, edges cut")))),e.createElement(b,{label:"Frames"},e.createElement("select",{className:"field",value:o.frameRate,onChange:e=>t.changeSettings({film:{...o,frameRate:Number(e.target.value)}})},e.createElement("option",{value:30},"30 a second"),e.createElement("option",{value:60},"60 a second"))),e.createElement(b,{label:"Quality"},e.createElement("select",{className:"field",value:o.bitrate,onChange:e=>t.changeSettings({film:{...o,bitrate:Number(e.target.value)}})},e.createElement("option",{value:4},"Small (4 Mb/s)"),e.createElement("option",{value:8},"Good (8 Mb/s)"),e.createElement("option",{value:16},"High (16 Mb/s)"),e.createElement("option",{value:25},"Master (25 Mb/s)")))),c&&(c.width>1.05*h.width||c.height>1.05*h.height)&&e.createElement("div",{className:"small muted"},"The tab is ",h.width,"×",h.height,": a ",c.width,"×",c.height," video scales it up, a little soft. A bigger window, or a screen with more pixels, keeps it sharp."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Loop: plays again after"},e.createElement("select",{className:"field",value:a.loopIdle,onChange:e=>t.changeSettings({loopIdle:Number(e.target.value)})},[10,20,30,60,120].map(t=>e.createElement("option",{key:t,value:1e3*t},t," s idle"))))))}function S({engine:t,entry:a,busy:n}){const{demo:l,origin:o,video:s}=a,r=i(t.timing(l).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:l.description},l.title),"app"!==o&&e.createElement("span",{className:"badge"},"edited"===o?"edited here":"made here"),s&&e.createElement("span",{className:"badge accent",title:`Filmed ${new Date(s.at).toLocaleString()}`},"video")),l.description&&e.createElement("div",{className:"small muted"},l.description),e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted grow"},l.steps.length," steps · ~",r," · ",t.languagesOf(l).join(", ")||"no narration"),e.createElement(u,{icon:"play",small:!0,kind:"primary",title:"Play",disabled:n,onClick:()=>{t.play(l)}}),e.createElement(u,{icon:"film",small:!0,title:"Film: a video with narration and subtitles",disabled:n,onClick:()=>{t.film(l)}}),e.createElement(u,{icon:"edit",small:!0,title:"Open in the studio",onClick:()=>t.openStudio(l)}),e.createElement(f,{title:"More",items:[{heading:"Play"},{label:"Present: waits after each step, the presenter's screen beside it",icon:"present",disabled:n,onClick:()=>{t.present(l)}},{label:"Guide: the viewer does it",icon:"guide",disabled:n,onClick:()=>{t.guide(l)}},{label:"Loop it: an expo booth",icon:"loop",disabled:n,onClick:()=>{t.loop([l])}},{heading:"Share"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(l).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(l)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...l,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(l)}},s&&{heading:"Video"},s&&{label:"Download the video",icon:"film",onClick:()=>t.downloadVideo(s,l.title)},s&&{label:"Subtitles .vtt",icon:"subtitles",onClick:()=>t.downloadVideo(s,l.title,"vtt")},s&&{label:"Subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,l.title,"srt")},s&&{label:"Share…",icon:"share",onClick:()=>{t.shareVideo(s,l.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...t.create(`${l.title} (copy)`),...JSON.parse(JSON.stringify(l)),id:t.create(l.title).id,title:`${l.title} (copy)`})},"edited"===o&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(l.id)},"here"===o&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${l.title}"?`)&&void t.remove(l.id)}]})))}export function Narration({engine:t}){const{settings:a,speech:n}=g(t),l=a.speech.voice,o=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement("section",{className:"section"},e.createElement("h3",null,"Narration"),e.createElement(w,{value:l,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),e.createElement("div",{className:"small muted"},N.find(([e])=>e===l)?.[2]),"free"===l&&e.createElement(C,{engine:t}),"elevenlabs"===l&&e.createElement(x,{engine:t}),"system"===l&&e.createElement(P,{engine:t,language:o}),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(b,{label:"Language"},e.createElement("select",{className:"field",value:a.language,onChange:e=>t.changeSettings({language:e.target.value})},e.createElement("option",{value:"page"},"The page's (",t.options.language?.()??o,")"),t.languages().map(t=>e.createElement("option",{key:t,value:t},t)))),e.createElement(b,{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)})}))),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(E,{label:"Wait for the presenter after each step",checked:a.waitForPresenter,onChange:e=>t.changeSettings({waitForPresenter:e})}),e.createElement(E,{label:"From a step: catch up first",title:"Earlier steps' actions quickly, so the app is where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})}),e.createElement(E,{label:"The 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("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9, Home and End go to a step, Esc stops: a presenter's clicker works."),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))}function C({engine:a}){const{settings:n}=g(a),[o,i]=l([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const l=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=o.filter(e=>e.language.split("_")[0]===i);return e.createElement(b,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:l,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!l&&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"},l.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===l)&&e.createElement("option",{value:l},l.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function x({engine:a}){const{settings:n}=g(a),{key:o,voice:i}=n.speech.elevenlabs,[r,c]=l([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});return t(()=>{o&&s(o).then(c,()=>c([]))},[o]),e.createElement("div",{className:"row"},e.createElement(b,{label:"API key, kept in this browser",className:"grow"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:o,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&e.createElement(b,{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 P({engine:a,language:n}){const{settings:o}=g(a),[i,s]=l(()=>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(b,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:o.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...o.speech,system:{...o.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))))}export function Recording({engine:t}){const{settings:a}=g(t);return e.createElement("section",{className:"section"},e.createElement("h3",null,"Recording"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"mic"})," Microphone: what I say becomes the narration"),checked:a.microphone,onChange:e=>t.changeSettings({microphone:e})}),e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"film"})," Film it too"),checked:a.filmRecording,onChange:e=>t.changeSettings({filmRecording:e})})),a.microphone&&e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},e.createElement(b,{label:"Speech to text"},e.createElement("select",{className:"field",value:a.transcriber,onChange:e=>t.changeSettings({transcriber:e.target.value})},e.createElement("option",{value:"whisper"},"Whisper, in the browser (private, free)"),e.createElement("option",{value:"elevenlabs"},"ElevenLabs Scribe (your key)"))),"whisper"===a.transcriber&&e.createElement(b,{label:"Model"},e.createElement("select",{className:"field",value:a.whisperModel,onChange:e=>t.changeSettings({whisperModel:e.target.value})},e.createElement("option",{value:"tiny"},"tiny: quick"),e.createElement("option",{value:"base"},"base"),e.createElement("option",{value:"small"},"small: best")))),e.createElement("div",{className:"small muted"},"Recording: Alt+N starts the next step, Alt+H records a hover where the pointer is, Esc stops."))}